datasignMiddleware.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. package middleware
  2. import (
  3. "GtDataStore/app/cmd/dtgateway/internal/config"
  4. "GtDataStore/app/model"
  5. "GtDataStore/common/crypto/md5"
  6. "GtDataStore/common/utils"
  7. "GtDataStore/common/xerr"
  8. "bytes"
  9. "context"
  10. "fmt"
  11. "github.com/zeromicro/go-zero/core/stores/sqlx"
  12. "github.com/zeromicro/go-zero/rest/httpx"
  13. "io/ioutil"
  14. "k8s.io/apimachinery/pkg/util/json"
  15. "net/http"
  16. "net/url"
  17. "sync"
  18. "time"
  19. )
  20. const (
  21. TIME_OUT = 10 // ts时间窗口大小, 单位: 秒
  22. S2_MIN_LENGTH = 2048
  23. S2_HEAD_LENGTH = 200
  24. S2_TAIL_LENGTH = 200
  25. APP_SECRET_CACHE_EXPIRE = 600
  26. )
  27. var (
  28. appSecrets = make(map[string]secretExpire)
  29. appSecretsLock sync.Mutex
  30. )
  31. type (
  32. secretExpire struct {
  33. Secret string
  34. Status int64
  35. Expire time.Time
  36. }
  37. DataSignMiddleware struct {
  38. AppInfo model.DcAppInfoModel
  39. }
  40. CommonParams struct {
  41. Ts int64 `form:"ts"`
  42. ProjectId int64 `form:"project_id"`
  43. Sign string `form:"sign"`
  44. SignFlag uint8 `form:"sign_flag,optional"`
  45. AppName string `header:"APP-NAME"`
  46. }
  47. )
  48. func NewDataSignMiddleware(conf config.Config) *DataSignMiddleware {
  49. mysql := sqlx.NewMysql(conf.DtDataStoreDB.DataSource)
  50. return &DataSignMiddleware{
  51. AppInfo: model.NewDcAppInfoModel(mysql),
  52. }
  53. }
  54. func (m *DataSignMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
  55. return func(w http.ResponseWriter, r *http.Request) {
  56. cps := CommonParams{}
  57. err := httpx.Parse(r, &cps)
  58. if err != nil {
  59. httpx.WriteJson(w, http.StatusOK, map[string]interface{}{
  60. "code": xerr.REUQEST_PARAM_ERROR,
  61. "msg": err.Error(),
  62. })
  63. return
  64. }
  65. // 验证时间窗口
  66. if m.checkTs(cps.Ts) == false {
  67. httpx.WriteJson(w, http.StatusOK, map[string]interface{}{
  68. "code": xerr.REUQEST_PARAM_TS_ERROR,
  69. "msg": "请求参数错误",
  70. })
  71. return
  72. }
  73. // 得到secret, 如果发生错误, 则响应失败
  74. appSecret, err := m.getAppSecret(cps.AppName)
  75. if err != nil {
  76. httpx.WriteJson(w, http.StatusOK, map[string]interface{}{
  77. "code": xerr.REUQEST_PARAM_APP_NAME_ERROR,
  78. "msg": err.Error(),
  79. })
  80. return
  81. }
  82. // 解析query, 得到sign和s1
  83. s1, err := m.parseQuery(r)
  84. if err != nil {
  85. fmt.Printf("m.parseQuery(r) error :s\n", err.Error())
  86. }
  87. s2, err := m.parseBody(r)
  88. if err != nil {
  89. fmt.Printf("m.parseBody(r) error :s\n", err.Error())
  90. }
  91. s3 := r.ContentLength
  92. csign := m.calcSign(s1, s2, appSecret, s3, cps.SignFlag)
  93. if csign != cps.Sign {
  94. httpx.WriteJson(w, http.StatusOK, map[string]interface{}{
  95. "code": xerr.REUQEST_PARAM_DATA_SIGN_ERROR,
  96. "msg": "未通过数据认证",
  97. })
  98. return
  99. }
  100. next(w, r)
  101. }
  102. }
  103. func (m *DataSignMiddleware) calcSign(s1, s2, appSecret string, s3 int64, signFlag uint8) string {
  104. // 处理s2
  105. if signFlag == 1 {
  106. s2 = m.cutS2(s2)
  107. } else {
  108. s2, _ = m.sortS2(s2)
  109. }
  110. //fmt.Printf("sign data: %s\n", fmt.Sprintf("%s%s%d%s", s1, s2, s3, appSecret))
  111. //fmt.Printf("md5: %s\n", md5.Md5([]byte(fmt.Sprintf("%s%s%d%s", s1, s2, s3, appSecret))))
  112. return md5.Md5([]byte(fmt.Sprintf("%s%s%d%s", s1, s2, s3, appSecret)))
  113. }
  114. func (m *DataSignMiddleware) cutS2(s2 string) string {
  115. s2l := len(s2)
  116. if s2l <= S2_MIN_LENGTH {
  117. return s2
  118. }
  119. return fmt.Sprintf("%s%s", s2[:S2_HEAD_LENGTH], s2[s2l-S2_TAIL_LENGTH:])
  120. }
  121. func (m *DataSignMiddleware) sortS2(s2 string) (string, error) {
  122. var mi map[string]interface{}
  123. if err := json.Unmarshal([]byte(s2), &mi); err != nil {
  124. return "", err
  125. }
  126. smi := utils.SortMapByKey(mi)
  127. if bs, err := json.Marshal(smi); err != nil {
  128. return "", err
  129. } else {
  130. return string(bs), nil
  131. }
  132. }
  133. func (m *DataSignMiddleware) parseBody(r *http.Request) (body string, err error) {
  134. if r.Method == http.MethodGet {
  135. return "", nil
  136. }
  137. cnt, _ := ioutil.ReadAll(r.Body)
  138. r.Body = ioutil.NopCloser(bytes.NewReader(cnt))
  139. return string(cnt), nil
  140. }
  141. func (m *DataSignMiddleware) parseQuery(r *http.Request) (query string, err error) {
  142. if vs, err := url.ParseQuery(r.URL.RawQuery); err != nil {
  143. return "", err
  144. } else {
  145. vs.Del("sign")
  146. return vs.Encode(), nil
  147. }
  148. }
  149. func (m *DataSignMiddleware) getAppSecret(appName string) (string, error) {
  150. if secret, ok := appSecrets[appName]; ok {
  151. if secret.Expire.After(time.Now()) == false {
  152. return secret.Secret, nil
  153. }
  154. }
  155. // 从数据库中读取appSecret
  156. if appInfo, err := m.AppInfo.FindOneByAppName(context.Background(), appName); err == nil {
  157. appSecretsLock.Lock()
  158. defer appSecretsLock.Unlock()
  159. appSecrets[appName] = secretExpire{
  160. Secret: appInfo.Secret,
  161. Status: appInfo.Status,
  162. Expire: time.Now().Add(APP_SECRET_CACHE_EXPIRE * time.Second),
  163. }
  164. if appInfo.Status == 0 {
  165. return appInfo.Secret, nil
  166. }
  167. }
  168. return "", xerr.NewErrCodeMsg(xerr.REUQEST_PARAM_APP_NAME_ERROR, "该app name错误, 无法进行数据验签")
  169. }
  170. func (m *DataSignMiddleware) checkTs(ts int64) bool {
  171. return time.Now().Unix()-ts <= TIME_OUT
  172. }