/
handler.go
611 lines (514 loc) · 18.5 KB
/
handler.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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
package workload
import (
"context"
"crypto"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"os"
"time"
"github.com/sirupsen/logrus"
"github.com/spiffe/go-spiffe/v2/bundle/spiffebundle"
"github.com/spiffe/go-spiffe/v2/proto/spiffe/workload"
"github.com/spiffe/go-spiffe/v2/spiffeid"
"github.com/spiffe/spire/pkg/agent/api/rpccontext"
"github.com/spiffe/spire/pkg/agent/client"
"github.com/spiffe/spire/pkg/agent/manager/cache"
"github.com/spiffe/spire/pkg/common/bundleutil"
"github.com/spiffe/spire/pkg/common/jwtsvid"
"github.com/spiffe/spire/pkg/common/telemetry"
"github.com/spiffe/spire/pkg/common/x509util"
"github.com/spiffe/spire/proto/spire/common"
"github.com/zeebo/errs"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/structpb"
)
type Manager interface {
SubscribeToCacheChanges(ctx context.Context, key cache.Selectors) (cache.Subscriber, error)
MatchingRegistrationEntries(selectors []*common.Selector) []*common.RegistrationEntry
FetchJWTSVID(ctx context.Context, entry *common.RegistrationEntry, audience []string) (*client.JWTSVID, error)
FetchWorkloadUpdate([]*common.Selector) *cache.WorkloadUpdate
}
type Attestor interface {
Attest(ctx context.Context) ([]*common.Selector, error)
}
type Config struct {
Manager Manager
Attestor Attestor
AllowUnauthenticatedVerifiers bool
AllowedForeignJWTClaims map[string]struct{}
TrustDomain spiffeid.TrustDomain
}
// Handler implements the Workload API interface
type Handler struct {
workload.UnsafeSpiffeWorkloadAPIServer
c Config
}
func New(c Config) *Handler {
return &Handler{
c: c,
}
}
// FetchJWTSVID processes request for a JWT-SVID. In case of multiple fetched SVIDs with same hint, the SVID that has the oldest
// associated entry will be returned.
func (h *Handler) FetchJWTSVID(ctx context.Context, req *workload.JWTSVIDRequest) (resp *workload.JWTSVIDResponse, err error) {
log := rpccontext.Logger(ctx)
if len(req.Audience) == 0 {
log.Error("Missing required audience parameter")
return nil, status.Error(codes.InvalidArgument, "audience must be specified")
}
if req.SpiffeId != "" {
if _, err := spiffeid.FromString(req.SpiffeId); err != nil {
log.WithField(telemetry.SPIFFEID, req.SpiffeId).WithError(err).Error("Invalid requested SPIFFE ID")
return nil, status.Errorf(codes.InvalidArgument, "invalid requested SPIFFE ID: %v", err)
}
}
selectors, err := h.c.Attestor.Attest(ctx)
if err != nil {
log.WithError(err).Error("Workload attestation failed")
return nil, err
}
log = log.WithField(telemetry.Registered, true)
entries := h.c.Manager.MatchingRegistrationEntries(selectors)
entries = filterRegistrations(entries, log)
resp = new(workload.JWTSVIDResponse)
for _, entry := range entries {
if req.SpiffeId != "" && entry.SpiffeId != req.SpiffeId {
continue
}
loopLog := log.WithField(telemetry.SPIFFEID, entry.SpiffeId)
svid, err := h.fetchJWTSVID(ctx, loopLog, entry, req.Audience)
if err != nil {
return nil, err
}
resp.Svids = append(resp.Svids, svid)
}
if len(resp.Svids) == 0 {
log.WithField(telemetry.Registered, false).Error("No identity issued")
return nil, status.Error(codes.PermissionDenied, "no identity issued")
}
return resp, nil
}
// FetchJWTBundles processes request for JWT bundles
func (h *Handler) FetchJWTBundles(_ *workload.JWTBundlesRequest, stream workload.SpiffeWorkloadAPI_FetchJWTBundlesServer) error {
ctx := stream.Context()
log := rpccontext.Logger(ctx)
selectors, err := h.c.Attestor.Attest(ctx)
if err != nil {
log.WithError(err).Error("Workload attestation failed")
return err
}
subscriber, err := h.c.Manager.SubscribeToCacheChanges(ctx, selectors)
if err != nil {
log.WithError(err).Error("Subscribe to cache changes failed")
return err
}
defer subscriber.Finish()
var previousResp *workload.JWTBundlesResponse
for {
select {
case update := <-subscriber.Updates():
if previousResp, err = sendJWTBundlesResponse(update, stream, log, h.c.AllowUnauthenticatedVerifiers, previousResp); err != nil {
return err
}
case <-ctx.Done():
return nil
}
}
}
// ValidateJWTSVID processes request for JWT-SVID validation
func (h *Handler) ValidateJWTSVID(ctx context.Context, req *workload.ValidateJWTSVIDRequest) (*workload.ValidateJWTSVIDResponse, error) {
log := rpccontext.Logger(ctx)
if req.Audience == "" {
log.Error("Missing required audience parameter")
return nil, status.Error(codes.InvalidArgument, "audience must be specified")
}
if req.Svid == "" {
log.Error("Missing required svid parameter")
return nil, status.Error(codes.InvalidArgument, "svid must be specified")
}
log = log.WithField(telemetry.Audience, req.Audience)
selectors, err := h.c.Attestor.Attest(ctx)
if err != nil {
log.WithError(err).Error("Workload attestation failed")
return nil, err
}
bundles := h.getWorkloadBundles(selectors)
keyStore, err := keyStoreFromBundles(bundles)
if err != nil {
log.WithError(err).Error("Failed to build key store from bundles")
return nil, status.Error(codes.Internal, err.Error())
}
id, claims, err := jwtsvid.ValidateToken(ctx, req.Svid, keyStore, []string{req.Audience})
if err != nil {
log.WithError(err).Warn("Failed to validate JWT")
return nil, status.Error(codes.InvalidArgument, err.Error())
}
log.WithField(telemetry.SPIFFEID, id).Debug("Successfully validated JWT")
if !id.MemberOf(h.c.TrustDomain) {
for claim := range claims {
if !isClaimAllowed(claim, h.c.AllowedForeignJWTClaims) {
delete(claims, claim)
}
}
}
// RFC 7519 structures `aud` as an array of StringOrURIs but has a special
// case where it MAY be specified as a single StringOrURI if there is only
// one audience. We have traditionally always returned it as an array but
// the JWT library we use now returns a single string when there is only
// one. To maintain backcompat, convert a single string value for the
// audience to a list.
if aud, ok := claims["aud"].(string); ok {
claims["aud"] = []string{aud}
}
s, err := structFromValues(claims)
if err != nil {
log.WithError(err).Error("Error deserializing claims from JWT-SVID")
return nil, status.Error(codes.InvalidArgument, err.Error())
}
return &workload.ValidateJWTSVIDResponse{
SpiffeId: id.String(),
Claims: s,
}, nil
}
// FetchX509SVID processes request for a x509 SVID. In case of multiple fetched SVIDs with same hint, the SVID that has the oldest
// associated entry will be returned.
func (h *Handler) FetchX509SVID(_ *workload.X509SVIDRequest, stream workload.SpiffeWorkloadAPI_FetchX509SVIDServer) error {
ctx := stream.Context()
log := rpccontext.Logger(ctx)
selectors, err := h.c.Attestor.Attest(ctx)
if err != nil {
log.WithError(err).Error("Workload attestation failed")
return err
}
subscriber, err := h.c.Manager.SubscribeToCacheChanges(ctx, selectors)
if err != nil {
log.WithError(err).Error("Subscribe to cache changes failed")
return err
}
defer subscriber.Finish()
// The agent health check currently exercises the Workload API.
// Only log if it is not the agent itself.
quietLogging := isAgent(ctx)
for {
select {
case update := <-subscriber.Updates():
update.Identities = filterIdentities(update.Identities, log)
if err := sendX509SVIDResponse(update, stream, log, quietLogging); err != nil {
return err
}
case <-ctx.Done():
return nil
}
}
}
// FetchX509Bundles processes request for x509 bundles
func (h *Handler) FetchX509Bundles(_ *workload.X509BundlesRequest, stream workload.SpiffeWorkloadAPI_FetchX509BundlesServer) error {
ctx := stream.Context()
log := rpccontext.Logger(ctx)
selectors, err := h.c.Attestor.Attest(ctx)
if err != nil {
log.WithError(err).Error("Workload attestation failed")
return err
}
subscriber, err := h.c.Manager.SubscribeToCacheChanges(ctx, selectors)
if err != nil {
log.WithError(err).Error("Subscribe to cache changes failed")
return err
}
defer subscriber.Finish()
// The agent health check currently exercises the Workload API.
// Only log if it is not the agent itself.
quietLogging := isAgent(ctx)
var previousResp *workload.X509BundlesResponse
for {
select {
case update := <-subscriber.Updates():
previousResp, err = sendX509BundlesResponse(update, stream, log, h.c.AllowUnauthenticatedVerifiers, previousResp, quietLogging)
if err != nil {
return err
}
case <-ctx.Done():
return nil
}
}
}
func (h *Handler) fetchJWTSVID(ctx context.Context, log logrus.FieldLogger, entry *common.RegistrationEntry, audience []string) (*workload.JWTSVID, error) {
spiffeID, err := spiffeid.FromString(entry.SpiffeId)
if err != nil {
log.WithError(err).Error("Invalid requested SPIFFE ID")
return nil, status.Errorf(codes.InvalidArgument, "invalid requested SPIFFE ID: %v", err)
}
svid, err := h.c.Manager.FetchJWTSVID(ctx, entry, audience)
if err != nil {
log.WithError(err).Error("Could not fetch JWT-SVID")
return nil, status.Errorf(codes.Unavailable, "could not fetch JWT-SVID: %v", err)
}
ttl := time.Until(svid.ExpiresAt)
log.WithField(telemetry.TTL, ttl.Seconds()).Debug("Fetched JWT SVID")
return &workload.JWTSVID{
SpiffeId: spiffeID.String(),
Svid: svid.Token,
Hint: entry.Hint,
}, nil
}
func sendX509BundlesResponse(update *cache.WorkloadUpdate, stream workload.SpiffeWorkloadAPI_FetchX509BundlesServer, log logrus.FieldLogger, allowUnauthenticatedVerifiers bool, previousResponse *workload.X509BundlesResponse, quietLogging bool) (*workload.X509BundlesResponse, error) {
if !allowUnauthenticatedVerifiers && !update.HasIdentity() {
if !quietLogging {
log.WithField(telemetry.Registered, false).Error("No identity issued")
}
return nil, status.Error(codes.PermissionDenied, "no identity issued")
}
resp, err := composeX509BundlesResponse(update)
if err != nil {
log.WithError(err).Error("Could not serialize X509 bundle response")
return nil, status.Errorf(codes.Unavailable, "could not serialize response: %v", err)
}
if proto.Equal(resp, previousResponse) {
return previousResponse, nil
}
if err := stream.Send(resp); err != nil {
log.WithError(err).Error("Failed to send X509 bundle response")
return nil, err
}
return resp, nil
}
func composeX509BundlesResponse(update *cache.WorkloadUpdate) (*workload.X509BundlesResponse, error) {
if update.Bundle == nil {
// This should be purely defensive since the cache should always supply
// a bundle.
return nil, errors.New("bundle not available")
}
bundles := make(map[string][]byte)
bundles[update.Bundle.TrustDomain().IDString()] = marshalBundle(update.Bundle.X509Authorities())
if update.HasIdentity() {
for _, federatedBundle := range update.FederatedBundles {
bundles[federatedBundle.TrustDomain().IDString()] = marshalBundle(federatedBundle.X509Authorities())
}
}
return &workload.X509BundlesResponse{
Bundles: bundles,
}, nil
}
func sendX509SVIDResponse(update *cache.WorkloadUpdate, stream workload.SpiffeWorkloadAPI_FetchX509SVIDServer, log logrus.FieldLogger, quietLogging bool) (err error) {
if len(update.Identities) == 0 {
if !quietLogging {
log.WithField(telemetry.Registered, false).Error("No identity issued")
}
return status.Error(codes.PermissionDenied, "no identity issued")
}
log = log.WithField(telemetry.Registered, true)
resp, err := composeX509SVIDResponse(update)
if err != nil {
log.WithError(err).Error("Could not serialize X.509 SVID response")
return status.Errorf(codes.Unavailable, "could not serialize response: %v", err)
}
if err := stream.Send(resp); err != nil {
log.WithError(err).Error("Failed to send X.509 SVID response")
return err
}
log = log.WithField(telemetry.Count, len(resp.Svids))
// log and emit telemetry on each SVID
// a response has already been sent so nothing is
// blocked on this logic
if !quietLogging {
for i, svid := range resp.Svids {
ttl := time.Until(update.Identities[i].SVID[0].NotAfter)
log.WithFields(logrus.Fields{
telemetry.SPIFFEID: svid.SpiffeId,
telemetry.TTL: ttl.Seconds(),
}).Debug("Fetched X.509 SVID")
}
}
return nil
}
func composeX509SVIDResponse(update *cache.WorkloadUpdate) (*workload.X509SVIDResponse, error) {
resp := new(workload.X509SVIDResponse)
resp.Svids = []*workload.X509SVID{}
resp.FederatedBundles = make(map[string][]byte)
bundle := marshalBundle(update.Bundle.X509Authorities())
for td, federatedBundle := range update.FederatedBundles {
resp.FederatedBundles[td.IDString()] = marshalBundle(federatedBundle.X509Authorities())
}
for _, identity := range update.Identities {
id := identity.Entry.SpiffeId
keyData, err := x509.MarshalPKCS8PrivateKey(identity.PrivateKey)
if err != nil {
return nil, fmt.Errorf("marshal key for %v: %w", id, err)
}
svid := &workload.X509SVID{
SpiffeId: id,
X509Svid: x509util.DERFromCertificates(identity.SVID),
X509SvidKey: keyData,
Bundle: bundle,
Hint: identity.Entry.Hint,
}
resp.Svids = append(resp.Svids, svid)
}
return resp, nil
}
func sendJWTBundlesResponse(update *cache.WorkloadUpdate, stream workload.SpiffeWorkloadAPI_FetchJWTBundlesServer, log logrus.FieldLogger, allowUnauthenticatedVerifiers bool, previousResponse *workload.JWTBundlesResponse) (*workload.JWTBundlesResponse, error) {
if !allowUnauthenticatedVerifiers && !update.HasIdentity() {
log.WithField(telemetry.Registered, false).Error("No identity issued")
return nil, status.Error(codes.PermissionDenied, "no identity issued")
}
resp, err := composeJWTBundlesResponse(update)
if err != nil {
log.WithError(err).Error("Could not serialize JWT bundle response")
return nil, status.Errorf(codes.Unavailable, "could not serialize response: %v", err)
}
if proto.Equal(resp, previousResponse) {
return previousResponse, nil
}
if err := stream.Send(resp); err != nil {
log.WithError(err).Error("Failed to send JWT bundle response")
return nil, err
}
return resp, nil
}
func composeJWTBundlesResponse(update *cache.WorkloadUpdate) (*workload.JWTBundlesResponse, error) {
if update.Bundle == nil {
// This should be purely defensive since the cache should always supply
// a bundle.
return nil, errors.New("bundle not available")
}
bundles := make(map[string][]byte)
jwksBytes, err := bundleutil.Marshal(update.Bundle, bundleutil.NoX509SVIDKeys(), bundleutil.StandardJWKS())
if err != nil {
return nil, err
}
bundles[update.Bundle.TrustDomain().IDString()] = jwksBytes
if update.HasIdentity() {
for _, federatedBundle := range update.FederatedBundles {
jwksBytes, err := bundleutil.Marshal(federatedBundle, bundleutil.NoX509SVIDKeys(), bundleutil.StandardJWKS())
if err != nil {
return nil, err
}
bundles[federatedBundle.TrustDomain().IDString()] = jwksBytes
}
}
return &workload.JWTBundlesResponse{
Bundles: bundles,
}, nil
}
// isAgent returns true if the caller PID from the provided context is the
// agent's process ID.
func isAgent(ctx context.Context) bool {
return rpccontext.CallerPID(ctx) == os.Getpid()
}
func (h *Handler) getWorkloadBundles(selectors []*common.Selector) (bundles []*spiffebundle.Bundle) {
update := h.c.Manager.FetchWorkloadUpdate(selectors)
if update.Bundle != nil {
bundles = append(bundles, update.Bundle)
}
for _, federatedBundle := range update.FederatedBundles {
bundles = append(bundles, federatedBundle)
}
return bundles
}
func marshalBundle(certs []*x509.Certificate) []byte {
bundle := []byte{}
for _, c := range certs {
bundle = append(bundle, c.Raw...)
}
return bundle
}
func keyStoreFromBundles(bundles []*spiffebundle.Bundle) (jwtsvid.KeyStore, error) {
trustDomainKeys := make(map[spiffeid.TrustDomain]map[string]crypto.PublicKey)
for _, bundle := range bundles {
td, err := spiffeid.TrustDomainFromString(bundle.TrustDomain().IDString())
if err != nil {
return nil, err
}
trustDomainKeys[td] = bundle.JWTAuthorities()
}
return jwtsvid.NewKeyStore(trustDomainKeys), nil
}
func structFromValues(values map[string]any) (*structpb.Struct, error) {
valuesJSON, err := json.Marshal(values)
if err != nil {
return nil, errs.Wrap(err)
}
s := new(structpb.Struct)
if err := protojson.Unmarshal(valuesJSON, s); err != nil {
return nil, errs.Wrap(err)
}
return s, nil
}
func isClaimAllowed(claim string, allowedClaims map[string]struct{}) bool {
switch claim {
case "sub", "exp", "aud":
return true
default:
_, ok := allowedClaims[claim]
return ok
}
}
func filterIdentities(identities []cache.Identity, log logrus.FieldLogger) []cache.Identity {
var filteredIdentities []cache.Identity
var entries []*common.RegistrationEntry
for _, identity := range identities {
entries = append(entries, identity.Entry)
}
entriesToRemove := getEntriesToRemove(entries, log)
for _, identity := range identities {
if _, ok := entriesToRemove[identity.Entry.EntryId]; !ok {
filteredIdentities = append(filteredIdentities, identity)
}
}
return filteredIdentities
}
func filterRegistrations(entries []*common.RegistrationEntry, log logrus.FieldLogger) []*common.RegistrationEntry {
var filteredEntries []*common.RegistrationEntry
entriesToRemove := getEntriesToRemove(entries, log)
for _, entry := range entries {
if _, ok := entriesToRemove[entry.EntryId]; !ok {
filteredEntries = append(filteredEntries, entry)
}
}
return filteredEntries
}
func getEntriesToRemove(entries []*common.RegistrationEntry, log logrus.FieldLogger) map[string]struct{} {
entriesToRemove := make(map[string]struct{})
hintsMap := make(map[string]*common.RegistrationEntry)
for _, entry := range entries {
if entry.Hint == "" {
continue
}
if entryWithNonUniqueHint, ok := hintsMap[entry.Hint]; ok {
entryToMaintain, entryToRemove := hintTieBreaking(entry, entryWithNonUniqueHint)
hintsMap[entry.Hint] = entryToMaintain
entriesToRemove[entryToRemove.EntryId] = struct{}{}
log.WithFields(logrus.Fields{
telemetry.Hint: entryToRemove.Hint,
telemetry.RegistrationID: entryToRemove.EntryId,
}).Warn("Ignoring entry with duplicate hint")
} else {
hintsMap[entry.Hint] = entry
}
}
return entriesToRemove
}
func hintTieBreaking(entryA *common.RegistrationEntry, entryB *common.RegistrationEntry) (maintain *common.RegistrationEntry, remove *common.RegistrationEntry) {
switch {
case entryA.CreatedAt < entryB.CreatedAt:
maintain = entryA
remove = entryB
case entryA.CreatedAt > entryB.CreatedAt:
maintain = entryB
remove = entryA
default:
if entryA.EntryId < entryB.EntryId {
maintain = entryA
remove = entryB
} else {
maintain = entryB
remove = entryA
}
}
return
}