Skip to content

Commit

Permalink
Fix EnableRelaxedDecoding implementation and add test coverage
Browse files Browse the repository at this point in the history
  • Loading branch information
iamcarbon committed Nov 12, 2024
1 parent e11a2fd commit 7aebefd
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 3 deletions.
22 changes: 19 additions & 3 deletions Src/Fido2.Models/Converters/Base64UrlConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,29 @@ public override byte[] Read(ref Utf8JsonReader reader, Type typeToConvert, JsonS
{
return Base64Url.DecodeFromUtf8(source);
}
catch
catch (Exception ex)
{
if (Base64.IsValid(source))
{
static byte[] DecodeBase64FromUtf8(scoped ReadOnlySpan<byte> source)
{
var rentedBuffer = ArrayPool<byte>.Shared.Rent(Base64.GetMaxDecodedFromUtf8Length(source.Length));

try
{
_ = Base64.DecodeFromUtf8(source, rentedBuffer, out _, out int written);

return rentedBuffer[0..written];
}
finally
{
ArrayPool<byte>.Shared.Return(rentedBuffer);
}
}

if (EnableRelaxedDecoding)
{
return Base64Url.DecodeFromUtf8(source);
return DecodeBase64FromUtf8(source);
}
else
{
Expand All @@ -52,7 +68,7 @@ public override byte[] Read(ref Utf8JsonReader reader, Type typeToConvert, JsonS
}
else
{
throw new JsonException("Invalid Base64Url data");
throw new JsonException(ex.Message, ex);
}
}
finally
Expand Down
36 changes: 36 additions & 0 deletions Tests/Fido2.Tests/Fido2UserTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Text.Json;

namespace Fido2NetLib.Tests;

public class Base64UrlConverterTests
{
[Fact]
public void RelaxedDecodingWorks()
{
string jsonText =
"""
{
"name": "anders",
"id": "7w80qsdaWWm5R+KK2O64MO/WSitunFbxH1H8mE9IVORxzbXdxXDY1VRQlayoK/Lmh3MI/p0M59Rh98D8r4EoJw==",
"displayName": "anders"
}
""";

Base64UrlConverter.EnableRelaxedDecoding = false;

try
{
_ = JsonSerializer.Deserialize<Fido2User>(jsonText);
}
catch (JsonException ex)
{
Assert.Equal("Expected data to be in Base64Url format, but received Base64 encoding instead.", ex.Message);
}

Base64UrlConverter.EnableRelaxedDecoding = true;

var user = JsonSerializer.Deserialize<Fido2User>(jsonText);

Assert.Equal("7w80qsdaWWm5R+KK2O64MO/WSitunFbxH1H8mE9IVORxzbXdxXDY1VRQlayoK/Lmh3MI/p0M59Rh98D8r4EoJw==", Convert.ToBase64String(user.Id));
}
}

0 comments on commit 7aebefd

Please sign in to comment.