GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — [fix][client] Expire cached OAuth2 tokens before the broker sees them expired by merlimat · Pull Request #27522 · apache/pulsar

Conversation

@merlimat

@merlimat merlimat commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

Motivation

AuthenticationOAuth2 caches the access token until expires_in seconds after the token response arrived. The broker decides that a connection's credentials have expired from the token's exp claim. The identity provider counts that claim from when it issued the token and writes it in whole seconds. So exp can come up to a second, plus the identity provider round trip, before the client's own expiry.

When the broker's periodic refresh check (authenticationRefreshCheckSeconds) lands in that gap, it sends an auth challenge. The client answers with its cached token, the broker rejects it as expired, and it closes the connection. The client's reconnects then fail the same way until its cache expires. Every producer and consumer on the connection is disconnected for that time. This affects any client using OAuth2 with the default lazy refresh (earlyTokenRefreshPercent = 1), including the broker's internal client when brokerClientAuthenticationPlugin is OAuth2.

This also makes TokenOauth2AuthenticatedProducerConsumerTest.testOAuth2TokenRefreshedWithoutReconnect flaky. With 3 s tokens and a 1 s refresh check, about 1 run in 100 fails its first attempt with:

NullPointerException: Cannot invoke "org.apache.pulsar.client.impl.ClientCnx.getAuthenticationDataProvider()"
because the return value of "org.apache.pulsar.client.impl.ProducerImpl.getClientCnx()" is null

The producer is reconnecting because the broker closed its connection.

Broker log of the failure:

Failed to authenticate {exception=Failed to authentication token: JWT expired 539 milliseconds ago at 2026-11-09T16:48:03.000Z.
Current time: 2026-11-09T16:48:03.539Z. Allowed clock skew: 0 milliseconds., operation=authentication-refresh, principal=my-admin-role, ...}

Current code path:

// AuthenticationOAuth2
public synchronized AuthenticationDataProvider getAuthData() throws PulsarClientException {
    ...
    if (this.cachedToken == null || this.cachedToken.isExpired()) {
        this.authenticate();
    }
    return this.cachedToken.getAuthData();   // the broker's REFRESH gets the cached token back
}

// AuthenticationOAuth2.CachedToken: counted from when the response arrived
this.expiresAt = AuthenticationOAuth2.this.clock.instant().plusSeconds(latest.getExpiresIn());

// AuthenticationProviderToken.TokenAuthenticationState, checked by ServerCnx.refreshAuthenticationCredentials()
public boolean isExpired() {
    return expiration < System.currentTimeMillis();   // expiration is the JWT exp claim, in whole seconds
}

Modifications

Count the token's lifetime from when it was requested, less one second for the whole-second exp claim:

private void authenticate() throws PulsarClientException {
    ...
    Instant requestedAt = this.clock.instant();
    TokenResult tr = this.flow.authenticate();
    this.cachedToken = new CachedToken(tr, requestedAt);
    handleSuccessfulTokenRefresh();
}

public CachedToken(TokenResult latest, Instant requestedAt) {
    this.latest = latest;
    this.expiresAt = requestedAt.plusSeconds(latest.getExpiresIn()).minusSeconds(1);
    ...
}

The identity provider issues the token after the request is sent, and the exp claim is rounded down by less than a second. So requestedAt + expires_in - 1 s is always before exp, and by the time the broker sees the token expired, the client has already dropped it and answers the refresh with a new one.

Behavior notes:

  • The client fetches a new token about a second earlier than before, plus the identity provider round trip.
  • A token with expires_in of 1 s or less is now fetched on every call; before, it was cached for up to a second.
  • Clock skew between the client and broker hosts is not covered, as before.

Verifying this change

  • New AuthenticationOAuth2Test.testGetAuthDataExpiresTokenBeforeItsExpClaim (mock clock): the token request takes 1.5 s, and the token must be refetched once requestedAt + expires_in - 1 s has passed. It fails before the change and passes after.
  • New TokenOauth2AuthenticatedProducerConsumerTest.testOAuth2TokenRefreshedWithoutReconnectAfterSlowTokenResponse: MockOIDCIdentityProvider.delayNextTokenResponse holds the client's first token response for 1.5 s after issuing the token. That is longer than the broker's 1 s refresh check, so the broker's first refresh after exp always finds the unfixed client still serving the expired token. It fails on both attempts before the change with the CI NPE, and passes after (2.7 s).
  • Ran locally: TokenOauth2AuthenticatedProducerConsumerTest, AdminOnlyOAuth2AuthTest, ProxyTlsWithAuthTest, the org.apache.pulsar.client.impl.auth.oauth2 client tests, and ./gradlew quickCheck. OAuth2IdpTlsFrameworkClientTest failed locally only because another process held port 8080; it is unrelated to this change.

Does this pull request potentially affect one of the following parts:

If the box was checked, please highlight the changes

  • Dependencies (add or upgrade a dependency)
  • The public API
  • The schema
  • The default values of configurations
  • The threading model
  • The binary protocol
  • The REST endpoints
  • The admin CLI options
  • The metrics
  • Anything that affects deployment

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
merlimat added 2 commits November 9, 2026 08:50
@merlimat
[fix][client] Expire cached OAuth2 tokens before the broker sees them…
390fd38
… expired

AuthenticationOAuth2 cached a token until expires_in seconds after the
token response arrived. The broker goes by the token's exp claim, which the
identity provider counts from when it issued the token, in whole seconds, so
it can be up to a second plus the identity provider round trip earlier. A
broker refresh check in that gap got the cached token back, rejected it as
expired and closed the connection, and the client's reconnects failed the
same way until its cache expired.

Count the token's lifetime from when it was requested, less one second for
the whole-second exp claim, so the client has dropped the token by the time
the broker sees it expired.

This also fixes the flaky
TokenOauth2AuthenticatedProducerConsumerTest.testOAuth2TokenRefreshedWithoutReconnect.
@merlimat
Merge remote-tracking branch 'apache/master' into mmerli/fix-oauth2-t…
a204625
…oken-refresh-flaky
codelipenghui
codelipenghui approved these changes Nov 9, 2026
View reviewed changes
@merlimat
merlimat merged commit e35988b into apache:master Nov 9, 2026
46 checks passed

Uh oh!

There was an error while loading. Please reload this page.

@merlimat merlimat added this to the 5.1.0 milestone Nov 9, 2026
@merlimat merlimat added the release/5.0.2 label Nov 9, 2026
lhotari pushed a commit that referenced this pull request Nov 11, 2026
@merlimat @lhotari
[fix][client] Expire cached OAuth2 tokens before the broker sees them…
20e35a9
… expired (#27522)

(cherry picked from commit e35988b)
@lhotari lhotari added the cherry-picked/branch-5.0 label Nov 11, 2026
This was referenced Nov 21, 2026
[improve][ci] Run CI for the 4.2.6 backports to branch-4.2 (do not merge) #27680
Closed
[improve][ci] Run CI for the 4.2.6 backports to branch-4.2 (do not merge) #27681
Closed
[improve][ci] Run CI for the 4.2.6 backports to branch-4.2 (do not merge) #27684
Closed
@lhotari lhotari added cherry-picked/branch-4.2 release/4.2.6 cherry-picked/branch-4.0 release/4.0.15 labels Nov 21, 2026
poorbarcode pushed a commit to poorbarcode/pulsar that referenced this pull request Nov 26, 2026
@merlimat @lhotari
[fix][client] Expire cached OAuth2 tokens before the broker sees them…
1750b44
… expired (apache#27522)

(cherry picked from commit e35988b)
poorbarcode pushed a commit to poorbarcode/pulsar that referenced this pull request Nov 26, 2026
@merlimat @lhotari
[fix][client] Expire cached OAuth2 tokens before the broker sees them…
e09f914
… expired (apache#27522)

(cherry picked from commit e35988b)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

@codelipenghui codelipenghui codelipenghui approved these changes

Uh oh!

There was an error while loading. Please reload this page.

Assignees

No one assigned

Labels

cherry-picked/branch-4.0 cherry-picked/branch-4.2 cherry-picked/branch-5.0 release/4.0.15 release/4.2.6 release/5.0.2

Projects

None yet

Milestone

5.1.0

Development

Successfully merging this pull request may close these issues.

Uh oh!

There was an error while loading. Please reload this page.

3 participants

@merlimat @codelipenghui @lhotari
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.