diff --git a/pkg/auth/common/token.go b/pkg/auth/common/token.go index 6a4141a49..b3960f97e 100644 --- a/pkg/auth/common/token.go +++ b/pkg/auth/common/token.go @@ -20,6 +20,8 @@ const ( extraIDToken = "id_token" ) +var currentTime = time.Now + const ( APITokenType = "api-token" IDTokenType = "id-token" @@ -97,7 +99,7 @@ func GetToken(g *types.GlobalServerAuth, tokenGetter func(refreshOrAPIToken, acc g.RefreshToken = token.RefreshToken g.AccessToken = token.AccessToken g.IDToken = token.IDToken - expiration := time.Now().Local().Add(time.Duration(token.ExpiresIn)) + expiration := currentTime().Local().Add(time.Duration(token.ExpiresIn) * time.Second) g.Expiration = expiration g.Permissions = claims.Permissions @@ -171,7 +173,7 @@ func ParseToken(tkn *oauth2.Token, idpType config.IdpType) (*Claims, error) { func IsExpired(tokenExpiry time.Time) bool { // refresh at half token life two := 2 - now := time.Now().Unix() + now := currentTime().Unix() halfDur := -time.Duration((tokenExpiry.Unix()-now)/int64(two)) * time.Second return tokenExpiry.Add(halfDur).Unix() < now } diff --git a/pkg/auth/common/token_test.go b/pkg/auth/common/token_test.go index 94884486a..ee4674e22 100644 --- a/pkg/auth/common/token_test.go +++ b/pkg/auth/common/token_test.go @@ -188,12 +188,19 @@ func TestGetToken_Valid_NotExpired(t *testing.T) { } func TestGetToken_Expired(t *testing.T) { + var theOneNow = time.Now() + // override currentTime to always returns same value + currentTime = func() time.Time { + return theOneNow + } + assert := assert.New(t) accessToken := generateJWTToken( `{"sub":"1234567890","username":"joe","context_name":"1516239022"}`, ) - expireTime := time.Now().Add(-time.Minute * 30) + + expireTime := currentTime().Add(-time.Minute * 30) serverAuth := configtypes.GlobalServerAuth{ Issuer: "https://oidc.example.com", @@ -206,7 +213,8 @@ func TestGetToken_Expired(t *testing.T) { } newRefreshToken := "LetMeInAgain" - newExpiry := int64(time.Until(time.Now().Add(time.Minute * 30)).Seconds()) + newExpiryTime := currentTime().Local().Add(time.Minute * 30) + newExpiry := int64(30 * 60) tokenGetter := createMockTokenGetter(newRefreshToken, newExpiry) @@ -215,4 +223,6 @@ func TestGetToken_Expired(t *testing.T) { assert.NotNil(tok) assert.Equal(tok.AccessToken, accessToken) assert.Equal(tok.RefreshToken, newRefreshToken) + assert.Equal(tok.Expiry, newExpiryTime) + assert.Equal(serverAuth.Expiration, newExpiryTime) }