Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
55 changes: 6 additions & 49 deletions server/authflow/finalize.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,11 @@ package authflow

import (
"context"
"errors"
"fmt"
"time"

"github.com/dexidp/dex/connector"
"github.com/dexidp/dex/server/tokens"
"github.com/dexidp/dex/server/useridentity"
"github.com/dexidp/dex/storage"
)

Expand Down Expand Up @@ -40,20 +39,12 @@ func (h *Handler) sessionAuthRequest(ctx context.Context, authReq storage.AuthRe
// finalizeLogin associates the user's identity with the current AuthRequest, then returns
// the approval page's path.
func (h *Handler) finalizeLogin(ctx context.Context, identity connector.Identity, authReq storage.AuthRequest, conn connector.Connector) (storage.AuthRequest, error) {
// Refuse to complete login for a locked account. BlockedUntil lives on the
// persisted UserIdentity, which only exists when the sessions feature is on;
// a first-time login (no stored identity yet) cannot be blocked.
// Enforce the account lock and persist the user's identity the same way
// every login path must. The UserIdentity row only exists when the
// sessions feature is on; a first-time login cannot be blocked.
if h.Sessions.Enabled() {
storedIdentity, err := h.Storage.GetUserIdentity(ctx, identity.UserID, authReq.ConnectorID)
switch {
case err == nil:
if !storedIdentity.BlockedUntil.IsZero() && h.Now().Before(storedIdentity.BlockedUntil) {
h.Logger.WarnContext(ctx, "login rejected for locked account",
"connector_id", authReq.ConnectorID, "user_id", identity.UserID, "blocked_until", storedIdentity.BlockedUntil)
return storage.AuthRequest{}, fmt.Errorf("account is locked until %s", storedIdentity.BlockedUntil.Format(time.RFC3339))
}
case !errors.Is(err, storage.ErrNotFound):
return storage.AuthRequest{}, fmt.Errorf("failed to look up user identity: %w", err)
if err := useridentity.RecordLogin(ctx, h.Storage, h.Logger, h.Now, identity, authReq.ConnectorID); err != nil {
return storage.AuthRequest{}, err
}
}

Expand Down Expand Up @@ -135,40 +126,6 @@ func (h *Handler) finalizeLogin(ctx context.Context, identity connector.Identity
}
}

// Create or update UserIdentity to persist user claims across sessions.
if h.Sessions.Enabled() {
now := h.Now()

_, err := h.Storage.GetUserIdentity(ctx, identity.UserID, authReq.ConnectorID)
switch {
case err != nil && errors.Is(err, storage.ErrNotFound):
ui := storage.UserIdentity{
UserID: identity.UserID,
ConnectorID: authReq.ConnectorID,
Claims: claims,
Consents: make(map[string][]string),
CreatedAt: now,
LastLogin: now,
}
if err := h.Storage.CreateUserIdentity(ctx, ui); err != nil {
h.Logger.ErrorContext(ctx, "failed to create user identity", "err", err)
return storage.AuthRequest{}, err
}
case err == nil:
if err := h.Storage.UpdateUserIdentity(ctx, identity.UserID, authReq.ConnectorID, func(old storage.UserIdentity) (storage.UserIdentity, error) {
old.Claims = claims
old.LastLogin = now
return old, nil
}); err != nil {
h.Logger.ErrorContext(ctx, "failed to update user identity", "err", err)
return storage.AuthRequest{}, err
}
default:
h.Logger.ErrorContext(ctx, "failed to get user identity", "err", err)
return storage.AuthRequest{}, err
}
}

// The identity is persisted; return the finalized request so the caller can
// create the session and advance the flow.
return h.Storage.GetAuthRequest(ctx, authReq.ID)
Expand Down
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
29 changes: 26 additions & 3 deletions server/grants/password.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,29 @@ package grants

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

"github.com/dexidp/dex/connector"
"github.com/dexidp/dex/server/connectors"
"github.com/dexidp/dex/server/oauth2"
"github.com/dexidp/dex/server/tokens"
"github.com/dexidp/dex/server/useridentity"
"github.com/dexidp/dex/storage"
)

// 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 +72,22 @@ 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}
}

// Enforce the account lock and 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, and
// a locked account cannot mint tokens. Without the identity row a
// password-grant refresh token can never be used while sessions are enabled.
if g.sessionsEnabled {
err := useridentity.RecordLogin(ctx, g.storage, g.logger, g.now, identity, g.connectorID)
var locked *useridentity.LockedError
switch {
case errors.As(err, &locked):
return nil, &oauth2.Error{Type: oauth2.InvalidGrant, Description: fmt.Sprintf("Account is locked until %s.", locked.Until.Format(time.RFC3339)), Status: http.StatusBadRequest}
case err != nil:
return nil, &oauth2.Error{Type: oauth2.ServerError, Status: http.StatusInternalServerError}
}
}

auth := tokens.Authorization{
Client: client,
Claims: tokens.ClaimsFromIdentity(identity),
Expand Down
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
57 changes: 57 additions & 0 deletions server/server_grant_password_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,63 @@ func TestHandlePassword_LocalPasswordDBClaims(t *testing.T) {
require.Equal(t, []string{"team-a", "team-a/admins"}, claims.Groups)
}

// TestHandlePasswordLockedAccountDenied covers the review on #5168: the
// password grant runs the same account-lock check the browser flow's finalize
// step does, or a locked account could still mint tokens.
func TestHandlePasswordLockedAccountDenied(t *testing.T) {
httpServer, s := newTestServer(t, func(c *Config) {
c.PasswordConnector = "local"
c.SessionConfig = testSessionConfig()
})
defer httpServer.Close()
seedLocalPasswordDB(t, s)

ctx := t.Context()
require.NoError(t, s.storage.CreateUserIdentity(ctx, storage.UserIdentity{
UserID: "user-id",
ConnectorID: "local",
Claims: storage.Claims{UserID: "user-id", Email: "user@example.com"},
Consents: map[string][]string{},
MFASecrets: map[string]*storage.MFASecret{},
WebAuthnCredentials: map[string][]storage.WebAuthnCredential{},
CreatedAt: time.Now(),
LastLogin: time.Now(),
BlockedUntil: time.Now().Add(time.Hour),
}))

u, err := url.Parse(s.issuerURL.String())
require.NoError(t, err)
u.Path = path.Join(u.Path, "/token")

makeReq := func() *httptest.ResponseRecorder {
v := url.Values{}
v.Add("scope", "openid email offline_access")
v.Add("grant_type", "password")
v.Add("username", "user@example.com")
v.Add("password", "secret")

req, _ := http.NewRequest("POST", u.String(), bytes.NewBufferString(v.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.SetBasicAuth("test", "barfoo")

rr := httptest.NewRecorder()
s.ServeHTTP(rr, req)
return rr
}

rr := makeReq()
require.Equal(t, http.StatusBadRequest, rr.Code, "locked account must not get tokens: %s", rr.Body.String())
require.Contains(t, rr.Body.String(), "invalid_grant")

// Clear the block: the same credentials must succeed again.
require.NoError(t, s.storage.UpdateUserIdentity(ctx, "user-id", "local", func(ui storage.UserIdentity) (storage.UserIdentity, error) {
ui.BlockedUntil = time.Time{}
return ui, nil
}))
rr = makeReq()
require.Equal(t, http.StatusOK, rr.Code, "unlocked account should get tokens: %s", rr.Body.String())
}

// TestHandlePasswordAllowedConnectors verifies the password grant enforces the
// client's AllowedConnectors (mirrors TestHandleTokenExchangeAllowedConnectors
// and TestHandleRefreshTokenAllowedConnectors — every token grant must enforce it).
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
72 changes: 72 additions & 0 deletions server/useridentity/useridentity.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// Package useridentity owns the per-user account record every login path
// shares: each login must enforce the account lock and keep the stored
// identity's claims and last-login time current, or the paths drift apart.
package useridentity

import (
"context"
"errors"
"fmt"
"log/slog"
"time"

"github.com/dexidp/dex/connector"
"github.com/dexidp/dex/server/tokens"
"github.com/dexidp/dex/storage"
)

// LockedError reports a login refused because the stored identity's
// BlockedUntil is still in the future.
type LockedError struct {
Until time.Time
}

func (e *LockedError) Error() string {
return fmt.Sprintf("account is locked until %s", e.Until.Format(time.RFC3339))
}

// RecordLogin refuses to proceed for a locked account, then creates the
// user's identity row on first login or refreshes its claims and last-login
// time on later ones.
//
// Call it only when the sessions feature is enabled: BlockedUntil and the
// UserIdentity row itself do not exist without it, and a first-time login
// (no stored identity yet) cannot be blocked.
func RecordLogin(ctx context.Context, s storage.Storage, logger *slog.Logger, now func() time.Time, identity connector.Identity, connectorID string) error {
stored, err := s.GetUserIdentity(ctx, identity.UserID, connectorID)
switch {
case errors.Is(err, storage.ErrNotFound):
t := now()
ui := storage.UserIdentity{
UserID: identity.UserID,
ConnectorID: connectorID,
Claims: tokens.ClaimsFromIdentity(identity),
Consents: make(map[string][]string),
CreatedAt: t,
LastLogin: t,
}
if err := s.CreateUserIdentity(ctx, ui); err != nil {
logger.ErrorContext(ctx, "failed to create user identity", "err", err)
return err
}
return nil
case err != nil:
return fmt.Errorf("failed to look up user identity: %w", err)
}

if !stored.BlockedUntil.IsZero() && now().Before(stored.BlockedUntil) {
logger.WarnContext(ctx, "login rejected for locked account",
"connector_id", connectorID, "user_id", identity.UserID, "blocked_until", stored.BlockedUntil)
return &LockedError{Until: stored.BlockedUntil}
}

if err := s.UpdateUserIdentity(ctx, identity.UserID, connectorID, func(old storage.UserIdentity) (storage.UserIdentity, error) {
old.Claims = tokens.ClaimsFromIdentity(identity)
old.LastLogin = now()
return old, nil
}); err != nil {
logger.ErrorContext(ctx, "failed to update user identity", "err", err)
return err
}
return nil
}
Loading