Skip to content
Open
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
46 changes: 38 additions & 8 deletions pkg/authserver/refresh_grant_guard.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,12 +114,13 @@ const guardRevokeTimeout = 5 * time.Second
// other refusals repeat on every replay of a kept refresh token, so they are
// logged at DEBUG.
type upstreamRefreshGuard struct {
tokens storage.UpstreamTokenStorage
refresher storage.UpstreamTokenRefresher
providers map[string]struct{}
revoker oauth2.TokenRevocationStorage
recheckDelay time.Duration
checkTimeout time.Duration
tokens storage.UpstreamTokenStorage
refresher storage.UpstreamTokenRefresher
providers map[string]struct{}
providerIssuers map[string]string
revoker oauth2.TokenRevocationStorage
recheckDelay time.Duration
checkTimeout time.Duration
// userKeyed is set only when storage is the user-keyed layer; the guard
// then checks the identity provider's row through the per-user reader
// instead of walking the session's rows. See
Expand All @@ -129,10 +130,20 @@ type upstreamRefreshGuard struct {

var _ fosite.TokenEndpointHandler = (*upstreamRefreshGuard)(nil)

// withRefreshGuardIssuers records the configured issuer/authority per upstream
// name so checkRow refuses rows issued by a previous IdP without contacting
// the newly configured IdP.
func withRefreshGuardIssuers(issuers map[string]string) func(*upstreamRefreshGuard) {
return func(g *upstreamRefreshGuard) {
g.providerIssuers = maps.Clone(issuers)
}
}

// newUpstreamRefreshGuard returns the guard for the given storage, the
// server's shared refresher and the names of the configured upstreams.
func newUpstreamRefreshGuard(
stor storage.Storage, refresher storage.UpstreamTokenRefresher, providerNames []string,
opts ...func(*upstreamRefreshGuard),
) (*upstreamRefreshGuard, error) {
if stor == nil {
return nil, errors.New("upstream refresh guard requires storage")
Expand All @@ -144,14 +155,18 @@ func newUpstreamRefreshGuard(
for _, name := range providerNames {
providers[name] = struct{}{}
}
return &upstreamRefreshGuard{
g := &upstreamRefreshGuard{
tokens: stor,
refresher: refresher,
providers: providers,
revoker: stor,
recheckDelay: rejectionRecheckDelay,
checkTimeout: guardCheckTimeout,
}, nil
}
for _, opt := range opts {
opt(g)
}
return g, nil
}

// CanSkipClientAuth always returns false. refreshGrantValidators never calls
Expand Down Expand Up @@ -286,6 +301,15 @@ func (g *upstreamRefreshGuard) checkRow(
reason: "upstream access token expired and its provider is no longer configured",
}
}
if !storage.UpstreamIssuerMatches(row.Issuer, g.providerIssuers[name]) {
// Not revoked: the stored credential was issued by a previous IdP
// before the upstream was repointed; refusing without revoking avoids
// breaking sessions across a rolling deploy while forcing re-auth.
return false, &refusal{
provider: name,
reason: "upstream access token expired and its issuer does not match the configured provider",
}
}
if row.RefreshToken == "" {
return false, &refusal{
provider: name, revoke: true,
Expand Down Expand Up @@ -313,6 +337,12 @@ func (g *upstreamRefreshGuard) checkRow(
// replica's cleanup). Not revoked, for the same reason as no rows.
return false, &refusal{provider: name, reason: "upstream token row was deleted during refresh"}
}
if errors.Is(err, storage.ErrIssuerMismatch) {
return false, &refusal{
provider: name,
reason: "upstream token issuer does not match the configured provider",
}
}
if !errors.Is(err, upstream.ErrGrantRejected) {
slog.DebugContext(ctx, "upstream refresh failed transiently; refresh grant guard is not refusing",
"provider_id", name, "error", err)
Expand Down
9 changes: 8 additions & 1 deletion pkg/authserver/refresh_grant_guard_user_keyed.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,12 @@ type userKeyedCheck struct {
// The identity provider is the first of providerNames.
func newUserKeyedUpstreamRefreshGuard(
stor storage.Storage, refresher storage.UpstreamTokenRefresher, providerNames []string,
opts ...func(*upstreamRefreshGuard),
) (*upstreamRefreshGuard, error) {
if len(providerNames) == 0 {
return nil, errors.New("user-keyed upstream refresh guard requires an identity provider")
}
guard, err := newUpstreamRefreshGuard(stor, refresher, providerNames)
guard, err := newUpstreamRefreshGuard(stor, refresher, providerNames, opts...)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -119,6 +120,12 @@ func (g *upstreamRefreshGuard) deadUserKeyedUpstream(ctx context.Context, tsid,
if holdsLiveToken(snapshot, userID) {
return nil
}
if snapshot != nil && snapshot.UserID == userID && !storage.UpstreamIssuerMatches(snapshot.Issuer, g.providerIssuers[idp]) {
return &refusal{
provider: idp,
reason: "upstream access token expired and its issuer does not match the configured provider",
}
}

err = g.askUserCredential(ctx, userID, idp)
switch {
Expand Down
35 changes: 35 additions & 0 deletions pkg/authserver/refresher.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ const upstreamConflictReadTimeout = 5 * time.Second
// optimization layered on top of the CAS guarantee, not a substitute for it.
type upstreamTokenRefresher struct {
providers map[string]upstream.OAuth2Provider
providerIssuers map[string]string
storage storage.UpstreamTokenStorage
refreshTokenLifespan time.Duration
sfGroup singleflight.Group
Expand Down Expand Up @@ -124,6 +125,9 @@ func (r *upstreamTokenRefresher) RefreshAndStore(
if _, ok := r.providers[expired.ProviderID]; !ok {
return nil, fmt.Errorf("no upstream provider configured for %q", expired.ProviderID)
}
if err := r.checkProviderIssuer(expired); err != nil {
return nil, err
}

ctx, err := r.withCanonicalUser(ctx, expired)
if err != nil {
Expand Down Expand Up @@ -219,6 +223,9 @@ func (r *upstreamTokenRefresher) refreshFromAuthoritativeRow(
"upstream token row missing on re-read for provider %q", expired.ProviderID,
)
}
if issuerErr := r.checkProviderIssuer(authoritative); issuerErr != nil {
return nil, issuerErr
}
if !authoritative.IsExpired(time.Now()) && rowChanged(expired, authoritative) {
return authoritative, nil
}
Expand All @@ -227,6 +234,9 @@ func (r *upstreamTokenRefresher) refreshFromAuthoritativeRow(
if !errors.Is(readErr, storage.ErrExpired) || authoritative == nil {
return nil, readErr
}
if issuerErr := r.checkProviderIssuer(authoritative); issuerErr != nil {
return nil, issuerErr
}
return r.redeem(ctx, sessionID, rowID, authoritative)
}

Expand Down Expand Up @@ -276,6 +286,9 @@ func (r *upstreamTokenRefresher) refreshAndStore(
if !ok {
return nil, fmt.Errorf("no upstream provider configured for %q", expired.ProviderID)
}
if err := r.checkProviderIssuer(expired); err != nil {
return nil, err
}

// Refresh tokens via the upstream provider
newTokens, err := provider.RefreshTokens(ctx, expired.RefreshToken, expired.UpstreamSubject)
Expand Down Expand Up @@ -312,9 +325,17 @@ func (r *upstreamTokenRefresher) refreshAndStore(
)
}

// Preserve the token's recorded issuer, or stamp the current provider's
// issuer onto legacy rows written before issuer binding existed.
issuer := expired.Issuer
if issuer == "" {
issuer = r.providerIssuers[expired.ProviderID]
}

// Build updated storage tokens preserving binding fields from the original
updated := &storage.UpstreamTokens{
ProviderID: expired.ProviderID,
Issuer: issuer,
AccessToken: newTokens.AccessToken,
RefreshToken: newTokens.RefreshToken,
IDToken: newTokens.IDToken,
Expand Down Expand Up @@ -641,3 +662,17 @@ func rowChanged(callerRow, stored *storage.UpstreamTokens) bool {
callerRow.IDToken != stored.IDToken ||
!callerRow.ExpiresAt.Equal(stored.ExpiresAt)
}

// checkProviderIssuer ensures a stored upstream token row is not refreshed
// against an upstream whose configured issuer/authority no longer matches the
// issuer that created the row.
func (r *upstreamTokenRefresher) checkProviderIssuer(row *storage.UpstreamTokens) error {
configured := r.providerIssuers[row.ProviderID]
if !storage.UpstreamIssuerMatches(row.Issuer, configured) {
return fmt.Errorf(
"%w: provider %q token issuer %q does not match configured issuer %q",
storage.ErrIssuerMismatch, row.ProviderID, row.Issuer, configured,
)
}
return nil
}
10 changes: 10 additions & 0 deletions pkg/authserver/server/handlers/callback.go
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,7 @@ func (h *Handler) CallbackHandler(w http.ResponseWriter, req *http.Request) {
// still bounds the storage lifetime instead of leaving the row indefinitely.
storageTokens := &storage.UpstreamTokens{
ProviderID: providerID,
Issuer: h.upstreamIssuerFor(providerID, result),
AccessToken: idpTokens.AccessToken,
RefreshToken: idpTokens.RefreshToken,
IDToken: idpTokens.IDToken,
Expand Down Expand Up @@ -446,6 +447,15 @@ func (h *Handler) maybeCarryForwardRefreshToken(
if prior == nil || prior.RefreshToken == "" {
return
}
if !storage.UpstreamIssuerMatches(prior.Issuer, storageTokens.Issuer) {
slog.Warn("skipping upstream refresh token carry-forward: prior token issuer mismatches configured upstream",
"user_id", subject,
"provider_id", providerID,
"prior_issuer", prior.Issuer,
"current_issuer", storageTokens.Issuer,
)
return
}
// Non-synthetic: defense-in-depth account-linking guard requires the prior
// row's upstream subject to match. Synthetic providers mint a fresh rotating
// subject every flow, so that equality can never hold and there is no stable
Expand Down
1 change: 1 addition & 0 deletions pkg/authserver/server/handlers/device_verification.go
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,7 @@ func (h *Handler) completeDeviceLogin(
// PendingDeviceConfirmation.UpstreamTokens's doc comment.
UpstreamTokens: &storage.UpstreamTokens{
ProviderID: pending.UpstreamProviderName,
Issuer: h.upstreamIssuerFor(pending.UpstreamProviderName, result),
AccessToken: result.Tokens.AccessToken,
RefreshToken: result.Tokens.RefreshToken,
IDToken: result.Tokens.IDToken,
Expand Down
39 changes: 39 additions & 0 deletions pkg/authserver/server/handlers/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,19 @@ type NamedUpstream struct {
// Either both are set or both are empty.
Issuer string
SubjectClaim string
// TokenIssuer optionally records the upstream's configured token-binding
// authority identifier (OIDC issuer URL or OAuth 2.0 token endpoint). When
// empty, EffectiveIssuer falls back to upstream.ProviderIssuer(Provider).
TokenIssuer string
}

// EffectiveIssuer returns the upstream's configured token-binding issuer/authority
// identifier, falling back to querying Provider if TokenIssuer is empty.
func (u NamedUpstream) EffectiveIssuer() string {
if u.TokenIssuer != "" {
return u.TokenIssuer
}
return upstream.ProviderIssuer(u.Provider)
}

// Handler provides HTTP handlers for the OAuth authorization server endpoints.
Expand Down Expand Up @@ -578,6 +591,10 @@ func (h *Handler) nextMissingUpstream(ctx context.Context, sessionID string, cha
// No token stored for this leg — prompt.
return name, nil
}
// Reject stored rows issued by a previous authority after the upstream was repointed.
if !storage.UpstreamIssuerMatches(tokens.Issuer, h.upstreamIssuer(name)) {
return name, nil
}
// A live token (or one with no asserted expiry) satisfies the leg.
if tokens.ExpiresAt.IsZero() || !tokens.IsExpired(time.Now()) {
continue
Expand Down Expand Up @@ -791,6 +808,28 @@ func (h *Handler) upstreamByName(name string) (upstream.OAuth2Provider, bool) {
return nil, false
}

// upstreamIssuer returns the configured authority identifier for the named upstream.
func (h *Handler) upstreamIssuer(name string) string {
for i := range h.upstreams {
if h.upstreams[i].Name == name {
return h.upstreams[i].EffectiveIssuer()
}
}
return ""
}

// upstreamIssuerFor returns the configured authority identifier for providerName,
// falling back to result.VerifiedIssuer when the configured provider exposes none.
func (h *Handler) upstreamIssuerFor(providerName string, result *upstream.Identity) string {
if issuer := h.upstreamIssuer(providerName); issuer != "" {
return issuer
}
if result != nil {
return result.VerifiedIssuer
}
return ""
}

// issuer returns the authorization-server issuer URL. NewHandler enforces
// that h.config and h.config.Config are non-nil, so this method does not
// re-validate.
Expand Down
Loading