-
Notifications
You must be signed in to change notification settings - Fork 3
/
pem.go
96 lines (74 loc) · 1.8 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
package auth0
import (
"context"
"encoding/json"
"errors"
"net/http"
"time"
"github.com/dgraph-io/ristretto"
"github.com/form3tech-oss/jwt-go"
)
// 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 != 200 { // nolint:gomnd
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
}
// nolint:forcetypeassert
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, 24*time.Hour) // nolint:gomnd
return cert, nil
}