-
Notifications
You must be signed in to change notification settings - Fork 3
/
verifier.go
198 lines (168 loc) · 4.94 KB
/
verifier.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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
// Copyright 2021 Monoskope Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package jwt
import (
"errors"
"fmt"
"io/ioutil"
"sync"
"time"
"github.com/finleap-connect/monoskope/pkg/logger"
"github.com/fsnotify/fsnotify"
"gopkg.in/square/go-jose.v2"
"gopkg.in/square/go-jose.v2/jwt"
)
// JWTVerifier verifies a JWT and parses claims
type JWTVerifier interface {
Verify(string, interface{}) error
JWKS() *jose.JSONWebKeySet
KeyExpiration() time.Duration
Close() error
}
type jwkWithExpiry struct {
jwk *jose.JSONWebKey
expiry time.Time
}
type jwtVerifier struct {
log logger.Logger
keyExpiration time.Duration
jsonWebKeys []jwkWithExpiry
watcher *fsnotify.Watcher
mutex sync.RWMutex
}
// NewVerifier creates a new verifier for raw JWT
func NewVerifier(publicKeyFilename string, keyExpiration time.Duration) (JWTVerifier, error) {
v := &jwtVerifier{
log: logger.WithName("jwt-verifier"),
jsonWebKeys: make([]jwkWithExpiry, 0),
keyExpiration: keyExpiration,
}
v.log.Info("Loading public key...", "publicKeyFilename", publicKeyFilename)
err := v.rotatePublicKey(publicKeyFilename)
if err != nil {
return nil, err
}
v.log.Info("Setting up watcher...")
watcher, err := fsnotify.NewWatcher()
if err != nil {
return nil, err
}
err = watcher.Add(publicKeyFilename)
if err != nil {
return nil, err
}
v.watcher = watcher
go v.loadPublicKeyOnFileChange()
return v, nil
}
func (v *jwtVerifier) loadPublicKeyOnFileChange() {
for {
select {
case event, ok := <-v.watcher.Events:
if !ok {
return
}
if event.Op&fsnotify.Write == fsnotify.Write {
v.log.Info("Public key has been changed. Updating...")
err := v.rotatePublicKey(event.Name)
if err != nil {
v.log.Error(err, "Error rotating public key.")
}
v.log.Info("Public key has been updated.", "KeyCount", len(v.jsonWebKeys))
}
case err, ok := <-v.watcher.Errors:
if !ok {
return
}
v.log.Error(err, "Error from watcher.")
}
}
}
// loadPublicKey loads the public key
func (v *jwtVerifier) rotatePublicKey(filename string) error {
v.mutex.Lock()
defer v.mutex.Unlock()
pubKeyBytes, err := ioutil.ReadFile(filename)
if err != nil {
return err
}
pubKey, err := LoadPublicKey(pubKeyBytes)
if err != nil {
return err
}
v.jsonWebKeys = append(v.jsonWebKeys, jwkWithExpiry{jwk: pubKey, expiry: time.Now().UTC().Add(v.keyExpiration)})
v.removeExpiredKeys()
return nil
}
// removeExpiredKeys removes expired public keys from cache
func (v *jwtVerifier) removeExpiredKeys() {
var validKeys []jwkWithExpiry
for _, k := range v.jsonWebKeys {
// check if expired and give a little extra time to verify
if k.expiry.Before(time.Now().UTC().Add(1*time.Minute)) && len(v.jsonWebKeys) > 1 {
v.log.Info("Public key expired. Removing from list.", "Expiry", k.expiry, "KeyCount", len(v.jsonWebKeys))
} else {
validKeys = append(validKeys, k)
}
}
if len(validKeys) == 0 {
err := fmt.Errorf("not a single valid public key available for verifying claims")
v.log.Error(err, "no public keys available")
panic(err)
}
v.jsonWebKeys = validKeys
}
// Verify parses the raw JWT, verifies the content against the public key of the verifier and parses the claims
func (v *jwtVerifier) Verify(rawJWT string, claims interface{}) error {
v.mutex.RLock()
defer v.mutex.RUnlock()
// remove outdated keys
v.removeExpiredKeys()
// parse the raw jwt
parsedJWT, err := jwt.ParseSigned(rawJWT)
if err != nil {
return err
}
kid := parsedJWT.Headers[0].KeyID
for _, key := range v.jsonWebKeys {
if key.jwk.KeyID == kid {
if err := parsedJWT.Claims(key.jwk, claims); err == nil {
v.log.Info("Successfully verified claims.", "Expiry", key.expiry, "KeyCount", len(v.jsonWebKeys), "KeyID", key.jwk.KeyID)
return nil
} else {
v.log.Info("Failed to verify claims.", "Expiry", key.expiry, "KeyCount", len(v.jsonWebKeys), "KeyID", key.jwk.KeyID, "error", err.Error())
}
}
}
// none of the known keys could verify claims
return errors.New("failed to verify claims")
}
func (v *jwtVerifier) JWKS() *jose.JSONWebKeySet {
v.mutex.RLock()
defer v.mutex.RUnlock()
jwks := &jose.JSONWebKeySet{
Keys: make([]jose.JSONWebKey, 0),
}
for _, k := range v.jsonWebKeys {
jwks.Keys = append(jwks.Keys, *k.jwk)
}
return jwks
}
func (v *jwtVerifier) KeyExpiration() time.Duration {
return v.keyExpiration
}
// Close closes file watcher
func (v *jwtVerifier) Close() error {
return v.watcher.Close()
}