Skip to content

Fix NPE race in NettyResponseFuture.cancel (#2042) #2088

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 9, 2025

Conversation

pratt4
Copy link
Contributor

@pratt4 pratt4 commented May 7, 2025

Fixes #2042

This is a typical TOCTOU (time-of-check/time-of-use) race https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use.
The NPE was occurring because the channel field could be set to null by another thread between the check and its use:

if (channel != null) { // time-of-check
Channels.setDiscard(channel); // time-of-use
Channels.silentlyCloseChannel(channel);
}

By copying channel into a local variable in one atomic read, we ensure that—even if another thread changes the field—the local reference remains valid.

P.S. It is hard to write a deterministic test that fails consistently, so this PR only includes the code fix.

@pratt4
Copy link
Contributor Author

pratt4 commented May 9, 2025

HI @hyperxpro ...
can you please review this pr whenever you get time?

@hyperxpro hyperxpro requested a review from Copilot May 9, 2025 17:28
Copy link
Contributor

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull Request Overview

This PR fixes a race condition that could lead to a NullPointerException when cancelling a response by copying the channel reference to a local variable.

  • Introduces a local variable "ch" to capture the channel in one atomic operation.
  • Prevents a TOCTOU race condition by ensuring the local reference remains valid during subsequent operations.

@hyperxpro hyperxpro merged commit 73911eb into AsyncHttpClient:main May 9, 2025
3 checks passed
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.

NPE in at org.asynchttpclient.netty.channel.Channels.setAttribute(Channels.java:36)
2 participants