Skip to content

Commit

Permalink
cache the authorisers rather than recreating them
Browse files Browse the repository at this point in the history
  • Loading branch information
hawkowl committed Jun 28, 2024
1 parent 269a709 commit 280b8b0
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
6 changes: 5 additions & 1 deletion pkg/env/core.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ type Core interface {
IsLocalDevelopmentMode() bool
IsCI() bool
NewMSITokenCredential() (azcore.TokenCredential, error)
NewMSIAuthorizer(...string) (autorest.Authorizer, error)
NewMSIAuthorizer(scope string) (autorest.Authorizer, error)
NewLiveConfigManager(context.Context) (liveconfig.Manager, error)
instancemetadata.InstanceMetadata

Expand All @@ -53,6 +53,8 @@ type core struct {

component ServiceComponent
componentLog *logrus.Entry

msiAuthorizers map[string]autorest.Authorizer
}

func (c *core) IsLocalDevelopmentMode() bool {
Expand Down Expand Up @@ -109,6 +111,7 @@ func NewCore(ctx context.Context, log *logrus.Entry, component ServiceComponent)
isCI: isCI,
component: component,
componentLog: componentLog,
msiAuthorizers: map[string]autorest.Authorizer{},
}, nil
}

Expand All @@ -131,5 +134,6 @@ func NewCoreForCI(ctx context.Context, log *logrus.Entry) (Core, error) {
return &core{
InstanceMetadata: im,
isLocalDevelopmentMode: isLocalDevelopmentMode,
msiAuthorizers: map[string]autorest.Authorizer{},
}, nil
}
13 changes: 11 additions & 2 deletions pkg/env/msiauthorizer.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,19 @@ func (c *core) NewMSITokenCredential() (azcore.TokenCredential, error) {
return azidentity.NewClientSecretCredential(tenantId, azureClientId, azureClientSecret, options)
}

func (c *core) NewMSIAuthorizer(scopes ...string) (autorest.Authorizer, error) {
func (c *core) NewMSIAuthorizer(scope string) (autorest.Authorizer, error) {
// To prevent creating multiple authorisers with independent token
// refreshes, store them in a cache per-scope when created
auth, ok := c.msiAuthorizers[scope]
if ok {
return auth, nil
}

token, err := c.NewMSITokenCredential()
if err != nil {
return nil, err
}
return azidext.NewTokenCredentialAdapter(token, scopes), nil
auth = azidext.NewTokenCredentialAdapter(token, []string{scope})
c.msiAuthorizers[scope] = auth
return auth, nil
}

0 comments on commit 280b8b0

Please sign in to comment.