Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(dingtalk): show linked identities to workspace admins (#7138)

YYClaw6377dc265644
diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.ts
index 876ccf3bdd..fbbf4d28ac 100644
--- a/packages/core/api/schema.test.ts
+++ b/packages/core/api/schema.test.ts
@@ -387,7 +387,11 @@ describe("ApiClient schema fallback", () => {
it("parses the new-server group-routing capability", async () => {
stubFetchJson({
- installations: [{ id: "dt-1", status: "active" }],
+ installations: [{
+ id: "dt-1",
+ status: "active",
+ bound_dingtalk_user_ids: ["staff-1001"],
+ }],
configured: true,
install_supported: true,
group_routing_supported: true,
@@ -395,6 +399,21 @@ describe("ApiClient schema fallback", () => {
const client = new ApiClient("https://api.example.test");
const res = await client.listDingTalkInstallations("ws-1");
expect(res.group_routing_supported).toBe(true);
+ expect(res.installations[0]?.bound_dingtalk_user_ids).toEqual(["staff-1001"]);
+ });
+
+ it("defaults missing or malformed linked-identity IDs to an empty list", async () => {
+ stubFetchJson({
+ installations: [
+ { id: "dt-old", status: "active" },
+ { id: "dt-broken", status: "active", bound_dingtalk_user_ids: "staff-1001" },
+ ],
+ configured: true,
+ });
+ const client = new ApiClient("https://api.example.test");
+ const res = await client.listDingTalkInstallations("ws-1");
+ expect(res.installations[0]?.bound_dingtalk_user_ids).toEqual([]);
+ expect(res.installations[1]?.bound_dingtalk_user_ids).toEqual([]);
});
});
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 4ecffe277f..888a124508 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -2468,6 +2468,7 @@ export const DingTalkInstallationSchema = z.object({
installed_at: z.string().default(""),
created_at: z.string().default(""),
updated_at: z.string().default(""),
+ bound_dingtalk_user_ids: z.array(z.string()).catch([]).default([]),
}).loose();
export const EMPTY_DINGTALK_INSTALLATION: DingTalkInstallation = {
@@ -2479,6 +2480,7 @@ export const EMPTY_DINGTALK_INSTALLATION: DingTalkInstallation = {
installed_at: "",
created_at: "",
updated_at: "",
+ bound_dingtalk_user_ids: [],
};
export const ListDingTalkInstallationsResponseSchema = z.object({
diff --git a/packages/core/types/dingtalk.ts b/packages/core/types/dingtalk.ts
index 3184798ff6..d247067ba6 100644
--- a/packages/core/types/dingtalk.ts
+++ b/packages/core/types/dingtalk.ts
@@ -14,6 +14,10 @@ export interface DingTalkInstallation {
installed_at: string;
created_at: string;
updated_at: string;
+ /** DingTalk staff ids linked by the currently authenticated Multica user for
+ * this bot. Member-scoped so the member-visible installation endpoint does
+ * not disclose other members' DingTalk identities. */
+ bound_dingtalk_user_ids?: string[];
}
export interface ListDingTalkInstallationsResponse {
diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.json
index 447cf79d8c..af625f530a 100644
--- a/packages/views/locales/en/settings.json
+++ b/packages/views/locales/en/settings.json
@@ -862,6 +862,7 @@
"empty_description_suffix": "to install a robot for it.",
"revoked_badge": "revoked",
"installed_at_label": "Installed {{when}}",
+ "identity_label": "Linked DingTalk identity: {{identity}}",
"disconnect": "Disconnect",
"disconnecting": "Disconnecting…",
"disconnect_confirm_title": "Disconnect this DingTalk bot?",
diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.json
index 7db046be6a..175b1d9d38 100644
--- a/packages/views/locales/ja/settings.json
+++ b/packages/views/locales/ja/settings.json
@@ -861,6 +861,7 @@
"empty_description_suffix": "をクリックしてロボットをインストールします。",
"revoked_badge": "取り消し済み",
"installed_at_label": "{{when}} にインストール",
+ "identity_label": "連携済みの DingTalk ID:{{identity}}",
"disconnect": "切断",
"disconnecting": "切断中…",
"disconnect_confirm_title": "この DingTalk ボットを切断しますか?",
diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.json
index 7fdaec28e7..2a5fa3b92b 100644
--- a/packages/views/locales/ko/settings.json
+++ b/packages/views/locales/ko/settings.json
@@ -986,6 +986,7 @@
"empty_description_suffix": "을(를) 클릭해 로봇을 설치하세요.",
"revoked_badge": "해제됨",
"installed_at_label": "{{when}}에 설치됨",
+ "identity_label": "연결된 DingTalk ID: {{identity}}",
"disconnect": "연결 해제",
"disconnecting": "연결 해제 중…",
"disconnect_confirm_title": "이 DingTalk 봇을 연결 해제할까요?",
diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.json
index c87623ece8..5c5768d17f 100644
--- a/packages/views/locales/zh-Hans/settings.json
+++ b/packages/views/locales/zh-Hans/settings.json
@@ -861,6 +861,7 @@
"empty_description_suffix": "为其安装机器人。",
"revoked_badge": "已撤销",
"installed_at_label": "安装于 {{when}}",
+ "identity_label": "钉钉绑定身份:{{identity}}",
"disconnect": "断开连接",
"disconnecting": "正在断开…",
"disconnect_confirm_title": "断开此钉钉机器人?",
diff --git a/packages/views/settings/components/dingtalk-tab.test.tsx b/packages/views/settings/components/dingtalk-tab.test.tsx
index 08883fa5a8..7889242b37 100644
--- a/packages/views/settings/components/dingtalk-tab.test.tsx
+++ b/packages/views/settings/components/dingtalk-tab.test.tsx
@@ -258,16 +258,54 @@ describe("DingTalkTab", () => {
it("lists a connected installation with its agent name and a disconnect control", () => {
installationsRef.current = {
- installations: [{ id: "i1", agent_id: "agent-7", status: "active" }],
+ installations: [{
+ id: "i1",
+ agent_id: "agent-7",
+ status: "active",
+ bound_dingtalk_user_ids: ["staff-1001", "staff-1002"],
+ }],
configured: true,
install_supported: true,
group_routing_supported: true,
};
renderUI(<DingTalkTab />);
expect(screen.getByText("Agent agent-7")).toBeTruthy();
+ expect(
+ screen.getByText(/Linked DingTalk identity: staff-1001, staff-1002 · Installed/),
+ ).toBeTruthy();
expect(screen.getByText(/Disconnect/i)).toBeTruthy();
});
+ it("does not render a linked identity when this member has no DingTalk binding", () => {
+ installationsRef.current = {
+ installations: [{ id: "i1", agent_id: "agent-7", status: "active" }],
+ configured: true,
+ install_supported: true,
+ group_routing_supported: true,
+ };
+ renderUI(<DingTalkTab />);
+ expect(screen.queryByText(/Linked DingTalk identity:/i)).toBeNull();
+ });
+
+ it("hides linked DingTalk identities from a regular workspace member", () => {
+ membersRef.current = [{ user_id: "user-1", role: "member" }];
+ installationsRef.current = {
+ installations: [{
+ id: "i1",
+ agent_id: "agent-7",
+ status: "active",
+ bound_dingtalk_user_ids: ["staff-must-stay-private"],
+ }],
+ configured: true,
+ install_supported: true,
+ group_routing_supported: true,
+ };
+ renderUI(<DingTalkTab />);
+ expect(screen.getByText("Agent agent-7")).toBeTruthy();
+ expect(screen.queryByText(/staff-must-stay-private/)).toBeNull();
+ expect(screen.queryByText(/Linked DingTalk identity:/i)).toBeNull();
+ });
+
it("shows a placeholder instead of 'Invalid Date' when installed_at is missing or malformed", () => {
installationsRef.current = {
installations: [
diff --git a/packages/views/settings/components/dingtalk-tab.tsx b/packages/views/settings/components/dingtalk-tab.tsx
index 06f0d97f13..92570b57aa 100644
--- a/packages/views/settings/components/dingtalk-tab.tsx
+++ b/packages/views/settings/components/dingtalk-tab.tsx
@@ -414,9 +414,12 @@ function InstallationRow({
const { getAgentName } = useActorName();
const isActive = installation.status === "active";
const agentName = getAgentName(installation.agent_id);
+ const linkedIdentityIDs = canManage
+ ? (installation.bound_dingtalk_user_ids ?? [])
+ : [];
return (
<div className="flex items-start justify-between gap-4 py-3 first:pt-0 last:pb-0">
- <div className="flex items-start gap-3">
+ <div className="flex min-w-0 items-start gap-3">
<ActorAvatar
actorType="agent"
actorId={installation.agent_id}
@@ -424,7 +427,7 @@ function InstallationRow({
enableHoverCard
profileLink
/>
- <div className="space-y-1">
+ <div className="min-w-0 space-y-1">
<p className="text-body font-medium">
{agentName}
{!isActive && (
@@ -433,7 +436,18 @@ function InstallationRow({
</span>
)}
</p>
- <p className="text-micro text-muted-foreground">
+ <p
+ className="max-w-full truncate text-micro text-muted-foreground"
+ title={linkedIdentityIDs.length > 0 ? linkedIdentityIDs.join(", ") : undefined}
+ >
+ {linkedIdentityIDs.length > 0 && (
+ <>
+ {t(($) => $.dingtalk.identity_label, {
+ identity: linkedIdentityIDs.join(", "),
+ })}
+ {" · "}
+ </>
+ )}
{t(($) => $.dingtalk.installed_at_label, {
when: formatInstalledAt(installation.installed_at),
})}
diff --git a/server/internal/handler/dingtalk.go b/server/internal/handler/dingtalk.go
index f732f96c34..2cab60a05c 100644
--- a/server/internal/handler/dingtalk.go
+++ b/server/internal/handler/dingtalk.go
@@ -9,8 +9,10 @@ import (
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/integrations/dingtalk"
+ "github.com/multica-ai/multica/server/internal/middleware"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/protocol"
)
@@ -20,14 +22,15 @@ import (
// server-internal (only the outbound sender decrypts it). WS lease columns are
// runtime state, not API surface, so they are omitted too.
type DingTalkInstallationResponse struct {
- ID string `json:"id"`
- WorkspaceID string `json:"workspace_id"`
- AgentID string `json:"agent_id"`
- InstallerUserID string `json:"installer_user_id"`
- Status string `json:"status"`
- InstalledAt string `json:"installed_at"`
- CreatedAt string `json:"created_at"`
- UpdatedAt string `json:"updated_at"`
+ ID string `json:"id"`
+ WorkspaceID string `json:"workspace_id"`
+ AgentID string `json:"agent_id"`
+ InstallerUserID string `json:"installer_user_id"`
+ Status string `json:"status"`
+ InstalledAt string `json:"installed_at"`
+ CreatedAt string `json:"created_at"`
+ UpdatedAt string `json:"updated_at"`
+ BoundDingTalkUserIDs []string `json:"bound_dingtalk_user_ids,omitempty"`
}
// DingTalkGroupRouteResponse is one group discovered from a Stream callback.
@@ -236,14 +239,43 @@ func (h *Handler) ListDingTalkInstallations(w http.ResponseWriter, r *http.Reque
if !ok {
return
}
+ userID, ok := requireUserID(w, r)
+ if !ok {
+ return
+ }
rows, err := h.DingTalkInstall.ListByWorkspace(r.Context(), wsUUID)
if err != nil {
writeError(w, http.StatusInternalServerError, "failed to list dingtalk installations")
return
}
+ bindingsByInstallation := map[pgtype.UUID][]string{}
+ member, hasMemberContext := middleware.MemberFromContext(r.Context())
+ canViewAccountBindings := hasMemberContext && (member.Role == "owner" || member.Role == "admin")
+ if canViewAccountBindings {
+ userUUID, ok := parseUUIDOrBadRequest(w, userID, "user id")
+ if !ok {
+ return
+ }
+ bindings, err := h.Queries.ListDingTalkUserBindingsForMember(r.Context(), db.ListDingTalkUserBindingsForMemberParams{
+ WorkspaceID: wsUUID,
+ MulticaUserID: userUUID,
+ })
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to list dingtalk user bindings")
+ return
+ }
+ for _, binding := range bindings {
+ bindingsByInstallation[binding.InstallationID] = append(
+ bindingsByInstallation[binding.InstallationID],
+ binding.ChannelUserID,
+ )
+ }
+ }
out := make([]DingTalkInstallationResponse, 0, len(rows))
for _, row := range rows {
- out = append(out, dingtalkInstallationToResponse(row))
+ response := dingtalkInstallationToResponse(row)
+ response.BoundDingTalkUserIDs = bindingsByInstallation[row.ID]
+ out = append(out, response)
}
writeJSON(w, http.StatusOK, map[string]any{
"installations": out,
@@ -449,6 +481,9 @@ func (h *Handler) RedeemDingTalkBindingToken(w http.ResponseWriter, r *http.Requ
}
return
}
+ h.publish(protocol.EventDingTalkAccountBindingUpdated, uuidToString(redeemed.WorkspaceID), "user", userID, map[string]any{
+ "id": uuidToString(redeemed.InstallationID),
+ })
writeJSON(w, http.StatusOK, RedeemDingTalkBindingTokenResponse{
WorkspaceID: uuidToString(redeemed.WorkspaceID),
InstallationID: uuidToString(redeemed.InstallationID),
diff --git a/server/internal/handler/dingtalk_group_routes_test.go b/server/internal/handler/dingtalk_group_routes_test.go
index 5dabbe56e4..a9fa2a87f2 100644
--- a/server/internal/handler/dingtalk_group_routes_test.go
+++ b/server/internal/handler/dingtalk_group_routes_test.go
@@ -60,6 +60,8 @@ func newDingTalkGroupRouteHandlerFixture(t *testing.T) dingtalkGroupRouteHandler
t.Cleanup(func() {
_, _ = testPool.Exec(context.Background(), `DELETE FROM channel_chat_session_binding WHERE installation_id = $1`, installationID)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM channel_user_binding WHERE installation_id = $1`, installationID)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM channel_binding_token WHERE installation_id = $1`, installationID)
_, _ = testPool.Exec(context.Background(), `DELETE FROM dingtalk_group_route WHERE installation_id = $1`, installationID)
_, _ = testPool.Exec(context.Background(), `DELETE FROM channel_installation WHERE id = $1`, installationID)
})
@@ -337,7 +339,7 @@ func TestListDingTalkInstallationsAdvertisesGroupRoutingCapability(t *testing.T)
})
t.Run("configured deployment", func(t *testing.T) {
- _ = newDingTalkGroupRouteHandlerFixture(t)
+ fx := newDingTalkGroupRouteHandlerFixture(t)
box, err := secretbox.New(make([]byte, secretbox.KeySize))
if err != nil {
t.Fatalf("create DingTalk test secret box: %v", err)
@@ -347,19 +349,69 @@ func TestListDingTalkInstallationsAdvertisesGroupRoutingCapability(t *testing.T)
t.Fatalf("create DingTalk install service: %v", err)
}
testHandler.DingTalkInstall = service
+ var regularMemberID string
+ if err := testPool.QueryRow(context.Background(), `
+ INSERT INTO "user" (name, email)
+ VALUES ('DingTalk installation list member', '[email protected]')
+ RETURNING id
+ `).Scan(&regularMemberID); err != nil {
+ t.Fatalf("create regular member for DingTalk installation listing: %v", err)
+ }
+ if _, err := testPool.Exec(context.Background(), `
+ INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'member')
+ `, testWorkspaceID, regularMemberID); err != nil {
+ t.Fatalf("add regular member for DingTalk installation listing: %v", err)
+ }
+ var adminMemberID string
+ if err := testPool.QueryRow(context.Background(), `
+ INSERT INTO "user" (name, email)
+ VALUES ('DingTalk installation list admin', '[email protected]')
+ RETURNING id
+ `).Scan(&adminMemberID); err != nil {
+ t.Fatalf("create admin for DingTalk installation listing: %v", err)
+ }
+ if _, err := testPool.Exec(context.Background(), `
+ INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'admin')
+ `, testWorkspaceID, adminMemberID); err != nil {
+ t.Fatalf("add admin for DingTalk installation listing: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM member WHERE workspace_id = $1 AND user_id IN ($2, $3)`, testWorkspaceID, regularMemberID, adminMemberID)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM "user" WHERE id IN ($1, $2)`, regularMemberID, adminMemberID)
+ })
+ if _, err := testPool.Exec(context.Background(), `
+ INSERT INTO channel_user_binding (
+ workspace_id, multica_user_id, installation_id,
+ channel_type, channel_user_id
+ ) VALUES
+ ($1, $2, $3, 'dingtalk', 'staff-current-member'),
+ ($1, $4, $3, 'dingtalk', 'staff-regular-member'),
+ ($1, $5, $3, 'dingtalk', 'staff-admin-member')
+ `, testWorkspaceID, testUserID, fx.installationID, regularMemberID, adminMemberID); err != nil {
+ t.Fatalf("seed member-scoped DingTalk bindings: %v", err)
+ }
req := requestWithRouteParams(
- httptest.NewRequest(http.MethodGet, "/api/workspaces/"+testWorkspaceID+"/dingtalk/installations", nil),
+ newRequest(http.MethodGet, "/api/workspaces/"+testWorkspaceID+"/dingtalk/installations", nil),
testWorkspaceID,
"",
)
+ ownerMember, err := testHandler.Queries.GetMemberByUserAndWorkspace(context.Background(), db.GetMemberByUserAndWorkspaceParams{
+ UserID: parseUUID(testUserID),
+ WorkspaceID: parseUUID(testWorkspaceID),
+ })
+ if err != nil {
+ t.Fatalf("load owner member context: %v", err)
+ }
+ req = req.WithContext(middleware.SetMemberContext(req.Context(), testWorkspaceID, ownerMember))
rec := httptest.NewRecorder()
testHandler.ListDingTalkInstallations(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("configured installations status = %d, want 200: %s", rec.Code, rec.Body.String())
}
var body struct {
- GroupRoutingSupported bool `json:"group_routing_supported"`
+ GroupRoutingSupported bool `json:"group_routing_supported"`
+ Installations []DingTalkInstallationResponse `json:"installations"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("decode configured installations response: %v", err)
@@ -367,6 +419,86 @@ func TestListDingTalkInstallationsAdvertisesGroupRoutingCapability(t *testing.T)
if !body.GroupRoutingSupported {
t.Fatal("configured deployment did not advertise group routing")
}
+ var found *DingTalkInstallationResponse
+ for i := range body.Installations {
+ if body.Installations[i].ID == fx.installationID {
+ found = &body.Installations[i]
+ break
+ }
+ }
+ if found == nil {
+ t.Fatalf("configured installations omitted fixture %s: %+v", fx.installationID, body.Installations)
+ }
+ if len(found.BoundDingTalkUserIDs) != 1 || found.BoundDingTalkUserIDs[0] != "staff-current-member" {
+ t.Fatalf("member-scoped DingTalk ids = %v, want [staff-current-member]", found.BoundDingTalkUserIDs)
+ }
+
+ lockTx, err := testPool.Begin(context.Background())
+ if err != nil {
+ t.Fatalf("begin controlled DingTalk binding-query failure: %v", err)
+ }
+ t.Cleanup(func() { _ = lockTx.Rollback(context.Background()) })
+ if _, err := lockTx.Exec(context.Background(), `LOCK TABLE channel_user_binding IN ACCESS EXCLUSIVE MODE`); err != nil {
+ _ = lockTx.Rollback(context.Background())
+ t.Fatalf("lock DingTalk bindings for controlled query failure: %v", err)
+ }
+ errorReq := requestWithRouteParams(
+ newRequest(http.MethodGet, "/api/workspaces/"+testWorkspaceID+"/dingtalk/installations", nil),
+ testWorkspaceID,
+ "",
+ )
+ errorReq = errorReq.WithContext(middleware.SetMemberContext(errorReq.Context(), testWorkspaceID, ownerMember))
+ errorCtx, cancelErrorRequest := context.WithTimeout(errorReq.Context(), 250*time.Millisecond)
+ errorReq = errorReq.WithContext(errorCtx)
+ errorRec := httptest.NewRecorder()
+ testHandler.ListDingTalkInstallations(errorRec, errorReq)
+ cancelErrorRequest()
+ if err := lockTx.Rollback(context.Background()); err != nil {
+ t.Fatalf("release controlled DingTalk binding lock: %v", err)
+ }
+ if errorRec.Code != http.StatusInternalServerError || !strings.Contains(errorRec.Body.String(), "failed to list dingtalk user bindings") {
+ t.Fatalf("binding query failure status = %d, want 500 without fallback: %s", errorRec.Code, errorRec.Body.String())
+ }
+
+ router := chi.NewRouter()
+ router.Route("/api/workspaces/{id}", func(r chi.Router) {
+ r.Use(middleware.RequireWorkspaceMemberFromURL(testHandler.Queries, "id"))
+ r.Get("/dingtalk/installations", testHandler.ListDingTalkInstallations)
+ })
+ memberReq := httptest.NewRequest(
+ http.MethodGet,
+ "/api/workspaces/"+testWorkspaceID+"/dingtalk/installations",
+ nil,
+ )
+ memberReq.Header.Set("X-User-ID", regularMemberID)
+ memberRec := httptest.NewRecorder()
+ router.ServeHTTP(memberRec, memberReq)
+ if memberRec.Code != http.StatusOK {
+ t.Fatalf("regular member installations status = %d: %s", memberRec.Code, memberRec.Body.String())
+ }
+ if !strings.Contains(memberRec.Body.String(), fx.installationID) {
+ t.Fatalf("regular member could not see connected bot: %s", memberRec.Body.String())
+ }
+ for _, forbidden := range []string{"bound_dingtalk_user_ids", "staff-regular-member"} {
+ if strings.Contains(memberRec.Body.String(), forbidden) {
+ t.Fatalf("regular member installation response leaked %q: %s", forbidden, memberRec.Body.String())
+ }
+ }
+
+ adminReq := httptest.NewRequest(
+ http.MethodGet,
+ "/api/workspaces/"+testWorkspaceID+"/dingtalk/installations",
+ nil,
+ )
+ adminReq.Header.Set("X-User-ID", adminMemberID)
+ adminRec := httptest.NewRecorder()
+ router.ServeHTTP(adminRec, adminReq)
+ if adminRec.Code != http.StatusOK {
+ t.Fatalf("admin installations status = %d: %s", adminRec.Code, adminRec.Body.String())
+ }
+ if !strings.Contains(adminRec.Body.String(), `"bound_dingtalk_user_ids":["staff-admin-member"]`) {
+ t.Fatalf("admin installation response omitted its DingTalk identity: %s", adminRec.Body.String())
+ }
})
}
diff --git a/server/internal/handler/dingtalk_test.go b/server/internal/handler/dingtalk_test.go
index df53209023..6293e5de65 100644
--- a/server/internal/handler/dingtalk_test.go
+++ b/server/internal/handler/dingtalk_test.go
@@ -1,9 +1,13 @@
package handler
import (
+ "context"
+ "net/http"
+ "net/http/httptest"
"testing"
"github.com/multica-ai/multica/server/internal/events"
+ dingtalkintegration "github.com/multica-ai/multica/server/internal/integrations/dingtalk"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/protocol"
)
@@ -40,3 +44,74 @@ func TestPublishDingTalkInstallationCreated(t *testing.T) {
t.Errorf("payload = %v, want installation id %s", got.Payload, instID)
}
}
+
+func TestRedeemDingTalkBindingTokenPublishesAccountBindingUpdateAfterCommit(t *testing.T) {
+ if testHandler == nil || testPool == nil {
+ t.Skip("database not available")
+ }
+
+ fx := newDingTalkGroupRouteHandlerFixture(t)
+ bindingService := dingtalkintegration.NewBindingTokenService(testHandler.Queries, testPool)
+ token, err := bindingService.Mint(
+ context.Background(),
+ parseUUID(testWorkspaceID),
+ parseUUID(fx.installationID),
+ "staff-binding-event",
+ )
+ if err != nil {
+ t.Fatalf("mint DingTalk binding token: %v", err)
+ }
+
+ bus := events.New()
+ h := &Handler{
+ Bus: bus,
+ DingTalkBindingTokens: bindingService,
+ }
+
+ var (
+ published events.Event
+ eventCount int
+ bindingAtEvent db.ChannelUserBinding
+ queryErr error
+ )
+ bus.Subscribe(protocol.EventDingTalkAccountBindingUpdated, func(event events.Event) {
+ eventCount++
+ published = event
+ // The synchronous subscriber reads through a separate pool connection,
+ // proving the binding transaction committed before the event fired.
+ bindingAtEvent, queryErr = testHandler.Queries.GetChannelUserBindingByUserID(
+ context.Background(),
+ db.GetChannelUserBindingByUserIDParams{
+ InstallationID: parseUUID(fx.installationID),
+ ChannelUserID: "staff-binding-event",
+ },
+ )
+ })
+
+ recorder := httptest.NewRecorder()
+ h.RedeemDingTalkBindingToken(recorder, newRequest(
+ http.MethodPost,
+ "/api/dingtalk/binding/redeem",
+ RedeemDingTalkBindingTokenRequest{Token: token.Raw},
+ ))
+
+ if recorder.Code != http.StatusOK {
+ t.Fatalf("redeem status = %d, body = %s", recorder.Code, recorder.Body.String())
+ }
+ if eventCount != 1 {
+ t.Fatalf("binding update event count = %d, want 1", eventCount)
+ }
+ if queryErr != nil {
+ t.Fatalf("binding was not visible when event fired: %v", queryErr)
+ }
+ if bindingAtEvent.MulticaUserID != parseUUID(testUserID) {
+ t.Errorf("binding user = %v, want %s", bindingAtEvent.MulticaUserID, testUserID)
+ }
+ if published.WorkspaceID != testWorkspaceID || published.ActorType != "user" || published.ActorID != testUserID {
+ t.Errorf("event envelope = %+v", published)
+ }
+ payload, ok := published.Payload.(map[string]any)
+ if !ok || payload["id"] != fx.installationID {
+ t.Errorf("payload = %v, want installation id %s", published.Payload, fx.installationID)
+ }
+}
diff --git a/server/pkg/db/generated/dingtalk.sql.go b/server/pkg/db/generated/dingtalk.sql.go
index d7f906ed9f..6066a177fb 100644
--- a/server/pkg/db/generated/dingtalk.sql.go
+++ b/server/pkg/db/generated/dingtalk.sql.go
@@ -351,6 +351,48 @@ func (q *Queries) ListDingTalkGroupRoutesByWorkspace(ctx context.Context, worksp
return items, nil
}
+const listDingTalkUserBindingsForMember = `-- name: ListDingTalkUserBindingsForMember :many
+SELECT installation_id, channel_user_id
+FROM channel_user_binding
+WHERE workspace_id = $1
+ AND multica_user_id = $2
+ AND channel_type = 'dingtalk'
+ORDER BY bound_at DESC, id ASC
+`
+
+type ListDingTalkUserBindingsForMemberParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ MulticaUserID pgtype.UUID `json:"multica_user_id"`
+}
+
+type ListDingTalkUserBindingsForMemberRow struct {
+ InstallationID pgtype.UUID `json:"installation_id"`
+ ChannelUserID string `json:"channel_user_id"`
+}
+
+// Returns only the requesting Multica member's DingTalk identities. The
+// installation list is member-visible, so returning every member's staff id
+// here would expose staff ID values more broadly than necessary.
+func (q *Queries) ListDingTalkUserBindingsForMember(ctx context.Context, arg ListDingTalkUserBindingsForMemberParams) ([]ListDingTalkUserBindingsForMemberRow, error) {
+ rows, err := q.db.Query(ctx, listDingTalkUserBindingsForMember, arg.WorkspaceID, arg.MulticaUserID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ListDingTalkUserBindingsForMemberRow{}
+ for rows.Next() {
+ var i ListDingTalkUserBindingsForMemberRow
+ if err := rows.Scan(&i.InstallationID, &i.ChannelUserID); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const lockDingTalkGroupRouteForAppend = `-- name: LockDingTalkGroupRouteForAppend :one
WITH target_agent AS MATERIALIZED (
SELECT a.id
diff --git a/server/pkg/db/queries/dingtalk.sql b/server/pkg/db/queries/dingtalk.sql
index 887ceace96..f95641e545 100644
--- a/server/pkg/db/queries/dingtalk.sql
+++ b/server/pkg/db/queries/dingtalk.sql
@@ -2,6 +2,17 @@
-- tables are shared, but these replacement semantics belong to DingTalk's BYO
-- AppKey model and deliberately stay out of the shared channel query surface.
+-- name: ListDingTalkUserBindingsForMember :many
+-- Returns only the requesting Multica member's DingTalk identities. The
+-- installation list is member-visible, so returning every member's staff id
+-- here would expose staff ID values more broadly than necessary.
+SELECT installation_id, channel_user_id
+FROM channel_user_binding
+WHERE workspace_id = sqlc.arg(workspace_id)
+ AND multica_user_id = sqlc.arg(multica_user_id)
+ AND channel_type = 'dingtalk'
+ORDER BY bound_at DESC, id ASC;
+
-- name: DiscoverDingTalkGroupRoute :one
-- Persist a group only after the shared inbound router has accepted the @bot
-- message and validated the sender's identity/workspace membership. The INSERT
diff --git a/server/pkg/protocol/events.go b/server/pkg/protocol/events.go
index 80388750c1..0550971789 100644
--- a/server/pkg/protocol/events.go
+++ b/server/pkg/protocol/events.go
@@ -184,10 +184,13 @@ const (
EventSlackInstallationRevoked = "slack_installation:revoked"
// DingTalk installation lifecycle follows the same create/revoke semantics
- // as Slack's BYO channel installation.
- EventDingTalkInstallationCreated = "dingtalk_installation:created"
- EventDingTalkInstallationRevoked = "dingtalk_installation:revoked"
- EventDingTalkGroupRouteUpdated = "dingtalk_group_route:updated"
+ // as Slack's BYO channel installation. BindingUpdated shares the
+ // dingtalk_installation prefix because it changes the member-scoped account
+ // identifiers returned by the installation listing.
+ EventDingTalkInstallationCreated = "dingtalk_installation:created"
+ EventDingTalkInstallationRevoked = "dingtalk_installation:revoked"
+ EventDingTalkAccountBindingUpdated = "dingtalk_installation:binding_updated"
+ EventDingTalkGroupRouteUpdated = "dingtalk_group_route:updated"
// WeCom smart-bot installation lifecycle. Same semantics as Lark /
// Slack: `created` covers both first install and re-install via