You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

aws_auth.go 8.1 kB

10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. package http
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/sha256"
  6. "encoding/hex"
  7. "fmt"
  8. "io"
  9. "net/http"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "github.com/aws/aws-sdk-go-v2/aws"
  14. v4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4"
  15. "github.com/aws/aws-sdk-go-v2/credentials"
  16. "github.com/gin-gonic/gin"
  17. "gitlink.org.cn/cloudream/common/consts/errorcode"
  18. "gitlink.org.cn/cloudream/common/pkgs/logger"
  19. "gitlink.org.cn/cloudream/storage/client/internal/config"
  20. )
  21. const (
  22. AuthRegion = "any"
  23. AuthService = "jcs"
  24. AuthorizationHeader = "Authorization"
  25. )
  26. type AWSAuth struct {
  27. cred aws.Credentials
  28. signer *v4.Signer
  29. }
  30. func NewAWSAuth(accessKey string, secretKey string) (*AWSAuth, error) {
  31. prod := credentials.NewStaticCredentialsProvider(accessKey, secretKey, "")
  32. cred, err := prod.Retrieve(context.TODO())
  33. if err != nil {
  34. return nil, err
  35. }
  36. return &AWSAuth{
  37. cred: cred,
  38. signer: v4.NewSigner(),
  39. }, nil
  40. }
  41. func (a *AWSAuth) Auth(c *gin.Context) {
  42. authorizationHeader := c.GetHeader(AuthorizationHeader)
  43. if authorizationHeader == "" {
  44. c.AbortWithStatusJSON(http.StatusBadRequest, Failed(errorcode.Unauthorized, "authorization header is missing"))
  45. return
  46. }
  47. _, headers, reqSig, err := parseAuthorizationHeader(authorizationHeader)
  48. if err != nil {
  49. c.AbortWithStatusJSON(http.StatusBadRequest, Failed(errorcode.Unauthorized, "invalid Authorization header format"))
  50. return
  51. }
  52. // 限制请求体大小
  53. rd := io.LimitReader(c.Request.Body, config.Cfg().MaxHTTPBodySize)
  54. body, err := io.ReadAll(rd)
  55. if err != nil {
  56. c.AbortWithStatusJSON(http.StatusBadRequest, Failed(errorcode.BadArgument, "read request body failed"))
  57. return
  58. }
  59. payloadHash := sha256.Sum256(body)
  60. hexPayloadHash := hex.EncodeToString(payloadHash[:])
  61. // 构造验签用的请求
  62. verifyReq, err := http.NewRequest(c.Request.Method, c.Request.URL.String(), nil)
  63. if err != nil {
  64. c.AbortWithStatusJSON(http.StatusOK, Failed(errorcode.OperationFailed, err.Error()))
  65. return
  66. }
  67. for _, h := range headers {
  68. verifyReq.Header.Add(h, c.Request.Header.Get(h))
  69. }
  70. verifyReq.Host = c.Request.Host
  71. timestamp, err := time.Parse("20060102T150405Z", c.GetHeader("X-Amz-Date"))
  72. if err != nil {
  73. c.AbortWithStatusJSON(http.StatusBadRequest, Failed(errorcode.BadArgument, "invalid X-Amz-Date header format"))
  74. return
  75. }
  76. signer := v4.NewSigner()
  77. err = signer.SignHTTP(context.TODO(), a.cred, verifyReq, hexPayloadHash, AuthService, AuthRegion, timestamp)
  78. if err != nil {
  79. logger.Warnf("sign request: %v", err)
  80. c.AbortWithStatusJSON(http.StatusOK, Failed(errorcode.OperationFailed, "sign request failed"))
  81. return
  82. }
  83. verifySig := getSignatureFromAWSHeader(verifyReq)
  84. if !strings.EqualFold(verifySig, reqSig) {
  85. c.AbortWithStatusJSON(http.StatusOK, Failed(errorcode.Unauthorized, "signature mismatch"))
  86. return
  87. }
  88. c.Request.Body = io.NopCloser(bytes.NewReader(body))
  89. c.Next()
  90. }
  91. func (a *AWSAuth) AuthWithoutBody(c *gin.Context) {
  92. authorizationHeader := c.GetHeader(AuthorizationHeader)
  93. if authorizationHeader == "" {
  94. c.AbortWithStatusJSON(http.StatusBadRequest, Failed(errorcode.Unauthorized, "authorization header is missing"))
  95. return
  96. }
  97. _, headers, reqSig, err := parseAuthorizationHeader(authorizationHeader)
  98. if err != nil {
  99. c.AbortWithStatusJSON(http.StatusBadRequest, Failed(errorcode.Unauthorized, "invalid Authorization header format"))
  100. return
  101. }
  102. // 构造验签用的请求
  103. verifyReq, err := http.NewRequest(c.Request.Method, c.Request.URL.String(), nil)
  104. if err != nil {
  105. c.AbortWithStatusJSON(http.StatusOK, Failed(errorcode.OperationFailed, err.Error()))
  106. return
  107. }
  108. for _, h := range headers {
  109. verifyReq.Header.Add(h, c.Request.Header.Get(h))
  110. }
  111. verifyReq.Host = c.Request.Host
  112. timestamp, err := time.Parse("20060102T150405Z", c.GetHeader("X-Amz-Date"))
  113. if err != nil {
  114. c.AbortWithStatusJSON(http.StatusBadRequest, Failed(errorcode.BadArgument, "invalid X-Amz-Date header format"))
  115. return
  116. }
  117. err = a.signer.SignHTTP(context.TODO(), a.cred, verifyReq, "", AuthService, AuthRegion, timestamp)
  118. if err != nil {
  119. logger.Warnf("sign request: %v", err)
  120. c.AbortWithStatusJSON(http.StatusOK, Failed(errorcode.OperationFailed, "sign request failed"))
  121. return
  122. }
  123. verifySig := getSignatureFromAWSHeader(verifyReq)
  124. if strings.EqualFold(verifySig, reqSig) {
  125. c.AbortWithStatusJSON(http.StatusOK, Failed(errorcode.Unauthorized, "signature mismatch"))
  126. return
  127. }
  128. c.Next()
  129. }
  130. func (a *AWSAuth) PresignedAuth(c *gin.Context) {
  131. query := c.Request.URL.Query()
  132. signature := query.Get("X-Amz-Signature")
  133. query.Del("X-Amz-Signature")
  134. if signature == "" {
  135. c.AbortWithStatusJSON(http.StatusBadRequest, Failed(errorcode.BadArgument, "missing X-Amz-Signature query parameter"))
  136. return
  137. }
  138. // alg := c.Request.URL.Query().Get("X-Amz-Algorithm")
  139. // cred := c.Request.URL.Query().Get("X-Amz-Credential")
  140. date := query.Get("X-Amz-Date")
  141. expiresStr := query.Get("X-Expires")
  142. expires, err := strconv.ParseInt(expiresStr, 10, 64)
  143. if err != nil {
  144. c.AbortWithStatusJSON(http.StatusBadRequest, Failed(errorcode.BadArgument, "invalid X-Expires format"))
  145. return
  146. }
  147. signedHeaders := strings.Split(query.Get("X-Amz-SignedHeaders"), ";")
  148. c.Request.URL.RawQuery = query.Encode()
  149. verifyReq, err := http.NewRequest(c.Request.Method, c.Request.URL.String(), nil)
  150. if err != nil {
  151. c.AbortWithStatusJSON(http.StatusOK, Failed(errorcode.OperationFailed, err.Error()))
  152. return
  153. }
  154. for _, h := range signedHeaders {
  155. verifyReq.Header.Add(h, c.Request.Header.Get(h))
  156. }
  157. verifyReq.Host = c.Request.Host
  158. timestamp, err := time.Parse("20060102T150405Z", date)
  159. if err != nil {
  160. c.AbortWithStatusJSON(http.StatusBadRequest, Failed(errorcode.BadArgument, "invalid X-Amz-Date format"))
  161. return
  162. }
  163. if time.Now().After(timestamp.Add(time.Duration(expires) * time.Second)) {
  164. c.AbortWithStatusJSON(http.StatusUnauthorized, Failed(errorcode.Unauthorized, "request expired"))
  165. return
  166. }
  167. signer := v4.NewSigner()
  168. uri, _, err := signer.PresignHTTP(context.TODO(), a.cred, verifyReq, "", AuthService, AuthRegion, timestamp)
  169. if err != nil {
  170. c.AbortWithStatusJSON(http.StatusOK, Failed(errorcode.OperationFailed, "sign request failed"))
  171. return
  172. }
  173. verifySig := getSignatureFromAWSQuery(uri)
  174. if !strings.EqualFold(verifySig, signature) {
  175. c.AbortWithStatusJSON(http.StatusOK, Failed(errorcode.Unauthorized, "signature mismatch"))
  176. return
  177. }
  178. c.Next()
  179. }
  180. // 解析 Authorization 头部
  181. func parseAuthorizationHeader(authorizationHeader string) (string, []string, string, error) {
  182. if !strings.HasPrefix(authorizationHeader, "AWS4-HMAC-SHA256 ") {
  183. return "", nil, "", fmt.Errorf("invalid Authorization header format")
  184. }
  185. authorizationHeader = strings.TrimPrefix(authorizationHeader, "AWS4-HMAC-SHA256")
  186. parts := strings.Split(authorizationHeader, ",")
  187. if len(parts) != 3 {
  188. return "", nil, "", fmt.Errorf("invalid Authorization header format")
  189. }
  190. var credential, signedHeaders, signature string
  191. for _, part := range parts {
  192. part = strings.TrimSpace(part)
  193. if strings.HasPrefix(part, "Credential=") {
  194. credential = strings.TrimPrefix(part, "Credential=")
  195. }
  196. if strings.HasPrefix(part, "SignedHeaders=") {
  197. signedHeaders = strings.TrimPrefix(part, "SignedHeaders=")
  198. }
  199. if strings.HasPrefix(part, "Signature=") {
  200. signature = strings.TrimPrefix(part, "Signature=")
  201. }
  202. }
  203. if credential == "" || signedHeaders == "" || signature == "" {
  204. return "", nil, "", fmt.Errorf("missing necessary parts in Authorization header")
  205. }
  206. headers := strings.Split(signedHeaders, ";")
  207. return credential, headers, signature, nil
  208. }
  209. func getSignatureFromAWSHeader(req *http.Request) string {
  210. auth := req.Header.Get(AuthorizationHeader)
  211. idx := strings.Index(auth, "Signature=")
  212. if idx == -1 {
  213. return ""
  214. }
  215. return auth[idx+len("Signature="):]
  216. }
  217. func getSignatureFromAWSQuery(uri string) string {
  218. idx := strings.Index(uri, "X-Amz-Signature=")
  219. if idx == -1 {
  220. return ""
  221. }
  222. andIdx := strings.Index(uri[idx:], "&")
  223. if andIdx == -1 {
  224. return uri[idx+len("X-Amz-Signature="):]
  225. }
  226. return uri[idx+len("X-Amz-Signature=") : andIdx]
  227. }

本项目旨在将云际存储公共基础设施化,使个人及企业可低门槛使用高效的云际存储服务(安装开箱即用云际存储客户端即可,无需关注其他组件的部署),同时支持用户灵活便捷定制云际存储的功能细节。