@@ -40,6 +40,14 @@ func WithTokenExchangeClientCache(cache cache.Cache) ExchangeClientOpts {
4040 }
4141}
4242
43+ // WithMinimumCacheTTL allows setting the minimum amount of time that a cache
44+ // entry must be valid for in order for it to be reused.
45+ func WithMinimumCacheTTL (ttl time.Duration ) ExchangeClientOpts {
46+ return func (c * TokenExchangeClient ) {
47+ c .minimumTTL = ttl
48+ }
49+ }
50+
4351func NewTokenExchangeClient (cfg TokenExchangeConfig , opts ... ExchangeClientOpts ) (* TokenExchangeClient , error ) {
4452 if cfg .Token == "" {
4553 return nil , fmt .Errorf ("%w: missing required token" , ErrMissingConfig )
@@ -50,9 +58,10 @@ func NewTokenExchangeClient(cfg TokenExchangeConfig, opts ...ExchangeClientOpts)
5058 }
5159
5260 c := & TokenExchangeClient {
53- cache : nil , // See below.
54- cfg : cfg ,
55- singlef : singleflight.Group {},
61+ cache : nil , // See below.
62+ minimumTTL : 15 * time .Second ,
63+ cfg : cfg ,
64+ singlef : singleflight.Group {},
5665 }
5766
5867 for _ , opt := range opts {
@@ -77,14 +86,14 @@ func NewTokenExchangeClient(cfg TokenExchangeConfig, opts ...ExchangeClientOpts)
7786 }
7887
7988 return c , nil
80-
8189}
8290
8391type TokenExchangeClient struct {
84- cache cache.Cache
85- cfg TokenExchangeConfig
86- client * http.Client
87- singlef singleflight.Group
92+ cache cache.Cache
93+ minimumTTL time.Duration // Minimum time that token must be valid to be reused.
94+ cfg TokenExchangeConfig
95+ client * http.Client
96+ singlef singleflight.Group
8897}
8998
9099type TokenExchangeRequest struct {
@@ -207,8 +216,6 @@ func (c *TokenExchangeClient) getCache(ctx context.Context, key string) (string,
207216}
208217
209218func (c * TokenExchangeClient ) setCache (ctx context.Context , token string , key string ) error {
210- const cacheLeeway = 15 * time .Second
211-
212219 parsed , err := jwt .ParseSigned (token )
213220 if err != nil {
214221 return fmt .Errorf ("failed to parse token: %v" , err )
@@ -219,7 +226,7 @@ func (c *TokenExchangeClient) setCache(ctx context.Context, token string, key st
219226 return fmt .Errorf ("failed to extract claims from the token: %v" , err )
220227 }
221228
222- return c .cache .Set (ctx , key , []byte (token ), time .Until (claims .Expiry .Time ())- cacheLeeway )
229+ return c .cache .Set (ctx , key , []byte (token ), time .Until (claims .Expiry .Time ())- c . minimumTTL )
223230}
224231
225232var _ TokenExchanger = StaticTokenExchanger {}
0 commit comments