@@ -22,6 +22,8 @@ type TokenExchanger interface {
2222 Exchange (ctx context.Context , r TokenExchangeRequest ) (* TokenExchangeResponse , error )
2323}
2424
25+ const defaultCacheTTL = 15 * time .Second
26+
2527var _ TokenExchanger = & TokenExchangeClient {}
2628
2729// ExchangeClientOpts allows setting custom parameters during construction.
@@ -40,6 +42,14 @@ func WithTokenExchangeClientCache(cache cache.Cache) ExchangeClientOpts {
4042 }
4143}
4244
45+ // WithMinimumCacheTTL allows setting the minimum amount of time that a cache
46+ // entry must be valid for in order for it to be reused.
47+ func WithMinimumCacheTTL (ttl time.Duration ) ExchangeClientOpts {
48+ return func (c * TokenExchangeClient ) {
49+ c .minimumTTL = ttl
50+ }
51+ }
52+
4353func NewTokenExchangeClient (cfg TokenExchangeConfig , opts ... ExchangeClientOpts ) (* TokenExchangeClient , error ) {
4454 if cfg .Token == "" {
4555 return nil , fmt .Errorf ("%w: missing required token" , ErrMissingConfig )
@@ -50,9 +60,10 @@ func NewTokenExchangeClient(cfg TokenExchangeConfig, opts ...ExchangeClientOpts)
5060 }
5161
5262 c := & TokenExchangeClient {
53- cache : nil , // See below.
54- cfg : cfg ,
55- singlef : singleflight.Group {},
63+ cache : nil , // See below.
64+ minimumTTL : defaultCacheTTL ,
65+ cfg : cfg ,
66+ singlef : singleflight.Group {},
5667 }
5768
5869 for _ , opt := range opts {
@@ -77,14 +88,14 @@ func NewTokenExchangeClient(cfg TokenExchangeConfig, opts ...ExchangeClientOpts)
7788 }
7889
7990 return c , nil
80-
8191}
8292
8393type TokenExchangeClient struct {
84- cache cache.Cache
85- cfg TokenExchangeConfig
86- client * http.Client
87- singlef singleflight.Group
94+ cache cache.Cache
95+ minimumTTL time.Duration // Minimum time that token must be valid to be reused.
96+ cfg TokenExchangeConfig
97+ client * http.Client
98+ singlef singleflight.Group
8899}
89100
90101type TokenExchangeRequest struct {
@@ -207,8 +218,6 @@ func (c *TokenExchangeClient) getCache(ctx context.Context, key string) (string,
207218}
208219
209220func (c * TokenExchangeClient ) setCache (ctx context.Context , token string , key string ) error {
210- const cacheLeeway = 15 * time .Second
211-
212221 parsed , err := jwt .ParseSigned (token )
213222 if err != nil {
214223 return fmt .Errorf ("failed to parse token: %v" , err )
@@ -219,7 +228,7 @@ func (c *TokenExchangeClient) setCache(ctx context.Context, token string, key st
219228 return fmt .Errorf ("failed to extract claims from the token: %v" , err )
220229 }
221230
222- return c .cache .Set (ctx , key , []byte (token ), time .Until (claims .Expiry .Time ())- cacheLeeway )
231+ return c .cache .Set (ctx , key , []byte (token ), time .Until (claims .Expiry .Time ())- c . minimumTTL )
223232}
224233
225234var _ TokenExchanger = StaticTokenExchanger {}
0 commit comments