Files
Enterprise-Knowledge-Base/internal/im/feishu/adapter_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

105 lines
3.0 KiB
Go

package feishu
import (
"context"
"strings"
"testing"
)
func TestFeishuThreadID_ThreadedReply(t *testing.T) {
// Simulate: message is a reply in a thread (root_id is set)
msg := &feishuMessage{
MessageID: "msg-reply-1",
RootID: "msg-root-1",
ParentID: "msg-parent-1",
}
threadID := msg.RootID
if threadID == "" {
threadID = msg.MessageID
}
if threadID != "msg-root-1" {
t.Errorf("threadID = %q, want %q", threadID, "msg-root-1")
}
}
func TestFeishuThreadID_TopLevelMessage(t *testing.T) {
// Simulate: top-level message (root_id is empty)
msg := &feishuMessage{
MessageID: "msg-top-1",
RootID: "",
ParentID: "",
}
threadID := msg.RootID
if threadID == "" {
threadID = msg.MessageID
}
if threadID != "msg-top-1" {
t.Errorf("threadID = %q, want %q (should use MessageID as fallback)", threadID, "msg-top-1")
}
}
func TestFeishuMessageStruct_JSONFields(t *testing.T) {
// Verify the struct fields exist and have correct zero values
msg := feishuMessage{}
if msg.RootID != "" {
t.Errorf("RootID zero value = %q, want empty", msg.RootID)
}
if msg.ParentID != "" {
t.Errorf("ParentID zero value = %q, want empty", msg.ParentID)
}
if msg.MessageID != "" {
t.Errorf("MessageID zero value = %q, want empty", msg.MessageID)
}
}
func TestImageCacheKey_StripsQuery(t *testing.T) {
cases := map[string]string{
"https://host/a.png?sig=1&t=2": "https://host/a.png",
"https://host/a.png": "https://host/a.png",
}
for in, want := range cases {
if got := imageCacheKey(in); got != want {
t.Errorf("imageCacheKey(%q) = %q, want %q", in, got, want)
}
}
}
func TestResolveMarkdownImages_NoImageUnchanged(t *testing.T) {
a := &Adapter{region: RegionFeishu}
in := "hello **world** [link](https://example.com)"
if got := a.resolveMarkdownImages(context.Background(), "tok", in); got != in {
t.Errorf("content without image was modified: %q", got)
}
}
func TestResolveMarkdownImages_FallbackToLinkOnFailure(t *testing.T) {
a := &Adapter{region: RegionFeishu}
// A direct-IP loopback URL fails SSRF validation before any network call,
// so the image must degrade to a plain markdown link (never left as ![]()).
in := "see ![diagram](http://127.0.0.1/x.png) here"
got := a.resolveMarkdownImages(context.Background(), "tok", in)
if strings.Contains(got, "![") {
t.Errorf("failed image should not remain as image markdown: %q", got)
}
if !strings.Contains(got, "[diagram](http://127.0.0.1/x.png)") {
t.Errorf("expected link fallback with alt text, got: %q", got)
}
}
// An image with no alt text falls back to the region's own label, so Lark users
// do not get a Chinese link label.
func TestResolveMarkdownImages_FallbackLabelFollowsRegion(t *testing.T) {
for _, region := range []Region{RegionFeishu, RegionLark} {
a := &Adapter{region: region}
got := a.resolveMarkdownImages(context.Background(), "tok", "![](http://127.0.0.1/x.png)")
want := "[" + region.ImageFallbackLabel + "](http://127.0.0.1/x.png)"
if got != want {
t.Errorf("%s fallback = %q, want %q", region.Label, got, want)
}
}
}