Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion server/grants/grants.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ func (h *Handler) Mount(m router.Mux) {
h.grants = map[string]Grant{}
h.register(h.SupportedGrantTypes,
&clientCredentials{issuer: h.Issuer, logger: h.Logger},
&password{issuer: h.Issuer, logger: h.Logger, connectorID: h.PasswordConnector},
&password{issuer: h.Issuer, logger: h.Logger, connectorID: h.PasswordConnector, storage: h.Storage, sessionsEnabled: h.SessionsEnabled, now: h.Now},
&tokenExchange{issuer: h.Issuer, logger: h.Logger, idJAG: newIDJAG(h.IDJAG, h.Issuer, h.Sessions, h.IDJAGMetrics, h.Logger)},
&authorizationCode{issuer: h.Issuer, storage: h.Storage, connectors: h.Connectors, now: h.Now, logger: h.Logger},
&refresh{storage: h.Storage, issuer: h.Issuer, policy: h.RefreshPolicy, sessions: h.Sessions, sessionsEnabled: h.SessionsEnabled, now: h.Now, logger: h.Logger},
Expand Down
58 changes: 55 additions & 3 deletions server/grants/password.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ package grants

import (
"context"
"errors"
"log/slog"
"net/http"
"time"

"github.com/dexidp/dex/connector"
"github.com/dexidp/dex/server/connectors"
Expand All @@ -15,9 +17,12 @@ import (
// password serves the Resource Owner Password Credentials grant: the client
// exchanges a username and password for tokens via a password-capable connector.
type password struct {
issuer *tokens.Issuer
logger *slog.Logger
connectorID string
issuer *tokens.Issuer
logger *slog.Logger
connectorID string
storage storage.Storage
sessionsEnabled bool
now func() time.Time
}

func (g *password) GrantType() string {
Expand Down Expand Up @@ -65,6 +70,16 @@ func (g *password) Authorize(ctx context.Context, req *Request, client storage.C
return nil, &oauth2.Error{Type: oauth2.AccessDenied, Description: "Invalid username or password", Status: http.StatusUnauthorized}
}

// Persist the user identity the same way the browser flow's finalize step
// does, so a refresh under sessions can resolve the cached claims instead
// of failing on a missing identity. Without this row a password-grant
// refresh token can never be used while sessions are enabled.
if g.sessionsEnabled {
if oerr := g.persistUserIdentity(ctx, identity); oerr != nil {
return nil, oerr
}
}

auth := tokens.Authorization{
Client: client,
Claims: tokens.ClaimsFromIdentity(identity),
Expand All @@ -75,3 +90,40 @@ func (g *password) Authorize(ctx context.Context, req *Request, client storage.C
}
return issueTokens(ctx, g.logger, g.issuer, auth, "", shouldIssueRefreshToken(conn, req.Scopes))
}

// persistUserIdentity creates the user's identity row on first login and
// refreshes its claims and last-login time on later ones — the same write the
// browser flow performs in server/authflow/finalize.go.
func (g *password) persistUserIdentity(ctx context.Context, identity connector.Identity) *oauth2.Error {
Comment thread
nabokihms marked this conversation as resolved.
Resolved
now := g.now()

_, err := g.storage.GetUserIdentity(ctx, identity.UserID, g.connectorID)
switch {
case errors.Is(err, storage.ErrNotFound):
ui := storage.UserIdentity{
UserID: identity.UserID,
ConnectorID: g.connectorID,
Claims: tokens.ClaimsFromIdentity(identity),
Consents: make(map[string][]string),
CreatedAt: now,
LastLogin: now,
}
if err := g.storage.CreateUserIdentity(ctx, ui); err != nil {
g.logger.ErrorContext(ctx, "failed to create user identity", "err", err)
return &oauth2.Error{Type: oauth2.ServerError, Status: http.StatusInternalServerError}
}
case err == nil:
if err := g.storage.UpdateUserIdentity(ctx, identity.UserID, g.connectorID, func(old storage.UserIdentity) (storage.UserIdentity, error) {
old.Claims = tokens.ClaimsFromIdentity(identity)
old.LastLogin = now
return old, nil
}); err != nil {
g.logger.ErrorContext(ctx, "failed to update user identity", "err", err)
return &oauth2.Error{Type: oauth2.ServerError, Status: http.StatusInternalServerError}
}
default:
g.logger.ErrorContext(ctx, "failed to get user identity", "err", err)
return &oauth2.Error{Type: oauth2.ServerError, Status: http.StatusInternalServerError}
}
return nil
}
10 changes: 10 additions & 0 deletions server/grants/refresh.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,16 @@ func (g *refresh) Authorize(ctx context.Context, req *Request, client storage.Cl
if g.sessionsEnabled {
ui, err := g.storage.GetUserIdentity(ctx, refreshToken.Claims.UserID, refreshToken.ConnectorID)
if err != nil {
if errors.Is(err, storage.ErrNotFound) {
// No identity was persisted for this token — minted before
// sessions were enabled, or by the password grant before it
// recorded one. Under sessions there are no cached claims to
// refresh against, so the token can no longer be honored:
// invalid_grant, not a server fault.
g.logger.InfoContext(ctx, "refresh: refused, no stored user identity",
"client_id", refreshToken.ClientID, "user_id", refreshToken.Claims.UserID)
return nil, &oauth2.Error{Type: oauth2.InvalidGrant, Description: "No user identity is stored for this refresh token.", Status: http.StatusBadRequest}
}
g.logger.ErrorContext(ctx, "failed to get user identity", "err", err)
return nil, &oauth2.Error{Type: oauth2.InvalidRequest, Status: http.StatusInternalServerError}
}
Expand Down
36 changes: 35 additions & 1 deletion server/server_grant_refresh_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,10 @@ func TestRefreshTokenAuthTime(t *testing.T) {
s.ServeHTTP(rr, req)

if tc.wantHTTPError {
assert.Equal(t, http.StatusInternalServerError, rr.Code)
// No persisted user identity means the token cannot be honored
// under sessions: invalid_grant, not a server error.
assert.Equal(t, http.StatusBadRequest, rr.Code)
assert.Contains(t, rr.Body.String(), `"error":"invalid_grant"`)
return
}
require.Equal(t, http.StatusOK, rr.Code)
Expand Down Expand Up @@ -966,6 +969,37 @@ func TestRefreshGrantStorageBackedPasswordDB(t *testing.T) {
require.NotEqual(t, second.RefreshToken, third.RefreshToken, "chained refresh did not rotate")
}

// TestRefreshGrantPasswordFlowWithSessions refreshes a token issued by the
// password grant while sessions are enabled (#5166). The password grant never
// passes through the browser finalize step that writes the user identity, so
// until the grant persisted one itself every refresh of its tokens failed with
// a 500.
func TestRefreshGrantPasswordFlowWithSessions(t *testing.T) {
httpServer, s := newTestServer(t, func(c *Config) {
c.PasswordConnector = "local"
c.SessionConfig = testSessionConfig()
})
defer httpServer.Close()
seedLocalPasswordDB(t, s)

first := doPasswordGrant(t, s)

rr := doRefreshGrant(t, s, first, 0)
require.Equal(t, http.StatusOK, rr.Code, "refresh grant failed: %s", rr.Body.String())
var second tokenResponse
require.NoError(t, json.Unmarshal(rr.Body.Bytes(), &second))
require.NotEqual(t, first, second.RefreshToken, "refresh token was not rotated")

// The refresh resolved cached claims: the grant recorded the user's
// identity the way the browser finalize step does.
_, err := s.storage.GetUserIdentity(t.Context(), "user-id", "local")
require.NoError(t, err, "password grant did not persist the user identity")

// Claims come from the stored identity, not the connector.
claims := decodeJWTClaims(t, second.IDToken)
require.Equal(t, "user@example.com", claims["email"])
}

func TestRefreshDoesNotLogConnectorData(t *testing.T) {
const upstreamToken = "upstream-refresh-token-must-not-be-logged"

Expand Down