Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 72 additions & 5 deletions internal/botinteraction/channel_feishu.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,14 +51,48 @@ func newFeishuChannel() *feishuChannel {

func (f *feishuChannel) Kind() string { return ChannelFeishu }

func (f *feishuChannel) client(bot domain.NotificationBot, cred Credential) *lark.Client {
return lark.NewClient(bot.BotID, cred.Secret,
func (f *feishuChannel) client(bot domain.NotificationBot, cred Credential, extra ...lark.ClientOptionFunc) *lark.Client {
return lark.NewClient(bot.BotID, cred.Secret, append([]lark.ClientOptionFunc{
lark.WithOpenBaseUrl(f.base),
lark.WithHttpClient(f.http),
lark.WithReqTimeout(sendTimeout),
lark.WithEnableTokenCache(true),
lark.WithLogLevel(larkcore.LogLevelError),
)
}, extra...)...)
}

// feishuTokenCache is a client-scoped token cache. The SDK's default cache is
// process-global, so rebuilding a client alone would keep reusing a stale
// token; giving the new client its own cache makes the rebuild effective.
type feishuTokenCache struct {
mu sync.Mutex
tokens map[string]feishuTokenValue
}

type feishuTokenValue struct {
value string
expires time.Time
}

func newFeishuTokenCache() *feishuTokenCache {
return &feishuTokenCache{tokens: make(map[string]feishuTokenValue)}
}

func (c *feishuTokenCache) Get(_ context.Context, key string) (string, error) {
c.mu.Lock()
defer c.mu.Unlock()
value, ok := c.tokens[key]
if !ok || !value.expires.After(time.Now()) {
return "", nil
}
return value.value, nil
}

func (c *feishuTokenCache) Set(_ context.Context, key, token string, ttl time.Duration) error {
c.mu.Lock()
defer c.mu.Unlock()
c.tokens[key] = feishuTokenValue{value: token, expires: time.Now().Add(ttl)}
return nil
}

// Verify obtains a tenant access token, which proves the App ID and Secret.
Expand Down Expand Up @@ -90,7 +124,8 @@ func (f *feishuChannel) Verify(ctx context.Context, bot domain.NotificationBot,
// ready. The SDK's own reconnect loop is disabled: the service reconnects
// with backoff and re-reads the credential each time.
func (f *feishuChannel) Connect(ctx context.Context, bot domain.NotificationBot, cred Credential, sink InboundSink) (Conn, error) {
conn := &feishuConn{channel: f, bot: bot, api: f.client(bot, cred), done: make(chan struct{})}
conn := &feishuConn{channel: f, bot: bot, cred: cred, done: make(chan struct{})}
conn.api = conn.freshAPI()
handler := dispatcher.NewEventDispatcher("", "").OnP2MessageReceiveV1(func(evCtx context.Context, ev *larkim.P2MessageReceiveV1) error {
inbound, ok := feishuEvent(ev)
if !ok {
Expand Down Expand Up @@ -330,6 +365,8 @@ func deref(s *string) string {
type feishuConn struct {
channel *feishuChannel
bot domain.NotificationBot
cred Credential
mu sync.Mutex // guards api
api *lark.Client
ws *larkws.Client
cancel context.CancelFunc
Expand All @@ -338,6 +375,24 @@ type feishuConn struct {
closeOnce sync.Once
}

// freshAPI builds a client with an empty token cache, forcing the next
// request to obtain a new tenant access token.
func (c *feishuConn) freshAPI() *lark.Client {
return c.channel.client(c.bot, c.cred, lark.WithTokenCache(newFeishuTokenCache()))
}

func (c *feishuConn) apiClient() *lark.Client {
c.mu.Lock()
defer c.mu.Unlock()
return c.api
}

func (c *feishuConn) resetAPI() {
c.mu.Lock()
defer c.mu.Unlock()
c.api = c.freshAPI()
}

func (c *feishuConn) Done() <-chan struct{} { return c.done }

// Close stops the client and waits for its workers to finish.
Expand Down Expand Up @@ -368,11 +423,14 @@ func (c *feishuConn) Reply(ctx context.Context, msg OutboundMessage) SendResult
body = body.Uuid(msg.SendKey)
}
req := larkim.NewReplyMessageReqBuilder().MessageId(msg.Route.MessageID).Body(body.Build()).Build()
resp, err := c.api.Im.V1.Message.Reply(ctx, req)
resp, err := c.apiClient().Im.V1.Message.Reply(ctx, req)
if err != nil {
return classifyFeishuTransport(err)
}
if !resp.Success() {
if feishuTokenInvalid[resp.Code] {
c.resetAPI()
}
return classifyFeishuCode(resp.Code)
}
out := SendResult{Outcome: Delivered}
Expand Down Expand Up @@ -404,6 +462,15 @@ var feishuRetryable = map[int]bool{
99991668: true, // invalid user access token
}

// feishuTokenInvalid codes mean the cached token is stale. Rate limiting
// (99991400) is deliberately excluded: there is nothing to refresh there.
var feishuTokenInvalid = map[int]bool{
99991661: true,
99991663: true,
99991664: true,
99991668: true,
}

func classifyFeishuCode(code int) SendResult {
detail := "飞书拒绝了这次回复(错误码 " + strconv.Itoa(code) + ")"
if feishuRetryable[code] {
Expand Down
2 changes: 1 addition & 1 deletion internal/botinteraction/channel_feishu_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ func TestFeishuVerifyAndReplyClassification(t *testing.T) {
}
api.tokenCode = 0

conn := &feishuConn{channel: ch, bot: bot, api: ch.client(bot, Credential{Secret: "s"})}
conn := &feishuConn{channel: ch, bot: bot, cred: Credential{Secret: "s"}, api: ch.client(bot, Credential{Secret: "s"})}
msg := OutboundMessage{InteractionID: "i", Text: "答复", SendKey: "send-key-for-test", Route: ReplyRoute{MessageID: "om_1"}}
if got := conn.Reply(context.Background(), msg); got.Outcome != Delivered || got.PlatformMessageID != "om_reply" {
t.Fatalf("reply = %+v", got)
Expand Down
124 changes: 124 additions & 0 deletions internal/botinteraction/channel_feishu_token_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
package botinteraction

import (
"agentflow/internal/domain"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
)

// TestFeishuReplyRebuildsClientAfterInvalidTenantToken covers issue #1485.
// The SDK caches the tenant token per client. A long-lived feishuConn must
// drop that client when Feishu reports the cached token invalid, otherwise
// every retry reuses the stale token forever.
func TestFeishuReplyRebuildsClientAfterInvalidTenantToken(t *testing.T) {
var mu sync.Mutex
tokenCalls, replyCalls := 0, 0
mux := http.NewServeMux()
mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, _ *http.Request) {
mu.Lock()
n := tokenCalls
tokenCalls++
mu.Unlock()
token := "t-token"
if n > 0 {
token = "t-token-2" // a fresh token is issued after the old one is invalidated
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"code": 0, "tenant_access_token": token, "expire": 7200,
})
})
mux.HandleFunc("/open-apis/im/v1/messages/", func(w http.ResponseWriter, r *http.Request) {
if !strings.HasSuffix(r.URL.Path, "/reply") {
t.Errorf("unexpected reply path %s", r.URL.Path)
}
mu.Lock()
replyCalls++
mu.Unlock()
w.Header().Set("Content-Type", "application/json")
switch r.Header.Get("Authorization") {
case "Bearer t-token":
_ = json.NewEncoder(w).Encode(map[string]any{"code": 99991663, "msg": "invalid tenant token"})
case "Bearer t-token-2":
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "data": map[string]any{"message_id": "om_reply"}})
default:
t.Errorf("unexpected authorization %q", r.Header.Get("Authorization"))
_ = json.NewEncoder(w).Encode(map[string]any{"code": 230001, "msg": "bad auth"})
}
})
srv := httptest.NewServer(mux)
defer srv.Close()

ch := newFeishuChannel()
ch.base = srv.URL
bot := domain.NotificationBot{ID: "cfg", Channel: domain.BotChannelFeishu, BotID: "cli_app"}
cred := Credential{Secret: "s"}
conn := &feishuConn{channel: ch, bot: bot, cred: cred}
conn.api = conn.freshAPI()
msg := OutboundMessage{Text: "答复", SendKey: "token-retry-key", Route: ReplyRoute{MessageID: "om_1"}}

first := conn.Reply(context.Background(), msg)
if first.Code != "99991663" || !first.Retryable {
t.Fatalf("first reply = %+v, want retryable 99991663", first)
}
second := conn.Reply(context.Background(), msg)
if second.Outcome != Delivered || second.PlatformMessageID != "om_reply" {
t.Fatalf("second reply = %+v, want delivered with the fresh token", second)
}
mu.Lock()
tokens, replies := tokenCalls, replyCalls
mu.Unlock()
if tokens < 2 {
t.Fatalf("token endpoint called %d time(s), want >= 2 after rebuilding the client", tokens)
}
if replies < 2 {
t.Fatalf("reply endpoint called %d time(s), want >= 2", replies)
}
}

// Rate limits and ordinary failures must not discard the client: rebuilding
// only clears the token cache and would not help either case.
func TestFeishuReplyKeepsClientOnRateLimitAndServerError(t *testing.T) {
var mu sync.Mutex
tokenCalls := 0
mux := http.NewServeMux()
mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, _ *http.Request) {
mu.Lock()
tokenCalls++
mu.Unlock()
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "tenant_access_token": "t-token", "expire": 7200})
})
mux.HandleFunc("/open-apis/im/v1/messages/", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{"code": 99991400, "msg": "rate limited"})
})
srv := httptest.NewServer(mux)
defer srv.Close()

ch := newFeishuChannel()
ch.base = srv.URL
bot := domain.NotificationBot{ID: "cfg", Channel: domain.BotChannelFeishu, BotID: "cli_app"}
cred := Credential{Secret: "s"}
conn := &feishuConn{channel: ch, bot: bot, cred: cred}
conn.api = conn.freshAPI()
msg := OutboundMessage{Text: "答复", Route: ReplyRoute{MessageID: "om_1"}}

for i := 0; i < 2; i++ {
got := conn.Reply(context.Background(), msg)
if got.Code != "99991400" || !got.Retryable {
t.Fatalf("reply %d = %+v, want retryable 99991400", i, got)
}
}
mu.Lock()
tokens := tokenCalls
mu.Unlock()
if tokens != 1 {
t.Fatalf("token endpoint called %d time(s), want 1 (client must be kept)", tokens)
}
}