S1-B D4.2: B 层搬运 openapi(HTTP API appkey 三鉴权域;73.4% -race 绿)
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
// openapi/auth.go Day 46:MD5 验签(协议 §鉴权:sign=MD5(userName+timestamp+MD5(password)))。
|
||||
// 顺序:用户名→账号存在→状态→业务配置→IP 白名单→时间戳±5min→签名比对。
|
||||
package openapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/md5"
|
||||
"crypto/subtle"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"go-sms/internal/model/entity"
|
||||
"go-sms/internal/service/account"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// AuthWindow 验签时间戳窗口(秒)。
|
||||
const AuthWindow = 300
|
||||
|
||||
// AuthContext 验签通过后的账号上下文(注入 gin.Context 供限流/提交使用)。
|
||||
type AuthContext struct {
|
||||
AccountID int64
|
||||
Username string
|
||||
Config *entity.AccountConfig // speed_limit/ext_code/回调地址
|
||||
Source int8 // Day 60:受理来源打标(0→API;CMPP/SMPP 由 access 传入 2/3)
|
||||
}
|
||||
|
||||
// Authenticator 外部 API 鉴权器(db 只读)。
|
||||
type Authenticator struct{ db *gorm.DB }
|
||||
|
||||
// NewAuthenticator 构造。
|
||||
func NewAuthenticator(db *gorm.DB) *Authenticator { return &Authenticator{db: db} }
|
||||
|
||||
// Authenticate 验签:返回上下文或 (code!=0, message)。失败码:1/2/3/4/16。
|
||||
func (a *Authenticator) Authenticate(ctx context.Context, userName, timestamp, sign, clientIP string) (*AuthContext, int, string) {
|
||||
if userName == "" {
|
||||
return nil, CodeNoUser, DocMsg(CodeNoUser)
|
||||
}
|
||||
var u entity.AccountUser
|
||||
if err := a.db.WithContext(ctx).
|
||||
Where("username = ?", userName). // Model 含软删,gorm 自动过滤
|
||||
First(&u).Error; err != nil {
|
||||
return nil, CodeAuthFail, DocMsg(CodeAuthFail) // 账号不存在统一鉴权失败(不泄露存在性)
|
||||
}
|
||||
if u.Status != 1 {
|
||||
return nil, CodeDisabled, DocMsg(CodeDisabled)
|
||||
}
|
||||
var cfg entity.AccountConfig
|
||||
if err := a.db.WithContext(ctx).
|
||||
Where("account_id = ? AND business = ?", u.ID, "sms").
|
||||
First(&cfg).Error; err != nil {
|
||||
return nil, CodeNoBiz, DocMsg(CodeNoBiz)
|
||||
}
|
||||
// IP 白名单(空白名单=放行;复用 account.IPAllowed 同一实现,支持 a.b.c.* 通配)。
|
||||
if !account.IPAllowed(u.IPBind, clientIP) {
|
||||
return nil, CodeAuthFail, "鉴权失败:来源 IP 不在白名单"
|
||||
}
|
||||
// 时间戳窗口(秒级)。
|
||||
ts, err := strconv.ParseInt(timestamp, 10, 64)
|
||||
if err != nil || time.Now().Unix()-ts > AuthWindow || ts-time.Now().Unix() > AuthWindow {
|
||||
return nil, CodeStaleTS, DocMsg(CodeStaleTS)
|
||||
}
|
||||
// 签名(Day62 统一式「库值即密码」):expect=MD5(userName+timestamp+MD5(库值)),
|
||||
// 客户 password 直接填库值;存量 md5 态库值同式成立(客户改填库值即可,无需双算)。
|
||||
if cfg.ApiSecret == "" {
|
||||
return nil, CodeAuthFail, "鉴权失败:接口密钥未签发,请联系管理员开通"
|
||||
}
|
||||
expectInner := fmt.Sprintf("%x", md5.Sum([]byte(cfg.ApiSecret)))
|
||||
expect := fmt.Sprintf("%x", md5.Sum([]byte(userName+timestamp+expectInner)))
|
||||
if subtle.ConstantTimeCompare([]byte(expect), []byte(sign)) != 1 {
|
||||
return nil, CodeAuthFail, DocMsg(CodeAuthFail)
|
||||
}
|
||||
return &AuthContext{AccountID: u.ID, Username: u.Username, Config: &cfg}, CodeOK, ""
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
// Package openapi Day 46:外部 HTTP API 提交服务(SMS_HTTP_1.6 协议)。
|
||||
// 鉴权=MD5(userName+timestamp+MD5(secret)) ±5min 窗口;响应=文档码表(code/message/msgId/smsCount)。
|
||||
package openapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
errs "go-sms/internal/pkg/errors"
|
||||
)
|
||||
|
||||
// 协议状态码(SMS_HTTP_1.6.docx 响应码表)。
|
||||
const (
|
||||
CodeOK = 0 // 成功
|
||||
CodeNoUser = 1 // 用户名为空
|
||||
CodeAuthFail = 2 // 鉴权失败(密码错/签名不符/密钥未发)
|
||||
CodeDisabled = 3 // 账号禁用
|
||||
CodeNoBiz = 4 // 业务未开通
|
||||
CodeMissingArg = 5 // 缺少必要参数
|
||||
CodeEmptyPhones = 6 // 号码列表为空
|
||||
CodeTooMany = 7 // 号码数量超限
|
||||
CodeEmptyBody = 8 // 短信内容为空
|
||||
CodeExtTooLong = 9 // 扩展码超长
|
||||
CodeCallLong = 10 // callData 超长
|
||||
CodeNoPushURL = 11 // 推送地址未注册
|
||||
CodeBadSchedule = 12 // 定时时间不合法
|
||||
CodeNoTask = 13 // 任务ID不存在
|
||||
CodeCountDiff = 14 // 数量不匹配(个性列表)
|
||||
CodeOneTooMany = 15 // 个性内容条数超限
|
||||
CodeStaleTS = 16 // 时间戳失效(±5min 窗口外)
|
||||
CodeOther = 99 // 其他错误
|
||||
)
|
||||
|
||||
// docMsgs 协议码默认文案(与 docx 状态码表对齐)。
|
||||
var docMsgs = map[int]string{
|
||||
CodeOK: "成功",
|
||||
CodeNoUser: "用户名为空",
|
||||
CodeAuthFail: "鉴权失败",
|
||||
CodeDisabled: "账号禁用",
|
||||
CodeNoBiz: "业务未开通",
|
||||
CodeMissingArg: "缺少必要参数",
|
||||
CodeEmptyPhones: "号码列表为空",
|
||||
CodeTooMany: "号码数量超限",
|
||||
CodeEmptyBody: "短信内容为空",
|
||||
CodeExtTooLong: "扩展码超长",
|
||||
CodeCallLong: "callData 超长",
|
||||
CodeNoPushURL: "推送地址未注册",
|
||||
CodeBadSchedule: "定时时间不合法",
|
||||
CodeNoTask: "任务ID不存在",
|
||||
CodeCountDiff: "数量不匹配",
|
||||
CodeOneTooMany: "个性内容条数超限",
|
||||
CodeStaleTS: "时间戳失效",
|
||||
CodeOther: "其他错误",
|
||||
}
|
||||
|
||||
// DocMsg 协议码默认文案。
|
||||
func DocMsg(code int) string { return docMsgs[code] }
|
||||
|
||||
// MapErr 内部错误 → 协议码(余额不足等业务拒绝带原始中文说明,便于客户端定位)。
|
||||
func MapErr(err error) (int, string) {
|
||||
if err == nil {
|
||||
return CodeOK, DocMsg(CodeOK)
|
||||
}
|
||||
var e *errs.Error
|
||||
if errors.As(err, &e) {
|
||||
switch e.Code {
|
||||
case errs.Arrears.Code: // ISC:007 余额不足
|
||||
return CodeOther, "余额不足:" + e.Msg
|
||||
case errs.InvalidParam.Code: // ISC:400 参数类(提交校验细节)
|
||||
return CodeMissingArg, e.Msg
|
||||
}
|
||||
}
|
||||
return CodeOther, DocMsg(CodeOther)
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
// openapi/service.go Day 46:外部 API 提交(sendMessageMass/sendMessageOne)。
|
||||
// 校验→send.Submit/SubmitPersonal 复用内部链(余额/审核分流/雪花明细)→sms-submit 事件投递。
|
||||
package openapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go-sms/internal/model/entity"
|
||||
"go-sms/internal/service/send"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// MaxScheduleAhead 定时最远时限(天)。
|
||||
const MaxScheduleAhead = 15 * 24 * time.Hour
|
||||
|
||||
// EventProducer 事件投递接口(*queue.Producer 实现;nil=降级只落库)。
|
||||
type EventProducer interface {
|
||||
Send(topic string, key, value []byte) error
|
||||
}
|
||||
|
||||
// Service 外部 API 提交服务。
|
||||
type Service struct {
|
||||
db *gorm.DB
|
||||
submit *send.SubmitService
|
||||
producer EventProducer
|
||||
}
|
||||
|
||||
// NewService 构造(producer 可 nil:Kafka 不可用时仅落库,发送由定时调度器 DB 认领兜底)。
|
||||
func NewService(db *gorm.DB, submit *send.SubmitService, producer EventProducer) *Service {
|
||||
return &Service{db: db, submit: submit, producer: producer}
|
||||
}
|
||||
|
||||
// Resp 协议响应(与 docx 示例对齐:code/message/msgId/smsCount)。
|
||||
type Resp struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
MsgID int64 `json:"msgId,omitempty"`
|
||||
SmsCount int `json:"smsCount,omitempty"`
|
||||
TaskNo string `json:"taskNo,omitempty"`
|
||||
}
|
||||
|
||||
// okResp 成功响应(附带任务号,便于客户端查单)。
|
||||
func okResp(task *entity.MessageTask) *Resp {
|
||||
return &Resp{Code: CodeOK, Message: DocMsg(CodeOK),
|
||||
MsgID: task.ID, SmsCount: task.MobileCount, TaskNo: task.TaskNo}
|
||||
}
|
||||
|
||||
// failResp 失败响应(空 msg 用码表默认文案)。
|
||||
func failResp(code int, msg string) *Resp {
|
||||
if msg == "" {
|
||||
msg = DocMsg(code)
|
||||
}
|
||||
return &Resp{Code: code, Message: msg}
|
||||
}
|
||||
|
||||
// MassReq sendMessageMass 请求(docx 字段名 camelCase)。
|
||||
type MassReq struct {
|
||||
UserName string `json:"userName"`
|
||||
Timestamp string `json:"timestamp"`
|
||||
Sign string `json:"sign"`
|
||||
PhoneList []string `json:"phoneList"`
|
||||
Content string `json:"content"`
|
||||
TemplateID string `json:"templateId"`
|
||||
SignName string `json:"signName"`
|
||||
SendTime string `json:"sendTime"`
|
||||
ExtCode string `json:"extCode"`
|
||||
CallData string `json:"callData"`
|
||||
Business string `json:"business"` // Day 49:sms(默认)/video 视频短信
|
||||
PresetMsgID int64 `json:"-"` // 内部:长短信聚合组ID 预置首条 DetailID(0=雪花默认;不收外部输入)
|
||||
// Day 70:计费口径分流(内部,不收外部输入)——fee≡上游真实片数。
|
||||
ContentEncoding int8 `json:"-"` // 0=默认 GBK 口径;1=UCS2(CMPP MsgFmt=8)
|
||||
FeeSegments int `json:"-"` // 段数覆写(入向长短信聚合=客户端 pk_total;0=按口径计算)
|
||||
}
|
||||
|
||||
// OneReq sendMessageOne 请求(phoneList 与 contentList 等长逐号配对)。
|
||||
type OneReq struct {
|
||||
UserName string `json:"userName"`
|
||||
Timestamp string `json:"timestamp"`
|
||||
Sign string `json:"sign"`
|
||||
PhoneList []string `json:"phoneList"`
|
||||
ContentList []string `json:"contentList"`
|
||||
SignName string `json:"signName"`
|
||||
SendTime string `json:"sendTime"`
|
||||
ExtCode string `json:"extCode"`
|
||||
CallData string `json:"callData"`
|
||||
}
|
||||
|
||||
// SendMass 群发提交(鉴权已由中间件完成,auth 注入账号上下文)。
|
||||
func (s *Service) SendMass(ctx context.Context, auth *AuthContext, req *MassReq, clientIP string) *Resp {
|
||||
sub, content, code, msg := s.buildMassSubmit(ctx, auth, req)
|
||||
if code != CodeOK {
|
||||
return failResp(code, msg)
|
||||
}
|
||||
res, err := s.submit.Submit(ctx, sub, nil, content, clientIP)
|
||||
if err != nil {
|
||||
c, m := MapErr(err)
|
||||
return failResp(c, m)
|
||||
}
|
||||
return okResp(res.Task)
|
||||
}
|
||||
|
||||
// NextMsgID 预生成雪花 MsgID(转发 send;接入层长短信聚合组ID 用)。
|
||||
func (s *Service) NextMsgID() int64 { return s.submit.NextMsgID() }
|
||||
|
||||
// SendMassFast P0-1(Day 63)接入快路径(CMPP access 专用):SubmitFast
|
||||
// 零 DB 写(Validate+Redis 预扣+DetailID 预生成+Deferred 事件),拦截/落库/
|
||||
// 审核/退费移消费侧补全;欠费为唯一同步拒绝,其余语义经 CMPP 状态回执告知。
|
||||
// Resp.MsgID=DetailID 雪花——与 Deliver msg_id 同口径(修复旧路径 task.ID
|
||||
// 口径不一致:客户端拿 resp.MsgID 配不上回执)。
|
||||
func (s *Service) SendMassFast(ctx context.Context, auth *AuthContext, req *MassReq, clientIP string) *Resp {
|
||||
sub, content, code, msg := s.buildMassSubmit(ctx, auth, req)
|
||||
if code != CodeOK {
|
||||
return failResp(code, msg)
|
||||
}
|
||||
res, err := s.submit.SubmitFast(ctx, sub, content, clientIP)
|
||||
if err != nil {
|
||||
c, m := MapErr(err)
|
||||
return failResp(c, m)
|
||||
}
|
||||
return &Resp{Code: CodeOK, Message: DocMsg(CodeOK),
|
||||
MsgID: res.MsgID, SmsCount: len(req.PhoneList), TaskNo: res.TaskNo}
|
||||
}
|
||||
|
||||
// buildMassSubmit SendMass/SendMassFast 共用前段:公共校验+模板解析+定时解析
|
||||
// (返回 nil content=校验失败,code/msg 为失败码)。
|
||||
func (s *Service) buildMassSubmit(ctx context.Context, auth *AuthContext, req *MassReq) (*send.SubmitReq, string, int, string) {
|
||||
if code, msg := validateCommon(req.ExtCode, req.CallData); code != CodeOK {
|
||||
return nil, "", code, msg
|
||||
}
|
||||
if len(req.PhoneList) == 0 {
|
||||
return nil, "", CodeEmptyPhones, ""
|
||||
}
|
||||
if len(req.PhoneList) > send.MaxMobiles {
|
||||
return nil, "", CodeTooMany, ""
|
||||
}
|
||||
content := req.Content
|
||||
if content == "" && req.TemplateID != "" {
|
||||
tpl := s.loadTemplate(ctx, auth.AccountID, req.TemplateID)
|
||||
if tpl == nil {
|
||||
return nil, "", CodeMissingArg, "模板不存在或未过审"
|
||||
}
|
||||
content = tpl.Content
|
||||
}
|
||||
if strings.TrimSpace(content) == "" {
|
||||
return nil, "", CodeEmptyBody, ""
|
||||
}
|
||||
scheduleAt, code, msg := parseSendTime(req.SendTime)
|
||||
if code != CodeOK {
|
||||
return nil, "", code, msg
|
||||
}
|
||||
sub := &send.SubmitReq{
|
||||
AccountID: auth.AccountID,
|
||||
SendType: send.SendTypeBatch,
|
||||
Mobiles: req.PhoneList,
|
||||
Content: content,
|
||||
Sign: req.SignName,
|
||||
Extend: req.ExtCode,
|
||||
CallData: req.CallData,
|
||||
Business: req.Business, // Day 49:sms/video(空由 Validate 规范化为 sms)
|
||||
Source: send.NormalizeTaskSource(auth.Source), // Day 60:受理来源(HTTP API=1;CMPP/SMPP 由 access 传 2/3)
|
||||
PresetMsgID: req.PresetMsgID, // 长短信聚合组ID 透传(0=默认雪花)
|
||||
ContentEncoding: req.ContentEncoding, // Day 70:计费口径分流(CMPP MsgFmt=8→UCS2)
|
||||
FeeSegments: req.FeeSegments, // Day 70:段数覆写(聚合=客户端 pk_total)
|
||||
}
|
||||
if scheduleAt != nil {
|
||||
sub.SendType = send.SendTypeTimer
|
||||
sub.SendAt = scheduleAt.Format("2006-01-02 15:04")
|
||||
}
|
||||
return sub, content, CodeOK, ""
|
||||
}
|
||||
|
||||
// SendOne 个性提交(phoneList/contentList 逐号配对,单次≤1000)。
|
||||
func (s *Service) SendOne(ctx context.Context, auth *AuthContext, req *OneReq, clientIP string) *Resp {
|
||||
if code, msg := validateCommon(req.ExtCode, req.CallData); code != CodeOK {
|
||||
return failResp(code, msg)
|
||||
}
|
||||
if len(req.PhoneList) == 0 {
|
||||
return failResp(CodeEmptyPhones, "")
|
||||
}
|
||||
if len(req.PhoneList) != len(req.ContentList) {
|
||||
return failResp(CodeCountDiff, "")
|
||||
}
|
||||
if len(req.ContentList) > send.MaxPersonalItems {
|
||||
return failResp(CodeOneTooMany, "")
|
||||
}
|
||||
for _, c := range req.ContentList {
|
||||
if strings.TrimSpace(c) == "" {
|
||||
return failResp(CodeEmptyBody, "")
|
||||
}
|
||||
}
|
||||
scheduleAt, code, msg := parseSendTime(req.SendTime)
|
||||
if code != CodeOK {
|
||||
return failResp(code, msg)
|
||||
}
|
||||
items := make([]send.PersonalItem, 0, len(req.PhoneList))
|
||||
for i, m := range req.PhoneList {
|
||||
items = append(items, send.PersonalItem{Mobile: m, Content: req.ContentList[i]})
|
||||
}
|
||||
res, err := s.submit.SubmitPersonal(ctx, auth.AccountID, items, scheduleAt, req.ExtCode, req.CallData, clientIP,
|
||||
send.NormalizeTaskSource(auth.Source)) // Day 60:受理来源打标
|
||||
if err != nil {
|
||||
c, m := MapErr(err)
|
||||
return failResp(c, m)
|
||||
}
|
||||
return okResp(res.Task)
|
||||
}
|
||||
|
||||
// validateCommon 扩展码/callData 长度校验(9/10)。
|
||||
func validateCommon(extCode, callData string) (int, string) {
|
||||
if len(extCode) > 32 {
|
||||
return CodeExtTooLong, ""
|
||||
}
|
||||
if len(callData) > 64 {
|
||||
return CodeCallLong, ""
|
||||
}
|
||||
return CodeOK, ""
|
||||
}
|
||||
|
||||
// parseSendTime 定时解析(docx yyyy-MM-dd HH:mm:ss;过去/超 15 天→12;空=立即)。
|
||||
func parseSendTime(v string) (*time.Time, int, string) {
|
||||
v = strings.TrimSpace(v)
|
||||
if v == "" {
|
||||
return nil, CodeOK, ""
|
||||
}
|
||||
at, err := time.ParseInLocation("2006-01-02 15:04:05", v, time.Local)
|
||||
if err != nil {
|
||||
at, err = time.ParseInLocation("2006-01-02 15:04", v, time.Local) // 兼容分钟精度
|
||||
if err != nil {
|
||||
return nil, CodeBadSchedule, "sendTime 格式须为 yyyy-MM-dd HH:mm:ss"
|
||||
}
|
||||
}
|
||||
now := time.Now()
|
||||
if !at.After(now) {
|
||||
return nil, CodeBadSchedule, "定时时刻须在未来"
|
||||
}
|
||||
if at.Sub(now) > MaxScheduleAhead {
|
||||
return nil, CodeBadSchedule, "定时时刻不能超过 15 天"
|
||||
}
|
||||
return &at, CodeOK, ""
|
||||
}
|
||||
|
||||
// loadTemplate 加载本账号可用模板(通过态;不存在/未过审/越权均 nil)。
|
||||
func (s *Service) loadTemplate(ctx context.Context, accountID int64, idStr string) *entity.TemplateSMS {
|
||||
id, err := strconv.ParseInt(strings.TrimSpace(idStr), 10, 64)
|
||||
if err != nil || id <= 0 {
|
||||
return nil
|
||||
}
|
||||
var tpl entity.TemplateSMS
|
||||
if err := s.db.WithContext(ctx).
|
||||
Where("id = ? AND account_id = ? AND status = 1", id, accountID).
|
||||
First(&tpl).Error; err != nil {
|
||||
return nil
|
||||
}
|
||||
return &tpl
|
||||
}
|
||||
Reference in New Issue
Block a user