Files
Enterprise-Knowledge-Base/internal/im/feishu/send_e2e_test.go
T
qilifan 9afb8b7b68 feat(im,datasource): support Lark, Feishu's international edition
Lark and Feishu are the same product deployed on two isolated clouds
(open.larksuite.com and open.feishu.cn). WeKnora touches both from two
places — the IM bot and the Wiki data-source connector — and this brings
Lark to parity across both. Neither API surface differs, so rather than
duplicate either implementation, each is parametrized by a Region and
registered twice.

IM (internal/im/feishu):
  Every API call routes through a.api(), which prefixes the region's
  host, and the WebSocket client passes larkws.WithDomain — the SDK
  defaults to open.feishu.cn, so Lark long connections would otherwise
  fail to authenticate.

Data source (internal/datasource/connector/feishu):
  Lark was half-supported: the client honoured a base_url override and a
  LarkBaseURL constant existed, but the connector registered only as
  "feishu" and the UI never exposed base_url, so Lark wikis could not be
  configured at all. Lark is now its own connector type. base_url is kept
  as an explicit override so data sources that pointed a "feishu"
  connector at open.larksuite.com keep working.

Bugs found and fixed along the way:

- Wiki resource links were hardcoded to https://feishu.cn/wiki/{token} in
  four places, so a Lark wiki linked into the wrong cloud entirely.
- Bot identity is now platform-prefixed (feishu:cli_x vs lark:cli_x).
  BotIdentity carries a unique index, so without this a Lark channel
  would be rejected as a duplicate of an unrelated Feishu bot sharing an
  app_id.
- The card image cache is now keyed by app_id. image_keys are issued per
  app on one cloud; a Feishu key handed to a Lark app fails the card
  update with code=200570.
- The datasource doc claimed Lark "adapts automatically" — it could not,
  since the UI had no way to reach base_url.

Permissions are where the clouds genuinely diverge. Identical APIs do not
mean identical permission catalogues: aily:file:read, aily:file:write and
corehr:file:download exist on Feishu but not on Lark, so pasting Feishu's
scope JSON into Lark fails to import. That JSON is also over-broad (it
covers products WeKnora never calls) and simultaneously incomplete (it
omits the drive:*/docx:* scopes the connector needs). Lark therefore gets
its own list, derived from the 17 endpoints the code actually calls and
checked identifier-by-identifier against Lark's own API reference, plus a
full Feishu→Lark mapping table marking each scope verified, unverified,
or absent. Both features use tenant_access_token only — no user_access_
token exists anywhere in the repo — so the user dimension stays empty.

Known limitation: Region.ThinkingText makes Lark's initial card
placeholder English, but once streaming starts the think-block headers
come from the shared MarkdownThinkStyle and are Chinese on every platform
(Lark, Slack, Telegram, Mattermost alike). Fixing that means threading a
locale through FormatIMDisplayContent, which has no platform context — a
cross-platform change, not a Lark one. Documented as such.

The channel-creation 400 message is now derived from validIMPlatforms so
the list cannot drift as platforms are added.

Tests: region invariants and per-region URL construction on both sides,
the Feishu/Lark bot-identity split, platform-to-channel mapping, base_url
override precedence, an end-to-end SendReply against a fake Open Platform
(token fetch, reply, thread-unsupported fallback, hard-error surfacing),
and a ListResources drive asserting wiki links never leak the other
cloud's host.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-17 11:05:54 +08:00

185 lines
5.7 KiB
Go

package feishu
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/Tencent/WeKnora/internal/im"
)
// testRegion returns a Lark-shaped region pointed at a fake Open Platform, so
// the whole send path can be driven without touching the real cloud. Region
// carries the host as a field precisely so this is possible.
func testRegion(baseURL string) Region {
r := RegionLark
r.OpenBaseURL = baseURL
return r
}
// fakeOpenPlatform records what the adapter asked for, and answers as the real
// Open Platform would.
type fakeOpenPlatform struct {
mu sync.Mutex
// paths records every request path in order.
paths []string
// replyAuth is the Authorization header seen on the reply call.
replyAuth string
// replyBody is the decoded JSON body of the reply call.
replyBody map[string]any
// sendBody is the decoded JSON body of the fallback send call.
sendBody map[string]any
// sendQuery is the raw query string of the fallback send call.
sendQuery string
// replyCode is returned from the reply endpoint (0 = success).
replyCode int
}
func (f *fakeOpenPlatform) handler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
f.paths = append(f.paths, r.URL.Path)
f.mu.Unlock()
switch {
case r.URL.Path == "/open-apis/auth/v3/tenant_access_token/internal":
_ = json.NewEncoder(w).Encode(map[string]any{
"code": 0, "tenant_access_token": "t-lark-xyz", "expire": 7200,
})
case strings.HasSuffix(r.URL.Path, "/reply"):
f.mu.Lock()
f.replyAuth = r.Header.Get("Authorization")
_ = json.NewDecoder(r.Body).Decode(&f.replyBody)
code := f.replyCode
f.mu.Unlock()
_ = json.NewEncoder(w).Encode(map[string]any{"code": code, "msg": "mock"})
case r.URL.Path == "/open-apis/im/v1/messages":
f.mu.Lock()
f.sendQuery = r.URL.RawQuery
_ = json.NewDecoder(r.Body).Decode(&f.sendBody)
f.mu.Unlock()
_ = json.NewEncoder(w).Encode(map[string]any{"code": 0, "msg": "ok"})
default:
http.NotFound(w, r)
}
})
}
func (f *fakeOpenPlatform) sawPath(want string) bool {
f.mu.Lock()
defer f.mu.Unlock()
for _, p := range f.paths {
if p == want {
return true
}
}
return false
}
// SendReply must fetch a token from the region's cloud and reply under the
// original message, carrying that token as a bearer credential.
func TestSendReply_EndToEnd_UsesRegionCloud(t *testing.T) {
fake := &fakeOpenPlatform{}
srv := httptest.NewServer(fake.handler())
defer srv.Close()
a := NewAdapter(testRegion(srv.URL), "cli_app", "secret", "", "")
incoming := &im.IncomingMessage{
Platform: im.PlatformLark,
UserID: "ou_user1",
ChatType: im.ChatTypeDirect,
MessageID: "om_msg1",
}
if err := a.SendReply(context.Background(), incoming, &im.ReplyMessage{Content: "hello lark"}); err != nil {
t.Fatalf("SendReply: %v", err)
}
if !fake.sawPath("/open-apis/auth/v3/tenant_access_token/internal") {
t.Errorf("no token fetch; paths = %v", fake.paths)
}
if !fake.sawPath("/open-apis/im/v1/messages/om_msg1/reply") {
t.Errorf("reply did not target the message; paths = %v", fake.paths)
}
if fake.replyAuth != "Bearer t-lark-xyz" {
t.Errorf("reply Authorization = %q, want %q", fake.replyAuth, "Bearer t-lark-xyz")
}
if got := fake.replyBody["msg_type"]; got != "text" {
t.Errorf("msg_type = %v, want text", got)
}
// content is a JSON-encoded string, per the Open Platform contract.
var content struct {
Text string `json:"text"`
}
raw, _ := fake.replyBody["content"].(string)
if err := json.Unmarshal([]byte(raw), &content); err != nil {
t.Fatalf("content is not a JSON string: %q", raw)
}
if content.Text != "hello lark" {
t.Errorf("text = %q, want %q", content.Text, "hello lark")
}
}
// A group that rejects reply-in-thread (230071) must still receive the answer
// via the plain send-message API, addressed to the chat.
func TestSendReply_EndToEnd_FallsBackToSendAPI(t *testing.T) {
fake := &fakeOpenPlatform{replyCode: 230071}
srv := httptest.NewServer(fake.handler())
defer srv.Close()
a := NewAdapter(testRegion(srv.URL), "cli_app", "secret", "", "")
incoming := &im.IncomingMessage{
Platform: im.PlatformLark,
UserID: "ou_user1",
ChatID: "oc_chat1",
ChatType: im.ChatTypeGroup,
MessageID: "om_msg1",
}
if err := a.SendReply(context.Background(), incoming, &im.ReplyMessage{Content: "grouped"}); err != nil {
t.Fatalf("SendReply: %v", err)
}
if !fake.sawPath("/open-apis/im/v1/messages") {
t.Fatalf("no fallback to send-message API; paths = %v", fake.paths)
}
if fake.sendQuery != "receive_id_type=chat_id" {
t.Errorf("send query = %q, want receive_id_type=chat_id", fake.sendQuery)
}
if got := fake.sendBody["receive_id"]; got != "oc_chat1" {
t.Errorf("receive_id = %v, want oc_chat1", got)
}
}
// A non-fallback-eligible error must surface, not be silently swallowed.
func TestSendReply_EndToEnd_HardErrorSurfaces(t *testing.T) {
fake := &fakeOpenPlatform{replyCode: 99991663} // app ticket invalid — not retryable
srv := httptest.NewServer(fake.handler())
defer srv.Close()
a := NewAdapter(testRegion(srv.URL), "cli_app", "secret", "", "")
incoming := &im.IncomingMessage{
Platform: im.PlatformLark, UserID: "ou_user1",
ChatType: im.ChatTypeDirect, MessageID: "om_msg1",
}
err := a.SendReply(context.Background(), incoming, &im.ReplyMessage{Content: "x"})
if err == nil {
t.Fatal("SendReply returned nil for a non-retryable API error")
}
if !strings.Contains(err.Error(), "99991663") {
t.Errorf("error %q does not mention the API code", err)
}
// The plain send API must not be tried for a hard error.
if fake.sawPath("/open-apis/im/v1/messages") {
t.Errorf("fell back to send-message API on a non-retryable error; paths = %v", fake.paths)
}
}