Skip to content

Commit

Permalink
feat: cache cloud tokens
Browse files Browse the repository at this point in the history
  • Loading branch information
adityathebe committed Dec 3, 2024
1 parent 872d21a commit 02035b1
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
22 changes: 22 additions & 0 deletions connection/common.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package connection

import (
"encoding/json"
"fmt"
"time"

"github.com/patrickmn/go-cache"
)

// caches cloud tokens. eg: EKS token, GKE token, ...
var tokenCache = cache.New(time.Hour, time.Hour)

func tokenCacheKey(cloud string, cred any, identifiers string) string {
switch v := cred.(type) {
case string:
return fmt.Sprintf("%s-%s-%s", cloud, v, identifiers)
default:
m, _ := json.Marshal(v)
return fmt.Sprintf("%s-%s", m, identifiers)
}
}
6 changes: 6 additions & 0 deletions connection/eks.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,12 +85,18 @@ func getEKSToken(ctx gocontext.Context, cluster string, conf aws.Config) (string
return "", fmt.Errorf("failed to retrive credentials from aws config: %w", err)
}

cacheKey := tokenCacheKey("eks", cred, cluster)
if found, ok := tokenCache.Get(cacheKey); ok {
return found.(string), nil
}

signedURI, err := getSignedSTSURI(ctx, cluster, cred)
if err != nil {
return "", fmt.Errorf("failed to get signed URI: %w", err)
}

token := v1Prefix + base64.RawURLEncoding.EncodeToString([]byte(signedURI))
tokenCache.Set(cacheKey, token, time.Minute*15)
return token, nil
}

Expand Down
10 changes: 10 additions & 0 deletions connection/gcp.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
package connection

import (
"strings"
"time"

"golang.org/x/oauth2"
"golang.org/x/oauth2/google"

"github.com/flanksource/commons/hash"
"github.com/flanksource/commons/utils"
"github.com/flanksource/duty/context"
"github.com/flanksource/duty/types"
Expand All @@ -29,6 +33,11 @@ func (g *GCPConnection) Validate() *GCPConnection {
}

func (g *GCPConnection) Token(ctx context.Context, scopes ...string) (*oauth2.Token, error) {
cacheKey := tokenCacheKey("gcp", hash.Sha256Hex(g.Credentials.ValueStatic), strings.Join(scopes, ","))
if found, ok := tokenCache.Get(cacheKey); ok {
return found.(*oauth2.Token), nil
}

creds, err := google.CredentialsFromJSON(ctx, []byte(g.Credentials.ValueStatic), scopes...)
if err != nil {
return nil, err
Expand All @@ -40,6 +49,7 @@ func (g *GCPConnection) Token(ctx context.Context, scopes ...string) (*oauth2.To
return nil, err
}

tokenCache.Set(cacheKey, token, time.Until(token.Expiry))
return token, nil
}

Expand Down

0 comments on commit 02035b1

Please sign in to comment.