Skip to content

fix: refresh dynamic auth credentials on dedicated connections - #1048

Merged
rueian merged 3 commits into
redis:mainfrom
FZambia:fix/auth-refresh-dedicated-pubsub
Nov 3, 2026
Merged

rueian merged 3 commits into
redis:mainfrom
FZambia:fix/auth-refresh-dedicated-pubsub

Conversation

@FZambia

@FZambia FZambia commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

TL;DR

A connection held by Dedicate() / Dedicated() never refreshed its AuthCredentials, so a long-lived pub/sub connection was dropped by the server once its credentials expired. The auth refresh now keeps running while a connection is checked out, and the reply of the refresh AUTH is ignored, so a refresh that cannot succeed no longer closes a working connection. No API change.

Real-world report: centrifugal/centrifugo#1296 (AWS ElastiCache with IAM auth, connection dropped with EOF every 12 hours).

Problem

AuthCredentials.RefreshAfter (#1008) makes every connection call AuthCredentialsFn again and send AUTH before its credentials expire. pool.Acquire calls StopTimer() on checkout, which paused that refresh, and pool.Store → ResetTimer() resumed it. A pub/sub connection is never returned while its subscriptions live, so its refresh never ran. Centrifugo/centrifuge and rueidiscompat.PubSub both subscribe on dedicated connections.

Fix

Two changes, both following the maintainer's suggestions in the review.

The refresh is not paused on checkout anymore. AUTH is an ordinary request, also on a subscribed RESP3 connection, and the background PING already runs on dedicated pub/sub pipes. A transaction is sent in one DoMulti (see the README's CAS section and rueidiscompat), which is written as a unit, so AUTH cannot land inside it.

The reply of the refresh AUTH is ignored. The AUTH can fail while the connection is still fine:

Closing the connection on such a reply turned every refresh into a reconnect. The connection now keeps its current credentials and the server drops it when they expire, which is also what happens when the new credentials are really wrong; the next connect then fails on HELLO. A connection that stopped replying is still closed by the background PING. An error from AuthCredentialsFn itself still closes the pipe, as before.

Stream pool is out of scope

nobg pipes, used by spool for DoStream / DoMultiStream, keep pausing the refresh on checkout. They have no queue and no background worker, and DoStream owns the connection synchronously and panics on concurrent use, so an unpaused refresh during a stream would be a new failure there. A stream held longer than the credential lifetime is therefore still not refreshed. It needs a different mechanism and is left for a separate change.

Verified against real servers

Valkey built from the release tags, loaded with Valkey's own tests/modules/auth.so, which authenticates through BlockClientOnAuth like a provider module. This branch with RefreshAfter set to 2s, holding a dedicated pub/sub connection with Receive for 8s, so three refreshes run on the subscribed connection.

Valkey RESP3 pub/sub connection, main RESP3 pub/sub connection, this branch RESP2 pub/sub connection, main RESP2 pub/sub connection, this branch
8.0.12 never refreshed survived three refreshes closed at the first refresh survived three refreshes
8.1.11 never refreshed survived three refreshes closed at the first refresh survived three refreshes
unstable (7dfa61e, includes #4863) never refreshed survived three refreshes closed at the first refresh survived three refreshes

On 8.1.11 the module AUTH on the subscribed RESP3 connection is still rejected by the server; the connection now simply keeps its credentials until they expire, as it did before this change.

Tests

  • Auth Credentials Refresh Runs While Checked Out replaces Timer Lifecycle: a regular pipe refreshes after StopTimer().
  • Auth Credentials Refresh Behind Blocking Command (new): the AUTH times out behind BLPOP, the pipe stays open and schedules the next refresh, and the queued AUTH is applied after the blocking reply.
  • Auth Credentials Refresh Timeout Keeps Pipe replaces Timeout: on a pipelining pipe an AUTH that hits ConnWriteTimeout does not close the pipe and its late reply is consumed.
  • Auth Credentials Refresh Rejected Keeps Pipe (new): an AUTH rejected by the server leaves the pipe open and schedules the next refresh.
  • Auth Credentials Refresh NoBg Pool Lifecycle (unchanged) pins that nobg pipes still pause.

TestNewPipe, TestPool*, TestMux*, TestPipe* and TestClose* pass under -race.


Note

Medium Risk
Changes long-lived connection lifecycle and when refresh AUTH failures close the pipe; behavior is security-adjacent (IAM/credentials) but scoped to error handling and timer scheduling with expanded tests.

Overview
Fixes long-lived dedicated/pub/sub connections (e.g. Dedicate(), IAM RefreshAfter) losing credentials because pool checkout used to pause the auth refresh timer via StopTimer()—those connections are rarely returned to the pool.

Auth refresh now keeps running while a pipelined pipe is checked out: StopTimer / ResetTimer only stop the auth timer when p.queue == nil (nobg stream pipes still pause, unchanged).

Periodic refresh AUTH no longer tears down the connection on a bad reply: refreshAuth fires AUTH but ignores the result instead of calling _exit on error. Failed or delayed refreshes (blocking commands + ConnWriteTimeout, RESP2 pub/sub rejection, Valkey module-auth on subscribed RESP3) leave the existing session credentials in place until the server expires them; dead connections are still detected via background PING. Errors from AuthCredentialsFn still close the pipe.

Tests were flipped/extended to assert refresh during checkout, behind BLPOP, on write timeout, and on server AUTH rejection—all without closing the pipe.

Reviewed by Cursor Bugbot for commit 496bddd. Bugbot is set up for automated code reviews on this repo. Configure here.

rueian pushed a commit that referenced this pull request Oct 30, 2026
…ground worker (#1050)

## Problem

`pipe.Close` can block forever when another waiter is in flight at the
same time.

`Close` starts the background worker only when it is the only waiter, so
that it does not race with a sync read (`8503b21`). Its graceful `PING`
then relies on the other waiter, assumed to be a `syncDo`, to start the
worker once the closed connection breaks its read. But the other waiter
can also be:

- a concurrent `Close`, for example the lifetime timer's `expired()`
racing with `pool.Acquire`, `pool.Store` or the user;
- a `Do` that sees the pipe already stopping and returns an error.

Both leave without starting a worker:

```
  Close A (e.g. lifetime timer)            Close B (or a Do)
  ─────────────────────────────            ─────────────────
  blcksig++ → 1
                                           blcksig++ → 2
                                           waits++   → 1
  waits++ → 2
  state 0→2 ✓, but waits != 1
    └─► background worker NOT started
                                           state CAS fails → skips the PING path,
                                           waits-- and returns (a Do returns an error)
  PutOne(PING)
  <-ch   ◄── never answered
             escape timer closes the conn after 1s,
             but no worker drains the queue
```

```
 ┌──────────────┐  PutOne(PING)  ┌──────────────┐  drain / answer  ┌─────────────────────┐
 │   Close A    │ ─────────────► │    queue     │ ◄──────────────  │  background worker  │
 │  waits <-ch  │                │              │                  │     NOT RUNNING     │
 └──────────────┘                └──────────────┘                  └─────────────────────┘
```

**Impact:** whichever `Close` loses never returns:

- **The lifetime timer's `Close` (`expired()`):** one leaked goroutine.
- **`pool.Acquire` / `pool.Store`:** they call `v.Close()` while holding
the pool lock (`p.cond.L`). Every later `Dedicated()`/`Dedicate()` call
and every blocking command on that pool then waits forever.
- **`client.Close()`:** shutdown never returns.

One realistic trigger: `ConnLifetime` is set, and an idle pooled
connection that only ever took the sync path has never started its
worker. Its lifetime timer fires at the same moment `pool.Acquire` takes
it, `Acquire` sees `StopTimer()` return false, and both call `Close`.
The window is nanoseconds wide, so it's rare.

CI caught it on #1048
(https://github.com/redis/rueidis/actions/runs/40632881130), in
`TestLifetimeTimerCrossTimerConstruction`: its tiny-lifetime case makes
`expired()` and the test's own `Close` race 500 times per run. The leak
detector fails with:

```
Expected not to leak 1 goroutines:
    goroutine … [chan receive, 1 minutes]
        github.com/redis/rueidis.(*pipe).Close at rueidis/pipe.go:…   (<-ch)
        github.com/redis/rueidis.(*pipe).expired
        github.com/redis/rueidis._newPipe.func3
```

## Origin

- **`8503b21`** ("fix: avoid racing with sync read when closing",
v0.0.53) introduced the race. At that point the losing `Close` gave up
waiting after one second and handed `<-ch` to a goroutine, so the race
only leaked that goroutine. The caller returned.
- **#1013** ("fix(pipe): don't let Close hang when the command ring is
full", v1.0.77) replaced the give-up with an escape timer, and `Close`
itself waits for the `PING`. The design assumes there is always a worker
to drain the queue. This race breaks that assumption, so since v1.0.77
the losing caller hangs.

## Fix

The escape timer calls `failSync(errClosing)` instead of only
`p.conn.Close()`. `failSync` closes the connection and starts the
**cleanup-only** background worker (`backgroundSkipReadWrite`). That
worker answers every queued request with the pipe's error until no
waiter is left, and it never reads or writes the connection.

| Situation when the escape fires | Before | After |
|---|---|---|
| Worker already running (silent peer) | conn closed, worker drains |
same: starting the worker is a no-op |
| Sync read in flight | conn closed, `syncDo` fails and starts the
worker | same: the cleanup worker does not read, so a late reply cannot
be misread |
| **No worker (this race)** | **`Close` blocks forever** | **cleanup
worker drains, `Close` returns** |

## Why this fix

| Alternative | Problem |
|---|---|
| Restore the pre-#1013 give-up after one second | Brings back the
goroutine leaked in this race, and the hang #1013 fixed, where `PutOne`
waits for a slot in a full ring. |
| Always start the regular worker in `Close`, or from the waiter that
leaves | That worker reads the connection while an in-flight `syncDo`
may still be reading it: the race `8503b21` prevents. |
| Count sync readers separately, so `Close` knows whether a `syncDo` is
in flight | `Close` could return promptly, but `syncDo`, `syncDoMulti`,
`DoStream` and `DoMultiStream` would all maintain the counter on the hot
path, for a rare race. |
| **Escape timer calls `failSync`** | Reuses the worker that exists for
exactly this state: a failed pipe whose connection a sync path may still
be reading. No new state, no hot-path cost, no change outside the race.
|

**Trade-off:** in this race, `Close` returns after the one-second escape
rather than promptly. Avoiding that would require telling a departing
waiter apart from an in-flight `syncDo`. Aborting a `syncDo` early would
break the graceful `PING`, so the second is paid only in the race.

## Tests

`TestCloseWithConcurrentWaiter` in `pipe_test.go` forces the losing
state deterministically. It counts an extra waiter before `Close`, the
way a concurrent `Close` or `Do` does, then checks that `Close` returns
and that no goroutine leaks.

- **Without the fix:** `Close hung without a background worker`,
followed by the same leak-detector panic as CI.
- **With the fix:** passes. The Close, ForceClose, lifetime-timer and
late-reply tests pass 3× under `-race`. The full root package suite
passes under `-race` against the docker-compose Redis setup.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes connection shutdown and pool/client close behavior, but the
fix is confined to the existing escape timer and reuse of
`failSync`/`backgroundSkipReadWrite`.
> 
> **Overview**
> Fixes **`pipe.Close`** blocking forever when a graceful shutdown
**PING** sits on the queue and nothing drains it—typically when two
**`Close`** calls (or a **`Close`** plus a **`Do`** that bails on
“stopping”) race so neither starts the background worker.
> 
> The one-second **escape timer** now calls **`failSync(errClosing)`**
instead of only closing the socket. That marks the pipe failed and
starts the **cleanup-only** background worker
(**`backgroundSkipReadWrite`**), which answers queued work without
reading the wire—the same path sync failures already use.
> 
> Comments on **`failSync`** and the **`Close`** PING path document this
case. **`TestCloseWithConcurrentWaiter`** simulates an extra waiter so
**`Close`** must return without relying on another goroutine to start
the worker.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e2b3d26. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
@rueian

rueian commented Nov 1, 2026

Copy link
Copy Markdown
Collaborator

Hi @FZambia, thanks for the PR, but I think we should probably never pause the auth timer during checkout.

We don't need to consider the MULTI … EXEC issue. They are usually sent through a DoMulti call so there won't be an AUTH queued in between.

Blocking commands are trickier, but what we can do are only two things:

  1. Ignore timeout errors from background AUTH/PING if they are cuased by a preceding blocking command.
  2. Stop background AUTH/PING beforing sending a blocking command.

We can start from 1. And 2 might be optional.

@FZambia
FZambia force-pushed the fix/auth-refresh-dedicated-pubsub branch from db7a5ff to 03705cd Compare November 1, 2026 15:06
@FZambia FZambia changed the title fix: refresh dynamic auth credentials on dedicated RESP3 pub/sub connections fix: refresh dynamic auth credentials on dedicated connections Nov 1, 2026

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 03705cd. Configure here.

Comment thread pipe.go Resolved
@FZambia

FZambia commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor Author

Many thanks @rueian

I reworked the PR:

  • StopTimer / ResetTimer no longer pause and resume the auth refresh, so it keeps running on checked-out pipes.
  • For blocking commands I did (1): refreshAuth ignores a non-Redis error from the AUTH when blcksig != 0, mirroring the background PING. The AUTH stays queued and is applied once the blocking command returns.

One exception, which I think has to be addressed separately: the nobg pipes used by spool for DoStream / DoMultiStream. They have no queue and no background worker, and DoStream panics on any concurrent use of the connection. If their refresh fired during a stream, the AUTH would either take the sync path and trigger the racing panic, or hit the queue path with a nil queue. So for p.queue == nil the pause stays, which keeps them exactly as they are today. A stream held longer than the credential lifetime is therefore still not refreshed, but that needs a different mechanism than the dedicated pool.

One more thing to know. Valkey 8.1.1 through the current 9.x releases have a server-side regression, valkey-io/valkey#4862: a module cannot block a RESP3 client that has subscriptions, so an AUTH handled asynchronously by a module gets no reply. On those servers, once the refresh runs on subscribed connections, every refresh AUTH will time out after ConnWriteTimeout and the connection will be closed and re-established, so users there would see a reconnect per refresh interval instead of one every 12 hours.

Tried to reproduce using Valkey, loaded with Valkey's own tests/modules/auth.so. That module authenticates asynchronously through BlockClientOnAuth, the same way a provider module does, so AUTH foo block_allow succeeds only via the module. Two experiments, both with this branch of rueidis:

  1. Open a dedicated RESP3 connection, SUBSCRIBE on it, then send that AUTH on the same connection and look at the reply.
  2. Set RefreshAfter to 2s, hold a dedicated pub/sub connection with Receive for 8s, so the refresh sends the AUTH three times on the subscribed connection, and see whether the connection is still open at the end.
Valkey 1. reply to AUTH on the subscribed connection 2. pub/sub connection after 8s and three refreshes
8.0.12 OK still open
8.1.11 ERR Blocking module command called from transaction closed by rueidis at the first refresh, after 1.5s
unstable (7dfa61e, includes valkey-io/valkey#4863) OK still open

So on those servers, once the refresh runs on subscribed connections, users would see a reconnect per refresh interval instead of one every 12 hours. The fix is merged in Valkey (valkey-io/valkey#4863) and backported, but no release contains it yet, and ElastiCache will pick it up later still. Redis and Valkey up to 8.0 are not affected.

@rueian

rueian commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator

Thanks, @FZambia. The Valkey server-side regression is unfortunate and might be huge. I wonder whether we should just always ignore the reply from the AUTH refreshes?

StopTimer paused the auth refresh of a pipe checked out from a pool, and
ResetTimer resumed it when the pipe was returned. A dedicated pub/sub pipe
is held for as long as its subscriptions live, so its credentials were
never refreshed and the server dropped the connection once they expired.

The refresh now keeps running on a checked-out pipe. AUTH is an ordinary
request, also on a subscribed RESP3 connection, and a transaction is sent
in one DoMulti so AUTH cannot land inside it. Behind a blocking command
the AUTH hits ConnWriteTimeout like the background PING does; that error
is ignored when a blocking command is in flight, since the AUTH stays
queued and is applied once the blocking command returns.

Only nobg pipes, as used by the stream pool, still pause the refresh on
checkout: DoStream owns its connection synchronously and cannot share it
with a concurrent AUTH.
A blocking command ahead of the refresh AUTH can be answered right when
the AUTH times out, so blcksig can already be zero when the timeout is
handled and a healthy pipe would be closed. Sample it before sending the
AUTH too, and keep the pipe open if either sample saw a blocking command.
A pipe that really stopped replying is still closed by the background
PING, which stalls behind the unanswered AUTH.
The refresh AUTH can fail while the connection is still fine: behind a
blocking command it hits ConnWriteTimeout and is applied once the
blocking command returns, a subscribed RESP2 connection rejects it, and
Valkey 8.1 to 9.x reject module auth on a subscribed RESP3 connection
(valkey-io/valkey#4862). Closing the connection on such a reply turned
every refresh into a reconnect. The connection now keeps its current
credentials and the server drops it when they expire, which is also what
happens when the new credentials are really wrong. A connection that
stopped replying is still closed by the background PING.

This replaces the blcksig sampling around the AUTH.
@FZambia
FZambia force-pushed the fix/auth-refresh-dedicated-pubsub branch from 599dc30 to 496bddd Compare November 2, 2026 17:15
@FZambia

FZambia commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor Author

The Valkey server-side regression is unfortunate and might be huge. I wonder whether we should just always ignore the reply from the AUTH refreshes?

Probably the best we can do here to not introduce more problems than improvements...

Done in 496bddd: refreshAuth now sends the AUTH and ignores its reply. That also replaces the blcksig sampling around the AUTH, so the blocking-command handling is gone with it.

While verifying I found that this also fixes a pre-existing problem on RESP2. A subscribed RESP2 connection rejects every command but pub/sub ones, and the internal RESP2 pub/sub pipe has its own refresh timer that was never paused, so since #1008 it got Can't execute 'auth': only (P|S)SUBSCRIBE / (P|S)UNSUBSCRIBE / PING / QUIT / RESET are allowed in this context at every refresh and was closed each time. With the reply ignored it stays open. It still sends a useless AUTH per interval; skipping the refresh on that pipe entirely could make sense – but I decided to not do not introduce changes in behavior. I suppose can be done separately if needed.

Same setup as before, Valkey built from the tags with tests/modules/auth.so, RefreshAfter 2s, a dedicated pub/sub connection held by Receive for 8s, so three refreshes run on it:

Valkey RESP3 pub/sub, main RESP3 pub/sub, this branch RESP2 pub/sub, main RESP2 pub/sub, this branch
8.0.12 never refreshed survived three refreshes closed at the first refresh survived three refreshes
8.1.11 never refreshed survived three refreshes closed at the first refresh survived three refreshes
unstable (7dfa61e, includes #4863) never refreshed survived three refreshes closed at the first refresh survived three refreshes

On 8.1.11 the server still rejects the module AUTH on the subscribed connection, so there the connection keeps its credentials until they expire, exactly as before this change.

I also rebased onto main to fix CI benchmark failure.

@rueian

rueian commented Nov 3, 2026

Copy link
Copy Markdown
Collaborator

Thanks @FZambia!

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.

2 participants