forked from futurenda/google-auth-id-token-verifier
-
Notifications
You must be signed in to change notification settings - Fork 1
/
certs.go
119 lines (105 loc) · 2.38 KB
/
certs.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package googleIDVerifier
import (
"crypto/rsa"
"encoding/base64"
"encoding/json"
"math/big"
"net/http"
"regexp"
"strconv"
"time"
)
type Certs struct {
Keys map[string]*rsa.PublicKey
Expiry time.Time
}
var (
cachedCerts *Certs
// Google Sign on certificates.
googleOAuth2FederatedSignonCertsURL = "https://www.googleapis.com/oauth2/v3/certs"
)
type key struct {
Kty string `json:"kty"`
Alg string `json:"alg"`
Use string `json:"use"`
Kid string `json:"Kid"`
N string `json:"n"`
E string `json:"e"`
}
type response struct {
Keys []*key `json:"keys"`
}
func getFederatedSignonCerts() (*Certs, error) {
if cachedCerts != nil {
if time.Now().Before(cachedCerts.Expiry) {
return cachedCerts, nil
}
}
res, cacheAge, err := fetchFederatedSignonCerts()
if err != nil {
return nil, err
}
parsedCerts, err := parseCerts(res, cacheAge)
if err != nil {
return nil, err
}
// cache certs
cachedCerts = parsedCerts
return parsedCerts, nil
}
func fetchFederatedSignonCerts() (*response, int64, error) {
resp, err := http.Get(googleOAuth2FederatedSignonCertsURL)
if err != nil {
return nil, 0, err
}
defer resp.Body.Close()
cacheControl := resp.Header.Get("cache-control")
cacheAge := int64(7200) // Set default cacheAge to 2 hours
if len(cacheControl) > 0 {
re := regexp.MustCompile("max-age=([0-9]*)")
match := re.FindAllStringSubmatch(cacheControl, -1)
if len(match) > 0 {
if len(match[0]) == 2 {
maxAge := match[0][1]
maxAgeInt, err := strconv.ParseInt(maxAge, 10, 64)
if err != nil {
return nil, 0, err
}
cacheAge = maxAgeInt
}
}
}
res := &response{}
err = json.NewDecoder(resp.Body).Decode(&res)
if err != nil {
return nil, 0, err
}
return res, cacheAge, nil
}
func parseCerts(res *response, cacheAge int64) (*Certs, error) {
keys := map[string]*rsa.PublicKey{}
for _, key := range res.Keys {
if key.Use == "sig" && key.Kty == "RSA" {
n, err := base64.RawURLEncoding.DecodeString(key.N)
if err != nil {
return nil, err
}
e, err := base64.RawURLEncoding.DecodeString(key.E)
if err != nil {
return nil, err
}
ei := big.NewInt(0).SetBytes(e).Int64()
if err != nil {
return nil, err
}
keys[key.Kid] = &rsa.PublicKey{
N: big.NewInt(0).SetBytes(n),
E: int(ei),
}
}
}
return &Certs{
Keys: keys,
Expiry: time.Now().Add(time.Second * time.Duration(cacheAge)),
}, nil
}