Skip to content

Commit

Permalink
[auth] Fix failed session refresh (#2350)
Browse files Browse the repository at this point in the history
  • Loading branch information
mikeland73 authored Oct 12, 2024
1 parent bb67992 commit 5bf73ed
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
9 changes: 8 additions & 1 deletion internal/boxcli/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,8 +96,15 @@ func whoAmICmd() *cobra.Command {
if err != nil {
return err
}
return box.UninitializedSecrets(cmd.Context()).
// TODO: WhoAmI should be a function in opensource/pkg/auth that takes in a session.
// That way we don't need to handle failed refresh token errors here.
err = box.UninitializedSecrets(cmd.Context()).
WhoAmI(cmd.Context(), cmd.OutOrStdout(), flags.showTokens)
if identity.IsRefreshTokenError(err) {
ux.Fwarningf(cmd.ErrOrStderr(), "Your session is expired. Please login again.\n")
return loginCmd().RunE(cmd, args)
}
return err
},
}

Expand Down
19 changes: 18 additions & 1 deletion internal/devbox/providers/identity/identity.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@ import (
"errors"
"os"
"path"
"strings"

"github.com/go-jose/go-jose/v4"
"github.com/go-jose/go-jose/v4/jwt"
"go.jetify.com/typeid"
"go.jetpack.io/devbox/internal/build"
"go.jetpack.io/devbox/internal/ux"
"go.jetpack.io/pkg/api"
"go.jetpack.io/pkg/auth"
"go.jetpack.io/pkg/auth/session"
Expand Down Expand Up @@ -40,7 +42,12 @@ func GenSession(ctx context.Context) (*session.Token, error) {
if err != nil {
return nil, err
}
return c.GetSession(ctx)
tok, err := c.GetSession(ctx)
if IsRefreshTokenError(err) {
ux.Fwarningf(os.Stderr, "Your session is expired. Please login again.\n")
return c.LoginFlow()
}
return tok, err
}

func Peek() (*session.Token, error) {
Expand Down Expand Up @@ -129,3 +136,13 @@ func GetOrgSlug(ctx context.Context) (string, error) {

return claims["org_trusted_metadata"].(map[string]any)["slug"].(string), nil
}

// invalid_grant or invalid_request usually means the refresh token is expired, revoked, or
// malformed. this belongs in opensource/pkg/auth
func IsRefreshTokenError(err error) bool {
if err == nil {
return false
}
return strings.Contains(err.Error(), "invalid_grant") ||
strings.Contains(err.Error(), "invalid_request")
}

0 comments on commit 5bf73ed

Please sign in to comment.