Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add FetchJWTSVIDs and SubscribeToJWTBundles #2789

Merged
merged 14 commits into from
Apr 5, 2022
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
139 changes: 132 additions & 7 deletions pkg/agent/api/delegatedidentity/v1/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,21 @@ import (
"crypto/x509"
"fmt"
"sort"
"time"

"github.com/sirupsen/logrus"
"github.com/spiffe/go-spiffe/v2/spiffeid"
delegatedidentityv1 "github.com/spiffe/spire-api-sdk/proto/spire/api/agent/delegatedidentity/v1"
"github.com/spiffe/spire-api-sdk/proto/spire/api/types"
"github.com/spiffe/spire/pkg/agent/api/rpccontext"
workload_attestor "github.com/spiffe/spire/pkg/agent/attestor/workload"
"github.com/spiffe/spire/pkg/agent/client"
"github.com/spiffe/spire/pkg/agent/endpoints"
"github.com/spiffe/spire/pkg/agent/manager"
"github.com/spiffe/spire/pkg/agent/manager/cache"
"github.com/spiffe/spire/pkg/common/bundleutil"
"github.com/spiffe/spire/pkg/common/idutil"
"github.com/spiffe/spire/pkg/common/telemetry"
"github.com/spiffe/spire/pkg/common/x509util"
"github.com/spiffe/spire/pkg/server/api"
"github.com/spiffe/spire/proto/spire/common"
Expand All @@ -33,10 +38,10 @@ type attestor interface {
}

type Config struct {
Log logrus.FieldLogger
Manager manager.Manager
Attestor workload_attestor.Attestor
AuthorizedDelegates []string
Log logrus.FieldLogger
Manager manager.Manager
Attestor workload_attestor.Attestor
AuthorizedDelegates []string
}

func New(config Config) *Service {
Expand All @@ -47,9 +52,9 @@ func New(config Config) *Service {
}

return &Service{
manager: config.Manager,
attestor: endpoints.PeerTrackerAttestor{Attestor: config.Attestor},
authorizedDelegates: AuthorizedDelegates,
manager: config.Manager,
attestor: endpoints.PeerTrackerAttestor{Attestor: config.Attestor},
authorizedDelegates: AuthorizedDelegates,
}
}

Expand Down Expand Up @@ -245,6 +250,126 @@ func (s *Service) SubscribeToX509Bundles(req *delegatedidentityv1.SubscribeToX50
}
}

func (s *Service) FetchJWTSVIDs(ctx context.Context, req *delegatedidentityv1.FetchJWTSVIDsRequest) (resp *delegatedidentityv1.FetchJWTSVIDsResponse, 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 _, err = s.isCallerAuthorized(ctx, log, nil); err != nil {
return nil, err
}

selectors, err := api.SelectorsFromProto(req.Selectors)
if err != nil {
log.WithError(err).Error("Invalid argument; could not parse provided selectors")
return nil, status.Error(codes.InvalidArgument, "could not parse provided selectors")
}
var spiffeIDs []spiffeid.ID

log = log.WithField(telemetry.Registered, true)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like registered is set to false if spiffeIDs is empty, but errors from matching identities (278l) will have Registered = true.
May we set Registered = true, only if spiffeIDs != 0?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I temporarily removed the Registered ID, and I looked at the description in telemetry. It is more like whether the caller is authenticated


identities := s.manager.MatchingIdentities(selectors)
for _, identity := range identities {

spiffeID, err := spiffeid.FromString(identity.Entry.SpiffeId)
if err != nil {
log.WithField(telemetry.SPIFFEID, identity.Entry.SpiffeId).WithError(err).Error("Invalid requested SPIFFE ID")
return nil, status.Errorf(codes.InvalidArgument, "invalid requested SPIFFE ID: %v", err)
}

spiffeIDs = append(spiffeIDs, spiffeID)
}

if len(spiffeIDs) == 0 {
log.WithField(telemetry.Registered, false).Error("No identity issued")
return nil, status.Error(codes.PermissionDenied, "no identity issued")
}

resp = new(delegatedidentityv1.FetchJWTSVIDsResponse)
for _, id := range spiffeIDs {
loopLog := log.WithField(telemetry.SPIFFEID, id.String())

var svid *client.JWTSVID
svid, err = s.manager.FetchJWTSVID(ctx, id, req.Audience)
if err != nil {
loopLog.WithError(err).Error("Could not fetch JWT-SVID")
return nil, status.Errorf(codes.Unavailable, "could not fetch JWT-SVID: %v", err)
}
resp.Svids = append(resp.Svids, &types.JWTSVID{
Token: svid.Token,
Id: &types.SPIFFEID{
TrustDomain: id.TrustDomain().String(),
Path: id.Path(),
},
ExpiresAt: svid.ExpiresAt.Unix(),
IssuedAt: svid.IssuedAt.Unix(),
})

ttl := time.Until(svid.ExpiresAt)
loopLog.WithField(telemetry.TTL, ttl.Seconds()).Debug("Fetched JWT SVID")
}

return resp, nil
}

func (s *Service) SubscribeToJWTBundles(req *delegatedidentityv1.SubscribeToJWTBundlesRequest, stream delegatedidentityv1.DelegatedIdentity_SubscribeToJWTBundlesServer) error {
ctx := stream.Context()
log := rpccontext.Logger(ctx)
cachedSelectors, err := s.isCallerAuthorized(ctx, log, nil)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

move cachedSelectors together to error verification

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure if your comment is

var cachedSelectors []*common.Selector
if cachedSelectors, err: = s.is CallerAuthorized (ctx, log, nil); err! = nil {return err} 

I looked at the spire code and did not recommend such an implementation. Are you sure we need this?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sorry for the confusion... it is basically put error verification together with line where error is returned,
for example:

ctx := stream.Context()
log := rpccontext.Logger(ctx)

cachedSelectors, err := s.isCallerAuthorized(ctx, log, nil)
if err != nil {
	return err
}

it is generally written this way to simplify reading

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

😯 I do pay little attention to this matter, it has been completed now.


if err != nil {
return err
}

subscriber := s.manager.SubscribeToBundleChanges()

// send initial update....
jwtbundles := make(map[string][]byte)
for td, bundle := range subscriber.Value() {
jwksBytes, err := bundleutil.Marshal(bundle, bundleutil.NoX509SVIDKeys(), bundleutil.StandardJWKS())
if err != nil {
return err
}
jwtbundles[td.IDString()] = jwksBytes
}

resp := &delegatedidentityv1.SubscribeToJWTBundlesResponse{
Bundles: jwtbundles,
}

if err := stream.Send(resp); err != nil {
return err
}
for {
select {
case <-subscriber.Changes():
if _, err := s.isCallerAuthorized(ctx, log, cachedSelectors); err != nil {
return err
}
for td, bundle := range subscriber.Next() {
jwksBytes, err := bundleutil.Marshal(bundle, bundleutil.NoX509SVIDKeys(), bundleutil.StandardJWKS())
if err != nil {
return err
}
jwtbundles[td.IDString()] = jwksBytes
}

resp := &delegatedidentityv1.SubscribeToJWTBundlesResponse{
Bundles: jwtbundles,
}

if err := stream.Send(resp); err != nil {
return err
}
case <-ctx.Done():
return nil
}
}
}

func marshalBundle(certs []*x509.Certificate) []byte {
bundle := []byte{}
for _, c := range certs {
Expand Down