feat: add DingTalk support group sender
This commit is contained in:
@@ -0,0 +1,271 @@
|
||||
package dingtalk
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/core"
|
||||
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/coverage"
|
||||
)
|
||||
|
||||
const (
|
||||
groupSendURL = "https://api.dingtalk.com/v1.0/robot/groupMessages/send"
|
||||
// maxGroupPayloadBytes caps the serialized JSON body sent to the group
|
||||
// message endpoint.
|
||||
maxGroupPayloadBytes = 64 << 10 // 64 KiB
|
||||
// questionRuneLimit caps the displayed question in the markdown body.
|
||||
questionRuneLimit = 500
|
||||
// answerRuneLimit caps the displayed answer in the markdown body.
|
||||
answerRuneLimit = 1000
|
||||
)
|
||||
|
||||
// SupportGroupSender sends DingTalk group Markdown notifications via the
|
||||
// official groupMessages/send OpenAPI. It is safe by construction: all
|
||||
// config fields are trimmed, nil client installs hardened defaults, and
|
||||
// all error paths are sanitised.
|
||||
type SupportGroupSender struct {
|
||||
clientID string
|
||||
clientSecret string
|
||||
openConversation string
|
||||
tokenURL string
|
||||
groupURL string
|
||||
apiClient *http.Client
|
||||
|
||||
mu sync.Mutex
|
||||
token string
|
||||
tokenTill time.Time
|
||||
}
|
||||
|
||||
// NewSupportGroupSender creates a SupportGroupSender. All three config values
|
||||
// are required after trimming. A nil http.Client installs a hardened default
|
||||
// (no redirects, Proxy=nil, 15s timeout).
|
||||
func NewSupportGroupSender(clientID, clientSecret, openConversationID string, client *http.Client) (*SupportGroupSender, error) {
|
||||
return newSupportGroupSender(clientID, clientSecret, openConversationID, client, oauthTokenURL, groupSendURL, false)
|
||||
}
|
||||
|
||||
// newSupportGroupSenderForTest is used by tests to inject httptest URLs.
|
||||
func newSupportGroupSenderForTest(clientID, clientSecret, openConversationID string, client *http.Client, tokenURL, groupURL string) (*SupportGroupSender, error) {
|
||||
return newSupportGroupSender(clientID, clientSecret, openConversationID, client, tokenURL, groupURL, true)
|
||||
}
|
||||
|
||||
func newSupportGroupSender(clientID, clientSecret, openConversationID string, client *http.Client, tokenURL, groupURL string, allowTest bool) (*SupportGroupSender, error) {
|
||||
clientID = strings.TrimSpace(clientID)
|
||||
clientSecret = strings.TrimSpace(clientSecret)
|
||||
openConversationID = strings.TrimSpace(openConversationID)
|
||||
if clientID == "" {
|
||||
return nil, errors.New("dingtalk group sender: clientID is required")
|
||||
}
|
||||
if clientSecret == "" {
|
||||
return nil, errors.New("dingtalk group sender: clientSecret is required")
|
||||
}
|
||||
if openConversationID == "" {
|
||||
return nil, errors.New("dingtalk group sender: openConversationId is required")
|
||||
}
|
||||
|
||||
base := &http.Client{Timeout: 15 * time.Second}
|
||||
if client != nil {
|
||||
copyClient := *client
|
||||
base = ©Client
|
||||
if base.Timeout <= 0 {
|
||||
base.Timeout = 15 * time.Second
|
||||
}
|
||||
}
|
||||
|
||||
apiClient := *base
|
||||
apiClient.CheckRedirect = func(*http.Request, []*http.Request) error {
|
||||
return errors.New("dingtalk API redirect refused")
|
||||
}
|
||||
if !allowTest {
|
||||
transport := http.DefaultTransport.(*http.Transport).Clone()
|
||||
transport.Proxy = nil
|
||||
apiClient.Transport = transport
|
||||
}
|
||||
|
||||
return &SupportGroupSender{
|
||||
clientID: clientID,
|
||||
clientSecret: clientSecret,
|
||||
openConversation: openConversationID,
|
||||
tokenURL: tokenURL,
|
||||
groupURL: groupURL,
|
||||
apiClient: &apiClient,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Send sends a support-case notification to the DingTalk group.
|
||||
func (s *SupportGroupSender) Send(ctx context.Context, notif coverage.SupportNotification) error {
|
||||
if notif.CaseID == "" {
|
||||
return errors.New("dingtalk group sender: CaseID is required")
|
||||
}
|
||||
|
||||
// Build the markdown notification body
|
||||
title, text := s.renderMarkdown(notif)
|
||||
msgParam := map[string]string{
|
||||
"title": title,
|
||||
"text": text,
|
||||
}
|
||||
msgParamJSON, err := json.Marshal(msgParam)
|
||||
if err != nil {
|
||||
return errors.New("dingtalk group sender: encode msgParam failed")
|
||||
}
|
||||
|
||||
body := map[string]any{
|
||||
"msgKey": "sampleMarkdown",
|
||||
"msgParam": string(msgParamJSON),
|
||||
"openConversationId": s.openConversation,
|
||||
"robotCode": s.clientID,
|
||||
}
|
||||
|
||||
bodyJSON, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return errors.New("dingtalk group sender: encode request body failed")
|
||||
}
|
||||
if len(bodyJSON) > maxGroupPayloadBytes {
|
||||
return fmt.Errorf("dingtalk group sender: payload exceeds %d bytes", maxGroupPayloadBytes)
|
||||
}
|
||||
|
||||
// Get access token
|
||||
token, err := s.accessToken(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// POST to groupMessages/send
|
||||
respPayload, err := s.doJSON(ctx, http.MethodPost, s.groupURL, body, token)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Check business response
|
||||
var bizResp struct {
|
||||
ProcessQueryKey string `json:"processQueryKey"`
|
||||
ErrCode int `json:"errcode"`
|
||||
}
|
||||
if err := json.Unmarshal(respPayload, &bizResp); err != nil {
|
||||
return errors.New("dingtalk group sender: invalid API response")
|
||||
}
|
||||
if bizResp.ErrCode != 0 {
|
||||
return errors.New("dingtalk group sender: API returned business error")
|
||||
}
|
||||
if strings.TrimSpace(bizResp.ProcessQueryKey) == "" {
|
||||
return errors.New("dingtalk group sender: incomplete API response")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// renderMarkdown produces a title and text for the group notification.
|
||||
func (s *SupportGroupSender) renderMarkdown(notif coverage.SupportNotification) (title, text string) {
|
||||
title = fmt.Sprintf("📋 知识缺失通知 #%s", notif.CaseID)
|
||||
|
||||
convType := "群聊"
|
||||
if notif.ConversationType == core.ConversationDirect {
|
||||
convType = "单聊"
|
||||
}
|
||||
|
||||
question := truncateRunes(notif.Question, questionRuneLimit)
|
||||
answer := truncateRunes(notif.Answer, answerRuneLimit)
|
||||
|
||||
var b strings.Builder
|
||||
b.WriteString("## 📋 知识缺失通知\n\n")
|
||||
b.WriteString(fmt.Sprintf("**Case ID:** %s\n\n", notif.CaseID))
|
||||
b.WriteString(fmt.Sprintf("**提问人:** %s\n\n", notif.SenderName))
|
||||
b.WriteString(fmt.Sprintf("**渠道/会话类型:** %s / %s\n\n", notif.Channel, convType))
|
||||
b.WriteString(fmt.Sprintf("**问题摘要:**\n> %s\n\n", question))
|
||||
b.WriteString(fmt.Sprintf("**回答摘要:**\n> %s\n\n", answer))
|
||||
b.WriteString(fmt.Sprintf("**相关结果数:** %d\n\n", notif.ReferenceCount))
|
||||
b.WriteString(fmt.Sprintf("**最高Score:** %.4f\n", notif.TopScore))
|
||||
|
||||
return title, b.String()
|
||||
}
|
||||
|
||||
func truncateRunes(s string, limit int) string {
|
||||
if limit <= 0 {
|
||||
return s
|
||||
}
|
||||
runes := []rune(s)
|
||||
if len(runes) <= limit {
|
||||
return s
|
||||
}
|
||||
return string(runes[:limit]) + "..."
|
||||
}
|
||||
|
||||
func (s *SupportGroupSender) accessToken(ctx context.Context) (string, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.token != "" && time.Now().Before(s.tokenTill) {
|
||||
return s.token, nil
|
||||
}
|
||||
|
||||
payload, err := s.doJSON(ctx, http.MethodPost, s.tokenURL, map[string]string{
|
||||
"appKey": s.clientID,
|
||||
"appSecret": s.clientSecret,
|
||||
}, "")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
var response struct {
|
||||
AccessToken string `json:"accessToken"`
|
||||
ExpireIn int64 `json:"expireIn"`
|
||||
}
|
||||
if json.Unmarshal(payload, &response) != nil || strings.TrimSpace(response.AccessToken) == "" {
|
||||
return "", errors.New("dingtalk group sender: invalid OAuth response")
|
||||
}
|
||||
|
||||
ttl := time.Duration(response.ExpireIn) * time.Second
|
||||
refreshAfter := ttl - 5*time.Minute
|
||||
if refreshAfter <= 0 {
|
||||
refreshAfter = ttl / 2
|
||||
}
|
||||
if refreshAfter <= 0 {
|
||||
refreshAfter = time.Minute
|
||||
}
|
||||
s.token = response.AccessToken
|
||||
s.tokenTill = time.Now().Add(refreshAfter)
|
||||
return s.token, nil
|
||||
}
|
||||
|
||||
func (s *SupportGroupSender) doJSON(ctx context.Context, method, endpoint string, value any, token string) ([]byte, error) {
|
||||
body, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return nil, errors.New("dingtalk group sender: encode API request failed")
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, method, endpoint, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, errors.New("dingtalk group sender: create API request failed")
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if token != "" {
|
||||
req.Header.Set("x-acs-dingtalk-access-token", token)
|
||||
}
|
||||
|
||||
resp, err := s.apiClient.Do(req)
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
// Propagate redirect errors so callers can detect them.
|
||||
if strings.Contains(err.Error(), "redirect") {
|
||||
return nil, err
|
||||
}
|
||||
return nil, errors.New("dingtalk group sender: API request failed")
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
// Discard body without reading it — sanitised error
|
||||
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, maxAPIResponseBytes))
|
||||
return nil, fmt.Errorf("dingtalk group sender: API HTTP %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
return readBoundedAPIResponse(resp)
|
||||
}
|
||||
@@ -0,0 +1,644 @@
|
||||
package dingtalk
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"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: "怎么配置钉钉机器人?",
|
||||
Answer: "进入钉钉开放平台,创建应用并获取AppKey和AppSecret。",
|
||||
SenderName: "张三",
|
||||
Channel: "dingtalk",
|
||||
ConversationType: core.ConversationGroup,
|
||||
ReferenceCount: 3,
|
||||
TopScore: 0.95,
|
||||
}
|
||||
}
|
||||
|
||||
// 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"] != "sampleMarkdown" {
|
||||
t.Fatalf("msgKey = %v, want sampleMarkdown", 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 very long Question and Answer
|
||||
longQ := strings.Repeat("你好", 300) // 600 runes, each 3 bytes → 1800 bytes
|
||||
longA := strings.Repeat("世界", 600) // 1200 runes, each 3 bytes → 3600 bytes
|
||||
|
||||
notif := newTestNotification()
|
||||
notif.Question = longQ
|
||||
notif.Answer = longA
|
||||
|
||||
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"]
|
||||
// The text field should contain the long question and answer, truncated
|
||||
if !strings.Contains(text, "你好") {
|
||||
t.Fatal("text missing question content")
|
||||
}
|
||||
if !strings.Contains(text, "世界") {
|
||||
t.Fatal("text missing answer 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"]
|
||||
|
||||
// Title should contain Case ID
|
||||
if !strings.Contains(title, "case-001") {
|
||||
t.Fatalf("title = %q, want containing case-001", title)
|
||||
}
|
||||
|
||||
// Text should contain key fields
|
||||
checks := []string{
|
||||
"case-001", // Case ID
|
||||
"张三", // SenderName
|
||||
"dingtalk", // Channel
|
||||
"群聊", // ConversationType (group → 群聊)
|
||||
"怎么配置", // Question snippet
|
||||
"钉钉开放平台", // Answer snippet
|
||||
"3", // ReferenceCount
|
||||
"0.95", // TopScore
|
||||
}
|
||||
for _, want := range checks {
|
||||
if !strings.Contains(text, want) {
|
||||
t.Fatalf("markdown text missing %q: %s", want, text)
|
||||
}
|
||||
}
|
||||
|
||||
// Should NOT call references "文档数"
|
||||
if strings.Contains(text, "文档数") {
|
||||
t.Fatalf("markdown text should not use '文档数': %s", text)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSupportGroupSenderDirectConversationType(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.ConversationType = core.ConversationDirect
|
||||
if err := s.Send(context.Background(), notif); err != nil {
|
||||
t.Fatalf("Send: %v", err)
|
||||
}
|
||||
|
||||
raw := gs.lastSendBody["msgParam"].(string)
|
||||
var mp map[string]string
|
||||
json.Unmarshal([]byte(raw), &mp)
|
||||
|
||||
if !strings.Contains(mp["text"], "单聊") {
|
||||
t.Fatalf("direct conversation should show '单聊': %s", mp["text"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestSupportGroupSenderEmptyQuestionAnswer(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.Question = ""
|
||||
notif.Answer = ""
|
||||
if err := s.Send(context.Background(), notif); err != nil {
|
||||
t.Fatalf("Send: %v", err)
|
||||
}
|
||||
|
||||
// Should still succeed, just show empty fields
|
||||
raw := gs.lastSendBody["msgParam"].(string)
|
||||
if !strings.Contains(raw, "case-001") {
|
||||
t.Fatal("markdown missing case ID")
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSupportGroupSenderPreservesLowScorePrecision(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.TopScore = 0.0149
|
||||
if err := s.Send(context.Background(), notif); err != nil {
|
||||
t.Fatalf("Send: %v", err)
|
||||
}
|
||||
|
||||
raw := gs.lastSendBody["msgParam"].(string)
|
||||
if !strings.Contains(raw, "0.0149") {
|
||||
t.Fatalf("low score precision lost: %s", raw)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSupportGroupSenderZeroReferences(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.ReferenceCount = 0
|
||||
notif.TopScore = 0
|
||||
if err := s.Send(context.Background(), notif); err != nil {
|
||||
t.Fatalf("Send: %v", err)
|
||||
}
|
||||
|
||||
raw := gs.lastSendBody["msgParam"].(string)
|
||||
var mp map[string]string
|
||||
json.Unmarshal([]byte(raw), &mp)
|
||||
|
||||
if !strings.Contains(mp["text"], "0") {
|
||||
t.Fatal("markdown missing ReferenceCount=0")
|
||||
}
|
||||
if !strings.Contains(mp["text"], "0.00") {
|
||||
t.Fatalf("markdown missing TopScore=0.00: %s", mp["text"])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package coverage
|
||||
|
||||
import "gitea.zheromiku.top/Weknora/dobotai-platform/internal/core"
|
||||
|
||||
// SupportNotification carries the minimum safe fields needed to render a
|
||||
// support-case notification in a DingTalk group. It must never contain
|
||||
// tokens, webhooks, raw IDs, raw API responses, or reference bodies.
|
||||
type SupportNotification struct {
|
||||
CaseID string
|
||||
Question string
|
||||
Answer string
|
||||
SenderName string
|
||||
Channel string
|
||||
ConversationType core.ConversationType
|
||||
ReferenceCount int
|
||||
TopScore float64
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
// Package coverage defines the domain logic for coverage evaluation.
|
||||
package coverage
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"gitea.zheromiku.top/Weknora/dobotai-platform/internal/core"
|
||||
)
|
||||
|
||||
func TestSupportNotificationFields(t *testing.T) {
|
||||
// Verify that SupportNotification is a plain data struct with only the
|
||||
// safe fields listed in the spec. Token, webhook, raw IDs, raw responses,
|
||||
// and reference bodies must NOT be present.
|
||||
notif := SupportNotification{
|
||||
CaseID: "case-001",
|
||||
Question: "怎么配置钉钉机器人?",
|
||||
Answer: "进入钉钉开放平台...",
|
||||
SenderName: "张三",
|
||||
Channel: "dingtalk",
|
||||
ConversationType: core.ConversationGroup,
|
||||
ReferenceCount: 3,
|
||||
TopScore: 0.95,
|
||||
}
|
||||
|
||||
if notif.CaseID != "case-001" {
|
||||
t.Fatalf("CaseID = %q, want case-001", notif.CaseID)
|
||||
}
|
||||
if notif.Question != "怎么配置钉钉机器人?" {
|
||||
t.Fatalf("Question = %q", notif.Question)
|
||||
}
|
||||
if notif.Answer != "进入钉钉开放平台..." {
|
||||
t.Fatalf("Answer = %q", notif.Answer)
|
||||
}
|
||||
if notif.SenderName != "张三" {
|
||||
t.Fatalf("SenderName = %q", notif.SenderName)
|
||||
}
|
||||
if notif.Channel != "dingtalk" {
|
||||
t.Fatalf("Channel = %q", notif.Channel)
|
||||
}
|
||||
if notif.ConversationType != core.ConversationGroup {
|
||||
t.Fatalf("ConversationType = %q", notif.ConversationType)
|
||||
}
|
||||
if notif.ReferenceCount != 3 {
|
||||
t.Fatalf("ReferenceCount = %d", notif.ReferenceCount)
|
||||
}
|
||||
if notif.TopScore != 0.95 {
|
||||
t.Fatalf("TopScore = %f", notif.TopScore)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSupportNotificationEmptyValues(t *testing.T) {
|
||||
// Zero-value notification should be safe to render (no panic).
|
||||
notif := SupportNotification{}
|
||||
if notif.CaseID != "" {
|
||||
t.Fatalf("expected empty CaseID")
|
||||
}
|
||||
if notif.Question != "" {
|
||||
t.Fatalf("expected empty Question")
|
||||
}
|
||||
if notif.Answer != "" {
|
||||
t.Fatalf("expected empty Answer")
|
||||
}
|
||||
if notif.ReferenceCount != 0 {
|
||||
t.Fatalf("expected zero ReferenceCount")
|
||||
}
|
||||
if notif.TopScore != 0 {
|
||||
t.Fatalf("expected zero TopScore")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user