Files
go-sms-V2/internal/service/interceptor/sign.go
T

71 lines
2.0 KiB
Go

// sign.go Day 42:签名拦截——Day41 验收二变(内容=签名+正文一体)后,
// 从内容提取首个【】签名校验存在性;账号白名单(报备)接入后校验归属。
package interceptor
import (
"context"
"strings"
errs "go-sms/internal/pkg/errors"
)
// SignAllowlist 账号签名白名单(签名报备审核通过后写入;nil=平台不限制)。
type SignAllowlist interface {
AllowedSigns(ctx context.Context, accountID int64) ([]string, error)
}
// Sign 签名拦截器。
type Sign struct {
Allow SignAllowlist // 可 nil
}
// NewSign 构造。
func NewSign(allow SignAllowlist) *Sign { return &Sign{Allow: allow} }
// Name 拦截器名。
func (s *Sign) Name() string { return "sign" }
// ExtractSign 提取内容首个【】签名(无则空串;与 FE mergeSign/后端口径一致——内容自带)。
func ExtractSign(content string) string {
const l = len("【") // UTF-8 3 字节
i := strings.Index(content, "【")
if i < 0 {
return ""
}
j := strings.Index(content[i+l:], "】")
if j <= 0 { // 空签名【】或未闭合
return ""
}
return content[i+l : i+l+j]
}
// Check 内容须含【】签名;配置白名单时签名须在列。
func (s *Sign) Check(ctx context.Context, r *Req) *Block {
sign := ExtractSign(r.Content)
if sign == "" {
e := errs.SignatureInvalid.WithMsg("内容缺少【】签名(签名+正文一体)")
return &Block{Interceptor: s.Name(), Code: e.Code, Msg: e.Msg, HTTP: e}
}
if s != nil && s.Allow != nil {
// Day51 R3:账号级签名白名单经请求级快照缓存(批量内只查一次)。
allowed := r.Scope.AllowedSigns(func() []string {
a, err := s.Allow.AllowedSigns(ctx, r.AccountID)
if err != nil {
return nil
}
return a
})
if len(allowed) > 0 {
for _, a := range allowed {
if a == sign {
return nil
}
}
e := errs.SignatureInvalid.WithMsg("签名未报备: " + sign)
return &Block{Interceptor: s.Name(), Code: e.Code, Msg: e.Msg, HTTP: e}
}
}
return nil
}