Skip to content

Commit fb9b033

Browse files
author
Patrick Müller
committed
fix(key_flow): Add 5 second leeway to refresh access tokens early
1 parent cf32f72 commit fb9b033

File tree

2 files changed

+14
-3
lines changed

2 files changed

+14
-3
lines changed

core/clients/key_flow.go

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ const (
3232
tokenAPI = "https://service-account.api.stackit.cloud/token" //nolint:gosec // linter false positive
3333
defaultTokenType = "Bearer"
3434
defaultScope = ""
35+
tokenExpirationLeeway = time.Second * 5
3536
)
3637

3738
// KeyFlow handles auth with SA key
@@ -400,11 +401,15 @@ func tokenExpired(token string) (bool, error) {
400401
if err != nil {
401402
return false, fmt.Errorf("parse token: %w", err)
402403
}
404+
403405
expirationTimestampNumeric, err := tokenParsed.Claims.GetExpirationTime()
404406
if err != nil {
405407
return false, fmt.Errorf("get expiration timestamp: %w", err)
406408
}
407-
expirationTimestamp := expirationTimestampNumeric.Time
408-
now := time.Now()
409-
return now.After(expirationTimestamp), nil
409+
410+
// Pretend to be `tokenExpirationLeeway` into the future to avoid token expiring
411+
// between retrieving the token and using it in the actual request.
412+
now := time.Now().Add(tokenExpirationLeeway)
413+
414+
return now.After(expirationTimestampNumeric.Time), nil
410415
}

core/clients/key_flow_test.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,12 @@ func TestTokenExpired(t *testing.T) {
209209
expectedErr: false,
210210
expectedIsExpired: true,
211211
},
212+
{
213+
desc: "token almost expired",
214+
tokenExpiresAt: time.Now().Add(tokenExpirationLeeway),
215+
expectedErr: false,
216+
expectedIsExpired: true,
217+
},
212218
{
213219
desc: "token invalid",
214220
tokenInvalid: true,

0 commit comments

Comments
 (0)