增加七牛回调配置与签名验签能力

This commit is contained in:
hello-dd-code
2026-02-28 16:43:54 +08:00
parent 016c47ba75
commit 37868e6654
4 changed files with 176 additions and 1 deletions
+65 -1
View File
@@ -9,6 +9,7 @@ import (
"encoding/json"
"errors"
"fmt"
"net/http"
"path"
"regexp"
"strings"
@@ -18,7 +19,9 @@ import (
)
var (
ErrQiniuNotConfigured = errors.New("qiniu is not configured")
ErrQiniuNotConfigured = errors.New("qiniu is not configured")
ErrQiniuCallbackUnauthorized = errors.New("qiniu callback unauthorized")
ErrQiniuCallbackInvalidHeader = errors.New("qiniu callback authorization header is invalid")
)
type QiniuService struct {
@@ -79,6 +82,19 @@ func (s *QiniuService) CreateUploadToken(miniProgramID uint, userID uint, filena
// 上传完成后返回给前端的 JSON(七牛会做变量替换)
"returnBody": `{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"mimeType":"$(mimeType)"}`,
}
if callbackURL := strings.TrimSpace(s.cfg.CallbackURL); callbackURL != "" {
putPolicy["callbackUrl"] = callbackURL
callbackBody := strings.TrimSpace(s.cfg.CallbackBody)
if callbackBody == "" {
callbackBody = "key=$(key)&hash=$(etag)&fsize=$(fsize)&mimeType=$(mimeType)"
}
callbackBodyType := strings.TrimSpace(s.cfg.CallbackBodyType)
if callbackBodyType == "" {
callbackBodyType = "application/x-www-form-urlencoded"
}
putPolicy["callbackBody"] = callbackBody
putPolicy["callbackBodyType"] = callbackBodyType
}
policyJSON, err := json.Marshal(putPolicy)
if err != nil {
@@ -100,6 +116,54 @@ func (s *QiniuService) CreateUploadToken(miniProgramID uint, userID uint, filena
}, nil
}
func (s *QiniuService) VerifyCallbackSignature(req *http.Request, rawBody []byte) error {
if s.cfg.AccessKey == "" || s.cfg.SecretKey == "" {
return ErrQiniuNotConfigured
}
authHeader := strings.TrimSpace(req.Header.Get("Authorization"))
if authHeader == "" {
return ErrQiniuCallbackInvalidHeader
}
parts := strings.SplitN(authHeader, " ", 2)
if len(parts) != 2 {
return ErrQiniuCallbackInvalidHeader
}
scheme := strings.TrimSpace(parts[0])
if !strings.EqualFold(scheme, "QBox") {
// 七牛上传回调使用 QBox;其它 scheme 视为非法。
return ErrQiniuCallbackInvalidHeader
}
token := strings.TrimSpace(parts[1])
tokenParts := strings.SplitN(token, ":", 2)
if len(tokenParts) != 2 {
return ErrQiniuCallbackInvalidHeader
}
accessKey := strings.TrimSpace(tokenParts[0])
providedSign := strings.TrimSpace(tokenParts[1])
if accessKey == "" || providedSign == "" {
return ErrQiniuCallbackInvalidHeader
}
if accessKey != s.cfg.AccessKey {
return ErrQiniuCallbackUnauthorized
}
signing := req.URL.Path
if req.URL.RawQuery != "" {
signing += "?" + req.URL.RawQuery
}
signing += "\n"
signing += string(rawBody)
expected := urlSafeBase64NoPad(hmacSHA1([]byte(s.cfg.SecretKey), []byte(signing)))
if !hmac.Equal([]byte(providedSign), []byte(expected)) {
return ErrQiniuCallbackUnauthorized
}
return nil
}
func hmacSHA1(secret []byte, data []byte) []byte {
mac := hmac.New(sha1.New, secret)
mac.Write(data)
@@ -0,0 +1,98 @@
package service
import (
"encoding/base64"
"encoding/json"
"net/http/httptest"
"strings"
"testing"
"wx_service/config"
)
func TestCreateUploadTokenWithCallbackPolicy(t *testing.T) {
t.Parallel()
svc := NewQiniuService(config.QiniuConfig{
AccessKey: "ak-test",
SecretKey: "sk-test",
Bucket: "bucket-test",
UploadURL: "https://upload.qiniup.com",
KeyPrefix: "uploads/",
CallbackURL: "https://api.example.com/api/v1/common/upload/qiniu/callback",
CallbackBody: "key=$(key)&hash=$(etag)",
CallbackBodyType: "application/x-www-form-urlencoded",
})
token, err := svc.CreateUploadToken(1, 2, "avatar.png")
if err != nil {
t.Fatalf("CreateUploadToken: %v", err)
}
tokenParts := strings.Split(token.Token, ":")
if len(tokenParts) != 3 {
t.Fatalf("unexpected token format: %s", token.Token)
}
policyRaw, err := base64.URLEncoding.WithPadding(base64.NoPadding).DecodeString(tokenParts[2])
if err != nil {
t.Fatalf("decode policy: %v", err)
}
var policy map[string]any
if err := json.Unmarshal(policyRaw, &policy); err != nil {
t.Fatalf("unmarshal policy: %v", err)
}
if got, _ := policy["callbackUrl"].(string); got != "https://api.example.com/api/v1/common/upload/qiniu/callback" {
t.Fatalf("callbackUrl=%q, want callback endpoint", got)
}
if got, _ := policy["callbackBody"].(string); got != "key=$(key)&hash=$(etag)" {
t.Fatalf("callbackBody=%q, want callback body", got)
}
if got, _ := policy["callbackBodyType"].(string); got != "application/x-www-form-urlencoded" {
t.Fatalf("callbackBodyType=%q, want form type", got)
}
}
func TestVerifyCallbackSignature(t *testing.T) {
t.Parallel()
cfg := config.QiniuConfig{
AccessKey: "ak-test",
SecretKey: "sk-test",
}
svc := NewQiniuService(cfg)
body := []byte("key=uploads/test.png&hash=abc")
req := httptest.NewRequest("POST", "http://example.com/api/v1/common/upload/qiniu/callback?x=1", strings.NewReader(string(body)))
signing := req.URL.Path + "?" + req.URL.RawQuery + "\n" + string(body)
sign := urlSafeBase64NoPad(hmacSHA1([]byte(cfg.SecretKey), []byte(signing)))
req.Header.Set("Authorization", "QBox "+cfg.AccessKey+":"+sign)
if err := svc.VerifyCallbackSignature(req, body); err != nil {
t.Fatalf("VerifyCallbackSignature: %v", err)
}
}
func TestVerifyCallbackSignatureInvalid(t *testing.T) {
t.Parallel()
cfg := config.QiniuConfig{
AccessKey: "ak-test",
SecretKey: "sk-test",
}
svc := NewQiniuService(cfg)
body := []byte("key=uploads/test.png&hash=abc")
req := httptest.NewRequest("POST", "http://example.com/api/v1/common/upload/qiniu/callback", strings.NewReader(string(body)))
req.Header.Set("Authorization", "QBox ak-test:bad-sign")
err := svc.VerifyCallbackSignature(req, body)
if err == nil {
t.Fatalf("expected signature verification error")
}
if err != ErrQiniuCallbackUnauthorized {
t.Fatalf("error=%v, want=%v", err, ErrQiniuCallbackUnauthorized)
}
}