-
Notifications
You must be signed in to change notification settings - Fork 3
/
pem.go
97 lines (74 loc) · 1.77 KB
/
pem.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
package auth0
import (
"context"
"encoding/json"
"errors"
"net/http"
"time"
"github.com/dgraph-io/ristretto"
"github.com/golang-jwt/jwt/v4"
)
const day = 24 * time.Hour
// ErrMissingCertificate from Auth0.
var ErrMissingCertificate = errors.New("missing certificate")
type jwksResponse struct {
Keys []jsonWebKeys `json:"keys"`
}
type jsonWebKeys struct {
Kty string `json:"kty"`
Kid string `json:"kid"`
Use string `json:"use"`
N string `json:"n"`
E string `json:"e"`
X5c []string `json:"x5c"`
}
type pem struct {
cfg *Config
client *http.Client
}
func (p *pem) Certificate(ctx context.Context, token *jwt.Token) (string, error) {
cert := ""
httpReq, err := http.NewRequestWithContext(ctx, "GET", p.cfg.JSONWebKeySet, nil)
if err != nil {
return cert, err
}
httpResp, err := p.client.Do(httpReq)
if err != nil {
return cert, err
}
defer httpResp.Body.Close()
if httpResp.StatusCode != http.StatusOK {
return cert, ErrInvalidResponse
}
var resp jwksResponse
if err := json.NewDecoder(httpResp.Body).Decode(&resp); err != nil {
return cert, err
}
for k := range resp.Keys {
if token.Header["kid"] == resp.Keys[k].Kid {
cert = "-----BEGIN CERTIFICATE-----\n" + resp.Keys[k].X5c[0] + "\n-----END CERTIFICATE-----"
}
}
if cert == "" {
return cert, ErrMissingCertificate
}
return cert, nil
}
type cachedPEM struct {
cfg *Config
cache *ristretto.Cache
Certificator
}
func (p *cachedPEM) Certificate(ctx context.Context, token *jwt.Token) (string, error) {
cacheKey := p.cfg.CacheKey("certificate")
v, ok := p.cache.Get(cacheKey)
if ok {
return v.(string), nil
}
cert, err := p.Certificator.Certificate(ctx, token)
if err != nil {
return cert, err
}
p.cache.SetWithTTL(cacheKey, cert, 0, day)
return cert, nil
}