-
Notifications
You must be signed in to change notification settings - Fork 2
/
certs.go
101 lines (88 loc) · 2.06 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
package googleidtokenverifier
import (
"crypto/rsa"
"encoding/base64"
"encoding/json"
"math/big"
"net/http"
"regexp"
"strconv"
"time"
)
const (
// From https://developers.google.com/identity/sign-in/web/backend-auth
googleCertsURL = "https://www.googleapis.com/oauth2/v3/certs"
)
var (
// used to extract max-age from cache-control HTTP header.
reMaxAge = regexp.MustCompile(`(?i)max-age=(\d+)`)
)
// Key is a cert key.
type Key struct {
Use string `json:"use"`
Kid string `json:"kid"`
Kty string `json:"kty"`
Alg string `json:"alg"`
N string `json:"n"`
E string `json:"e"`
}
// Certs are google certs.
type Certs struct {
Keys map[string]rsa.PublicKey
Expiry time.Time
}
// global unique google certs.
var gCerts *Certs
// listCerts lists google certs.
func listCerts() (*Certs, error) {
// use cached
if gCerts != nil && time.Now().Before(gCerts.Expiry) {
return gCerts, nil
}
// fetch certs
resp, err := http.Get(googleCertsURL)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// respect cache-control
cacheAge := 5 * 60
if cacheControl := resp.Header.Get("Cache-Control"); cacheControl != "" {
if matches := reMaxAge.FindStringSubmatch(cacheControl); len(matches) == 2 {
maxAge, err := strconv.ParseInt(matches[1], 10, 64)
if err == nil {
cacheAge = int(maxAge)
}
}
}
// parse all keys
keysObj := struct {
Keys []Key `json:"keys"`
}{}
if err := json.NewDecoder(resp.Body).Decode(&keysObj); err != nil {
return nil, err
}
pubKeys := map[string]rsa.PublicKey{}
for _, key := range keysObj.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
}
pubKeys[key.Kid] = rsa.PublicKey{
N: big.NewInt(0).SetBytes(n),
E: int(big.NewInt(0).SetBytes(e).Int64()),
}
}
}
// save to certs
gCerts = &Certs{
Keys: pubKeys,
Expiry: time.Now().Add(time.Second * time.Duration(cacheAge)),
}
return gCerts, nil
}