Skip to content

ReauthenticateAsync: refresh AUTH on all live connections, including dedicated subscription connections - #3373

Open
mgravell wants to merge 11 commits into
mainfrom
marc/reauthenticate
Open

mgravell wants to merge 11 commits into
mainfrom
marc/reauthenticate

Conversation

@mgravell

@mgravell mgravell commented Nov 21, 2026 •

Copy link
Copy Markdown
Member

Fixes #3372.

Since the RESP3 connection split (#3264), the dedicated subscription connection cannot be reached via IServer commands — Execute("AUTH", ...) always targets the interactive connection. Wrappers that keep expiring credentials fresh (e.g. Microsoft.Azure.StackExchangeRedis with Entra ID tokens on Azure Managed Redis) therefore only cover the interactive connection; the subscription connection's auth lapses, the server eventually drops it, and publications in the reconnect window are lost.

What this adds

ReauthenticateAsync(ReauthenticateOptions, CommandFlags), a public method on ConnectionMultiplexer and an extension method on IConnectionMultiplexer. It re-issues AUTH with the currently configured credentials (ConfigurationOptions.User/Password) on every established connection of every server, returning the number of connections covered:

  • Interactive connections: always.
  • Dedicated subscription connections: where in-place AUTH is legal — RESP3 (any state), or RESP2 with no active subscriptions. A RESP2 connection with live subscriptions is in subscriber mode, which rejects AUTH; those are skipped and keep today's lapse-and-reconnect behaviour (documented), which picks up the updated credentials on the reconnect handshake since the multiplexer reads the live options instance.
  • Shared subscription connection (SharedSubscriptionConnection=true): one connection, one AUTH — no double-send.
  • Multi-group (IConnectionGroup): refreshes every member, not just the active one — a stale standby would otherwise fail over unauthenticated.
  • Best effort: every established connection (and every multi-group member) is attempted; one that fails is logged as a warning (event id 142) and skipped rather than faulting the call. The result counts connections actually refreshed, and the call only faults if nothing succeeded.
  • FailFast routing fix: with BacklogPolicy.FailFast, a message for an explicitly chosen server was refused whenever that server's interactive connection was down, even when bound for a subscription connection that was up, because PrepareToPushMessageToBridge checked ServerEndPoint.IsConnected. The subscription bridge already applies the backlog policy against its own state, so that check is now skipped for subscription-bound messages.
  • ConnectionFailureType.Reauthentication (new enum value): what ConnectionFailed reports when AllowReconnect recycles a connection. Previously the shared recycle path always reported MaintenanceHandoff, which consumers are told to filter as planned maintenance.

Ad-hoc AUTH mirror for existing callers: the Microsoft.Azure.StackExchangeRedis extension (and anything like it) rotates with server.ExecuteAsync("AUTH", user, password) per server — IServer-based, confirmed against its source. The ad-hoc path already resolves the command string to RedisCommand.AUTH, so an ad-hoc AUTH against an IServer is now automatically shadowed onto that server's dedicated subscription connection wherever ReauthenticateAsync would AUTH it in place (RESP3, or RESP2 not in subscriber mode). Existing wrapper versions get the subscription refresh with no code change. Best-effort: the caller's result reflects only their own command, so if the mirrored AUTH fails, that is logged as a warning (event id 141) via ConfigurationOptions.LoggerFactory, and the subscription connection falls back to authenticating with the configured credentials when it next reconnects; the RESP2 subscriber-mode case is still skipped (that connection would reject it), for which ReauthenticateAsync(AllowReconnect) remains the full answer.

The intended rotation pattern (now also in docs/Authentication.md):

options.Password = await GetFreshTokenAsync();
await muxer.ReauthenticateAsync();

Notes from the investigation (details on the issue): detection of an already-deauthenticated subscription connection was already sound — a server-side close is seen immediately by the read loop, and a -NOAUTH reply to the subscription keepalive ping is treated as a connection failure by the tracer — so this API closes the prevention gap, not a detection one.

Validation

  • New in-process tests (no external server) assert the routing from the server's side — how many AUTH commands arrived, including one arriving on a connection with live subscriptions, which is the connection the issue reports as unreachable: RESP3 dual (2 connections authed), RESP3 shared (1), RESP2 subscribed (interactive only, subscriber-mode connection untouched, subscription keeps delivering), no-credentials (throws), rejected credentials (faults). Three further tests cover the ad-hoc mirror: RESP3 ad-hoc AUTH reaches both connections, RESP2 with an idle (established, unsubscribed) subscription connection reaches both, RESP2 in subscriber mode leaves it alone. A fourth has the server reject the mirrored AUTH, and asserts that the failure is logged and the subscription keeps delivering. The mirror is also checked on each of the four IServer.Execute overloads (sync and async, with and without a database), and ReauthenticateAsync is covered with FireAndForget and on a multi-group connection, where the standby member must be refreshed as well as the active one. Further tests cover best-effort behaviour (a refusing subscription connection, and a group member with no credentials), the FailFast case with the interactive connection down and the subscription connection up (which fails without the routing fix), whitespace-only passwords, and dispatch of the extension method.
  • Full Build.csproj Release build green (all TFMs, analyzers).
  • Full unit suite on net10.0: 6736 passed; the only failures are the 8 pre-existing SortedSetScanLarge ZSCAN environment failures also noted on Pub/sub: overlapping subscription restores cannot register on two servers #3353, unrelated.

Open questions for review

  • Interface addition. Now avoided: ReauthenticateAsync is an extension method on IConnectionMultiplexer rather than an interface member, so existing third-party implementations keep compiling and loading. It dispatches to ConnectionMultiplexer and the multi-group multiplexer, and throws NotSupportedException for anything else (custom implementations and decorators).
  • RESP2 + active subscriptions: skipped rather than proactively recycled. Now addressed opt-in: ReauthenticateOptions.AllowReconnect recycles connections that cannot re-AUTH in place (the same deliberate drop the MOVING handoff uses - reconnect handshakes with fresh credentials and restores subscriptions, backlog holding new work meanwhile). Not the default, because vanilla password rotation does not invalidate established connections - there a forced reconnect is an interruption for no benefit; it exists for servers that enforce credential expiry.
  • Sentinel: the managed sentinel connection is a separate inner multiplexer and is not touched; it can get the same treatment later if sentinel deployments adopt token auth.

… dedicated subscription connections

Since the RESP3 split (#3264), the dedicated subscription connection cannot
be reached via IServer commands, so token-rotation wrappers that keep
connections authenticated with periodic AUTH could only cover the
interactive connection; the subscription connection's auth lapsed and the
server eventually dropped it, losing publications in the window (#3372).

IConnectionMultiplexer.ReauthenticateAsync sends AUTH with the currently
configured credentials to every established connection: the interactive
connection, and the dedicated subscription connection where in-place AUTH
is legal (RESP3, or RESP2 with no active subscriptions - subscriber mode
rejects AUTH under RESP2, so those connections keep today's
lapse-and-reconnect behaviour, which picks up the updated credentials).
Multi-group connections refresh every member, not just the active one.

Asserted from the server's side in the in-process tests: the AUTH count
per connection, including one arriving on a connection with live
subscriptions - the connection the issue reports as unreachable.
…hat cannot re-AUTH in place

A RESP2 connection in subscriber mode rejects AUTH, so by default it is
skipped and relies on the server dropping it when its authentication
lapses. On a server that enforces credential expiry, that drop happens at
a moment of the server's choosing; AllowReconnect instead recycles the
connection now (the same deliberate drop the MOVING handoff uses), so the
replacement handshakes with the fresh credentials and restores the
subscriptions while the backlog holds new work. Not the default because
vanilla password rotation does not invalidate established connections -
there, a forced reconnect is an interruption for no benefit.
Existing rotation callers predate ReauthenticateAsync: the
Microsoft.Azure.StackExchangeRedis extension refreshes Entra ID tokens
with server.ExecuteAsync("AUTH", user, password) per connected server,
which only ever reaches the interactive connection. The ad-hoc path
already resolves the command to RedisCommand.AUTH, so recognise it and
re-issue the same command on that server's dedicated subscription
connection wherever ReauthenticateAsync would AUTH it in place (RESP3,
or RESP2 not in subscriber mode) - existing libraries get the
subscription refresh with no code change. Best-effort by design: the
caller's result reflects only their own command.
The ad-hoc IServer AUTH mirror was fire-and-forget with errors discarded, so a
failure there was invisible: the caller only sees the interactive reply. Log it
as a warning via the configured LoggerFactory. Event 141, since v4 already uses
134-140.

Claude-Session: https://claude.ai/code/session_01DUpQ8dy8FLBwADei2VzLmZ
…get, and multi-group

The AUTH mirror is wired into each Execute[Async] overload separately, but only
one was tested; ReauthenticateAsync with FireAndForget and the multi-group
fan-out to standby members had no coverage at all.

Claude-Session: https://claude.ai/code/session_01DUpQ8dy8FLBwADei2VzLmZ
…tion; docs

RecycleConnection always reported MaintenanceHandoff, whose docs tell consumers
to filter it as planned maintenance; a credential-rotation recycle would have
been blamed on the server. Add ConnectionFailureType.Reauthentication (13),
pass the failure type into RecycleConnection, and treat it like a handoff when
deciding whether to abort the backlog.

Docs: RESP2 subscription connections are in subscriber mode by default (the
configuration channel), partial failure semantics, per-member options for
multi-group, and the scope and argument reuse of the ad-hoc AUTH shadow.

Claude-Session: https://claude.ai/code/session_01DUpQ8dy8FLBwADei2VzLmZ
…plexer member

A new interface member breaks already-compiled third-party implementations at
type load. The extension dispatches to ConnectionMultiplexer (via the internal
IInternalConnectionMultiplexer, so the test fixture's wrapper still forwards)
and to MultiGroupMultiplexer, and throws NotSupportedException otherwise.

Claude-Session: https://claude.ai/code/session_01DUpQ8dy8FLBwADei2VzLmZ
…Fast routing fix

- Best effort: a failing connection (or multi-group member) is logged (event
  142) and skipped rather than faulting the whole call; the count is of
  connections actually refreshed, and the call only faults if nothing
  succeeded.
- FailFast: a message bound for the subscription connection was refused when
  the *interactive* connection was down, because PrepareToPushMessageToBridge
  checked ServerEndPoint.IsConnected; the subscription bridge applies the
  backlog policy itself against its own state, so skip that check for it.
- A whitespace-only password counts as no credentials, as in the handshake.

Claude-Session: https://claude.ai/code/session_01DUpQ8dy8FLBwADei2VzLmZ
…alueTuple

The library must not reference System.ValueTuple (SanityChecks.ValueTupleNotReferenced).

Claude-Session: https://claude.ai/code/session_01DUpQ8dy8FLBwADei2VzLmZ
…iber-mode misjudgement

The IServer AUTH shadow shared the caller's argument collection, but can be
written after Execute returns, when the caller is free to clear or reuse it -
and ExecuteMessage writes the RESP header from Count before enumerating, so a
late change could desync the subscription connection. It now takes a copy up
front, which also retires the "don't reuse the collection" caveat in the docs.

Also document that the RESP2 "is this connection in subscriber mode?" check
works from the server's last reported counts, so it can briefly misjudge (a
SUBSCRIBE in flight, or only sharded subscriptions, which are counted
separately); such a connection gets a rejected in-place AUTH and is not
recycled, even with AllowReconnect.
@mgravell
mgravell requested a review from philon-msft December 1, 2026 16:07
Comment thread docs/Authentication.md
Whether a RESP2 subscription connection is in subscriber mode is judged from the subscription counts the server
last reported, so it can briefly be wrong - for example while a `SUBSCRIBE` is still in flight, or when the
connection holds only sharded (`SSUBSCRIBE`) subscriptions, which the server counts separately. A connection
misjudged as idle is sent an in-place `AUTH`, which the server rejects; that is logged as a warning (event id 142)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
misjudged as idle is sent an in-place `AUTH`, which the server rejects; that is logged as a warning (event id 142)
misjudged as interactive is sent an in-place `AUTH`, which the server rejects; that is logged as a warning (event id 142)

?

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

No public API to reauthenticate dedicated RESP3 subscription connections

2 participants