-
Notifications
You must be signed in to change notification settings - Fork 0
/
publicKey.go
67 lines (54 loc) · 1.61 KB
/
publicKey.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
package hid
import (
"fmt"
"github.com/dgrijalva/jwt-go"
"github.com/pkg/errors"
)
// PKS (Public Key Set) stores a slice of public keys and their metadata
type PKS struct {
Keys []struct {
KeyID string `json:"kid"`
Algorithm string `json:"alg"`
X5C []string `json:"x5c"`
} `json:"keys"`
}
// newPKS renews the stored public key set for the external HID server
func (hid *HID) newPKS() error {
err := hid.client.Get(hid.JWKSuri, &hid.PKS)
if err != nil {
return errors.Wrap(err, "while renewing HID public key set")
}
return nil
}
// keyFunc converts a jwt token to a RSA public key
func keyFunc(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
cert, err := getPemCert(token)
if err != nil {
return nil, err
}
return jwt.ParseRSAPublicKeyFromPEM([]byte(cert))
}
// getPemCert extracts the pem certificate from a jwt token
func getPemCert(token *jwt.Token) (cert string, err error) {
for _, k := range tmpPKS.Keys {
if kid, ok := token.Header["kid"].(string); ok {
if kid == k.KeyID {
cert = "-----BEGIN CERTIFICATE-----\n" + k.X5C[0] + "\n-----END CERTIFICATE-----"
return
}
} else {
return "", errors.New("expecting JWT header to have string kid")
}
}
return "", errors.New("Unable to find corresponding kid")
}
var tmpPKS PKS // needs to be globally accessible because of how dgrijalva/jwt-go works. Not for caching; set before each use, nil after use.
func provideKeys(pks PKS) {
tmpPKS = pks
}
func revokeKeys() {
tmpPKS = PKS{nil}
}