Debian Codegraph @

oss/authenticate_callback.go

raw symbols SCIP
1 package oss
2
3 import (
4 "crypto"
5 "crypto/md5"
6 "crypto/rsa"
7 "crypto/x509"
8 "encoding/base64"
9 "encoding/pem"
10 "errors"
11 "io/ioutil"
12 "net/http"
13 "regexp"
14 "strings"
15 "sync"
16 )
17
18 type authenticationType struct {
19 lock *sync.RWMutex
20 certificate map[string]*rsa.PublicKey
21 }
22
23 var (
24 authentication = authenticationType{lock: &sync.RWMutex{}, certificate: map[string]*rsa.PublicKey{}}
25 urlReg = regexp.MustCompile(`^http(|s)://gosspublic.alicdn.com/[0-9a-zA-Z]`)
26 )
27
28 //验证OSS向业务服务器发来的回调函数。
29 //该方法是并发安全的
30 //pubKeyUrl 回调请求头中[x-oss-pub-key-url]一项,以Base64编码
31 //reqUrl oss所发来请求的url,由path+query组成
32 //reqBody oss所发来请求的body
33 //authorization authorization为回调头中的签名
34 func AuthenticateCallBack(pubKeyUrl, reqUrl, reqBody, authorization string) error {
35 //获取证书url
36 keyURL, err := base64.URLEncoding.DecodeString(pubKeyUrl)
37 if err != nil {
38 return err
39 }
40 url := string(keyURL)
41 //判断证书是否来自于阿里云
42 if !urlReg.Match(keyURL) {
43 return errors.New("certificate address error")
44 }
45 //获取文件名
46 rs := []rune(url)
47 filename := string(rs[strings.LastIndex(url, "/") : len(rs)-1])
48 authentication.lock.RLock()
49 certificate := authentication.certificate[filename]
50 authentication.lock.RUnlock()
51 //内存中没有证书,下载
52 if certificate == nil {
53 authentication.lock.Lock()
54 res, err := http.Get(url)
55 if err != nil {
56 return err
57 }
58 defer res.Body.Close()
59 body, err := ioutil.ReadAll(res.Body)
60 if err != nil {
61 return err
62 }
63 block, _ := pem.Decode(body)
64 if block == nil {
65 return errors.New("certificate error")
66 }
67 pubKey, err := x509.ParsePKIXPublicKey(block.Bytes)
68 if err != nil {
69 return err
70 }
71 certificate = pubKey.(*rsa.PublicKey)
72 authentication.certificate[filename] = certificate
73 authentication.lock.Unlock()
74 }
75 //证书准备完毕,开始验证
76 //解析签名
77 signature, err := base64.StdEncoding.DecodeString(authorization)
78 if err != nil {
79 return err
80 }
81 hashed := md5.New()
82 hashed.Write([]byte(reqUrl + "\n" + reqBody))
83 if err := rsa.VerifyPKCS1v15(certificate, crypto.MD5, hashed.Sum(nil), signature); err != nil {
84 return err
85 }
86 //验证通过
87 return nil
88 }