2021-01-06 00:22:38 +00:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
"strings"
|
2021-01-14 21:15:56 +00:00
|
|
|
"time"
|
2021-01-06 00:22:38 +00:00
|
|
|
|
|
|
|
"github.com/dexidp/dex/connector"
|
|
|
|
"github.com/dexidp/dex/server/internal"
|
|
|
|
"github.com/dexidp/dex/storage"
|
|
|
|
)
|
|
|
|
|
|
|
|
func contains(arr []string, item string) bool {
|
|
|
|
for _, itemFromArray := range arr {
|
|
|
|
if itemFromArray == item {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
type refreshError struct {
|
|
|
|
msg string
|
|
|
|
code int
|
|
|
|
desc string
|
|
|
|
}
|
|
|
|
|
2022-10-02 20:40:22 +00:00
|
|
|
func (r *refreshError) Error() string {
|
|
|
|
return fmt.Sprintf("refresh token error: status %d, %q %s", r.code, r.msg, r.desc)
|
|
|
|
}
|
|
|
|
|
2021-03-09 05:13:54 +00:00
|
|
|
func newInternalServerError() *refreshError {
|
|
|
|
return &refreshError{msg: errInvalidRequest, desc: "", code: http.StatusInternalServerError}
|
|
|
|
}
|
2021-01-14 21:15:56 +00:00
|
|
|
|
|
|
|
func newBadRequestError(desc string) *refreshError {
|
|
|
|
return &refreshError{msg: errInvalidRequest, desc: desc, code: http.StatusBadRequest}
|
|
|
|
}
|
|
|
|
|
2021-01-06 00:22:38 +00:00
|
|
|
func (s *Server) refreshTokenErrHelper(w http.ResponseWriter, err *refreshError) {
|
|
|
|
s.tokenErrHelper(w, err.msg, err.desc, err.code)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) extractRefreshTokenFromRequest(r *http.Request) (*internal.RefreshToken, *refreshError) {
|
|
|
|
code := r.PostFormValue("refresh_token")
|
|
|
|
if code == "" {
|
2021-01-14 21:15:56 +00:00
|
|
|
return nil, newBadRequestError("No refresh token is found in request.")
|
2021-01-06 00:22:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
token := new(internal.RefreshToken)
|
|
|
|
if err := internal.Unmarshal(code, token); err != nil {
|
|
|
|
// For backward compatibility, assume the refresh_token is a raw refresh token ID
|
|
|
|
// if it fails to decode.
|
|
|
|
//
|
|
|
|
// Because refresh_token values that aren't unmarshable were generated by servers
|
|
|
|
// that don't have a Token value, we'll still reject any attempts to claim a
|
|
|
|
// refresh_token twice.
|
|
|
|
token = &internal.RefreshToken{RefreshId: code, Token: ""}
|
|
|
|
}
|
|
|
|
|
|
|
|
return token, nil
|
|
|
|
}
|
|
|
|
|
2022-10-02 20:40:22 +00:00
|
|
|
type refreshContext struct {
|
|
|
|
storageToken *storage.RefreshToken
|
|
|
|
requestToken *internal.RefreshToken
|
|
|
|
|
|
|
|
connector Connector
|
|
|
|
connectorData []byte
|
|
|
|
|
|
|
|
scopes []string
|
|
|
|
}
|
|
|
|
|
2021-01-06 00:22:38 +00:00
|
|
|
// getRefreshTokenFromStorage checks that refresh token is valid and exists in the storage and gets its info
|
2022-10-02 20:40:22 +00:00
|
|
|
func (s *Server) getRefreshTokenFromStorage(clientID string, token *internal.RefreshToken) (*refreshContext, *refreshError) {
|
|
|
|
refreshCtx := refreshContext{requestToken: token}
|
|
|
|
|
2021-01-14 21:15:56 +00:00
|
|
|
invalidErr := newBadRequestError("Refresh token is invalid or has already been claimed by another client.")
|
2021-01-06 00:22:38 +00:00
|
|
|
|
2022-10-02 20:40:22 +00:00
|
|
|
// Get RefreshToken
|
2021-01-14 21:15:56 +00:00
|
|
|
refresh, err := s.storage.GetRefresh(token.RefreshId)
|
2021-01-06 00:22:38 +00:00
|
|
|
if err != nil {
|
|
|
|
if err != storage.ErrNotFound {
|
2022-04-12 13:21:35 +00:00
|
|
|
s.logger.Errorf("failed to get refresh token: %v", err)
|
2021-03-09 05:13:54 +00:00
|
|
|
return nil, newInternalServerError()
|
2021-01-06 00:22:38 +00:00
|
|
|
}
|
2021-01-14 21:15:56 +00:00
|
|
|
return nil, invalidErr
|
2021-01-06 00:22:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if refresh.ClientID != clientID {
|
|
|
|
s.logger.Errorf("client %s trying to claim token for client %s", clientID, refresh.ClientID)
|
2021-12-08 05:05:10 +00:00
|
|
|
// According to https://datatracker.ietf.org/doc/html/rfc6749#section-5.2 Dex should respond with an
|
2021-12-05 19:45:52 +00:00
|
|
|
// invalid grant error if token has already been claimed by another client.
|
|
|
|
return nil, &refreshError{msg: errInvalidGrant, desc: invalidErr.desc, code: http.StatusBadRequest}
|
2021-01-06 00:22:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if refresh.Token != token.Token {
|
|
|
|
switch {
|
|
|
|
case !s.refreshTokenPolicy.AllowedToReuse(refresh.LastUsed):
|
|
|
|
fallthrough
|
|
|
|
case refresh.ObsoleteToken != token.Token:
|
|
|
|
fallthrough
|
|
|
|
case refresh.ObsoleteToken == "":
|
|
|
|
s.logger.Errorf("refresh token with id %s claimed twice", refresh.ID)
|
2021-01-14 21:15:56 +00:00
|
|
|
return nil, invalidErr
|
2021-01-06 00:22:38 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-14 21:15:56 +00:00
|
|
|
expiredErr := newBadRequestError("Refresh token expired.")
|
2021-01-06 00:22:38 +00:00
|
|
|
if s.refreshTokenPolicy.CompletelyExpired(refresh.CreatedAt) {
|
|
|
|
s.logger.Errorf("refresh token with id %s expired", refresh.ID)
|
2021-01-14 21:15:56 +00:00
|
|
|
return nil, expiredErr
|
2021-01-06 00:22:38 +00:00
|
|
|
}
|
2021-01-11 10:06:31 +00:00
|
|
|
|
2021-01-06 00:22:38 +00:00
|
|
|
if s.refreshTokenPolicy.ExpiredBecauseUnused(refresh.LastUsed) {
|
2021-03-09 05:13:54 +00:00
|
|
|
s.logger.Errorf("refresh token with id %s expired due to inactivity", refresh.ID)
|
2021-01-14 21:15:56 +00:00
|
|
|
return nil, expiredErr
|
2021-01-06 00:22:38 +00:00
|
|
|
}
|
|
|
|
|
2022-10-02 20:40:22 +00:00
|
|
|
refreshCtx.storageToken = &refresh
|
|
|
|
|
|
|
|
// Get Connector
|
|
|
|
refreshCtx.connector, err = s.getConnector(refresh.ConnectorID)
|
|
|
|
if err != nil {
|
|
|
|
s.logger.Errorf("connector with ID %q not found: %v", refresh.ConnectorID, err)
|
|
|
|
return nil, newInternalServerError()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get Connector Data
|
|
|
|
session, err := s.storage.GetOfflineSessions(refresh.Claims.UserID, refresh.ConnectorID)
|
|
|
|
switch {
|
|
|
|
case err != nil:
|
|
|
|
if err != storage.ErrNotFound {
|
|
|
|
s.logger.Errorf("failed to get offline session: %v", err)
|
|
|
|
return nil, newInternalServerError()
|
|
|
|
}
|
|
|
|
case len(refresh.ConnectorData) > 0:
|
|
|
|
// Use the old connector data if it exists, should be deleted once used
|
|
|
|
refreshCtx.connectorData = refresh.ConnectorData
|
|
|
|
default:
|
|
|
|
refreshCtx.connectorData = session.ConnectorData
|
|
|
|
}
|
|
|
|
|
|
|
|
return &refreshCtx, nil
|
2021-01-06 00:22:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) getRefreshScopes(r *http.Request, refresh *storage.RefreshToken) ([]string, *refreshError) {
|
|
|
|
// Per the OAuth2 spec, if the client has omitted the scopes, default to the original
|
|
|
|
// authorized scopes.
|
|
|
|
//
|
|
|
|
// https://tools.ietf.org/html/rfc6749#section-6
|
|
|
|
scope := r.PostFormValue("scope")
|
|
|
|
|
|
|
|
if scope == "" {
|
|
|
|
return refresh.Scopes, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
requestedScopes := strings.Fields(scope)
|
|
|
|
var unauthorizedScopes []string
|
|
|
|
|
|
|
|
// Per the OAuth2 spec, if the client has omitted the scopes, default to the original
|
|
|
|
// authorized scopes.
|
|
|
|
//
|
|
|
|
// https://tools.ietf.org/html/rfc6749#section-6
|
|
|
|
for _, requestScope := range requestedScopes {
|
|
|
|
if !contains(refresh.Scopes, requestScope) {
|
|
|
|
unauthorizedScopes = append(unauthorizedScopes, requestScope)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(unauthorizedScopes) > 0 {
|
|
|
|
desc := fmt.Sprintf("Requested scopes contain unauthorized scope(s): %q.", unauthorizedScopes)
|
2021-01-14 21:15:56 +00:00
|
|
|
return nil, newBadRequestError(desc)
|
2021-01-06 00:22:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return requestedScopes, nil
|
|
|
|
}
|
|
|
|
|
2022-10-02 20:40:22 +00:00
|
|
|
func (s *Server) refreshWithConnector(ctx context.Context, rCtx *refreshContext, ident connector.Identity) (connector.Identity, *refreshError) {
|
2021-01-06 00:22:38 +00:00
|
|
|
// Can the connector refresh the identity? If so, attempt to refresh the data
|
|
|
|
// in the connector.
|
|
|
|
//
|
|
|
|
// TODO(ericchiang): We may want a strict mode where connectors that don't implement
|
|
|
|
// this interface can't perform refreshing.
|
2022-10-02 20:40:22 +00:00
|
|
|
if refreshConn, ok := rCtx.connector.Connector.(connector.RefreshConnector); ok {
|
|
|
|
s.logger.Debugf("connector data before refresh: %s", ident.ConnectorData)
|
|
|
|
|
|
|
|
newIdent, err := refreshConn.Refresh(ctx, parseScopes(rCtx.scopes), ident)
|
2021-01-06 00:22:38 +00:00
|
|
|
if err != nil {
|
|
|
|
s.logger.Errorf("failed to refresh identity: %v", err)
|
2022-10-02 20:40:22 +00:00
|
|
|
return ident, newInternalServerError()
|
2021-01-06 00:22:38 +00:00
|
|
|
}
|
|
|
|
|
2022-10-02 20:40:22 +00:00
|
|
|
return newIdent, nil
|
|
|
|
}
|
2021-01-06 00:22:38 +00:00
|
|
|
return ident, nil
|
|
|
|
}
|
|
|
|
|
2021-01-14 21:15:56 +00:00
|
|
|
// updateOfflineSession updates offline session in the storage
|
|
|
|
func (s *Server) updateOfflineSession(refresh *storage.RefreshToken, ident connector.Identity, lastUsed time.Time) *refreshError {
|
|
|
|
offlineSessionUpdater := func(old storage.OfflineSessions) (storage.OfflineSessions, error) {
|
|
|
|
if old.Refresh[refresh.ClientID].ID != refresh.ID {
|
|
|
|
return old, errors.New("refresh token invalid")
|
|
|
|
}
|
2022-10-02 20:40:22 +00:00
|
|
|
|
2021-01-14 21:15:56 +00:00
|
|
|
old.Refresh[refresh.ClientID].LastUsed = lastUsed
|
2022-10-02 20:40:22 +00:00
|
|
|
if len(ident.ConnectorData) > 0 {
|
|
|
|
old.ConnectorData = ident.ConnectorData
|
|
|
|
}
|
|
|
|
|
|
|
|
s.logger.Debugf("saved connector data: %s %s", ident.UserID, ident.ConnectorData)
|
|
|
|
|
2021-01-14 21:15:56 +00:00
|
|
|
return old, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Update LastUsed time stamp in refresh token reference object
|
|
|
|
// in offline session for the user.
|
|
|
|
err := s.storage.UpdateOfflineSessions(refresh.Claims.UserID, refresh.ConnectorID, offlineSessionUpdater)
|
|
|
|
if err != nil {
|
|
|
|
s.logger.Errorf("failed to update offline session: %v", err)
|
2021-03-09 05:13:54 +00:00
|
|
|
return newInternalServerError()
|
2021-01-14 21:15:56 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-01-06 00:22:38 +00:00
|
|
|
// updateRefreshToken updates refresh token and offline session in the storage
|
2022-10-02 20:40:22 +00:00
|
|
|
func (s *Server) updateRefreshToken(ctx context.Context, rCtx *refreshContext) (*internal.RefreshToken, connector.Identity, *refreshError) {
|
|
|
|
var rerr *refreshError
|
|
|
|
|
|
|
|
newToken := &internal.RefreshToken{
|
|
|
|
Token: rCtx.requestToken.Token,
|
|
|
|
RefreshId: rCtx.requestToken.RefreshId,
|
2021-01-06 00:22:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
lastUsed := s.now()
|
2021-01-14 21:15:56 +00:00
|
|
|
|
2022-10-02 20:40:22 +00:00
|
|
|
ident := connector.Identity{
|
|
|
|
UserID: rCtx.storageToken.Claims.UserID,
|
|
|
|
Username: rCtx.storageToken.Claims.Username,
|
|
|
|
PreferredUsername: rCtx.storageToken.Claims.PreferredUsername,
|
|
|
|
Email: rCtx.storageToken.Claims.Email,
|
|
|
|
EmailVerified: rCtx.storageToken.Claims.EmailVerified,
|
|
|
|
Groups: rCtx.storageToken.Claims.Groups,
|
|
|
|
ConnectorData: rCtx.connectorData,
|
|
|
|
}
|
|
|
|
|
2021-01-06 00:22:38 +00:00
|
|
|
refreshTokenUpdater := func(old storage.RefreshToken) (storage.RefreshToken, error) {
|
2022-10-02 20:40:22 +00:00
|
|
|
rotationEnabled := s.refreshTokenPolicy.RotationEnabled()
|
|
|
|
reusingAllowed := s.refreshTokenPolicy.AllowedToReuse(old.LastUsed)
|
|
|
|
|
|
|
|
switch {
|
|
|
|
case !rotationEnabled && reusingAllowed:
|
|
|
|
// If rotation is disabled and the offline session was updated not so long ago - skip further actions.
|
|
|
|
return old, nil
|
|
|
|
|
|
|
|
case rotationEnabled && reusingAllowed:
|
|
|
|
if old.Token != rCtx.requestToken.Token && old.ObsoleteToken != rCtx.requestToken.Token {
|
2021-01-06 00:22:38 +00:00
|
|
|
return old, errors.New("refresh token claimed twice")
|
|
|
|
}
|
|
|
|
|
2022-10-02 20:40:22 +00:00
|
|
|
// Return previously generated token for all requests with an obsolete tokens
|
|
|
|
if old.ObsoleteToken == rCtx.requestToken.Token {
|
|
|
|
newToken.Token = old.Token
|
|
|
|
}
|
|
|
|
|
|
|
|
// Do not update last used time for offline session if token is allowed to be reused
|
|
|
|
lastUsed = old.LastUsed
|
|
|
|
ident.ConnectorData = nil
|
|
|
|
return old, nil
|
|
|
|
|
|
|
|
case rotationEnabled && !reusingAllowed:
|
|
|
|
if old.Token != rCtx.requestToken.Token {
|
|
|
|
return old, errors.New("refresh token claimed twice")
|
|
|
|
}
|
|
|
|
|
|
|
|
// Issue new refresh token
|
2021-01-06 00:22:38 +00:00
|
|
|
old.ObsoleteToken = old.Token
|
2022-10-02 20:40:22 +00:00
|
|
|
newToken.Token = storage.NewID()
|
2021-01-06 00:22:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
old.Token = newToken.Token
|
2022-10-02 20:40:22 +00:00
|
|
|
old.LastUsed = lastUsed
|
|
|
|
|
|
|
|
// ConnectorData has been moved to OfflineSession
|
|
|
|
old.ConnectorData = []byte{}
|
|
|
|
|
|
|
|
// Call only once if there is a request which is not in the reuse interval.
|
|
|
|
// This is required to avoid multiple calls to the external IdP for concurrent requests.
|
|
|
|
// Dex will call the connector's Refresh method only once if request is not in reuse interval.
|
|
|
|
ident, rerr = s.refreshWithConnector(ctx, rCtx, ident)
|
|
|
|
if rerr != nil {
|
|
|
|
return old, rerr
|
|
|
|
}
|
|
|
|
|
2021-01-06 00:22:38 +00:00
|
|
|
// Update the claims of the refresh token.
|
|
|
|
//
|
|
|
|
// UserID intentionally ignored for now.
|
|
|
|
old.Claims.Username = ident.Username
|
|
|
|
old.Claims.PreferredUsername = ident.PreferredUsername
|
|
|
|
old.Claims.Email = ident.Email
|
|
|
|
old.Claims.EmailVerified = ident.EmailVerified
|
|
|
|
old.Claims.Groups = ident.Groups
|
|
|
|
|
|
|
|
return old, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Update refresh token in the storage.
|
2022-10-02 20:40:22 +00:00
|
|
|
err := s.storage.UpdateRefreshToken(rCtx.storageToken.ID, refreshTokenUpdater)
|
2021-01-06 00:22:38 +00:00
|
|
|
if err != nil {
|
|
|
|
s.logger.Errorf("failed to update refresh token: %v", err)
|
2022-10-02 20:40:22 +00:00
|
|
|
return nil, ident, newInternalServerError()
|
2021-01-06 00:22:38 +00:00
|
|
|
}
|
|
|
|
|
2022-10-02 20:40:22 +00:00
|
|
|
rerr = s.updateOfflineSession(rCtx.storageToken, ident, lastUsed)
|
2021-10-18 20:37:55 +00:00
|
|
|
if rerr != nil {
|
2022-10-02 20:40:22 +00:00
|
|
|
return nil, ident, rerr
|
2021-10-18 20:37:55 +00:00
|
|
|
}
|
|
|
|
|
2022-10-02 20:40:22 +00:00
|
|
|
return newToken, ident, nil
|
2021-01-06 00:22:38 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// handleRefreshToken handles a refresh token request https://tools.ietf.org/html/rfc6749#section-6
|
2021-01-14 21:15:56 +00:00
|
|
|
// this method is the entrypoint for refresh tokens handling
|
2021-01-06 00:22:38 +00:00
|
|
|
func (s *Server) handleRefreshToken(w http.ResponseWriter, r *http.Request, client storage.Client) {
|
|
|
|
token, rerr := s.extractRefreshTokenFromRequest(r)
|
|
|
|
if rerr != nil {
|
|
|
|
s.refreshTokenErrHelper(w, rerr)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-10-02 20:40:22 +00:00
|
|
|
rCtx, rerr := s.getRefreshTokenFromStorage(client.ID, token)
|
2021-01-06 00:22:38 +00:00
|
|
|
if rerr != nil {
|
|
|
|
s.refreshTokenErrHelper(w, rerr)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-10-02 20:40:22 +00:00
|
|
|
rCtx.scopes, rerr = s.getRefreshScopes(r, rCtx.storageToken)
|
2021-01-06 00:22:38 +00:00
|
|
|
if rerr != nil {
|
|
|
|
s.refreshTokenErrHelper(w, rerr)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-10-02 20:40:22 +00:00
|
|
|
newToken, ident, rerr := s.updateRefreshToken(r.Context(), rCtx)
|
2021-01-06 00:22:38 +00:00
|
|
|
if rerr != nil {
|
|
|
|
s.refreshTokenErrHelper(w, rerr)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
claims := storage.Claims{
|
|
|
|
UserID: ident.UserID,
|
|
|
|
Username: ident.Username,
|
|
|
|
PreferredUsername: ident.PreferredUsername,
|
|
|
|
Email: ident.Email,
|
|
|
|
EmailVerified: ident.EmailVerified,
|
|
|
|
Groups: ident.Groups,
|
|
|
|
}
|
|
|
|
|
2022-10-02 20:40:22 +00:00
|
|
|
accessToken, err := s.newAccessToken(client.ID, claims, rCtx.scopes, rCtx.storageToken.Nonce, rCtx.storageToken.ConnectorID)
|
2021-01-06 00:22:38 +00:00
|
|
|
if err != nil {
|
|
|
|
s.logger.Errorf("failed to create new access token: %v", err)
|
2021-03-09 05:13:54 +00:00
|
|
|
s.refreshTokenErrHelper(w, newInternalServerError())
|
2021-01-06 00:22:38 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-10-02 20:40:22 +00:00
|
|
|
idToken, expiry, err := s.newIDToken(client.ID, claims, rCtx.scopes, rCtx.storageToken.Nonce, accessToken, "", rCtx.storageToken.ConnectorID)
|
2021-01-06 00:22:38 +00:00
|
|
|
if err != nil {
|
|
|
|
s.logger.Errorf("failed to create ID token: %v", err)
|
2021-03-09 05:13:54 +00:00
|
|
|
s.refreshTokenErrHelper(w, newInternalServerError())
|
2021-01-06 00:22:38 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
rawNewToken, err := internal.Marshal(newToken)
|
|
|
|
if err != nil {
|
|
|
|
s.logger.Errorf("failed to marshal refresh token: %v", err)
|
2021-03-09 05:13:54 +00:00
|
|
|
s.refreshTokenErrHelper(w, newInternalServerError())
|
2021-01-06 00:22:38 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
resp := s.toAccessTokenResponse(idToken, accessToken, rawNewToken, expiry)
|
|
|
|
s.writeAccessToken(w, resp)
|
|
|
|
}
|