oss_api.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. /*
  2. * @description: 阿里云oss相关
  3. * @Author: CP
  4. * @Date: 2020-12-04 10:06:19
  5. * @FilePath: \construction_management\web\api\oss_api.go
  6. */
  7. package api
  8. import (
  9. "crypto"
  10. "crypto/hmac"
  11. "crypto/md5"
  12. "crypto/rsa"
  13. "crypto/sha1"
  14. "crypto/x509"
  15. "encoding/base64"
  16. "encoding/json"
  17. "encoding/pem"
  18. "errors"
  19. "fmt"
  20. "hash"
  21. "io"
  22. "io/ioutil"
  23. "net/http"
  24. "strconv"
  25. "time"
  26. "github.com/kataras/iris/v12"
  27. "go.mod/conf"
  28. )
  29. type OssApi struct {
  30. //框架-web应用上下文环境
  31. Ctx iris.Context
  32. }
  33. const (
  34. base64Table = "123QRSTUabcdVWXYZHijKLAWDCABDstEFGuvwxyzGHIJklmnopqr234560178912"
  35. )
  36. var coder = base64.NewEncoding(base64Table)
  37. func base64Encode(src []byte) []byte {
  38. return []byte(coder.EncodeToString(src))
  39. }
  40. func get_gmt_iso8601(expire_end int64) string {
  41. var tokenExpire = time.Unix(expire_end, 0).UTC().Format("2006-01-02T15:04:05Z")
  42. return tokenExpire
  43. }
  44. type ConfigStruct struct {
  45. Expiration string `json:"expiration"`
  46. Conditions [][]string `json:"conditions"`
  47. }
  48. type PolicyToken struct {
  49. AccessKeyId string `json:"accessId"`
  50. Host string `json:"host"`
  51. Expire int64 `json:"expire"`
  52. Signature string `json:"signature"`
  53. Policy string `json:"policy"`
  54. Directory string `json:"dir"`
  55. Callback string `json:"callback"`
  56. }
  57. type CallbackParam struct {
  58. CallbackUrl string `json:"callbackUrl"`
  59. CallbackBody string `json:"callbackBody"`
  60. CallbackBodyType string `json:"callbackBodyType"`
  61. }
  62. func get_policy_token() string {
  63. now := time.Now().Unix()
  64. expire_end := now + conf.Expire_time
  65. var tokenExpire = get_gmt_iso8601(expire_end)
  66. //create post policy json
  67. var config ConfigStruct
  68. config.Expiration = tokenExpire
  69. var condition []string
  70. condition = append(condition, "starts-with")
  71. condition = append(condition, "$key")
  72. condition = append(condition, conf.Upload_dir)
  73. config.Conditions = append(config.Conditions, condition)
  74. //calucate signature
  75. result, err := json.Marshal(config)
  76. debyte := base64.StdEncoding.EncodeToString(result)
  77. h := hmac.New(func() hash.Hash { return sha1.New() }, []byte(conf.AccessKeySecret))
  78. io.WriteString(h, debyte)
  79. signedStr := base64.StdEncoding.EncodeToString(h.Sum(nil))
  80. var callbackParam CallbackParam
  81. callbackParam.CallbackUrl = conf.CallbackUrl
  82. callbackParam.CallbackBody = "filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}"
  83. callbackParam.CallbackBodyType = "application/x-www-form-urlencoded"
  84. callback_str, err := json.Marshal(callbackParam)
  85. if err != nil {
  86. fmt.Println("callback json err:", err)
  87. }
  88. callbackBase64 := base64.StdEncoding.EncodeToString(callback_str)
  89. var policyToken PolicyToken
  90. policyToken.AccessKeyId = conf.AccessKeyId
  91. policyToken.Host = conf.OssHost
  92. policyToken.Expire = expire_end
  93. policyToken.Signature = string(signedStr)
  94. policyToken.Directory = conf.Upload_dir
  95. policyToken.Policy = string(debyte)
  96. policyToken.Callback = string(callbackBase64)
  97. response, err := json.Marshal(policyToken)
  98. if err != nil {
  99. fmt.Println("json err:", err)
  100. }
  101. return string(response)
  102. }
  103. // 获得上传Oss签名
  104. func (c *OssApi) GetSignature() {
  105. policyToken := PolicyToken{}
  106. response := get_policy_token()
  107. json.Unmarshal([]byte(response), &policyToken)
  108. c.Ctx.JSON(iris.Map{
  109. "code": 0,
  110. "msg": "",
  111. "data": policyToken,
  112. })
  113. }
  114. func handlerRequest(w http.ResponseWriter, r *http.Request) {
  115. if r.Method == "GET" {
  116. response := get_policy_token()
  117. w.Header().Set("Access-Control-Allow-Methods", "POST")
  118. w.Header().Set("Access-Control-Allow-Origin", "*")
  119. io.WriteString(w, response)
  120. }
  121. if r.Method == "POST" {
  122. fmt.Println("\nHandle Post Request ... ")
  123. // Get PublicKey bytes
  124. bytePublicKey, err := getPublicKey(r)
  125. if err != nil {
  126. responseFailed(w)
  127. return
  128. }
  129. // Get Authorization bytes : decode from Base64String
  130. byteAuthorization, err := getAuthorization(r)
  131. if err != nil {
  132. responseFailed(w)
  133. return
  134. }
  135. // Get MD5 bytes from Newly Constructed Authrization String.
  136. byteMD5, err := getMD5FromNewAuthString(r)
  137. if err != nil {
  138. responseFailed(w)
  139. return
  140. }
  141. // verifySignature and response to client
  142. if verifySignature(bytePublicKey, byteMD5, byteAuthorization) {
  143. // do something you want accoding to callback_body ...
  144. responseSuccess(w) // response OK : 200
  145. } else {
  146. responseFailed(w) // response FAILED : 400
  147. }
  148. }
  149. }
  150. // getPublicKey : Get PublicKey bytes from Request.URL
  151. func getPublicKey(r *http.Request) ([]byte, error) {
  152. var bytePublicKey []byte
  153. // get PublicKey URL
  154. publicKeyURLBase64 := r.Header.Get("x-oss-pub-key-url")
  155. if publicKeyURLBase64 == "" {
  156. fmt.Println("GetPublicKey from Request header failed : No x-oss-pub-key-url field. ")
  157. return bytePublicKey, errors.New("no x-oss-pub-key-url field in Request header ")
  158. }
  159. publicKeyURL, _ := base64.StdEncoding.DecodeString(publicKeyURLBase64)
  160. // fmt.Printf("publicKeyURL={%s}\n", publicKeyURL)
  161. // get PublicKey Content from URL
  162. responsePublicKeyURL, err := http.Get(string(publicKeyURL))
  163. if err != nil {
  164. fmt.Printf("Get PublicKey Content from URL failed : %s \n", err.Error())
  165. return bytePublicKey, err
  166. }
  167. bytePublicKey, err = ioutil.ReadAll(responsePublicKeyURL.Body)
  168. if err != nil {
  169. fmt.Printf("Read PublicKey Content from URL failed : %s \n", err.Error())
  170. return bytePublicKey, err
  171. }
  172. defer responsePublicKeyURL.Body.Close()
  173. // fmt.Printf("publicKey={%s}\n", bytePublicKey)
  174. return bytePublicKey, nil
  175. }
  176. // getAuthorization : decode from Base64String
  177. func getAuthorization(r *http.Request) ([]byte, error) {
  178. var byteAuthorization []byte
  179. // Get Authorization bytes : decode from Base64String
  180. strAuthorizationBase64 := r.Header.Get("authorization")
  181. if strAuthorizationBase64 == "" {
  182. fmt.Println("Failed to get authorization field from request header. ")
  183. return byteAuthorization, errors.New("no authorization field in Request header")
  184. }
  185. byteAuthorization, _ = base64.StdEncoding.DecodeString(strAuthorizationBase64)
  186. return byteAuthorization, nil
  187. }
  188. // getMD5FromNewAuthString : Get MD5 bytes from Newly Constructed Authrization String.
  189. func getMD5FromNewAuthString(r *http.Request) ([]byte, error) {
  190. var byteMD5 []byte
  191. // Construct the New Auth String from URI+Query+Body
  192. bodyContent, err := ioutil.ReadAll(r.Body)
  193. r.Body.Close()
  194. if err != nil {
  195. fmt.Printf("Read Request Body failed : %s \n", err.Error())
  196. return byteMD5, err
  197. }
  198. strCallbackBody := string(bodyContent)
  199. // fmt.Printf("r.URL.RawPath={%s}, r.URL.Query()={%s}, strCallbackBody={%s}\n", r.URL.RawPath, r.URL.Query(), strCallbackBody)
  200. strURLPathDecode, errUnescape := unescapePath(r.URL.Path, encodePathSegment) //url.PathUnescape(r.URL.Path) for Golang v1.8.2+
  201. if errUnescape != nil {
  202. fmt.Printf("url.PathUnescape failed : URL.Path=%s, error=%s \n", r.URL.Path, err.Error())
  203. return byteMD5, errUnescape
  204. }
  205. // Generate New Auth String prepare for MD5
  206. strAuth := ""
  207. if r.URL.RawQuery == "" {
  208. strAuth = fmt.Sprintf("%s\n%s", strURLPathDecode, strCallbackBody)
  209. } else {
  210. strAuth = fmt.Sprintf("%s?%s\n%s", strURLPathDecode, r.URL.RawQuery, strCallbackBody)
  211. }
  212. // fmt.Printf("NewlyConstructedAuthString={%s}\n", strAuth)
  213. // Generate MD5 from the New Auth String
  214. md5Ctx := md5.New()
  215. md5Ctx.Write([]byte(strAuth))
  216. byteMD5 = md5Ctx.Sum(nil)
  217. return byteMD5, nil
  218. }
  219. /* VerifySignature
  220. * VerifySignature需要三个重要的数据信息来进行签名验证: 1>获取公钥PublicKey; 2>生成新的MD5鉴权串; 3>解码Request携带的鉴权串;
  221. * 1>获取公钥PublicKey : 从RequestHeader的"x-oss-pub-key-url"字段中获取 URL, 读取URL链接的包含的公钥内容, 进行解码解析, 将其作为rsa.VerifyPKCS1v15的入参。
  222. * 2>生成新的MD5鉴权串 : 把Request中的url中的path部分进行urldecode, 加上url的query部分, 再加上body, 组合之后进行MD5编码, 得到MD5鉴权字节串。
  223. * 3>解码Request携带的鉴权串 : 获取RequestHeader的"authorization"字段, 对其进行Base64解码,作为签名验证的鉴权对比串。
  224. * rsa.VerifyPKCS1v15进行签名验证,返回验证结果。
  225. * */
  226. func verifySignature(bytePublicKey []byte, byteMd5 []byte, authorization []byte) bool {
  227. pubBlock, _ := pem.Decode(bytePublicKey)
  228. if pubBlock == nil {
  229. fmt.Printf("Failed to parse PEM block containing the public key")
  230. return false
  231. }
  232. pubInterface, err := x509.ParsePKIXPublicKey(pubBlock.Bytes)
  233. if (pubInterface == nil) || (err != nil) {
  234. fmt.Printf("x509.ParsePKIXPublicKey(publicKey) failed : %s \n", err.Error())
  235. return false
  236. }
  237. pub := pubInterface.(*rsa.PublicKey)
  238. errorVerifyPKCS1v15 := rsa.VerifyPKCS1v15(pub, crypto.MD5, byteMd5, authorization)
  239. if errorVerifyPKCS1v15 != nil {
  240. fmt.Printf("\nSignature Verification is Failed : %s \n", errorVerifyPKCS1v15.Error())
  241. //printByteArray(byteMd5, "AuthMd5(fromNewAuthString)")
  242. //printByteArray(bytePublicKey, "PublicKeyBase64")
  243. //printByteArray(authorization, "AuthorizationFromRequest")
  244. return false
  245. }
  246. fmt.Printf("\nSignature Verification is Successful. \n")
  247. return true
  248. }
  249. // responseSuccess : Response 200 to client
  250. func responseSuccess(w http.ResponseWriter) {
  251. strResponseBody := "{\"Status\":\"OK\"}"
  252. w.Header().Set("Content-Type", "application/json")
  253. w.Header().Set("Content-Length", strconv.Itoa(len(strResponseBody)))
  254. w.WriteHeader(http.StatusOK)
  255. w.Write([]byte(strResponseBody))
  256. fmt.Printf("\nPost Response : 200 OK . \n")
  257. }
  258. // responseFailed : Response 400 to client
  259. func responseFailed(w http.ResponseWriter) {
  260. w.WriteHeader(http.StatusBadRequest)
  261. fmt.Printf("\nPost Response : 400 BAD . \n")
  262. }
  263. func printByteArray(byteArrary []byte, arrName string) {
  264. fmt.Printf("++++++++ printByteArray : ArrayName=%s, ArrayLength=%d \n", arrName, len(byteArrary))
  265. for i := 0; i < len(byteArrary); i++ {
  266. fmt.Printf("%02x", byteArrary[i])
  267. }
  268. fmt.Printf("\n-------- printByteArray : End . \n")
  269. }
  270. type EscapeError string
  271. func (e EscapeError) Error() string {
  272. return "invalid URL escape " + strconv.Quote(string(e))
  273. }
  274. type InvalidHostError string
  275. func (e InvalidHostError) Error() string {
  276. return "invalid character " + strconv.Quote(string(e)) + " in host name"
  277. }
  278. type encoding int
  279. const (
  280. encodePath encoding = 1 + iota
  281. encodePathSegment
  282. encodeHost
  283. encodeZone
  284. encodeUserPassword
  285. encodeQueryComponent
  286. encodeFragment
  287. )
  288. // unescapePath : unescapes a string; the mode specifies, which section of the URL string is being unescaped.
  289. func unescapePath(s string, mode encoding) (string, error) {
  290. // Count %, check that they're well-formed.
  291. mode = encodePathSegment
  292. n := 0
  293. hasPlus := false
  294. for i := 0; i < len(s); {
  295. switch s[i] {
  296. case '%':
  297. n++
  298. if i+2 >= len(s) || !ishex(s[i+1]) || !ishex(s[i+2]) {
  299. s = s[i:]
  300. if len(s) > 3 {
  301. s = s[:3]
  302. }
  303. return "", EscapeError(s)
  304. }
  305. // Per https://tools.ietf.org/html/rfc3986#page-21
  306. // in the host component %-encoding can only be used
  307. // for non-ASCII bytes.
  308. // But https://tools.ietf.org/html/rfc6874#section-2
  309. // introduces %25 being allowed to escape a percent sign
  310. // in IPv6 scoped-address literals. Yay.
  311. if mode == encodeHost && unhex(s[i+1]) < 8 && s[i:i+3] != "%25" {
  312. return "", EscapeError(s[i : i+3])
  313. }
  314. if mode == encodeZone {
  315. // RFC 6874 says basically "anything goes" for zone identifiers
  316. // and that even non-ASCII can be redundantly escaped,
  317. // but it seems prudent to restrict %-escaped bytes here to those
  318. // that are valid host name bytes in their unescaped form.
  319. // That is, you can use escaping in the zone identifier but not
  320. // to introduce bytes you couldn't just write directly.
  321. // But Windows puts spaces here! Yay.
  322. v := unhex(s[i+1])<<4 | unhex(s[i+2])
  323. if s[i:i+3] != "%25" && v != ' ' && shouldEscape(v, encodeHost) {
  324. return "", EscapeError(s[i : i+3])
  325. }
  326. }
  327. i += 3
  328. case '+':
  329. hasPlus = mode == encodeQueryComponent
  330. i++
  331. default:
  332. if (mode == encodeHost || mode == encodeZone) && s[i] < 0x80 && shouldEscape(s[i], mode) {
  333. return "", InvalidHostError(s[i : i+1])
  334. }
  335. i++
  336. }
  337. }
  338. if n == 0 && !hasPlus {
  339. return s, nil
  340. }
  341. t := make([]byte, len(s)-2*n)
  342. j := 0
  343. for i := 0; i < len(s); {
  344. switch s[i] {
  345. case '%':
  346. t[j] = unhex(s[i+1])<<4 | unhex(s[i+2])
  347. j++
  348. i += 3
  349. case '+':
  350. if mode == encodeQueryComponent {
  351. t[j] = ' '
  352. } else {
  353. t[j] = '+'
  354. }
  355. j++
  356. i++
  357. default:
  358. t[j] = s[i]
  359. j++
  360. i++
  361. }
  362. }
  363. return string(t), nil
  364. }
  365. // Please be informed that for now shouldEscape does not check all
  366. // reserved characters correctly. See golang.org/issue/5684.
  367. func shouldEscape(c byte, mode encoding) bool {
  368. // §2.3 Unreserved characters (alphanum)
  369. if 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || '0' <= c && c <= '9' {
  370. return false
  371. }
  372. if mode == encodeHost || mode == encodeZone {
  373. // §3.2.2 Host allows
  374. // sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "="
  375. // as part of reg-name.
  376. // We add : because we include :port as part of host.
  377. // We add [ ] because we include [ipv6]:port as part of host.
  378. // We add < > because they're the only characters left that
  379. // we could possibly allow, and Parse will reject them if we
  380. // escape them (because hosts can't use %-encoding for
  381. // ASCII bytes).
  382. switch c {
  383. case '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=', ':', '[', ']', '<', '>', '"':
  384. return false
  385. }
  386. }
  387. switch c {
  388. case '-', '_', '.', '~': // §2.3 Unreserved characters (mark)
  389. return false
  390. case '$', '&', '+', ',', '/', ':', ';', '=', '?', '@': // §2.2 Reserved characters (reserved)
  391. // Different sections of the URL allow a few of
  392. // the reserved characters to appear unescaped.
  393. switch mode {
  394. case encodePath: // §3.3
  395. // The RFC allows : @ & = + $ but saves / ; , for assigning
  396. // meaning to individual path segments. This package
  397. // only manipulates the path as a whole, so we allow those
  398. // last three as well. That leaves only ? to escape.
  399. return c == '?'
  400. case encodePathSegment: // §3.3
  401. // The RFC allows : @ & = + $ but saves / ; , for assigning
  402. // meaning to individual path segments.
  403. return c == '/' || c == ';' || c == ',' || c == '?'
  404. case encodeUserPassword: // §3.2.1
  405. // The RFC allows ';', ':', '&', '=', '+', '$', and ',' in
  406. // userinfo, so we must escape only '@', '/', and '?'.
  407. // The parsing of userinfo treats ':' as special so we must escape
  408. // that too.
  409. return c == '@' || c == '/' || c == '?' || c == ':'
  410. case encodeQueryComponent: // §3.4
  411. // The RFC reserves (so we must escape) everything.
  412. return true
  413. case encodeFragment: // §4.1
  414. // The RFC text is silent but the grammar allows
  415. // everything, so escape nothing.
  416. return false
  417. }
  418. }
  419. // Everything else must be escaped.
  420. return true
  421. }
  422. func ishex(c byte) bool {
  423. switch {
  424. case '0' <= c && c <= '9':
  425. return true
  426. case 'a' <= c && c <= 'f':
  427. return true
  428. case 'A' <= c && c <= 'F':
  429. return true
  430. }
  431. return false
  432. }
  433. func unhex(c byte) byte {
  434. switch {
  435. case '0' <= c && c <= '9':
  436. return c - '0'
  437. case 'a' <= c && c <= 'f':
  438. return c - 'a' + 10
  439. case 'A' <= c && c <= 'F':
  440. return c - 'A' + 10
  441. }
  442. return 0
  443. }