Skip to content
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

Remove closure from JsonWebTokenHandler.ValidateSignature #2169

Merged
merged 1 commit into from
Jul 26, 2023
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -1760,7 +1760,8 @@ private static JsonWebToken ValidateSignature(JsonWebToken jwtToken, TokenValida
{
if (kidMatched)
{
var isKidInTVP = keysInTokenValidationParameters.Any(x => x.KeyId.Equals(jwtToken.Kid));
JsonWebToken localJwtToken = jwtToken; // avoid closure on non-exceptional path
Copy link
Contributor

Choose a reason for hiding this comment

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

This is so tricky to catch both when coding and in review. Is there a way a static analyzer could catch this? It would probably be super noisy.

I assume the best way to find these today is to look at the allocations in a trace?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I assume the best way to find these today is to look at the allocations in a trace?

They certainly jump out at you there. "What is <>__DisplayClass_52 and why is it being allocated 18,000 times?"

In other projects, every now and then I'll also load up all the relevant assemblies in ILSpy, search for DisplayClass, and just flip through all of them to see whether they make sense.

Of course, the real solution is to avoid the patterns that lead to this in the first place, e.g. don't use Any(x => ...) and you won't close over anything, or use APIs that allow the TState to be passed in. And if you can avoid closing over stuff, protect it by using static on the lambda so they don't then regress.

var isKidInTVP = keysInTokenValidationParameters.Any(x => x.KeyId.Equals(localJwtToken.Kid));
var keyLocation = isKidInTVP ? "TokenValidationParameters" : "Configuration";
throw LogHelper.LogExceptionMessage(new SecurityTokenInvalidSignatureException(LogHelper.FormatInvariant(TokenLogMessages.IDX10511,
keysAttempted,
Expand Down