Files
dobotai-platform/internal/channels/dingtalk/group_sender_test.go
2026-08-13 18:22:43 +08:00

600 lines
19 KiB
Go

package dingtalk
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/core"
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/coverage"
)
// groupTestServer provides a configurable httptest server for group message
// tests, with token and groupMessages/send endpoints.
type groupTestServer struct {
server *httptest.Server
tokenCalls int
sendCalls int
lastTokenBody map[string]string
lastSendBody map[string]any
lastSendHeader string
tokenStatus int
tokenResponse any
sendStatus int
sendResponse any
}
func newGroupTestServer() *groupTestServer {
gs := &groupTestServer{
tokenStatus: http.StatusOK,
tokenResponse: map[string]any{"accessToken": "test-token", "expireIn": 3600},
sendStatus: http.StatusOK,
sendResponse: map[string]any{"processQueryKey": "pqk-123"},
}
gs.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/token":
gs.tokenCalls++
gs.lastTokenBody = make(map[string]string)
json.NewDecoder(r.Body).Decode(&gs.lastTokenBody)
w.Header().Set("Content-Type", "application/json")
if gs.tokenStatus != http.StatusOK {
w.WriteHeader(gs.tokenStatus)
return
}
json.NewEncoder(w).Encode(gs.tokenResponse)
case "/groupMessages/send":
gs.sendCalls++
gs.lastSendHeader = r.Header.Get("x-acs-dingtalk-access-token")
gs.lastSendBody = make(map[string]any)
json.NewDecoder(r.Body).Decode(&gs.lastSendBody)
w.Header().Set("Content-Type", "application/json")
if gs.sendStatus != http.StatusOK {
w.WriteHeader(gs.sendStatus)
return
}
json.NewEncoder(w).Encode(gs.sendResponse)
default:
http.NotFound(w, r)
}
}))
return gs
}
func (gs *groupTestServer) Close() { gs.server.Close() }
func (gs *groupTestServer) URL() string { return gs.server.URL }
func newTestNotification() coverage.SupportNotification {
return coverage.SupportNotification{
CaseID: "case-001",
Question: "怎么配置钉钉机器人?",
SenderName: "张三",
Channel: "dingtalk",
ConversationType: core.ConversationGroup,
AskedAt: time.Date(2026, 7, 24, 10, 16, 35, 0, time.FixedZone("CST", 8*60*60)),
PreviousQuestions: []string{"之前的问题一", "之前的问题二"},
FAQRecordID: "record-001",
}
}
// helper to create a sender with test URLs.
func newTestGroupSender(t *testing.T, clientID, clientSecret, openConvID string, client *http.Client, tokenURL, groupURL string) *SupportGroupSender {
t.Helper()
s, err := newSupportGroupSenderForTest(clientID, clientSecret, openConvID, client, tokenURL, groupURL)
if err != nil {
t.Fatalf("newSupportGroupSenderForTest: %v", err)
}
return s
}
// -------- 1. fail closed on missing config --------
func TestSupportGroupSenderMissingConfigFailsClosed(t *testing.T) {
tests := []struct {
name, clientID, clientSecret, openConvID string
wantErr string
}{
{name: "empty clientID", clientSecret: "s", openConvID: "c", wantErr: "clientID"},
{name: "empty clientSecret", clientID: "a", openConvID: "c", wantErr: "clientSecret"},
{name: "empty openConversationId", clientID: "a", clientSecret: "s", wantErr: "openConversationId"},
{name: "all empty", wantErr: "clientID"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := NewSupportGroupSender(tt.clientID, tt.clientSecret, tt.openConvID, nil)
if err == nil {
t.Fatal("expected error, got nil")
}
if !strings.Contains(err.Error(), tt.wantErr) {
t.Fatalf("error = %v, want containing %q", err, tt.wantErr)
}
})
}
}
// -------- 2. exact endpoint, body, header --------
func TestSupportGroupSenderExactEndpointBodyHeader(t *testing.T) {
gs := newGroupTestServer()
defer gs.Close()
s := newTestGroupSender(t, "appKey", "appSecret", "cid-abc", gs.server.Client(), gs.URL()+"/token", gs.URL()+"/groupMessages/send")
notif := newTestNotification()
ctx := context.Background()
if err := s.Send(ctx, notif); err != nil {
t.Fatalf("Send: %v", err)
}
// Verify token endpoint was called
if gs.tokenCalls != 1 {
t.Fatalf("tokenCalls = %d, want 1", gs.tokenCalls)
}
if gs.lastTokenBody["appKey"] != "appKey" || gs.lastTokenBody["appSecret"] != "appSecret" {
t.Fatalf("token body = %+v", gs.lastTokenBody)
}
// Verify send endpoint
if gs.sendCalls != 1 {
t.Fatalf("sendCalls = %d, want 1", gs.sendCalls)
}
if gs.lastSendHeader != "test-token" {
t.Fatalf("send header = %q, want test-token", gs.lastSendHeader)
}
body := gs.lastSendBody
if body["msgKey"] != "sampleActionCard" {
t.Fatalf("msgKey = %v, want sampleActionCard", body["msgKey"])
}
if body["openConversationId"] != "cid-abc" {
t.Fatalf("openConversationId = %v, want cid-abc", body["openConversationId"])
}
if body["robotCode"] != "appKey" {
t.Fatalf("robotCode = %v, want appKey", body["robotCode"])
}
// msgParam must be a JSON string
msgParamRaw, ok := body["msgParam"].(string)
if !ok {
t.Fatalf("msgParam is not a string, got %T", body["msgParam"])
}
// Parse msgParam as JSON
var msgParam map[string]string
if err := json.Unmarshal([]byte(msgParamRaw), &msgParam); err != nil {
t.Fatalf("msgParam is not valid JSON: %v (raw=%s)", err, msgParamRaw)
}
if msgParam["title"] == "" {
t.Fatal("msgParam.title is empty")
}
if msgParam["text"] == "" {
t.Fatal("msgParam.text is empty")
}
}
// -------- 3. msgParam is valid JSON string --------
func TestSupportGroupSenderMsgParamIsValidJSON(t *testing.T) {
gs := newGroupTestServer()
defer gs.Close()
s := newTestGroupSender(t, "appKey", "appSecret", "cid-abc", gs.server.Client(), gs.URL()+"/token", gs.URL()+"/groupMessages/send")
if err := s.Send(context.Background(), newTestNotification()); err != nil {
t.Fatalf("Send: %v", err)
}
raw := gs.lastSendBody["msgParam"].(string)
var mp map[string]any
if err := json.Unmarshal([]byte(raw), &mp); err != nil {
t.Fatalf("msgParam not valid JSON: %v", err)
}
// Verify required keys exist
if _, ok := mp["title"]; !ok {
t.Fatal("msgParam missing title")
}
if _, ok := mp["text"]; !ok {
t.Fatal("msgParam missing text")
}
}
// -------- 4. OAuth token reuse --------
func TestSupportGroupSenderTokenReuse(t *testing.T) {
gs := newGroupTestServer()
gs.tokenResponse = map[string]any{"accessToken": "reused-token", "expireIn": 7200}
defer gs.Close()
s := newTestGroupSender(t, "appKey", "appSecret", "cid-abc", gs.server.Client(), gs.URL()+"/token", gs.URL()+"/groupMessages/send")
// Send twice
if err := s.Send(context.Background(), newTestNotification()); err != nil {
t.Fatalf("first Send: %v", err)
}
if err := s.Send(context.Background(), newTestNotification()); err != nil {
t.Fatalf("second Send: %v", err)
}
// Token should only be fetched once
if gs.tokenCalls != 1 {
t.Fatalf("tokenCalls = %d, want 1 (token should be reused)", gs.tokenCalls)
}
if gs.sendCalls != 2 {
t.Fatalf("sendCalls = %d, want 2", gs.sendCalls)
}
}
// -------- 5. no redirects --------
func TestSupportGroupSenderRejectsRedirect(t *testing.T) {
// Create a target server
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}))
defer target.Close()
// Create a redirector
redirector := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, target.URL+"/groupMessages/send", http.StatusFound)
}))
defer redirector.Close()
_, err := newSupportGroupSenderForTest("appKey", "appSecret", "cid-abc", redirector.Client(),
redirector.URL+"/token", redirector.URL+"/groupMessages/send")
if err != nil {
t.Fatalf("newSupportGroupSenderForTest: %v", err)
}
// token endpoint also redirects
redirector2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, target.URL+"/token", http.StatusFound)
}))
defer redirector2.Close()
s := newTestGroupSender(t, "appKey", "appSecret", "cid-abc", redirector2.Client(),
redirector2.URL+"/token", redirector2.URL+"/groupMessages/send")
err = s.Send(context.Background(), newTestNotification())
if err == nil {
t.Fatal("expected redirect error, got nil")
}
if !strings.Contains(err.Error(), "redirect") {
t.Fatalf("error = %v, want containing 'redirect'", err)
}
}
// -------- 6. non-2xx sanitized error --------
func TestSupportGroupSenderNon2xxSanitized(t *testing.T) {
gs := newGroupTestServer()
gs.sendStatus = http.StatusInternalServerError
defer gs.Close()
s := newTestGroupSender(t, "appKey", "appSecret", "cid-abc", gs.server.Client(), gs.URL()+"/token", gs.URL()+"/groupMessages/send")
err := s.Send(context.Background(), newTestNotification())
if err == nil {
t.Fatal("expected error for 500, got nil")
}
errStr := err.Error()
// Error must NOT contain clientSecret
if strings.Contains(errStr, "appSecret") {
t.Fatalf("error leaks clientSecret: %s", errStr)
}
// Error must NOT contain access token
if strings.Contains(errStr, "test-token") {
t.Fatalf("error leaks access token: %s", errStr)
}
// Error must NOT contain conversation ID
if strings.Contains(errStr, "cid-abc") {
t.Fatalf("error leaks openConversationId: %s", errStr)
}
// Error must NOT contain question
if strings.Contains(errStr, "怎么配置") {
t.Fatalf("error leaks question: %s", errStr)
}
// Error must NOT contain answer
if strings.Contains(errStr, "钉钉开放平台") {
t.Fatalf("error leaks answer: %s", errStr)
}
}
// -------- 7. business failure (non-success response) sanitized --------
func TestSupportGroupSenderBusinessFailureSanitized(t *testing.T) {
gs := newGroupTestServer()
gs.sendStatus = http.StatusOK
// Simulate a business error: DingTalk returns 200 but with error code
gs.sendResponse = map[string]any{
"errcode": 40035,
"errmsg": "不合法的参数",
}
defer gs.Close()
s := newTestGroupSender(t, "appKey", "appSecret", "cid-abc", gs.server.Client(), gs.URL()+"/token", gs.URL()+"/groupMessages/send")
err := s.Send(context.Background(), newTestNotification())
if err == nil {
t.Fatal("expected business error, got nil")
}
errStr := err.Error()
if strings.Contains(errStr, "appSecret") {
t.Fatalf("error leaks clientSecret: %s", errStr)
}
if strings.Contains(errStr, "test-token") {
t.Fatalf("error leaks access token: %s", errStr)
}
if strings.Contains(errStr, "cid-abc") {
t.Fatalf("error leaks openConversationId: %s", errStr)
}
if strings.Contains(errStr, "怎么配置") {
t.Fatalf("error leaks question: %s", errStr)
}
}
// -------- 8. long Unicode truncation / 64KiB limit --------
func TestSupportGroupSenderLongUnicodeTruncation(t *testing.T) {
gs := newGroupTestServer()
defer gs.Close()
s := newTestGroupSender(t, "appKey", "appSecret", "cid-abc", gs.server.Client(), gs.URL()+"/token", gs.URL()+"/groupMessages/send")
// Create a notification with a very long current and historical question.
longQ := strings.Repeat("你好", 300)
longPrevious := strings.Repeat("世界", 600)
notif := newTestNotification()
notif.Question = longQ
notif.PreviousQuestions = []string{longPrevious}
if err := s.Send(context.Background(), notif); err != nil {
t.Fatalf("Send with long content: %v", err)
}
// The msgParam text should contain truncated versions
raw := gs.lastSendBody["msgParam"].(string)
var mp map[string]string
if err := json.Unmarshal([]byte(raw), &mp); err != nil {
t.Fatalf("msgParam not valid JSON: %v", err)
}
text := mp["text"]
// Both current and historical questions are present and rune-truncated.
if !strings.Contains(text, "你好") {
t.Fatal("text missing current question content")
}
if !strings.Contains(text, "世界") {
t.Fatal("text missing historical question content")
}
// The full body size must be <= 64KiB
bodyBytes, _ := json.Marshal(gs.lastSendBody)
if len(bodyBytes) > 64*1024 {
t.Fatalf("body size = %d, exceeds 64KiB", len(bodyBytes))
}
}
func TestSupportGroupSenderPayloadExceeds64KiB(t *testing.T) {
gs := newGroupTestServer()
defer gs.Close()
s := newTestGroupSender(t, "appKey", "appSecret", "cid-abc", gs.server.Client(), gs.URL()+"/token", gs.URL()+"/groupMessages/send")
notif := newTestNotification()
// Use a very long SenderName to push the rendered markdown + JSON
// serialization beyond 64 KiB. Question/Answer are truncated to 500/1000
// runes, so they won't contribute much. The SenderName is not truncated.
notif.SenderName = strings.Repeat("张", 70*1024) // ~70KB of UTF-8
err := s.Send(context.Background(), notif)
if err == nil {
t.Fatal("expected error for oversized payload, got nil")
}
if !strings.Contains(err.Error(), "exceeds") && !strings.Contains(err.Error(), "64") && !strings.Contains(err.Error(), "KiB") {
t.Fatalf("error = %v, want size-limit error", err)
}
}
// -------- 9. error JSON response does not leak --------
func TestSupportGroupSenderErrorJSONNotLeaked(t *testing.T) {
gs := newGroupTestServer()
gs.sendStatus = http.StatusBadRequest
// Return a large error body
gs.sendResponse = nil
// Override handler to return raw error JSON
gs.server.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/token" {
gs.tokenCalls++
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(gs.tokenResponse)
return
}
gs.sendCalls++
w.WriteHeader(http.StatusBadRequest)
// Write raw error JSON with sensitive-looking content
io.WriteString(w, `{"errcode":40035,"errmsg":"invalid parameter cid-abc","raw":"user appSecret leaked"}`)
})
defer gs.Close()
s := newTestGroupSender(t, "appKey", "appSecret", "cid-abc", gs.server.Client(), gs.URL()+"/token", gs.URL()+"/groupMessages/send")
err := s.Send(context.Background(), newTestNotification())
if err == nil {
t.Fatal("expected error, got nil")
}
errStr := err.Error()
// Error must not contain the raw response body
if strings.Contains(errStr, "40035") || strings.Contains(errStr, "invalid parameter") {
t.Fatalf("error leaks raw API response: %s", errStr)
}
if strings.Contains(errStr, "appSecret") {
t.Fatalf("error leaks clientSecret: %s", errStr)
}
if strings.Contains(errStr, "cid-abc") {
t.Fatalf("error leaks conversation ID: %s", errStr)
}
}
// -------- 10. validation: empty CaseID --------
func TestSupportGroupSenderRejectsEmptyCaseID(t *testing.T) {
gs := newGroupTestServer()
defer gs.Close()
s := newTestGroupSender(t, "appKey", "appSecret", "cid-abc", gs.server.Client(), gs.URL()+"/token", gs.URL()+"/groupMessages/send")
notif := newTestNotification()
notif.CaseID = ""
err := s.Send(context.Background(), notif)
if err == nil {
t.Fatal("expected error for empty CaseID, got nil")
}
if !strings.Contains(err.Error(), "CaseID") {
t.Fatalf("error = %v, want containing 'CaseID'", err)
}
}
// -------- 11. nil client installs hardened defaults --------
func TestSupportGroupSenderNilClientDefaults(t *testing.T) {
gs := newGroupTestServer()
defer gs.Close()
// Use nil client and verify it still works with httptest URLs
s, err := newSupportGroupSenderForTest("appKey", "appSecret", "cid-abc", nil, gs.URL()+"/token", gs.URL()+"/groupMessages/send")
if err != nil {
t.Fatalf("newSupportGroupSenderForTest with nil client: %v", err)
}
if err := s.Send(context.Background(), newTestNotification()); err != nil {
t.Fatalf("Send with nil client: %v", err)
}
}
// -------- 12. Markdown content verification --------
func TestSupportGroupSenderMarkdownContent(t *testing.T) {
gs := newGroupTestServer()
defer gs.Close()
s := newTestGroupSender(t, "appKey", "appSecret", "cid-abc", gs.server.Client(), gs.URL()+"/token", gs.URL()+"/groupMessages/send")
notif := newTestNotification()
if err := s.Send(context.Background(), notif); err != nil {
t.Fatalf("Send: %v", err)
}
raw := gs.lastSendBody["msgParam"].(string)
var mp map[string]string
if err := json.Unmarshal([]byte(raw), &mp); err != nil {
t.Fatalf("msgParam not valid JSON: %v", err)
}
text := mp["text"]
title := mp["title"]
if title != "知识库未覆盖提醒" {
t.Fatalf("title = %q", title)
}
for _, want := range []string{"张三", "2026-07-24 10:16:35", "怎么配置", "之前的问题一", "之前的问题二", "Chinese"} {
if !strings.Contains(text, want) {
t.Fatalf("action-card text missing %q: %s", want, text)
}
}
for _, forbidden := range []string{"case-001", "回答摘要", "相关结果", "Score", "置信度"} {
if strings.Contains(text, forbidden) {
t.Fatalf("action-card text contains forbidden %q: %s", forbidden, text)
}
}
if mp["singleTitle"] != "去回答" || mp["singleURL"] == "" {
t.Fatalf("missing FAQ action: %#v", mp)
}
}
func TestSupportGroupSenderNoPreviousQuestions(t *testing.T) {
gs := newGroupTestServer()
defer gs.Close()
s := newTestGroupSender(t, "appKey", "appSecret", "cid-abc", gs.server.Client(), gs.URL()+"/token", gs.URL()+"/groupMessages/send")
notif := newTestNotification()
notif.PreviousQuestions = nil
if err := s.Send(context.Background(), notif); err != nil {
t.Fatalf("Send: %v", err)
}
if raw := gs.lastSendBody["msgParam"].(string); !strings.Contains(raw, "暂无历史问题") {
t.Fatalf("missing empty-history copy: %s", raw)
}
}
func TestSupportGroupSenderSendTestDoesNotRequireFAQBinding(t *testing.T) {
gs := newGroupTestServer()
defer gs.Close()
sender, err := newSupportGroupSenderForTest(
"appKey", "appSecret", "cid-abc",
gs.server.Client(), gs.URL()+"/token", gs.URL()+"/groupMessages/send",
)
if err != nil {
t.Fatal(err)
}
if err = sender.SendTest(context.Background()); err != nil {
t.Fatalf("SendTest: %v", err)
}
if gs.sendCalls != 1 {
t.Fatalf("sendCalls=%d want=1", gs.sendCalls)
}
if gs.lastSendBody["openConversationId"] != "cid-abc" || gs.lastSendBody["robotCode"] != "appKey" {
t.Fatalf("body=%v", gs.lastSendBody)
}
if gs.lastSendBody["msgKey"] != "sampleMarkdown" {
t.Fatalf("msgKey=%v want=sampleMarkdown", gs.lastSendBody["msgKey"])
}
var params map[string]string
if err = json.Unmarshal([]byte(gs.lastSendBody["msgParam"].(string)), &params); err != nil {
t.Fatal(err)
}
if params["title"] != "DobotAI 技术支持群绑定测试" || !strings.Contains(params["text"], "测试成功") {
t.Fatalf("params=%v", params)
}
}
func TestSupportGroupSenderRejectsMalformedOrIncompleteSuccessResponse(t *testing.T) {
tests := []struct {
name string
response any
}{
{name: "malformed JSON", response: json.RawMessage(`{`)},
{name: "missing processQueryKey", response: map[string]any{}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gs := newGroupTestServer()
gs.sendResponse = tt.response
defer gs.Close()
s := newTestGroupSender(t, "appKey", "appSecret", "cid-abc", gs.server.Client(), gs.URL()+"/token", gs.URL()+"/groupMessages/send")
err := s.Send(context.Background(), newTestNotification())
if err == nil {
t.Fatal("expected fail-closed error, got nil")
}
if strings.Contains(err.Error(), "cid-abc") || strings.Contains(err.Error(), "怎么配置") {
t.Fatalf("error leaks notification data: %v", err)
}
})
}
}