Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6735 fix(lark): recover from a rejected tenant_access_token instead of replaying it (#7618)
Bohan Jiangc0f5650e094d
diff --git a/server/internal/integrations/lark/client.go b/server/internal/integrations/lark/client.goindex 44419f5300..8d53f984df 100644--- a/server/internal/integrations/lark/client.go+++ b/server/internal/integrations/lark/client.go@@ -131,6 +131,20 @@ type APIClient interface {DeleteMessageReaction(ctx context.Context, p DeleteReactionParams) error}+// TokenCacheInvalidator is implemented by an APIClient that caches+// tenant_access_token in-process, so credential rotation can tell it to+// forget what it holds. Rotation is invisible otherwise: re-registering+// a Bot issues a new app_secret under the SAME app_id, Lark revokes+// every token minted from the old one, and the cache key does not+// change.+//+// It is deliberately separate from APIClient rather than a method on it:+// only the real HTTP client holds a cache, and the stub / fakes have+// nothing to forget. Callers type-assert and skip when it is absent.+type TokenCacheInvalidator interface {+ InvalidateTokenCache(appID string)+}+// ListMessagesParams selects a bounded, recent window of messages in a// single Lark chat for the group-context prefetch. Only the fields the// enricher needs today are exposed (ChatID, ThreadID, PageSize, EndTime);diff --git a/server/internal/integrations/lark/http_client.go b/server/internal/integrations/lark/http_client.goindex f9d369eebd..80a1e6246f 100644--- a/server/internal/integrations/lark/http_client.go+++ b/server/internal/integrations/lark/http_client.go@@ -71,13 +71,24 @@ const (// transfers off the connector ACK path.maxMessageResourceBytes = 100 << 20- // Lark's "invalid tenant_access_token" / "tenant_access_token- // expired" error codes. When we see either, drop the cached token- // so the next call refreshes from /tenant_access_token/internal.- // 99991663 = expired, 99991664 = invalid. Documented at:- // open.feishu.cn/document/server-docs/api-call-guide/server-error-codes.- codeTokenExpired = 99991663- codeTokenInvalid = 99991664+ // Access-credential rejections. Seeing one means the token we+ // presented is not usable, so drop the cached entry and re-mint from+ // /tenant_access_token/internal. Both are from Lark's generic+ // error-code table:+ // open.feishu.cn/document/server-docs/api-call-guide/generic-error-code.+ //+ // 99991663 covers BOTH halves for the only credential this client+ // mints — "tenant_access_token 已过期" and "凭证无效" share the one+ // code — and is the code the wedged-cache bug reported in #7611 hit.+ //+ // 99991664 is app_access_token, which this client never mints. It+ // stays in the class deliberately: it is unambiguously "the+ // credential you presented was rejected", and if Lark ever answers it+ // for a call we authenticated with a tenant token, re-minting is the+ // only recovery. Being wrong costs one bounded refresh and one+ // replay, while leaving it out would cost another wedged cache.+ codeTenantTokenInvalid = 99991663+ codeAppTokenInvalid = 99991664)// HTTPClientConfig configures the production Lark HTTP APIClient.@@ -261,6 +272,48 @@ func (c *httpAPIClient) invalidateToken(appID string) {c.mu.Unlock()}+// InvalidateTokenCache drops the cached tenant_access_token for an+// app_id from outside the client. It exists for credential rotation:+// re-registering a Bot issues a new app_secret, which makes Lark revoke+// every token minted from the previous one, and the cache — keyed by+// app_id, which does NOT change — would otherwise keep replaying a+// token Lark now rejects.+func (c *httpAPIClient) InvalidateTokenCache(appID string) {+ c.invalidateToken(appID)+}++// doAuthedJSON performs one tenant_access_token-authenticated call. When+// Lark rejects the token itself, it drops the cached entry, mints a+// fresh token and replays the request exactly once.+//+// Replaying is safe for every caller here: Lark rejects a bad token+// during authentication, before the request is processed, so nothing was+// delivered and the retry cannot duplicate a message. Without it the+// refresh would only help the NEXT call and the reply that triggered it+// would still be lost.+//+// Only token errors are retried. Business codes, 5xx and network+// failures are returned untouched — those are either definitive or+// ambiguous about delivery, and neither is fixed by a new token.+func (c *httpAPIClient) doAuthedJSON(ctx context.Context, creds InstallationCredentials, method, path string, body, out any) error {+ token, err := c.tenantAccessToken(ctx, creds)+ if err != nil {+ return err+ }+ err = c.doJSON(ctx, c.resolveBaseURL(creds), method, path, token, body, out)+ if !isTokenError(larkErrorCode(err)) {+ return err+ }+ c.cfg.Logger.Warn("lark http client: tenant_access_token rejected; refreshing and retrying once",+ "app_id", creds.AppID, "path", path, "err", err)+ c.invalidateToken(creds.AppID)+ fresh, refreshErr := c.tenantAccessToken(ctx, creds)+ if refreshErr != nil {+ return fmt.Errorf("%w (token refresh failed: %v)", err, refreshErr)+ }+ return c.doJSON(ctx, c.resolveBaseURL(creds), method, path, fresh, body, out)+}+// outboundMessageRequest builds the (path, body) the three send methods// share. When target.IsSet() the message is routed through Lark's reply// endpoint (POST /im/v1/messages/{message_id}/reply) so it threads back@@ -297,10 +350,6 @@ func (c *httpAPIClient) SendInteractiveCard(ctx context.Context, p SendCardParamif p.CardJSON == "" {return "", errors.New("lark http client: missing card json")}- token, err := c.tenantAccessToken(ctx, p.InstallationID)- if err != nil {- return "", err- }path, body := outboundMessageRequest(p.ChatID, "interactive", p.CardJSON, p.ReplyTarget)var resp struct {Code int `json:"code"`@@ -309,7 +358,7 @@ func (c *httpAPIClient) SendInteractiveCard(ctx context.Context, p SendCardParamMessageID string `json:"message_id"`} `json:"data"`}- if err := c.doJSON(ctx, c.resolveBaseURL(p.InstallationID), http.MethodPost, path, token, body, &resp); err != nil {+ if err := c.doAuthedJSON(ctx, p.InstallationID, http.MethodPost, path, body, &resp); err != nil {return "", fmt.Errorf("lark http client: send interactive card: %w", err)}if resp.Code != 0 || resp.Data.MessageID == "" {@@ -334,10 +383,6 @@ func (c *httpAPIClient) SendTextMessage(ctx context.Context, p SendTextParams) (if p.Text == "" {return "", errors.New("lark http client: missing text")}- token, err := c.tenantAccessToken(ctx, p.InstallationID)- if err != nil {- return "", err- }// Lark's `text` msg_type expects content = JSON-encoded {"text": "..."}.// json.Marshal handles the escape of newlines / quotes / unicode so// the agent's reply round-trips intact.@@ -353,7 +398,7 @@ func (c *httpAPIClient) SendTextMessage(ctx context.Context, p SendTextParams) (MessageID string `json:"message_id"`} `json:"data"`}- if err := c.doJSON(ctx, c.resolveBaseURL(p.InstallationID), http.MethodPost, path, token, body, &resp); err != nil {+ if err := c.doAuthedJSON(ctx, p.InstallationID, http.MethodPost, path, body, &resp); err != nil {return "", fmt.Errorf("lark http client: send text message: %w", err)}if resp.Code != 0 || resp.Data.MessageID == "" {@@ -387,10 +432,6 @@ func (c *httpAPIClient) SendMarkdownCard(ctx context.Context, p SendMarkdownCardif p.Markdown == "" {return "", errors.New("lark http client: missing markdown body")}- token, err := c.tenantAccessToken(ctx, p.InstallationID)- if err != nil {- return "", err- }card := map[string]any{"schema": "2.0","body": map[string]any{@@ -416,7 +457,7 @@ func (c *httpAPIClient) SendMarkdownCard(ctx context.Context, p SendMarkdownCardMessageID string `json:"message_id"`} `json:"data"`}- if err := c.doJSON(ctx, c.resolveBaseURL(p.InstallationID), http.MethodPost, path, token, body, &resp); err != nil {+ if err := c.doAuthedJSON(ctx, p.InstallationID, http.MethodPost, path, body, &resp); err != nil {return "", fmt.Errorf("lark http client: send markdown card: %w", err)}if resp.Code != 0 || resp.Data.MessageID == "" {@@ -438,17 +479,13 @@ func (c *httpAPIClient) PatchInteractiveCard(ctx context.Context, p PatchCardParif p.CardJSON == "" {return errors.New("lark http client: missing card json")}- token, err := c.tenantAccessToken(ctx, p.InstallationID)- if err != nil {- return err- }body := map[string]string{"content": p.CardJSON}var resp struct {Code int `json:"code"`Msg string `json:"msg"`}path := "/open-apis/im/v1/messages/" + url.PathEscape(p.LarkCardMessageID)- if err := c.doJSON(ctx, c.resolveBaseURL(p.InstallationID), http.MethodPatch, path, token, body, &resp); err != nil {+ if err := c.doAuthedJSON(ctx, p.InstallationID, http.MethodPatch, path, body, &resp); err != nil {return fmt.Errorf("lark http client: patch interactive card: %w", err)}if resp.Code != 0 {@@ -475,10 +512,6 @@ func (c *httpAPIClient) SendBindingPromptCard(ctx context.Context, p BindingPromif err != nil {return fmt.Errorf("lark http client: render binding prompt: %w", err)}- token, err := c.tenantAccessToken(ctx, p.InstallationID)- if err != nil {- return err- }q := url.Values{}q.Set("receive_id_type", "open_id")body := map[string]string{@@ -491,7 +524,7 @@ func (c *httpAPIClient) SendBindingPromptCard(ctx context.Context, p BindingPromMsg string `json:"msg"`}path := "/open-apis/im/v1/messages?" + q.Encode()- if err := c.doJSON(ctx, c.resolveBaseURL(p.InstallationID), http.MethodPost, path, token, body, &resp); err != nil {+ if err := c.doAuthedJSON(ctx, p.InstallationID, http.MethodPost, path, body, &resp); err != nil {return fmt.Errorf("lark http client: send binding prompt: %w", err)}if resp.Code != 0 {@@ -536,10 +569,6 @@ func (c *httpAPIClient) GetBotInfo(ctx context.Context, creds InstallationCredenif creds.AppID == "" || creds.AppSecret == "" {return BotInfo{}, errors.New("lark http client: missing app credentials for GetBotInfo")}- token, err := c.tenantAccessToken(ctx, creds)- if err != nil {- return BotInfo{}, err- }var botResp struct {Code int `json:"code"`Msg string `json:"msg"`@@ -547,7 +576,7 @@ func (c *httpAPIClient) GetBotInfo(ctx context.Context, creds InstallationCredenOpenID string `json:"open_id"`} `json:"bot"`}- if err := c.doJSON(ctx, c.resolveBaseURL(creds), http.MethodGet, "/open-apis/bot/v3/info", token, nil, &botResp); err != nil {+ if err := c.doAuthedJSON(ctx, creds, http.MethodGet, "/open-apis/bot/v3/info", nil, &botResp); err != nil {return BotInfo{}, fmt.Errorf("lark http client: bot info: %w", err)}if botResp.Code != 0 {@@ -564,7 +593,7 @@ func (c *httpAPIClient) GetBotInfo(ctx context.Context, creds InstallationCreden// return the BotInfo with empty UnionID. Callers (Registration-// Service.finishSuccess) accept the gap and persist what they// have.- unionID, lookupErr := c.fetchBotUnionID(ctx, c.resolveBaseURL(creds), creds.AppID, token, botResp.Bot.OpenID)+ unionID, lookupErr := c.fetchBotUnionID(ctx, creds, botResp.Bot.OpenID)if lookupErr != nil {c.cfg.Logger.Warn("lark http client: bot union_id lookup failed; continuing without it","app_id", creds.AppID,@@ -592,10 +621,6 @@ func (c *httpAPIClient) GetMessage(ctx context.Context, creds InstallationCredenif messageID == "" {return nil, errors.New("lark http client: missing message_id")}- token, err := c.tenantAccessToken(ctx, creds)- if err != nil {- return nil, err- }q := url.Values{}q.Set("user_id_type", "open_id")path := "/open-apis/im/v1/messages/" + url.PathEscape(messageID) + "?" + q.Encode()@@ -607,7 +632,7 @@ func (c *httpAPIClient) GetMessage(ctx context.Context, creds InstallationCredenItems []larkRESTMessageItem `json:"items"`} `json:"data"`}- if err := c.doJSON(ctx, c.resolveBaseURL(creds), http.MethodGet, path, token, nil, &resp); err != nil {+ if err := c.doAuthedJSON(ctx, creds, http.MethodGet, path, nil, &resp); err != nil {return nil, fmt.Errorf("lark http client: get message: %w", err)}if resp.Code != 0 {@@ -651,10 +676,6 @@ func (c *httpAPIClient) ListChatMessages(ctx context.Context, creds Installation} else if size > larkListMessagesMaxPageSize {size = larkListMessagesMaxPageSize}- token, err := c.tenantAccessToken(ctx, creds)- if err != nil {- return nil, err- }q := url.Values{}if p.ThreadID != "" {// Topic-scoped window: only this 话题's messages, so a @-mention@@ -683,7 +704,7 @@ func (c *httpAPIClient) ListChatMessages(ctx context.Context, creds InstallationItems []larkRESTMessageItem `json:"items"`} `json:"data"`}- if err := c.doJSON(ctx, c.resolveBaseURL(creds), http.MethodGet, path, token, nil, &resp); err != nil {+ if err := c.doAuthedJSON(ctx, creds, http.MethodGet, path, nil, &resp); err != nil {return nil, fmt.Errorf("lark http client: list chat messages: %w", err)}if resp.Code != 0 {@@ -733,10 +754,6 @@ func (c *httpAPIClient) DownloadMessageResourceStream(ctx context.Context, credsif p.FileKey == "" {return DownloadedResourceStream{}, errors.New("lark http client: missing file_key")}- token, err := c.tenantAccessToken(ctx, creds)- if err != nil {- return DownloadedResourceStream{}, err- }q := url.Values{}if p.Type != "" {q.Set("type", p.Type)@@ -746,6 +763,28 @@ func (c *httpAPIClient) DownloadMessageResourceStream(ctx context.Context, credspath += "?" + encoded}+ // Same refresh-and-retry contract as doAuthedJSON: Lark rejects a bad+ // token before it serves any bytes, so replaying the GET once cannot+ // produce a half-downloaded resource.+ for attempt := 0; ; attempt++ {+ token, err := c.tenantAccessToken(ctx, creds)+ if err != nil {+ return DownloadedResourceStream{}, err+ }+ stream, err := c.downloadMessageResourceStreamOnce(ctx, creds, path, token)+ if err == nil {+ return stream, nil+ }+ if attempt > 0 || !isTokenError(larkErrorCode(err)) {+ return DownloadedResourceStream{}, err+ }+ c.cfg.Logger.Warn("lark http client: tenant_access_token rejected on resource download; refreshing and retrying once",+ "app_id", creds.AppID, "err", err)+ c.invalidateToken(creds.AppID)+ }+}++func (c *httpAPIClient) downloadMessageResourceStreamOnce(ctx context.Context, creds InstallationCredentials, path, token string) (DownloadedResourceStream, error) {downloadCtx := ctxvar cancel context.CancelFuncif c.cfg.ResourceDownloadTimeout > 0 {@@ -782,7 +821,13 @@ func (c *httpAPIClient) DownloadMessageResourceStream(ctx context.Context, credsif readErr != nil {return DownloadedResourceStream{}, readErr}- return DownloadedResourceStream{}, fmt.Errorf("lark http client: download resource: http %d: %s", resp.StatusCode, truncate(string(rawBody), 512))+ code, msg := parseLarkErrorBody(rawBody)+ return DownloadedResourceStream{}, fmt.Errorf("lark http client: download resource: %w", &larkAPIStatusError{+ StatusCode: resp.StatusCode,+ Code: code,+ Msg: msg,+ Raw: truncate(string(rawBody), 512),+ })}contentType := resp.Header.Get("Content-Type")if strings.Contains(strings.ToLower(contentType), "json") {@@ -796,9 +841,8 @@ func (c *httpAPIClient) DownloadMessageResourceStream(ctx context.Context, credsMsg string `json:"msg"`}if err := json.Unmarshal(rawBody, &apiResp); err == nil && apiResp.Code != 0 {- if isTokenError(apiResp.Code) {- c.invalidateToken(creds.AppID)- }+ // Token invalidation is the retry loop's job in the caller —+ // it owns both this shape and the non-2xx one.return DownloadedResourceStream{}, &APIError{Op: "download resource", Code: apiResp.Code, Msg: apiResp.Msg}}return DownloadedResourceStream{@@ -904,10 +948,6 @@ func (c *httpAPIClient) AddMessageReaction(ctx context.Context, p AddReactionParif p.EmojiType == "" {return "", errors.New("lark http client: missing emoji_type")}- token, err := c.tenantAccessToken(ctx, p.InstallationID)- if err != nil {- return "", err- }body := map[string]any{"reaction_type": map[string]string{"emoji_type": p.EmojiType},}@@ -919,7 +959,7 @@ func (c *httpAPIClient) AddMessageReaction(ctx context.Context, p AddReactionParReactionID string `json:"reaction_id"`} `json:"data"`}- if err := c.doJSON(ctx, c.resolveBaseURL(p.InstallationID), http.MethodPost, path, token, body, &resp); err != nil {+ if err := c.doAuthedJSON(ctx, p.InstallationID, http.MethodPost, path, body, &resp); err != nil {return "", fmt.Errorf("lark http client: add message reaction: %w", err)}if resp.Code != 0 || resp.Data.ReactionID == "" {@@ -940,16 +980,12 @@ func (c *httpAPIClient) DeleteMessageReaction(ctx context.Context, p DeleteReactif p.ReactionID == "" {return errors.New("lark http client: missing reaction_id")}- token, err := c.tenantAccessToken(ctx, p.InstallationID)- if err != nil {- return err- }path := "/open-apis/im/v1/messages/" + url.PathEscape(p.MessageID) + "/reactions/" + url.PathEscape(p.ReactionID)var resp struct {Code int `json:"code"`Msg string `json:"msg"`}- if err := c.doJSON(ctx, c.resolveBaseURL(p.InstallationID), http.MethodDelete, path, token, nil, &resp); err != nil {+ if err := c.doAuthedJSON(ctx, p.InstallationID, http.MethodDelete, path, nil, &resp); err != nil {return fmt.Errorf("lark http client: delete message reaction: %w", err)}if resp.Code != 0 {@@ -975,10 +1011,6 @@ func (c *httpAPIClient) BatchGetUsers(ctx context.Context, creds InstallationCreif len(openIDs) > larkBatchGetUsersMaxIDs {openIDs = openIDs[:larkBatchGetUsersMaxIDs]}- token, err := c.tenantAccessToken(ctx, creds)- if err != nil {- return nil, err- }q := url.Values{}q.Set("user_id_type", "open_id")for _, id := range openIDs {@@ -998,7 +1030,7 @@ func (c *httpAPIClient) BatchGetUsers(ctx context.Context, creds InstallationCre} `json:"items"`} `json:"data"`}- if err := c.doJSON(ctx, c.resolveBaseURL(creds), http.MethodGet, path, token, nil, &resp); err != nil {+ if err := c.doAuthedJSON(ctx, creds, http.MethodGet, path, nil, &resp); err != nil {return nil, fmt.Errorf("lark http client: batch get users: %w", err)}if resp.Code != 0 {@@ -1075,7 +1107,7 @@ func (it larkRESTMessageItem) normalize() LarkMessage {// scope is restricted. Caller logs and continues; the decoder still// works in single-bot deployments where open_id-based matching is// unambiguous.-func (c *httpAPIClient) fetchBotUnionID(ctx context.Context, baseURL, appID, token, openID string) (string, error) {+func (c *httpAPIClient) fetchBotUnionID(ctx context.Context, creds InstallationCredentials, openID string) (string, error) {if openID == "" {return "", errors.New("empty open_id")}@@ -1091,7 +1123,7 @@ func (c *httpAPIClient) fetchBotUnionID(ctx context.Context, baseURL, appID, tok} `json:"user"`} `json:"data"`}- if err := c.doJSON(ctx, baseURL, http.MethodGet, path, token, nil, &resp); err != nil {+ if err := c.doAuthedJSON(ctx, creds, http.MethodGet, path, nil, &resp); err != nil {return "", fmt.Errorf("contact users: %w", err)}if resp.Code != 0 {@@ -1100,7 +1132,7 @@ func (c *httpAPIClient) fetchBotUnionID(ctx context.Context, baseURL, appID, tok// the bearer would do nothing and a stale token would keep// being reused on every retry until natural TTL expiry.if isTokenError(resp.Code) {- c.invalidateToken(appID)+ c.invalidateToken(creds.AppID)}return "", fmt.Errorf("contact users: code=%d msg=%q", resp.Code, resp.Msg)}@@ -1142,7 +1174,17 @@ func (c *httpAPIClient) doJSON(ctx context.Context, baseURL, method, path, tokenreturn fmt.Errorf("read body: %w", err)}if resp.StatusCode < 200 || resp.StatusCode >= 300 {- return fmt.Errorf("http %d: %s", resp.StatusCode, truncate(string(rawBody), 512))+ // Lark still reports its business code in the body of a non-2xx+ // reply, so parse it instead of collapsing the response into an+ // opaque transport error. Everything that classifies by code —+ // token invalidation above all — is unreachable otherwise.+ code, msg := parseLarkErrorBody(rawBody)+ return &larkAPIStatusError{+ StatusCode: resp.StatusCode,+ Code: code,+ Msg: msg,+ Raw: truncate(string(rawBody), 512),+ }}if out != nil && len(rawBody) > 0 {if err := json.Unmarshal(rawBody, out); err != nil {@@ -1152,8 +1194,70 @@ func (c *httpAPIClient) doJSON(ctx context.Context, baseURL, method, path, tokenreturn nil}+// parseLarkErrorBody best-effort extracts Lark's {code, msg} envelope+// from an error body. A body that is not JSON at all (a proxy's HTML+// error page, an empty 502) yields 0 / "" — no code, nothing to+// classify — which keeps such failures on the plain-transport path.+func parseLarkErrorBody(raw []byte) (int, string) {+ var env struct {+ Code int `json:"code"`+ Msg string `json:"msg"`+ }+ if err := json.Unmarshal(raw, &env); err != nil {+ return 0, ""+ }+ return env.Code, env.Msg+}+func isTokenError(code int) bool {- return code == codeTokenExpired || code == codeTokenInvalid+ return code == codeTenantTokenInvalid || code == codeAppTokenInvalid+}++// larkAPIStatusError is a Lark reply that failed with a NON-2xx HTTP+// status. It carries the business code Lark put in the body, because+// Lark reports authentication failures that way: an invalid or expired+// tenant_access_token comes back as HTTP 400 with {"code":99991663},+// not as a 2xx envelope (#7611). A client that only reads the body of+// 2xx replies can therefore never notice its cached token died, and+// replays the dead token until the process restarts.+//+// Code is 0 when the body carried no parsable Lark envelope.+type larkAPIStatusError struct {+ StatusCode int+ Code int+ Msg string+ Raw string+}++func (e *larkAPIStatusError) Error() string {+ // Preserve the historical wording — operators grep their logs for it.+ return fmt.Sprintf("http %d: %s", e.StatusCode, e.Raw)+}++// larkErrorCode digs the Lark business code out of err, from either+// shape that carries one: a non-2xx reply (larkAPIStatusError) or a 2xx+// envelope a call site rejected (APIError). Returns 0 for anything else,+// including network failures and timeouts, so a code-keyed lookup on the+// result never matches an ambiguous transport error.+func larkErrorCode(err error) int {+ code, _, _ := larkErrorCodeMsg(err)+ return code+}++// larkErrorCodeMsg is larkErrorCode plus Lark's `msg` and whether err+// carried a code at all. Classifiers that fall back to matching error+// TEXT need the third result: "no code" and "code 0" must not both look+// like a Lark verdict, or a gateway's HTML 502 would classify as one.+func larkErrorCodeMsg(err error) (int, string, bool) {+ var statusErr *larkAPIStatusError+ if errors.As(err, &statusErr) {+ return statusErr.Code, statusErr.Msg, statusErr.Code != 0+ }+ var apiErr *APIError+ if errors.As(err, &apiErr) {+ return apiErr.Code, apiErr.Msg, apiErr.Code != 0+ }+ return 0, "", false}// APIError is a structured Lark business error: the request reached@@ -1194,17 +1298,20 @@ var threadReplyUnsupportedCodes = map[int]struct{}{230111: {}, // cannot reply to a self-destructing message}-// isThreadReplyUnsupported reports whether err is a Lark APIError whose-// code means the threaded reply cannot land on this target. Only such-// errors are safe to retry at the chat level. Transport errors and-// other business codes return false.+// isThreadReplyUnsupported reports whether err carries a Lark business+// code meaning the threaded reply cannot land on this target. Only such+// errors are safe to retry at the chat level. Transport errors and other+// business codes return false.+//+// The code is read through larkErrorCode, so it is found whether Lark+// answered with a 2xx envelope or a non-2xx status — a definitive+// "nothing was sent" verdict is equally definitive either way, and only+// codes on the list get here. Errors with no Lark code (network failure,+// timeout, a proxy's HTML 502) yield code 0, which is not on the list, so+// ambiguous delivery still never triggers the fallback.func isThreadReplyUnsupported(err error) bool {- var apiErr *APIError- if errors.As(err, &apiErr) {- _, ok := threadReplyUnsupportedCodes[apiErr.Code]- return ok- }- return false+ _, ok := threadReplyUnsupportedCodes[larkErrorCode(err)]+ return ok}func truncate(s string, n int) string {diff --git a/server/internal/integrations/lark/http_client_test.go b/server/internal/integrations/lark/http_client_test.goindex 109d9838d3..796b9b807d 100644--- a/server/internal/integrations/lark/http_client_test.go+++ b/server/internal/integrations/lark/http_client_test.go@@ -999,7 +999,7 @@ func TestHTTPClient_SendInteractiveCard_TokenExpired_InvalidatesCache(t *testingfake.sendN.Add(1)n := sendCalls.Add(1)if n == 1 {- writeJSON(w, map[string]any{"code": codeTokenExpired, "msg": "expired"})+ writeJSON(w, map[string]any{"code": codeTenantTokenInvalid, "msg": "expired"})return}writeJSON(w, map[string]any{"code": 0, "data": map[string]string{"message_id": "om_ok"}})diff --git a/server/internal/integrations/lark/http_client_tokenrefresh_test.go b/server/internal/integrations/lark/http_client_tokenrefresh_test.gonew file mode 100644index 0000000000..6a83095808--- /dev/null+++ b/server/internal/integrations/lark/http_client_tokenrefresh_test.go@@ -0,0 +1,302 @@+package lark++import (+ "context"+ "fmt"+ "net/http"+ "strings"+ "sync/atomic"+ "testing"+ "time"+)++// Lark reports an invalid / expired tenant_access_token as HTTP 400 with+// the code in the BODY, not as a 2xx envelope:+//+// http 400: {"code":99991663,"msg":"Invalid access token for authorization..."}+//+// Every test in this file drives that exact shape. It is the shape the+// client used to be blind to (#7611): the transport error short-circuited+// before the body was ever parsed, so the cached token was never dropped+// and every later outbound replayed it until the process restarted.++const invalidTokenMsg = "Invalid access token for authorization. Please make a request with token attached."++// writeLarkStatusError writes the non-2xx + business-code reply Lark+// actually sends.+func writeLarkStatusError(w http.ResponseWriter, status, code int, msg string) {+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(status)+ _, _ = fmt.Fprintf(w, `{"code":%d,"msg":%q}`, code, msg)+}++// stubRotatingToken hands out a different token per mint so a test can+// tell the replayed request apart from the original one. The last entry+// is repeated once the list runs out.+func stubRotatingToken(f *larkFakeServer, tokens ...string) {+ f.mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, r *http.Request) {+ n := int(f.tokenN.Add(1))+ tok := tokens[len(tokens)-1]+ if n <= len(tokens) {+ tok = tokens[n-1]+ }+ writeJSON(w, map[string]any{+ "code": 0,+ "msg": "ok",+ "tenant_access_token": tok,+ "expire": 7200,+ })+ })+}++func (c *httpAPIClient) cachedTokenValue(appID string) (string, bool) {+ c.mu.Lock()+ defer c.mu.Unlock()+ t, ok := c.tokens[appID]+ if !ok {+ return "", false+ }+ return t.value, true+}++// TestHTTPClient_SendCard_HTTP400TokenExpired_RefreshesAndRetries is the+// direct regression test for #7611: the send that hits the dead token+// must recover by itself, not merely unblock the NEXT send.+func TestHTTPClient_SendCard_HTTP400TokenExpired_RefreshesAndRetries(t *testing.T) {+ fake := newLarkFake(t)+ stubRotatingToken(fake, "tok_dead", "tok_fresh")++ var attempts atomic.Int32+ fake.mux.HandleFunc("/open-apis/im/v1/messages", func(w http.ResponseWriter, r *http.Request) {+ switch n := attempts.Add(1); n {+ case 1:+ if got := r.Header.Get("Authorization"); got != "Bearer tok_dead" {+ t.Errorf("first attempt auth = %q, want the cached token", got)+ }+ writeLarkStatusError(w, http.StatusBadRequest, codeTenantTokenInvalid, invalidTokenMsg)+ case 2:+ if got := r.Header.Get("Authorization"); got != "Bearer tok_fresh" {+ t.Errorf("retry auth = %q, want the refreshed token", got)+ }+ writeJSON(w, map[string]any{"code": 0, "data": map[string]string{"message_id": "om_ok"}})+ default:+ t.Errorf("send called %d times, want at most 2", n)+ }+ })++ c := newTestClient(fake, time.Now)+ msgID, err := c.SendInteractiveCard(context.Background(), SendCardParams{+ InstallationID: testCreds(),+ ChatID: ChatID("oc"),+ CardJSON: `{}`,+ })+ if err != nil {+ t.Fatalf("send must recover from a rejected token: %v", err)+ }+ if msgID != "om_ok" {+ t.Errorf("message id = %q, want om_ok", msgID)+ }+ if got := attempts.Load(); got != 2 {+ t.Errorf("send attempts = %d, want 2 (original + one replay)", got)+ }+ if got := fake.tokenN.Load(); got != 2 {+ t.Errorf("token mints = %d, want 2 (the dead one was dropped)", got)+ }+ if cached, ok := c.cachedTokenValue(testCreds().AppID); !ok || cached != "tok_fresh" {+ t.Errorf("cache holds %q (present=%v), want tok_fresh", cached, ok)+ }+}++// TestHTTPClient_SendMarkdownCard_HTTP400TokenExpired_StopsAfterOneRetry+// pins the other half of the contract: refreshing must not turn into a+// refresh storm when the fresh token is rejected too.+func TestHTTPClient_SendMarkdownCard_HTTP400TokenExpired_StopsAfterOneRetry(t *testing.T) {+ fake := newLarkFake(t)+ stubRotatingToken(fake, "tok_a", "tok_b", "tok_c")++ var attempts atomic.Int32+ fake.mux.HandleFunc("/open-apis/im/v1/messages", func(w http.ResponseWriter, r *http.Request) {+ attempts.Add(1)+ writeLarkStatusError(w, http.StatusBadRequest, codeTenantTokenInvalid, invalidTokenMsg)+ })++ c := newTestClient(fake, time.Now)+ _, err := c.SendMarkdownCard(context.Background(), SendMarkdownCardParams{+ InstallationID: testCreds(),+ ChatID: ChatID("oc"),+ Markdown: "**hi**",+ })+ if err == nil {+ t.Fatal("a permanently rejected token must surface as an error")+ }+ // The wording operators see in their logs (#7611).+ if !strings.Contains(err.Error(), "lark http client: send markdown card: http 400") {+ t.Errorf("error should keep the transport wording: %v", err)+ }+ if got := attempts.Load(); got != 2 {+ t.Errorf("send attempts = %d, want exactly 2", got)+ }+ if got := fake.tokenN.Load(); got != 2 {+ t.Errorf("token mints = %d, want exactly 2", got)+ }+}++// TestHTTPClient_AddMessageReaction_HTTP400TokenExpired_RefreshesAndRetries+// covers the typing-indicator path, which is where the reporter saw the+// failure first.+func TestHTTPClient_AddMessageReaction_HTTP400TokenExpired_RefreshesAndRetries(t *testing.T) {+ fake := newLarkFake(t)+ stubRotatingToken(fake, "tok_dead", "tok_fresh")++ var attempts atomic.Int32+ fake.mux.HandleFunc("/open-apis/im/v1/messages/om_1/reactions", func(w http.ResponseWriter, r *http.Request) {+ if n := attempts.Add(1); n == 1 {+ writeLarkStatusError(w, http.StatusBadRequest, codeTenantTokenInvalid, invalidTokenMsg)+ return+ }+ writeJSON(w, map[string]any{"code": 0, "data": map[string]string{"reaction_id": "re_1"}})+ })++ c := newTestClient(fake, time.Now)+ reactionID, err := c.AddMessageReaction(context.Background(), AddReactionParams{+ InstallationID: testCreds(),+ MessageID: "om_1",+ EmojiType: "Typing",+ })+ if err != nil {+ t.Fatalf("add reaction must recover from a rejected token: %v", err)+ }+ if reactionID != "re_1" {+ t.Errorf("reaction id = %q, want re_1", reactionID)+ }+ if got := fake.tokenN.Load(); got != 2 {+ t.Errorf("token mints = %d, want 2", got)+ }+}++// TestHTTPClient_HTTP400NonTokenError_KeepsCachedToken guards the other+// direction: a 400 that is NOT about the token must not drop a healthy+// cache entry or replay the request.+func TestHTTPClient_HTTP400NonTokenError_KeepsCachedToken(t *testing.T) {+ fake := newLarkFake(t)+ stubRotatingToken(fake, "tok_good")++ var attempts atomic.Int32+ fake.mux.HandleFunc("/open-apis/im/v1/messages", func(w http.ResponseWriter, r *http.Request) {+ attempts.Add(1)+ writeLarkStatusError(w, http.StatusBadRequest, 230001, "bot is not in the chat")+ })++ c := newTestClient(fake, time.Now)+ _, err := c.SendInteractiveCard(context.Background(), SendCardParams{+ InstallationID: testCreds(),+ ChatID: ChatID("oc"),+ CardJSON: `{}`,+ })+ if err == nil {+ t.Fatal("a non-token 400 must still be an error")+ }+ if got := attempts.Load(); got != 1 {+ t.Errorf("send attempts = %d, want 1 (no replay for a non-token failure)", got)+ }+ if got := fake.tokenN.Load(); got != 1 {+ t.Errorf("token mints = %d, want 1 (the cached token is still good)", got)+ }+ if cached, ok := c.cachedTokenValue(testCreds().AppID); !ok || cached != "tok_good" {+ t.Errorf("cache holds %q (present=%v), want the token to survive", cached, ok)+ }+}++// TestHTTPClient_DownloadResource_HTTP400TokenExpired_RefreshesAndRetries+// covers the resource path, which builds its request by hand instead of+// going through doJSON and so needs its own refresh-and-retry.+func TestHTTPClient_DownloadResource_HTTP400TokenExpired_RefreshesAndRetries(t *testing.T) {+ fake := newLarkFake(t)+ stubRotatingToken(fake, "tok_dead", "tok_fresh")++ var attempts atomic.Int32+ fake.mux.HandleFunc("/open-apis/im/v1/messages/om_1/resources/img_1", func(w http.ResponseWriter, r *http.Request) {+ if n := attempts.Add(1); n == 1 {+ writeLarkStatusError(w, http.StatusBadRequest, codeTenantTokenInvalid, invalidTokenMsg)+ return+ }+ if got := r.Header.Get("Authorization"); got != "Bearer tok_fresh" {+ t.Errorf("retry auth = %q, want the refreshed token", got)+ }+ w.Header().Set("Content-Type", "image/png")+ _, _ = w.Write([]byte{7, 8, 9})+ })++ c := newTestClient(fake, time.Now)+ got, err := c.DownloadMessageResource(context.Background(), testCreds(), DownloadResourceParams{+ MessageID: "om_1",+ FileKey: "img_1",+ Type: "image",+ })+ if err != nil {+ t.Fatalf("download must recover from a rejected token: %v", err)+ }+ if string(got.Data) != string([]byte{7, 8, 9}) {+ t.Errorf("downloaded bytes = %v", got.Data)+ }+ if n := attempts.Load(); n != 2 {+ t.Errorf("download attempts = %d, want 2", n)+ }+}++// TestHTTPClient_InvalidateTokenCache_ForcesRemint covers credential+// rotation: re-registering a Bot issues a new app_secret under the same+// app_id, Lark revokes the old token, and nothing about the cache key+// changes — so the holder has to be told.+func TestHTTPClient_InvalidateTokenCache_ForcesRemint(t *testing.T) {+ fake := newLarkFake(t)+ stubRotatingToken(fake, "tok_first", "tok_second")+ fake.stubSend(map[string]any{"code": 0, "data": map[string]string{"message_id": "om_ok"}}, nil)++ c := newTestClient(fake, time.Now)+ send := func() {+ t.Helper()+ if _, err := c.SendInteractiveCard(context.Background(), SendCardParams{+ InstallationID: testCreds(),+ ChatID: ChatID("oc"),+ CardJSON: `{}`,+ }); err != nil {+ t.Fatalf("send: %v", err)+ }+ }++ send()+ send()+ if got := fake.tokenN.Load(); got != 1 {+ t.Fatalf("token mints = %d, want 1 while the cached token is alive", got)+ }++ var invalidator TokenCacheInvalidator = c+ invalidator.InvalidateTokenCache(testCreds().AppID)++ send()+ if got := fake.tokenN.Load(); got != 2 {+ t.Errorf("token mints = %d, want 2 after the cache was invalidated", got)+ }+ if got := fake.lastAuth(); got != "Bearer tok_second" {+ t.Errorf("auth after rotation = %q, want the re-minted token", got)+ }+}++// TestIsThreadReplyUnsupported_ReadsNon2xxBodyCode pins the second place+// the non-2xx short-circuit went unnoticed: the thread -> chat fallback+// classifies by business code too, and a code Lark delivered with a 400+// is exactly as definitive as one it delivered with a 200.+func TestIsThreadReplyUnsupported_ReadsNon2xxBodyCode(t *testing.T) {+ if !isThreadReplyUnsupported(&larkAPIStatusError{StatusCode: 400, Code: 230071, Msg: "no reply in thread"}) {+ t.Error("230071 delivered as HTTP 400 should classify as thread-reply-unsupported")+ }+ if isThreadReplyUnsupported(&larkAPIStatusError{StatusCode: 400, Code: codeTenantTokenInvalid, Msg: invalidTokenMsg}) {+ t.Error("a token failure must never trigger the chat-level fallback")+ }+ // A gateway error carries no Lark code: delivery is ambiguous and the+ // fallback could duplicate the reply.+ if isThreadReplyUnsupported(&larkAPIStatusError{StatusCode: 502, Raw: "<html>bad gateway</html>"}) {+ t.Error("a body with no Lark code must not classify")+ }+}diff --git a/server/internal/integrations/lark/inbound_enricher.go b/server/internal/integrations/lark/inbound_enricher.goindex e3b5a3b36f..94258ef882 100644--- a/server/internal/integrations/lark/inbound_enricher.go+++ b/server/internal/integrations/lark/inbound_enricher.go@@ -470,9 +470,17 @@ func classifyRecentContextFetchError(err error) recentContextFetchClassificationif errors.Is(err, errRecentContextChannelUnbound) {return recentContextFetchClassification{category: recentContextFailureChannelUnbound}}- var apiErr *APIError- if errors.As(err, &apiErr) {- return classifyRecentContextAPIError(apiErr.Code, apiErr.Msg)+ // A Lark business code names the failure exactly, so prefer it over+ // the text heuristics below — read through larkErrorCodeMsg it is+ // found in either shape that carries one: the 2xx envelope a call+ // site rejected (*APIError) and the non-2xx reply the HTTP client+ // returns. Only a code that resolves to a real category short-+ // circuits; anything else falls through, so a status-only signal+ // like "http 403" still classifies on the error text.+ if code, msg, ok := larkErrorCodeMsg(err); ok {+ if cls := classifyRecentContextAPIError(code, msg); cls.category != recentContextFailureUnknown {+ return cls+ }}var netErr net.Errorif errors.Is(err, context.DeadlineExceeded) ||diff --git a/server/internal/integrations/lark/inbound_enricher_recent_test.go b/server/internal/integrations/lark/inbound_enricher_recent_test.goindex 7366ebb17c..68b3649120 100644--- a/server/internal/integrations/lark/inbound_enricher_recent_test.go+++ b/server/internal/integrations/lark/inbound_enricher_recent_test.go@@ -3,6 +3,7 @@ package larkimport ("context""errors"+ "fmt""strings""testing")@@ -675,12 +676,13 @@ func TestEnrichRecentContextRateLimitedDoesNotRetry(t *testing.T) {}// TestEnrichRecentContextProductionErrorShapes covers the classifier on-// the real error shape ListChatMessages returns: a plain wrapped error-// string ("...: code=%d msg=%q"), NOT an *APIError. The typed-APIError-// tests above exercise classifyRecentContextAPIError, but production-// traffic only ever reaches the string path, so pin that too — including-// that token errors DO retry (client refreshes the token) while permission-// and deleted errors do not.+// the error shapes ListChatMessages returns in production: a wrapped+// "...: code=%d msg=%q" string for a 2xx envelope, and the typed non-2xx+// reply for everything Lark answers with a status code — including the+// HTTP 400 it uses for a rejected tenant_access_token. The typed-APIError+// tests above exercise classifyRecentContextAPIError directly; this pins+// what actually arrives, including that token errors DO retry (the client+// refreshes the token) while permission and deleted errors do not.func TestEnrichRecentContextProductionErrorShapes(t *testing.T) {t.Parallel()cases := []struct {@@ -707,6 +709,33 @@ func TestEnrichRecentContextProductionErrorShapes(t *testing.T) {wantLine: "[Recent Lark context temporarily unavailable; continuing with the latest message.]",wantCalls: 2,},+ {+ // The shape Lark actually sends for a rejected token: HTTP+ // 400 with the code in the body. Its text carries `"code":`+ // (JSON), not the `code=` the string heuristics look for, so+ // only reading the typed code classifies it.+ name: "token_expired_http_400_retries_then_degrades",+ err: fmt.Errorf("lark http client: list chat messages: %w", &larkAPIStatusError{+ StatusCode: 400,+ Code: codeTenantTokenInvalid,+ Msg: "Invalid access token for authorization.",+ Raw: `{"code":99991663,"msg":"Invalid access token for authorization."}`,+ }),+ wantLine: "[Recent Lark context temporarily unavailable; continuing with the latest message.]",+ wantCalls: 2,+ },+ {+ // A code the classifier does not know must fall through to+ // the text heuristics rather than swallow the status signal.+ name: "unknown_code_falls_through_to_http_status",+ err: fmt.Errorf("lark http client: list chat messages: %w", &larkAPIStatusError{+ StatusCode: 403,+ Code: 99991672,+ Raw: `{"code":99991672,"msg":""}`,+ }),+ wantLine: "[Recent Lark context unavailable: the bot cannot read this chat history. Continuing with the latest message.]",+ wantCalls: 1,+ },}for _, tc := range cases {tc := tcdiff --git a/server/internal/integrations/lark/registration_service.go b/server/internal/integrations/lark/registration_service.goindex 2dd640869d..6f67963e46 100644--- a/server/internal/integrations/lark/registration_service.go+++ b/server/internal/integrations/lark/registration_service.go@@ -542,6 +542,16 @@ func (s *RegistrationService) finishSuccess(ctx context.Context, sess *registrat// call below hits the right open-platform host: a Lark-international// install must reach open.larksuite.com, not the Feishu default.creds := InstallationCredentials{AppID: res.ClientID, AppSecret: res.ClientSecret, Region: region}+ // Re-registering an existing Bot issues a fresh client_secret under+ // the SAME client_id, and Lark revokes every tenant_access_token+ // minted from the previous one. The API client caches tokens by+ // app_id — which did not change — so tell it to drop the entry+ // before we mint with the new credentials; otherwise the first call+ // below, and every outbound after it, replays a token Lark now+ // rejects (#7611).+ if invalidator, ok := s.api.(TokenCacheInvalidator); ok {+ invalidator.InvalidateTokenCache(res.ClientID)+ }info, err := s.api.GetBotInfo(ctx, creds)if err != nil {s.cfg.Logger.Warn("lark registration: bot info failed",diff --git a/server/internal/integrations/lark/registration_service_test.go b/server/internal/integrations/lark/registration_service_test.goindex 40f24cd2e2..658334ddbf 100644--- a/server/internal/integrations/lark/registration_service_test.go+++ b/server/internal/integrations/lark/registration_service_test.go@@ -336,3 +336,62 @@ func (c *fakeClockSvc) Now() time.Time {defer c.mu.Unlock()return c.now}++// rotatingCredsAPIClient records the order of the two calls+// finishSuccess makes before it touches the database, so the test can+// assert the cache is dropped BEFORE a token is minted with the new+// credentials.+type rotatingCredsAPIClient struct {+ APIClient // unused methods; the test only drives the two below++ mu sync.Mutex+ calls []string+ creds InstallationCredentials+}++func (c *rotatingCredsAPIClient) InvalidateTokenCache(appID string) {+ c.mu.Lock()+ defer c.mu.Unlock()+ c.calls = append(c.calls, "invalidate:"+appID)+}++func (c *rotatingCredsAPIClient) GetBotInfo(_ context.Context, creds InstallationCredentials) (BotInfo, error) {+ c.mu.Lock()+ defer c.mu.Unlock()+ c.calls = append(c.calls, "botinfo:"+creds.AppID)+ c.creds = creds+ // Fail so finishSuccess returns before the database work; the+ // ordering assertion below is what this test is about.+ return BotInfo{}, errors.New("bot info unavailable")+}++// TestFinishSuccess_DropsCachedTokenBeforeMintingWithRotatedCreds covers+// credential rotation (#7611): a re-registration issues a new+// client_secret under the SAME client_id, so Lark revokes every token+// minted from the old one while the in-process cache — keyed by app_id —+// keeps looking valid. Nothing recovers on its own if the stale entry+// survives into the first call made with the new credentials.+func TestFinishSuccess_DropsCachedTokenBeforeMintingWithRotatedCreds(t *testing.T) {+ api := &rotatingCredsAPIClient{}+ svc := &RegistrationService{+ cfg: RegistrationServiceConfig{}.withDefaults(),+ api: api,+ sessions: make(map[string]*registrationSession),+ }+ sess := ®istrationSession{id: "sess-rotate", status: RegistrationStatusPending}++ svc.finishSuccess(context.Background(), sess, &PollResult{+ ClientID: "cli_rotated",+ ClientSecret: "secret_new",+ }, RegionFeishu)++ api.mu.Lock()+ defer api.mu.Unlock()+ want := []string{"invalidate:cli_rotated", "botinfo:cli_rotated"}+ if len(api.calls) != len(want) || api.calls[0] != want[0] || api.calls[1] != want[1] {+ t.Fatalf("call order = %v, want %v", api.calls, want)+ }+ if api.creds.AppSecret != "secret_new" {+ t.Errorf("bot info credentials carried app_secret %q, want the rotated one", api.creds.AppSecret)+ }+}