Debian Codegraph @

pkg/client/rp/jwks.go

raw
1 package rp
2
3 import (
4 "context"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "net/http"
9 "sync"
10
11 jose "github.com/go-jose/go-jose/v4"
12
13 "github.com/zitadel/oidc/v3/pkg/client"
14 httphelper "github.com/zitadel/oidc/v3/pkg/http"
15 "github.com/zitadel/oidc/v3/pkg/oidc"
16 )
17
18 func NewRemoteKeySet(client *http.Client, jwksURL string, opts ...func(*remoteKeySet)) oidc.KeySet {
19 keyset := &remoteKeySet{httpClient: client, jwksURL: jwksURL}
20 for _, opt := range opts {
21 opt(keyset)
22 }
23 return keyset
24 }
25
26 // SkipRemoteCheck will suppress checking for new remote keys if signature validation fails with cached keys
27 // and no kid header is set in the JWT.
28 //
29 // This might be handy to save some unnecessary round trips in cases where the JWT does not contain a kid header and
30 // there is only a single remote key.
31 // Please notice that remote keys will then only be fetched if cached keys are empty.
32 func SkipRemoteCheck() func(set *remoteKeySet) {
33 return func(set *remoteKeySet) {
34 set.skipRemoteCheck = true
35 }
36 }
37
38 type remoteKeySet struct {
39 jwksURL string
40 httpClient *http.Client
41 defaultAlg string
42 skipRemoteCheck bool
43
44 // guard all other fields
45 mu sync.Mutex
46
47 // inflight suppresses parallel execution of updateKeys and allows
48 // multiple goroutines to wait for its result.
49 inflight *inflight
50
51 // A set of cached keys and their expiry.
52 cachedKeys []jose.JSONWebKey
53 }
54
55 // inflight is used to wait on some in-flight request from multiple goroutines.
56 type inflight struct {
57 doneCh chan struct{}
58
59 keys []jose.JSONWebKey
60 err error
61 }
62
63 func newInflight() *inflight {
64 return &inflight{doneCh: make(chan struct{})}
65 }
66
67 // wait returns a channel that multiple goroutines can receive on. Once it returns
68 // a value, the inflight request is done and result() can be inspected.
69 func (i *inflight) wait() <-chan struct{} {
70 return i.doneCh
71 }
72
73 // done can only be called by a single goroutine. It records the result of the
74 // inflight request and signals other goroutines that the result is safe to
75 // inspect.
76 func (i *inflight) done(keys []jose.JSONWebKey, err error) {
77 i.keys = keys
78 i.err = err
79 close(i.doneCh)
80 }
81
82 // result cannot be called until the wait() channel has returned a value.
83 func (i *inflight) result() ([]jose.JSONWebKey, error) {
84 return i.keys, i.err
85 }
86
87 func (r *remoteKeySet) VerifySignature(ctx context.Context, jws *jose.JSONWebSignature) ([]byte, error) {
88 ctx, span := client.Tracer.Start(ctx, "VerifySignature")
89 defer span.End()
90
91 keyID, alg := oidc.GetKeyIDAndAlg(jws)
92 if alg == "" {
93 alg = r.defaultAlg
94 }
95 payload, err := r.verifySignatureCached(jws, keyID, alg)
96 if payload != nil {
97 return payload, nil
98 }
99 if err != nil {
100 return nil, err
101 }
102 return r.verifySignatureRemote(ctx, jws, keyID, alg)
103 }
104
105 // verifySignatureCached checks for a matching key in the cached key list
106 //
107 // if there is only one possible, it tries to verify the signature and will return the payload if successful
108 //
109 // it only returns an error if signature validation fails and keys exactMatch which is if either:
110 // - both kid are empty and skipRemoteCheck is set to true
111 // - or both (JWT and JWK) kid are equal
112 //
113 // otherwise it will return no error (so remote keys will be loaded)
114 func (r *remoteKeySet) verifySignatureCached(jws *jose.JSONWebSignature, keyID, alg string) ([]byte, error) {
115 keys := r.keysFromCache()
116 if len(keys) == 0 {
117 return nil, nil
118 }
119 key, err := oidc.FindMatchingKey(keyID, oidc.KeyUseSignature, alg, keys...)
120 if err != nil {
121 // no key / multiple found, try with remote keys
122 return nil, nil //nolint:nilerr
123 }
124 payload, err := jws.Verify(&key)
125 if payload != nil {
126 return payload, nil
127 }
128 if !r.exactMatch(key.KeyID, keyID) {
129 // no exact key match, try getting better match with remote keys
130 return nil, nil
131 }
132 return nil, fmt.Errorf("signature verification failed: %w", err)
133 }
134
135 func (r *remoteKeySet) exactMatch(jwkID, jwsID string) bool {
136 if jwkID == "" && jwsID == "" {
137 return r.skipRemoteCheck
138 }
139 return jwkID == jwsID
140 }
141
142 func (r *remoteKeySet) verifySignatureRemote(ctx context.Context, jws *jose.JSONWebSignature, keyID, alg string) ([]byte, error) {
143 ctx, span := client.Tracer.Start(ctx, "verifySignatureRemote")
144 defer span.End()
145
146 keys, err := r.keysFromRemote(ctx)
147 if err != nil {
148 return nil, fmt.Errorf("unable to fetch key for signature validation: %w", err)
149 }
150 key, err := oidc.FindMatchingKey(keyID, oidc.KeyUseSignature, alg, keys...)
151 if err != nil {
152 return nil, fmt.Errorf("unable to validate signature: %w", err)
153 }
154 payload, err := jws.Verify(&key)
155 if err != nil {
156 return nil, fmt.Errorf("signature verification failed: %w", err)
157 }
158 return payload, nil
159 }
160
161 func (r *remoteKeySet) keysFromCache() (keys []jose.JSONWebKey) {
162 r.mu.Lock()
163 defer r.mu.Unlock()
164 return r.cachedKeys
165 }
166
167 // keysFromRemote syncs the key set from the remote set, records the values in the
168 // cache, and returns the key set.
169 func (r *remoteKeySet) keysFromRemote(ctx context.Context) ([]jose.JSONWebKey, error) {
170 ctx, span := client.Tracer.Start(ctx, "keysFromRemote")
171 defer span.End()
172
173 // Need to lock to inspect the inflight request field.
174 r.mu.Lock()
175 // If there's not a current inflight request, create one.
176 if r.inflight == nil {
177 r.inflight = newInflight()
178
179 // This goroutine has exclusive ownership over the current inflight
180 // request. It releases the resource by nil'ing the inflight field
181 // once the goroutine is done.
182 go r.updateKeys(ctx)
183 }
184 inflight := r.inflight
185 r.mu.Unlock()
186
187 select {
188 case <-ctx.Done():
189 return nil, ctx.Err()
190 case <-inflight.wait():
191 return inflight.result()
192 }
193 }
194
195 func (r *remoteKeySet) updateKeys(ctx context.Context) {
196 ctx, span := client.Tracer.Start(ctx, "updateKeys")
197 defer span.End()
198
199 // Sync keys and finish inflight when that's done.
200 keys, err := r.fetchRemoteKeys(ctx)
201
202 r.inflight.done(keys, err)
203
204 // Lock to update the keys and indicate that there is no longer an
205 // inflight request.
206 r.mu.Lock()
207 defer r.mu.Unlock()
208
209 if err == nil {
210 r.cachedKeys = keys
211 }
212
213 // Free inflight so a different request can run.
214 r.inflight = nil
215 }
216
217 func (r *remoteKeySet) fetchRemoteKeys(ctx context.Context) ([]jose.JSONWebKey, error) {
218 ctx, span := client.Tracer.Start(ctx, "fetchRemoteKeys")
219 defer span.End()
220
221 req, err := http.NewRequestWithContext(ctx, "GET", r.jwksURL, nil)
222 if err != nil {
223 return nil, fmt.Errorf("oidc: can't create request: %v", err)
224 }
225
226 keySet := new(jsonWebKeySet)
227 if err = httphelper.HttpRequest(r.httpClient, req, keySet); err != nil {
228 return nil, fmt.Errorf("oidc: failed to get keys: %v", err)
229 }
230 return keySet.Keys, nil
231 }
232
233 // jsonWebKeySet is an alias for jose.JSONWebKeySet which ignores unknown key types (kty)
234 type jsonWebKeySet jose.JSONWebKeySet
235
236 // UnmarshalJSON overrides the default jose.JSONWebKeySet method to ignore any error
237 // which might occur because of unknown key types (kty)
238 func (k *jsonWebKeySet) UnmarshalJSON(data []byte) (err error) {
239 var raw rawJSONWebKeySet
240 err = json.Unmarshal(data, &raw)
241 if err != nil {
242 return fmt.Errorf("oidc: failed to unmarshall key set: %w", err)
243 }
244 for i, key := range raw.Keys {
245 webKey := new(jose.JSONWebKey)
246 if err = webKey.UnmarshalJSON(key); err != nil {
247 if errors.Is(err, jose.ErrUnsupportedKeyType) {
248 continue
249 }
250
251 return fmt.Errorf("oidc: failed to unmarshal key %d from set: %w", i, err)
252 }
253
254 k.Keys = append(k.Keys, *webKey)
255 }
256 return nil
257 }
258
259 type rawJSONWebKeySet struct {
260 Keys []json.RawMessage `json:"keys"`
261 }