350 lines
13 KiB
Go
350 lines
13 KiB
Go
// openapi_test.go Day 46:外部 API 提交单测——MD5 验签全路径(对/错签/过期/禁用/
|
|
// 未开通/密钥未发/IP 白名单)+群发个性校验码表+透传字段落库+余额拒绝。
|
|
package openapi
|
|
|
|
import (
|
|
"context"
|
|
"crypto/md5"
|
|
"fmt"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/glebarez/sqlite"
|
|
"gorm.io/gorm"
|
|
|
|
"go-sms/internal/model/entity"
|
|
"go-sms/internal/service/audit"
|
|
"go-sms/internal/service/send"
|
|
"go-sms/internal/util"
|
|
)
|
|
|
|
// newTestDB 测试库(openapi 全链表;audit_record 撞名索引原生建表,注记见 review_test.go)。
|
|
func newTestDB(t *testing.T) *gorm.DB {
|
|
t.Helper()
|
|
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for _, m := range []any{
|
|
&entity.AccountUser{}, &entity.AccountConfig{},
|
|
&entity.MessageTask{}, &entity.MessageDetail{}, &entity.TemplateSMS{},
|
|
} {
|
|
if err := db.Migrator().CreateTable(m); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
db.Exec(`CREATE TABLE audit_record (
|
|
id integer primary key autoincrement, created_at datetime,
|
|
biz_type text, biz_id integer, account_id integer, content text,
|
|
status integer, auditor text, audit_at datetime, reason text)`)
|
|
// Day48:预扣/退款流水(索引撞名故原生建表,同 submit_test 注记)。
|
|
db.Exec(`CREATE TABLE account_balance_log (
|
|
id integer primary key autoincrement, created_at datetime,
|
|
account_id integer, biz_type text, amount integer,
|
|
balance_after integer, ref_id text, operator text, remark text)`)
|
|
return db
|
|
}
|
|
|
|
const testSecret = "d46a1b2c3d4e5f60718293a4b5c6d7e8"
|
|
|
|
// mkAccount 建号+短信配置(默认:启用/已发密钥/免审/余额 10000;mutate 可覆写)。
|
|
func mkAccount(t *testing.T, db *gorm.DB, id int64, mutate func(u *entity.AccountUser, c *entity.AccountConfig)) {
|
|
t.Helper()
|
|
u := &entity.AccountUser{Username: fmt.Sprintf("user%d", id), Status: 1, Balance: 10000}
|
|
u.ID = id // 主键在嵌入 Model
|
|
c := &entity.AccountConfig{AccountID: id, Business: "sms", AuditMode: 0}
|
|
if mutate != nil {
|
|
mutate(u, c)
|
|
}
|
|
statusDisabled := u.Status == 0 // Create 会回填 default:1,先记意图
|
|
if c.ApiSecret == "-" { // "-" 约定:显式留空(密钥未签发场景)
|
|
c.ApiSecret = ""
|
|
} else if c.ApiSecret == "" {
|
|
c.ApiSecret = md5Hex(testSecret)
|
|
}
|
|
if err := db.Create(u).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
// gorm default 标签坑:Status 零值建行会被 default:1 覆盖且回填 struct,需 Updates(map) 强制写。
|
|
if statusDisabled {
|
|
if err := db.Model(&entity.AccountUser{}).Where("id = ?", u.ID).
|
|
Updates(map[string]any{"status": 0}).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
if err := db.Create(c).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
|
|
// signFor 协议签名:MD5(userName+ts+MD5(secret))。
|
|
func signFor(user, ts, secret string) string {
|
|
inner := fmt.Sprintf("%x", md5.Sum([]byte(secret)))
|
|
return fmt.Sprintf("%x", md5.Sum([]byte(user+ts+inner)))
|
|
}
|
|
|
|
// md5Hex Day62 统一式:存量 md5 态种子下客户须填「库值」(即本函数结果)。
|
|
func md5Hex(s string) string { return fmt.Sprintf("%x", md5.Sum([]byte(s))) }
|
|
|
|
// newSvc 装配服务(真 SubmitService+审核分流;producer nil=不投事件)。
|
|
func newSvc(t *testing.T, db *gorm.DB) (*Service, *Authenticator) {
|
|
t.Helper()
|
|
sf, err := util.NewSnowflake(1)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
submit := send.NewSubmitService(db, sf, audit.NewReviewService(db))
|
|
return NewService(db, submit, nil), NewAuthenticator(db)
|
|
}
|
|
|
|
func authed(t *testing.T, a *Authenticator, user string) *AuthContext {
|
|
t.Helper()
|
|
ts := fmt.Sprintf("%d", time.Now().Unix())
|
|
auth, code, msg := a.Authenticate(context.Background(), user, ts, signFor(user, ts, md5Hex(testSecret)), "127.0.0.1")
|
|
if code != CodeOK {
|
|
t.Fatalf("预置验签失败: code=%d msg=%s", code, msg)
|
|
}
|
|
return auth
|
|
}
|
|
|
|
// ---- 验签 ----
|
|
|
|
func TestAuthenticateOK(t *testing.T) {
|
|
db := newTestDB(t)
|
|
mkAccount(t, db, 1, nil)
|
|
svc, a := newSvc(t, db)
|
|
_ = svc
|
|
ts := fmt.Sprintf("%d", time.Now().Unix())
|
|
auth, code, msg := a.Authenticate(context.Background(), "user1", ts, signFor("user1", ts, md5Hex(testSecret)), "127.0.0.1")
|
|
if code != CodeOK || auth == nil || auth.AccountID != 1 {
|
|
t.Fatalf("code=%d msg=%s auth=%v", code, msg, auth)
|
|
}
|
|
if auth.Config == nil || auth.Config.Business != "sms" {
|
|
t.Fatal("config 未注入")
|
|
}
|
|
}
|
|
|
|
// Day62 统一式「库值即密码」:库存原样密码 P(非 md5 态),客户 password 填 P →
|
|
// sign=MD5(user+ts+MD5(P)) == expect=MD5(user+ts+MD5(库值)) 通。
|
|
func TestAuthenticatePlainSecretOK(t *testing.T) {
|
|
db := newTestDB(t)
|
|
mkAccount(t, db, 1, func(u *entity.AccountUser, c *entity.AccountConfig) {
|
|
c.ApiSecret = "plain66" // 原样态:库值即密码(6 位)
|
|
})
|
|
_, a := newSvc(t, db)
|
|
ts := fmt.Sprintf("%d", time.Now().Unix())
|
|
auth, code, msg := a.Authenticate(context.Background(), "user1", ts, signFor("user1", ts, "plain66"), "127.0.0.1")
|
|
if code != CodeOK || auth == nil {
|
|
t.Fatalf("plain-secret code=%d msg=%s auth=%v", code, msg, auth)
|
|
}
|
|
}
|
|
|
|
func TestAuthenticateFailures(t *testing.T) {
|
|
mk := func(mutate func(u *entity.AccountUser, c *entity.AccountConfig)) (*Authenticator, string, string) {
|
|
db := newTestDB(t)
|
|
mkAccount(t, db, 1, mutate)
|
|
_, a := newSvc(t, db)
|
|
return a, "user1", "127.0.0.1"
|
|
}
|
|
now := fmt.Sprintf("%d", time.Now().Unix())
|
|
|
|
// 空用户名 → 1
|
|
a, u, ip := mk(nil)
|
|
if _, code, _ := a.Authenticate(context.Background(), "", now, "x", ip); code != CodeNoUser {
|
|
t.Fatalf("空用户名 code=%d 期望 1", code)
|
|
}
|
|
// 不存在账号 → 2(不泄露存在性)
|
|
if _, code, _ := a.Authenticate(context.Background(), "nobody", now, "x", ip); code != CodeAuthFail {
|
|
t.Fatalf("不存在账号 code=%d 期望 2", code)
|
|
}
|
|
// 错签名 → 2
|
|
if _, code, _ := a.Authenticate(context.Background(), u, now, "deadbeef", ip); code != CodeAuthFail {
|
|
t.Fatalf("错签名 code=%d 期望 2", code)
|
|
}
|
|
// 时间戳过期(±5min 窗口外) → 16
|
|
stale := fmt.Sprintf("%d", time.Now().Add(-10*time.Minute).Unix())
|
|
if _, code, _ := a.Authenticate(context.Background(), u, stale, signFor(u, stale, md5Hex(testSecret)), ip); code != CodeStaleTS {
|
|
t.Fatalf("过期时间戳 code=%d 期望 16", code)
|
|
}
|
|
// 账号禁用 → 3
|
|
a, u, ip = mk(func(u *entity.AccountUser, c *entity.AccountConfig) { u.Status = 0 })
|
|
if _, code, _ := a.Authenticate(context.Background(), u, now, signFor(u, now, md5Hex(testSecret)), ip); code != CodeDisabled {
|
|
t.Fatalf("禁用 code=%d 期望 3", code)
|
|
}
|
|
// 密钥未签发 → 2
|
|
a, u, ip = mk(func(u *entity.AccountUser, c *entity.AccountConfig) { c.ApiSecret = "-" })
|
|
if _, code, msg := a.Authenticate(context.Background(), u, now, signFor(u, now, md5Hex(testSecret)), ip); code != CodeAuthFail || !strings.Contains(msg, "密钥") {
|
|
t.Fatalf("密钥未发 code=%d msg=%s 期望 2+密钥提示", code, msg)
|
|
}
|
|
// IP 白名单拒绝 → 2(IP 维度并入鉴权失败)
|
|
a, u, _ = mk(func(u *entity.AccountUser, c *entity.AccountConfig) {
|
|
u.IPBind = `["10.1.1.1"]`
|
|
})
|
|
if _, code, _ := a.Authenticate(context.Background(), u, now, signFor(u, now, md5Hex(testSecret)), "192.168.1.9"); code != CodeAuthFail {
|
|
t.Fatalf("白名单拒绝 code=%d 期望 2", code)
|
|
}
|
|
// 白名单命中 → 放行
|
|
if _, code, _ := a.Authenticate(context.Background(), u, now, signFor(u, now, md5Hex(testSecret)), "10.1.1.1"); code != CodeOK {
|
|
t.Fatalf("白名单命中 code=%d 期望 0", code)
|
|
}
|
|
}
|
|
|
|
// ---- sendMessageMass ----
|
|
|
|
func TestSendMassOKAndPassthrough(t *testing.T) {
|
|
db := newTestDB(t)
|
|
mkAccount(t, db, 1, nil)
|
|
svc, a := newSvc(t, db)
|
|
auth := authed(t, a, "user1")
|
|
future := time.Now().Add(2 * time.Hour).Format("2006-01-02 15:04:05")
|
|
resp := svc.SendMass(context.Background(), auth, &MassReq{
|
|
PhoneList: []string{"13800138000", "13800138001"},
|
|
Content: "【测试】验证码123", SendTime: future,
|
|
ExtCode: "6688", CallData: "order-9527",
|
|
}, "10.2.3.4")
|
|
if resp.Code != CodeOK || resp.SmsCount != 2 || resp.MsgID == 0 || resp.TaskNo == "" {
|
|
t.Fatalf("resp=%+v", resp)
|
|
}
|
|
// 定时+透传落库校验
|
|
var task entity.MessageTask
|
|
if err := db.First(&task, resp.MsgID).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if task.SendType != 3 || task.ScheduleAt == nil || task.CallData != "order-9527" || task.MobileCount != 2 {
|
|
t.Fatalf("task 落库不符: type=%d schedule=%v callData=%q", task.SendType, task.ScheduleAt, task.CallData)
|
|
}
|
|
var details []entity.MessageDetail
|
|
db.Where("task_id = ?", task.ID).Find(&details)
|
|
if len(details) != 2 || details[0].ExtCode != "6688" || details[0].CallData != "order-9527" {
|
|
t.Fatalf("detail 透传缺失: n=%d ext=%q call=%q", len(details), details[0].ExtCode, details[0].CallData)
|
|
}
|
|
}
|
|
|
|
func TestSendMassValidationCodes(t *testing.T) {
|
|
db := newTestDB(t)
|
|
mkAccount(t, db, 1, nil)
|
|
svc, a := newSvc(t, db)
|
|
auth := authed(t, a, "user1")
|
|
ctx := context.Background()
|
|
cases := []struct {
|
|
name string
|
|
req *MassReq
|
|
want int
|
|
}{
|
|
{"空号码", &MassReq{Content: "x"}, CodeEmptyPhones},
|
|
{"空内容", &MassReq{PhoneList: []string{"13800138000"}}, CodeEmptyBody},
|
|
{"callData超长", &MassReq{PhoneList: []string{"13800138000"}, Content: "x", CallData: strings.Repeat("a", 65)}, CodeCallLong},
|
|
{"扩展码超长", &MassReq{PhoneList: []string{"13800138000"}, Content: "x", ExtCode: strings.Repeat("1", 33)}, CodeExtTooLong},
|
|
{"定时过去", &MassReq{PhoneList: []string{"13800138000"}, Content: "x", SendTime: "2020-01-01 00:00:00"}, CodeBadSchedule},
|
|
{"定时超15天", &MassReq{PhoneList: []string{"13800138000"}, Content: "x", SendTime: time.Now().Add(16 * 24 * time.Hour).Format("2006-01-02 15:04:05")}, CodeBadSchedule},
|
|
}
|
|
for _, tc := range cases {
|
|
if got := svc.SendMass(ctx, auth, tc.req, "1.1.1.1").Code; got != tc.want {
|
|
t.Fatalf("%s: code=%d 期望 %d", tc.name, got, tc.want)
|
|
}
|
|
}
|
|
// 号码超万 → 7
|
|
phones := make([]string, 10001)
|
|
for i := range phones {
|
|
phones[i] = "13800138000"
|
|
}
|
|
if got := svc.SendMass(ctx, auth, &MassReq{PhoneList: phones, Content: "x"}, "1.1.1.1").Code; got != CodeTooMany {
|
|
t.Fatalf("超万 code=%d 期望 7", got)
|
|
}
|
|
// 余额不足 → 99+余额文案(ISC:007 映射)
|
|
db.Model(&entity.AccountUser{}).Where("id = 1").Update("balance", 0)
|
|
if r := svc.SendMass(ctx, auth, &MassReq{PhoneList: []string{"13800138000"}, Content: "x"}, "1.1.1.1"); r.Code != CodeOther || !strings.Contains(r.Message, "余额不足") {
|
|
t.Fatalf("余额 resp=%+v", r)
|
|
}
|
|
}
|
|
|
|
// ---- sendMessageOne ----
|
|
|
|
func TestSendOneOK(t *testing.T) {
|
|
db := newTestDB(t)
|
|
mkAccount(t, db, 1, nil)
|
|
svc, a := newSvc(t, db)
|
|
auth := authed(t, a, "user1")
|
|
resp := svc.SendOne(context.Background(), auth, &OneReq{
|
|
PhoneList: []string{"13800138000", "13800138001"},
|
|
ContentList: []string{"【测试】A你好", "【测试】B你好"},
|
|
ExtCode: "77", CallData: "cd-1",
|
|
}, "1.1.1.1")
|
|
if resp.Code != CodeOK || resp.SmsCount != 2 {
|
|
t.Fatalf("resp=%+v", resp)
|
|
}
|
|
var details []entity.MessageDetail
|
|
db.Where("task_id = ?", resp.MsgID).Order("mobile").Find(&details)
|
|
if len(details) != 2 {
|
|
t.Fatalf("明细 n=%d", len(details))
|
|
}
|
|
// 逐号独立内容(SendType=2)+透传
|
|
if !strings.Contains(details[0].Content, "A你好") || !strings.Contains(details[1].Content, "B你好") {
|
|
t.Fatalf("独立内容错: %q / %q", details[0].Content, details[1].Content)
|
|
}
|
|
if details[0].ExtCode != "77" || details[0].CallData != "cd-1" {
|
|
t.Fatalf("透传缺失: %+v", details[0])
|
|
}
|
|
var task entity.MessageTask
|
|
db.First(&task, resp.MsgID)
|
|
if task.SendType != 2 {
|
|
t.Fatalf("个性任务 type=%d 期望 2", task.SendType)
|
|
}
|
|
}
|
|
|
|
func TestSendOneValidation(t *testing.T) {
|
|
db := newTestDB(t)
|
|
mkAccount(t, db, 1, nil)
|
|
svc, a := newSvc(t, db)
|
|
auth := authed(t, a, "user1")
|
|
ctx := context.Background()
|
|
if got := svc.SendOne(ctx, auth, &OneReq{PhoneList: []string{"13800138000"}}, "1.1.1.1").Code; got != CodeCountDiff {
|
|
t.Fatalf("数量不匹配 code=%d 期望 14", got)
|
|
}
|
|
if got := svc.SendOne(ctx, auth, &OneReq{}, "1.1.1.1").Code; got != CodeEmptyPhones {
|
|
t.Fatalf("空号码 code=%d 期望 6", got)
|
|
}
|
|
}
|
|
|
|
// TestSendMassSourcePassthrough Day 60:受理来源透传——HTTP API 缺省=1,
|
|
// auth.Source 由 access 协议接入注入(CMPP=2/SMPP=3),落 message_task.source。
|
|
func TestSendMassSourcePassthrough(t *testing.T) {
|
|
db := newTestDB(t)
|
|
mkAccount(t, db, 1, nil)
|
|
svc, a := newSvc(t, db)
|
|
auth := authed(t, a, "user1")
|
|
|
|
// HTTP API 直入(auth.Source 零值)→ 归一 API=1。
|
|
resp := svc.SendMass(context.Background(), auth, &MassReq{
|
|
PhoneList: []string{"13800138000"}, Content: "【测试】来源A",
|
|
}, "10.0.0.1")
|
|
if resp.Code != CodeOK {
|
|
t.Fatalf("API 提交 resp=%+v", resp)
|
|
}
|
|
var task entity.MessageTask
|
|
if err := db.First(&task, resp.MsgID).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if task.Source != send.TaskSourceAPI {
|
|
t.Fatalf("HTTP API source=%d, 期望 %d", task.Source, send.TaskSourceAPI)
|
|
}
|
|
|
|
// SMPP 协议接入(access.SubmitSM 注入 auth.Source=3)→ 透传落库。
|
|
authSMPP := *auth
|
|
authSMPP.Source = send.TaskSourceSMPP
|
|
resp2 := svc.SendMass(context.Background(), &authSMPP, &MassReq{
|
|
PhoneList: []string{"13800138002"}, Content: "【测试】来源S",
|
|
}, "protocol")
|
|
if resp2.Code != CodeOK {
|
|
t.Fatalf("SMPP 提交 resp=%+v", resp2)
|
|
}
|
|
var task2 entity.MessageTask
|
|
if err := db.First(&task2, resp2.MsgID).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if task2.Source != send.TaskSourceSMPP {
|
|
t.Fatalf("SMPP source=%d, 期望 %d", task2.Source, send.TaskSourceSMPP)
|
|
}
|
|
}
|