Skip to content

Commit

Permalink
Fix incorrect storing of expiration time
Browse files Browse the repository at this point in the history
Signed-off-by: Vui Lam <vui.lam@broadcom.com>
  • Loading branch information
vuil committed Oct 7, 2024
1 parent eb91f11 commit 1e0a132
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
6 changes: 4 additions & 2 deletions pkg/auth/common/token.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ const (
extraIDToken = "id_token"
)

var currentTime = time.Now

const (
APITokenType = "api-token"
IDTokenType = "id-token"
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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
}
14 changes: 12 additions & 2 deletions pkg/auth/common/token_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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)

Expand All @@ -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)
}

0 comments on commit 1e0a132

Please sign in to comment.