Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
fix(im): only reply to Feishu group messages mentioning this bot (#3505)
johnnyjy591b12ca6c40
diff --git a/internal/background/listeners_test.go b/internal/background/listeners_test.goindex 1fd10521f..b0cda0b24 100644--- a/internal/background/listeners_test.go+++ b/internal/background/listeners_test.go@@ -39,7 +39,7 @@ func TestListenersRunInOrderAndSurviveErrors(t *testing.T) {s := interfaces.SessionRef{TenantID: 1, SessionID: "s"}l.NotifyStop(context.Background(), s)- l.NotifyDelete(context.Background(), s)+ require.ErrorContains(t, l.NotifyDelete(context.Background(), s), "a failed")require.Equal(t, []string{"a:stop", "b:stop", "a:delete", "b:delete"}, log)require.Len(t, warnings, 2)@@ -61,7 +61,7 @@ func TestNotifyDeleteClearsSharedStateLast(t *testing.T) {sawDuringListener = len(items)}))- l.NotifyDelete(ctx, s)+ require.NoError(t, l.NotifyDelete(ctx, s))require.Equal(t, 1, sawDuringListener, "feature listeners must run before shared state is cleared")items, err := registry.List(ctx, s)diff --git a/internal/im/feishu/adapter.go b/internal/im/feishu/adapter.goindex e6af8e400..4fe2d9f26 100644--- a/internal/im/feishu/adapter.go+++ b/internal/im/feishu/adapter.go@@ -35,6 +35,7 @@ import ("github.com/Tencent/WeKnora/internal/logger""github.com/Tencent/WeKnora/internal/utils""github.com/gin-gonic/gin"+ larkim "github.com/larksuite/oapi-sdk-go/v3/service/im/v1")// Compile-time checks for the optional IM capabilities implemented by Adapter.@@ -66,6 +67,12 @@ type Adapter struct {tokenMu sync.MutextokenCache stringtokenExpAt time.Time++ // botOpenID is this app's own bot open_id. Feishu reports every bot+ // mention with mentioned_type == "bot"; the open_id is what distinguishes+ // this bot from other bots in the same group.+ botOpenIDMu sync.Mutex+ botOpenID string}// NewAdapter creates a new adapter for the given region (RegionFeishu or RegionLark).@@ -90,6 +97,55 @@ func NewAdapter(region Region, appID, appSecret, verificationToken, encryptKey,}, nil}+// BotOpenID returns the app's own bot open_id, fetching and caching it on the+// first use. Both the WebSocket and webhook event paths use this value to+// distinguish a mention of this bot from mentions of other bots in a group.+func (a *Adapter) BotOpenID(ctx context.Context) (string, error) {+ a.botOpenIDMu.Lock()+ defer a.botOpenIDMu.Unlock()++ if a.botOpenID != "" {+ return a.botOpenID, nil+ }++ accessToken, err := a.getTenantAccessToken(ctx)+ if err != nil {+ return "", fmt.Errorf("get access token: %w", err)+ }++ req, err := http.NewRequestWithContext(ctx, http.MethodGet, a.api("/open-apis/bot/v3/info"), nil)+ if err != nil {+ return "", fmt.Errorf("create bot info request: %w", err)+ }+ req.Header.Set("Authorization", "Bearer "+accessToken)++ resp, err := httpClient.Do(req)+ if err != nil {+ return "", fmt.Errorf("request bot info: %w", err)+ }+ defer func() { _ = resp.Body.Close() }()++ var result struct {+ Code int `json:"code"`+ Msg string `json:"msg"`+ Bot struct {+ OpenID string `json:"open_id"`+ } `json:"bot"`+ }+ if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {+ return "", fmt.Errorf("decode bot info: %w", err)+ }+ if result.Code != 0 {+ return "", fmt.Errorf("bot info error: code=%d msg=%s", result.Code, result.Msg)+ }+ if result.Bot.OpenID == "" {+ return "", fmt.Errorf("bot info response missing open_id")+ }++ a.botOpenID = result.Bot.OpenID+ return a.botOpenID, nil+}+// validateAPIBaseURL checks that a custom Feishu/Lark API base URL uses an// http(s) scheme and passes SSRF validation. Empty or the region default is// allowed without further checks. Mirrors wecom.validateEndpointURL but allows@@ -294,13 +350,14 @@ type feishuEvent struct {}type feishuMessage struct {- MessageID string `json:"message_id"`- RootID string `json:"root_id"`- ParentID string `json:"parent_id"`- MessageType string `json:"message_type"`- ChatType string `json:"chat_type"`- ChatID string `json:"chat_id"`- Content string `json:"content"`+ MessageID string `json:"message_id"`+ RootID string `json:"root_id"`+ ParentID string `json:"parent_id"`+ MessageType string `json:"message_type"`+ ChatType string `json:"chat_type"`+ ChatID string `json:"chat_id"`+ Content string `json:"content"`+ Mentions []*larkim.MentionEvent `json:"mentions,omitempty"`}type feishuSender struct {@@ -356,6 +413,23 @@ func (a *Adapter) ParseCallback(c *gin.Context) (*im.IncomingMessage, error) {}msg := eventBody.Event.Message+ // Keep webhook delivery in sync with the WebSocket path. In group chats+ // Feishu may deliver every message when the app has the "receive all group+ // messages" permission; only continue when this app's own bot is mentioned.+ if msg.ChatType == "group" {+ botOpenID, err := a.BotOpenID(c.Request.Context())+ if err != nil {+ logger.Warnf(c.Request.Context(),+ "[%s] failed to resolve bot open_id; ignoring group message: %v", a.region.Label, err)+ return nil, nil+ }+ if !mentionsBot(botOpenID, msg.Mentions) {+ logger.Infof(c.Request.Context(),+ "[%s] ignoring group message without this bot mention: msg_id=%q", a.region.Label, msg.MessageID)+ return nil, nil+ }+ }+// Compute thread ID: use root_id for threaded replies, or message_id for top-level messages.threadID := msg.RootIDif threadID == "" {diff --git a/internal/im/feishu/adapter_test.go b/internal/im/feishu/adapter_test.goindex eb4484426..c7e19e20d 100644--- a/internal/im/feishu/adapter_test.go+++ b/internal/im/feishu/adapter_test.go@@ -1,12 +1,16 @@package feishuimport (+ "bytes""context""encoding/json""net/http""net/http/httptest""strings""testing"++ "github.com/Tencent/WeKnora/internal/im"+ "github.com/gin-gonic/gin")func TestFeishuThreadID_ThreadedReply(t *testing.T) {@@ -59,6 +63,84 @@ func TestFeishuMessageStruct_JSONFields(t *testing.T) {}}+func TestParseCallbackGroupMentionGate(t *testing.T) {+ useTestHTTPClient(t)++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/open-apis/auth/v3/tenant_access_token/internal":+ _ = json.NewEncoder(w).Encode(map[string]any{+ "code": 0, "tenant_access_token": "test-token", "expire": 7200,+ })+ case "/open-apis/bot/v3/info":+ _ = json.NewEncoder(w).Encode(map[string]any{+ "code": 0, "msg": "ok",+ "bot": map[string]any{"open_id": "ou_this_bot"},+ })+ default:+ http.NotFound(w, r)+ }+ }))+ defer srv.Close()++ adapter, err := NewAdapter(testRegion(srv.URL), "app", "secret", "", "", "")+ if err != nil {+ t.Fatalf("NewAdapter: %v", err)+ }++ gin.SetMode(gin.TestMode)++ tests := []struct {+ name string+ mentions string+ wantNil bool+ }{+ {+ name: "no mention",+ mentions: `[]`,+ wantNil: true,+ },+ {+ name: "mentions a different bot",+ mentions: `[{"key":"@_user_1","mentioned_type":"bot","id":{"open_id":"ou_other_bot"}}]`,+ wantNil: true,+ },+ {+ name: "mentions this bot",+ mentions: `[{"key":"@_user_1","mentioned_type":"bot","id":{"open_id":"ou_this_bot"}}]`,+ wantNil: false,+ },+ }++ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ body := `{"header":{"event_type":"im.message.receive_v1"},"event":{"message":{` ++ `"message_id":"om_1","message_type":"text","chat_type":"group","chat_id":"oc_group",` ++ `"content":"{\"text\":\"@_user_1 hello\"}","mentions":` + test.mentions + `}}}`+ recorder := httptest.NewRecorder()+ ctx, _ := gin.CreateTestContext(recorder)+ ctx.Request = httptest.NewRequest(http.MethodPost, "/", bytes.NewBufferString(body))+ ctx.Request.Header.Set("Content-Type", "application/json")++ got, err := adapter.ParseCallback(ctx)+ if err != nil {+ t.Fatalf("ParseCallback: %v", err)+ }+ if test.wantNil && got != nil {+ t.Fatalf("ParseCallback() = %+v, want nil", got)+ }+ if !test.wantNil {+ if got == nil {+ t.Fatal("ParseCallback() returned nil, want message mentioning this bot")+ }+ if got.ChatType != im.ChatTypeGroup || got.Content != "hello" {+ t.Fatalf("ParseCallback() = %+v, want group message with content \"hello\"", got)+ }+ }+ })+ }+}+func TestImageCacheKey_StripsQuery(t *testing.T) {cases := map[string]string{"https://host/a.png?sig=1&t=2": "https://host/a.png",diff --git a/internal/im/feishu/factory.go b/internal/im/feishu/factory.goindex c9ef1c4a7..34659a7b6 100644--- a/internal/im/feishu/factory.go+++ b/internal/im/feishu/factory.go@@ -41,7 +41,7 @@ func NewFactory(region Region) im.AdapterFactory {return adapter, nil, nilcase "websocket":- client := NewLongConnClient(region, appID, appSecret, apiBaseURL, msgHandler)+ client := NewLongConnClient(region, appID, appSecret, apiBaseURL, adapter, msgHandler)wsCtx, wsCancel := context.WithCancel(context.Background())go func() {diff --git a/internal/im/feishu/longconn.go b/internal/im/feishu/longconn.goindex 12ab15006..2673ebf04 100644--- a/internal/im/feishu/longconn.go+++ b/internal/im/feishu/longconn.go@@ -16,23 +16,36 @@ import (// MessageHandler is called when an IM message is received via long connection.type MessageHandler func(ctx context.Context, msg *im.IncomingMessage) error+// botOpenIDProvider supplies this app's own Feishu/Lark bot open_id. It is+// shared with the webhook path so both delivery modes use the same mention+// matching rule.+type botOpenIDProvider interface {+ BotOpenID(ctx context.Context) (string, error)+}+// LongConnClient manages a Feishu/Lark WebSocket long connection.type LongConnClient struct {- region Region- appID string- wsClient *larkws.Client+ region Region+ appID string+ wsClient *larkws.Client+ botOpenIDProvider botOpenIDProvider}// NewLongConnClient creates a long connection client on the given region's cloud.// apiBaseURL overrides the SDK's bootstrap domain (empty uses the region// default); set it to a reverse-proxy origin for private/internal deployments.// When a message arrives, it converts it to IncomingMessage and calls handler.-func NewLongConnClient(region Region, appID, appSecret, apiBaseURL string, handler MessageHandler) *LongConnClient {+func NewLongConnClient(+ region Region, appID, appSecret, apiBaseURL string,+ botOpenIDProvider botOpenIDProvider, handler MessageHandler,+) *LongConnClient {+ var client *LongConnClient+// Long connection mode does not require verificationToken or encryptKey;// those are only used for webhook signature verification and decryption.eventHandler := dispatcher.NewEventDispatcher("", "").OnP2MessageReceiveV1(func(ctx context.Context, event *larkim.P2MessageReceiveV1) error {- msg := convertEvent(region, event)+ msg := convertEvent(region, client.botOpenID(ctx), event)if msg == nil {return nil}@@ -56,7 +69,13 @@ func NewLongConnClient(region Region, appID, appSecret, apiBaseURL string, handllarkws.WithDomain(apiBaseURL),)- return &LongConnClient{region: region, appID: appID, wsClient: wsClient}+ client = &LongConnClient{+ region: region,+ appID: appID,+ wsClient: wsClient,+ botOpenIDProvider: botOpenIDProvider,+ }+ return client}// Start begins the WebSocket long connection. It blocks until ctx is cancelled.@@ -65,6 +84,22 @@ func (c *LongConnClient) Start(ctx context.Context) error {return c.wsClient.Start(ctx)}+// botOpenID resolves this app's own bot open_id through the shared provider.+// An empty value makes convertEvent fail closed for group messages, which is+// safer than answering a message addressed to another bot.+func (c *LongConnClient) botOpenID(ctx context.Context) string {+ if c.botOpenIDProvider == nil {+ logger.Warnf(ctx, "[%s] bot open_id provider is not configured", c.region.Label)+ return ""+ }+ openID, err := c.botOpenIDProvider.BotOpenID(ctx)+ if err != nil {+ logger.Warnf(ctx, "[%s] failed to resolve bot open_id; ignoring group message: %v", c.region.Label, err)+ return ""+ }+ return openID+}+// Close tears down the WebSocket long connection.//// This is the only reliable way to stop a long connection: the SDK's@@ -108,7 +143,7 @@ func (l *feishuLoggerAdapter) Error(ctx context.Context, args ...interface{}) {// convertEvent converts a Feishu/Lark SDK event to a unified IncomingMessage.// Supports text, file, image and post messages. Returns nil for other types.-func convertEvent(region Region, event *larkim.P2MessageReceiveV1) *im.IncomingMessage {+func convertEvent(region Region, botOpenID string, event *larkim.P2MessageReceiveV1) *im.IncomingMessage {if event == nil || event.Event == nil || event.Event.Message == nil {logger.Warnf(context.Background(), "[%s][RX] event dropped: nil event/event/message", region.Label)return nil@@ -120,11 +155,12 @@ func convertEvent(region Region, event *larkim.P2MessageReceiveV1) *im.IncomingM// delivers (or doesn't). This is the single chokepoint for all message// types — adding it here catches text/file/image/post uniformly.logger.Infof(context.Background(),- "[%s][RX] msg_type=%q chat_type=%q chat_id=%q msg_id=%q root_id=%q parent_id=%q thread_id=%q content=%q",+ "[%s][RX] msg_type=%q chat_type=%q chat_id=%q msg_id=%q root_id=%q parent_id=%q "++ "thread_id=%q content=%q mentions=%v",region.Label,ptrStr(msg.MessageType), ptrStr(msg.ChatType), ptrStr(msg.ChatId),ptrStr(msg.MessageId), ptrStr(msg.RootId), ptrStr(msg.ParentId),- ptrStr(msg.ThreadId), ptrStr(msg.Content),+ ptrStr(msg.ThreadId), ptrStr(msg.Content), describeMentions(msg.Mentions),)if msg.MessageType == nil {@@ -133,6 +169,18 @@ func convertEvent(region Region, event *larkim.P2MessageReceiveV1) *im.IncomingMmsgType := *msg.MessageType+ // With the "receive all group messages" permission Feishu can deliver+ // messages that are not aimed at this bot; without it, only @-mentions are+ // delivered. Only handle a group message when this bot itself is explicitly+ // @-mentioned. Feishu reports bot mentions as mentioned_type="bot", so we+ // compare the mention open_id with this app's own bot open_id.+ isGroup := msg.ChatType != nil && *msg.ChatType == "group"+ if isGroup && !mentionsBot(botOpenID, msg.Mentions) {+ logger.Infof(context.Background(),+ "[%s][RX] ignoring group message without this bot mention: msg_id=%q", region.Label, ptrStr(msg.MessageId))+ return nil+ }+// Sender infoopenID := ""if event.Event.Sender != nil && event.Event.Sender.SenderId != nil && event.Event.Sender.SenderId.OpenId != nil {@@ -169,6 +217,45 @@ func convertEvent(region Region, event *larkim.P2MessageReceiveV1) *im.IncomingM}}+// mentionsBot reports whether a Feishu group event explicitly @-mentions this+// app's own bot. Feishu marks all bot mentions as mentioned_type == "bot", so+// the open_id is required to distinguish this bot from other bots.+func mentionsBot(botOpenID string, mentions []*larkim.MentionEvent) bool {+ if botOpenID == "" {+ return false+ }+ for _, mention := range mentions {+ if mention == nil {+ continue+ }+ if mention.MentionedType != nil && *mention.MentionedType == "bot" {+ if mention.Id != nil && mention.Id.OpenId != nil && *mention.Id.OpenId == botOpenID {+ return true+ }+ }+ }+ return false+}++// describeMentions renders mention metadata compactly for receive logs.+func describeMentions(mentions []*larkim.MentionEvent) []string {+ out := make([]string, 0, len(mentions))+ for _, mention := range mentions {+ if mention == nil {+ continue+ }+ key := ptrStr(mention.Key)+ mentionedType := ptrStr(mention.MentionedType)+ name := ptrStr(mention.Name)+ openID := ""+ if mention.Id != nil && mention.Id.OpenId != nil {+ openID = *mention.Id.OpenId+ }+ out = append(out, fmt.Sprintf("key=%s type=%s name=%s open_id=%s", key, mentionedType, name, openID))+ }+ return out+}+// convertTextEvent handles text message type.func convertTextEvent(region Region, msg *larkim.EventMessage,diff --git a/internal/im/feishu/longconn_test.go b/internal/im/feishu/longconn_test.goindex 97fac794b..973aab16c 100644--- a/internal/im/feishu/longconn_test.go+++ b/internal/im/feishu/longconn_test.go@@ -7,6 +7,90 @@ import (larkim "github.com/larksuite/oapi-sdk-go/v3/service/im/v1")+func stringPtr(s string) *string { return &s }++func TestConvertEventIgnoresGroupMessageWithoutBotMention(t *testing.T) {+ event := &larkim.P2MessageReceiveV1{+ Event: &larkim.P2MessageReceiveV1Data{+ Message: &larkim.EventMessage{+ MessageType: stringPtr("text"),+ ChatType: stringPtr("group"),+ ChatId: stringPtr("oc_group"),+ MessageId: stringPtr("om_message"),+ Content: stringPtr(`{"text":"知识库最新文档"}`),+ },+ Sender: &larkim.EventSender{+ SenderId: &larkim.UserId{OpenId: stringPtr("ou_sender")},+ },+ },+ }++ if got := convertEvent(RegionFeishu, "ou_bot", event); got != nil {+ t.Fatalf("convertEvent() = %+v, want nil for group message without bot mention", got)+ }+}++func TestConvertEventKeepsGroupMessageThatMentionsBot(t *testing.T) {+ event := &larkim.P2MessageReceiveV1{+ Event: &larkim.P2MessageReceiveV1Data{+ Message: &larkim.EventMessage{+ MessageType: stringPtr("text"),+ ChatType: stringPtr("group"),+ ChatId: stringPtr("oc_group"),+ MessageId: stringPtr("om_message"),+ Content: stringPtr(`{"text":"@_user_1 亚信有什么ai安全产品"}`),+ Mentions: []*larkim.MentionEvent{{+ Key: stringPtr("@_user_1"),+ MentionedType: stringPtr("bot"),+ Name: stringPtr("WeKnora"),+ Id: &larkim.UserId{OpenId: stringPtr("ou_bot")},+ }},+ },+ Sender: &larkim.EventSender{+ SenderId: &larkim.UserId{OpenId: stringPtr("ou_sender")},+ },+ },+ }++ got := convertEvent(RegionFeishu, "ou_bot", event)+ if got == nil {+ t.Fatal("convertEvent() returned nil for group message that mentions the bot")+ }+ if got.Content != "亚信有什么ai安全产品" {+ t.Fatalf("Content = %q, want %q", got.Content, "亚信有什么ai安全产品")+ }+ if got.ChatType != im.ChatTypeGroup {+ t.Fatalf("ChatType = %q, want %q", got.ChatType, im.ChatTypeGroup)+ }+}++func TestConvertEventIgnoresGroupMessageThatMentionsDifferentBot(t *testing.T) {+ event := &larkim.P2MessageReceiveV1{+ Event: &larkim.P2MessageReceiveV1Data{+ Message: &larkim.EventMessage{+ MessageType: stringPtr("text"),+ ChatType: stringPtr("group"),+ ChatId: stringPtr("oc_group"),+ MessageId: stringPtr("om_message"),+ Content: stringPtr(`{"text":"@_user_1 hello"}`),+ Mentions: []*larkim.MentionEvent{{+ Key: stringPtr("@_user_1"),+ MentionedType: stringPtr("bot"),+ Name: stringPtr("OtherBot"),+ Id: &larkim.UserId{OpenId: stringPtr("ou_other_bot")},+ }},+ },+ Sender: &larkim.EventSender{+ SenderId: &larkim.UserId{OpenId: stringPtr("ou_sender")},+ },+ },+ }++ if got := convertEvent(RegionFeishu, "ou_bot", event); got != nil {+ t.Fatalf("convertEvent() = %+v, want nil for group message mentioning a different bot", got)+ }+}+func TestConvertPostEventPreservesEmbeddedImage(t *testing.T) {content := `{"title":"","content":[[{"tag":"at","user_id":"ou_bot"},{"tag":"text","text":"请描述这张图"},{"tag":"img","image_key":"img_v3_abc"}]]}`msg := &larkim.EventMessage{Content: &content}