diff --git a/.env.example b/.env.example index 5076afe..e840eb7 100755 --- a/.env.example +++ b/.env.example @@ -55,6 +55,13 @@ QINIU_CDN_DOMAIN= QINIU_KEY_PREFIX=uploads/ # token 有效期(秒) QINIU_TOKEN_EXPIRE_SECONDS=300 +# 上传回调地址(可选):配置后,七牛上传成功会回调该地址 +# 示例: https://api.example.com/api/v1/common/upload/qiniu/callback +QINIU_CALLBACK_URL= +# 回调内容模板(可选) +QINIU_CALLBACK_BODY=key=$(key)&hash=$(etag)&fsize=$(fsize)&mimeType=$(mimeType) +# 回调内容类型(可选) +QINIU_CALLBACK_BODY_TYPE=application/x-www-form-urlencoded # 微信公众号(网页授权 OAuth2) WECHAT_OA_APP_ID=replace-with-oa-appid diff --git a/config/config.go b/config/config.go index 41a3812..8679776 100755 --- a/config/config.go +++ b/config/config.go @@ -79,6 +79,9 @@ type QiniuConfig struct { CDNDomain string KeyPrefix string TokenExpireSeconds int + CallbackURL string + CallbackBody string + CallbackBodyType string } // WeChatOfficialConfig 用于微信公众号网页授权(OAuth2)相关接口。 @@ -152,6 +155,9 @@ func LoadConfig() { CDNDomain: getEnv("QINIU_CDN_DOMAIN", ""), KeyPrefix: getEnv("QINIU_KEY_PREFIX", "uploads/"), TokenExpireSeconds: getEnvAsInt("QINIU_TOKEN_EXPIRE_SECONDS", 300), + CallbackURL: getEnv("QINIU_CALLBACK_URL", ""), + CallbackBody: getEnv("QINIU_CALLBACK_BODY", "key=$(key)&hash=$(etag)&fsize=$(fsize)&mimeType=$(mimeType)"), + CallbackBodyType: getEnv("QINIU_CALLBACK_BODY_TYPE", "application/x-www-form-urlencoded"), }, WeChatOA: WeChatOfficialConfig{ AppID: getEnv("WECHAT_OA_APP_ID", ""), diff --git a/internal/common/qiniu/service/qiniu_service.go b/internal/common/qiniu/service/qiniu_service.go index 4d5a6da..a02d169 100644 --- a/internal/common/qiniu/service/qiniu_service.go +++ b/internal/common/qiniu/service/qiniu_service.go @@ -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) diff --git a/internal/common/qiniu/service/qiniu_service_test.go b/internal/common/qiniu/service/qiniu_service_test.go new file mode 100644 index 0000000..79c5f83 --- /dev/null +++ b/internal/common/qiniu/service/qiniu_service_test.go @@ -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) + } +}