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

Update JwtDecoder to prevent NullReferenceException in AllKeysHaveValues() #487

Merged
merged 3 commits into from
Dec 15, 2023
Merged
Show file tree
Hide file tree
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
15 changes: 13 additions & 2 deletions src/JWT/JwtDecoder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,18 @@ private static bool AllKeysHaveValues(byte[][] keys)
if (keys.Length == 0)
return false;

return Array.TrueForAll(keys, key => key.Length > 0);
return Array.TrueForAll(keys, key => KeyHasValue(key));
}

private static bool KeyHasValue(byte[] key)
{
if (key is null)
return false;

if (key.Length == 0)
return false;

return true;
}

private void ValidateNoneAlgorithm(JwtParts jwt)
Expand All @@ -308,4 +319,4 @@ private void ValidateNoneAlgorithm(JwtParts jwt)
}
}
}
}
}
34 changes: 34 additions & 0 deletions tests/JWT.Tests.Common/JwtDecoderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,40 @@ public void DecodeToObject_Should_Throw_Exception_On_Invalid_Multiple_Keys()
.Throw<SignatureVerificationException>("because providing the wrong key must raise an error when the signature is verified");
}

[TestMethod]
public void DecodeToObject_Should_Throw_Exception_On_Key_Is_Null()
{
const string token = TestData.Token;
var key = (byte[])null;

var serializer = CreateSerializer();
var validator = new JwtValidator(serializer, new UtcDateTimeProvider());
var urlEncoder = new JwtBase64UrlEncoder();
var decoder = new JwtDecoder(serializer, validator, urlEncoder, TestData.HMACSHA256Algorithm);

Action action = () => decoder.DecodeToObject<Customer>(token, key, verify: true);

action.Should()
.Throw<ArgumentOutOfRangeException>();
}

[TestMethod]
public void DecodeToObject_Should_Throw_Exception_On_Multiple_Keys_Containing_Null()
{
const string token = TestData.Token;
var keys = new byte[][] { (byte[])null };

var serializer = CreateSerializer();
var validator = new JwtValidator(serializer, new UtcDateTimeProvider());
var urlEncoder = new JwtBase64UrlEncoder();
var decoder = new JwtDecoder(serializer, validator, urlEncoder, TestData.HMACSHA256Algorithm);

Action action = () => decoder.DecodeToObject<Customer>(token, keys, verify: true);

action.Should()
.Throw<ArgumentOutOfRangeException>();
}

[TestMethod]
public void DecodeToObject_Should_Throw_Exception_On_Invalid_Expiration_Claim()
{
Expand Down