Skip to content

Commit

Permalink
Fix refresh expiry code and add tests (#577)
Browse files Browse the repository at this point in the history
  • Loading branch information
banikharbanda authored Jun 3, 2024
1 parent 47bbbf3 commit 574c71c
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
12 changes: 12 additions & 0 deletions go/pkg/credshelper/credshelper.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,14 @@ func (c *Credentials) RemoveFromDisk() {
}
}

// refreshStatus checks refresh expiry of credentials in case a manual refresh is required.
func (c *Credentials) refreshStatus() error {
if !c.refreshExp.IsZero() && c.refreshExp.Before(nowFn()) {
return fmt.Errorf("credentials cannot be refreshed automatically, manual re-authentication required")
}
return nil
}

// Token retrieves an oauth2 token from the external tokensource.
func (ts *externalTokenSource) Token() (*oauth2.Token, error) {
if ts == nil {
Expand Down Expand Up @@ -215,6 +223,10 @@ func NewExternalCredentials(credshelper string, credshelperArgs []string, credsF
return creds, nil
}
log.Warningf("Failed to use cached credentials: %v", err)
if err = creds.refreshStatus(); err != nil {
creds.RemoveFromDisk()
return nil, err
}
}
credsOut, err := runCredsHelperCmd(credsHelperCmd)
if err != nil {
Expand Down
17 changes: 16 additions & 1 deletion go/pkg/credshelper/credshelper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ func TestCredentialsHelperCache(t *testing.T) {
if err != nil {
t.Errorf("failed to create dir for credentials file %q: %v", cf, err)
}
credsHelperCmd := newReusableCmd("echo", []string{`{"headers":{"hdr":"val"},"token":"testToken", "expiry":""}`})
credsHelperCmd := newReusableCmd("echo", []string{`{"headers":{"hdr":"val"},"token":"testToken", "expiry":"","refresh_expiry":""}`})
ts := &grpcOauth.TokenSource{
TokenSource: oauth2.ReuseTokenSourceWithExpiry(
&oauth2.Token{},
Expand Down Expand Up @@ -318,6 +318,21 @@ func TestGetRequestMetadata(t *testing.T) {
}
}

func TestRefreshStatus(t *testing.T) {
c := Credentials{refreshExp: time.Time{}}
if err := c.refreshStatus(); err != nil {
t.Errorf("RefreshStatus returned an error when refreshExpiry is zero")
}
c.refreshExp = time.Now().Add(time.Hour)
if err := c.refreshStatus(); err != nil {
t.Errorf("RefreshStatus returned an error when refreshExpiry has not passed")
}
c.refreshExp = time.Now().Add(-time.Hour)
if err := c.refreshStatus(); err == nil {
t.Errorf("RefreshStatus did not return an error when refreshExpiry when it has passed")
}
}

func TestReusableCmd(t *testing.T) {
binary := "echo"
args := []string{"hello"}
Expand Down

0 comments on commit 574c71c

Please sign in to comment.