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

Use function name as cache key for function access tokens #30

Merged
merged 2 commits into from
Jun 14, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -199,9 +199,12 @@ client := sdk.NewClientWithOpts(gatewayURL, http.DefaultClient, sdk.WithFunction
Optionally a `TokenCache` can be configured to cache function access tokens and prevent the client from having to do a token exchange each time a function is invoked.

```go
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

fnTokenCache := sdk.NewMemoryTokenCache()
// Start garbage collection to remove expired tokens from the cache.
go fnTokenCache.StartGC(context.Background(), time.Second*10)
go fnTokenCache.StartGC(ctx, time.Second*10)

client := sdk.NewClientWithOpts(
gatewayUrl,
Expand Down
18 changes: 1 addition & 17 deletions functions.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package sdk

import (
"crypto/sha256"
"fmt"
"net/http"
)
Expand Down Expand Up @@ -36,8 +35,7 @@ func (c *Client) InvokeFunction(name, namespace string, async bool, auth bool, r
if c.fnTokenCache != nil {
// Function access tokens are cached as long as the token is valid
// to prevent having to do a token exchange each time the function is invoked.
cacheKey := getFunctionTokenCacheKey(idToken, fmt.Sprintf("%s.%s", name, namespace))

cacheKey := fmt.Sprintf("%s.%s", name, namespace)
token, ok := c.fnTokenCache.Get(cacheKey)
if !ok {
token, err = ExchangeIDToken(tokenURL, idToken, WithScope(scope), WithAudience(audience))
Expand All @@ -63,17 +61,3 @@ func (c *Client) InvokeFunction(name, namespace string, async bool, auth bool, r

return c.do(req)
}

// getFunctionTokenCacheKey computes a cache key for caching a function access token based
// on the original id token that is exchanged for the function access token and the function
// name e.g. figlet.openfaas-fn.
// The original token is included in the hash to avoid cache hits for a function when the
// source token changes.
func getFunctionTokenCacheKey(idToken string, serviceName string) string {
hash := sha256.New()
hash.Write([]byte(idToken))
hash.Write([]byte(serviceName))

sum := hash.Sum(nil)
return fmt.Sprintf("%x", sum)
}
Loading