Skip to content

Makes the hashing algorithm used for ETags pluggable #1007

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 1 commit into from
Jun 11, 2021
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
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,7 @@ private void AddSerializationLayer()
_services.AddScoped(typeof(AtomicOperationsResponseSerializer));
_services.AddScoped(sp => sp.GetRequiredService<IJsonApiSerializerFactory>().GetSerializer());
_services.AddScoped<IResourceObjectBuilder, ResponseResourceObjectBuilder>();
_services.AddSingleton<IFingerprintGenerator, FingerprintGenerator>();
_services.AddSingleton<IETagGenerator, ETagGenerator>();
}

Expand Down
34 changes: 7 additions & 27 deletions src/JsonApiDotNetCore/Serialization/ETagGenerator.cs
Original file line number Diff line number Diff line change
@@ -1,46 +1,26 @@
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using Microsoft.Net.Http.Headers;

namespace JsonApiDotNetCore.Serialization
{
/// <inheritdoc />
internal sealed class ETagGenerator : IETagGenerator
{
private static readonly uint[] LookupTable = Enumerable.Range(0, 256).Select(ToLookupEntry).ToArray();
private readonly IFingerprintGenerator _fingerprintGenerator;

private static uint ToLookupEntry(int index)
public ETagGenerator(IFingerprintGenerator fingerprintGenerator)
{
string hex = index.ToString("X2");
return hex[0] + ((uint)hex[1] << 16);
ArgumentGuard.NotNull(fingerprintGenerator, nameof(fingerprintGenerator));

_fingerprintGenerator = fingerprintGenerator;
}

/// <inheritdoc />
public EntityTagHeaderValue Generate(string requestUrl, string responseBody)
{
byte[] buffer = Encoding.UTF8.GetBytes(requestUrl + "|" + responseBody);

using HashAlgorithm hashAlgorithm = MD5.Create();
byte[] hash = hashAlgorithm.ComputeHash(buffer);
string fingerprint = _fingerprintGenerator.Generate(ArrayFactory.Create(requestUrl, responseBody));
string eTagValue = "\"" + fingerprint + "\"";

string eTagValue = "\"" + ByteArrayToHex(hash) + "\"";
return EntityTagHeaderValue.Parse(eTagValue);
}

// https://stackoverflow.com/questions/311165/how-do-you-convert-a-byte-array-to-a-hexadecimal-string-and-vice-versa
private static string ByteArrayToHex(byte[] bytes)
{
char[] buffer = new char[bytes.Length * 2];

for (int index = 0; index < bytes.Length; index++)
{
uint value = LookupTable[bytes[index]];
buffer[2 * index] = (char)value;
buffer[2 * index + 1] = (char)(value >> 16);
}

return new string(buffer);
}
}
}
54 changes: 54 additions & 0 deletions src/JsonApiDotNetCore/Serialization/FingerprintGenerator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace JsonApiDotNetCore.Serialization
{
/// <inheritdoc />
internal sealed class FingerprintGenerator : IFingerprintGenerator
{
private static readonly byte[] Separator = Encoding.UTF8.GetBytes("|");
private static readonly uint[] LookupTable = Enumerable.Range(0, 256).Select(ToLookupEntry).ToArray();

private static uint ToLookupEntry(int index)
{
string hex = index.ToString("X2");
return hex[0] + ((uint)hex[1] << 16);
}

/// <inheritdoc />
public string Generate(IEnumerable<string> elements)
{
ArgumentGuard.NotNull(elements, nameof(elements));

using var hasher = IncrementalHash.CreateHash(HashAlgorithmName.MD5);

foreach (string element in elements)
{
byte[] buffer = Encoding.UTF8.GetBytes(element);
hasher.AppendData(buffer);
hasher.AppendData(Separator);
}

byte[] hash = hasher.GetHashAndReset();
return ByteArrayToHex(hash);
}

private static string ByteArrayToHex(byte[] bytes)
{
// https://stackoverflow.com/questions/311165/how-do-you-convert-a-byte-array-to-a-hexadecimal-string-and-vice-versa

char[] buffer = new char[bytes.Length * 2];

for (int index = 0; index < bytes.Length; index++)
{
uint value = LookupTable[bytes[index]];
buffer[2 * index] = (char)value;
buffer[2 * index + 1] = (char)(value >> 16);
}

return new string(buffer);
}
}
}
17 changes: 17 additions & 0 deletions src/JsonApiDotNetCore/Serialization/IFingerprintGenerator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using System.Collections.Generic;
using JetBrains.Annotations;

namespace JsonApiDotNetCore.Serialization
{
/// <summary>
/// Provides a method to generate a fingerprint for a collection of string values.
/// </summary>
[PublicAPI]
public interface IFingerprintGenerator
{
/// <summary>
/// Generates a fingerprint for the specified elements.
/// </summary>
public string Generate(IEnumerable<string> elements);
}
}
2 changes: 1 addition & 1 deletion src/JsonApiDotNetCore/Serialization/JsonApiReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ public async Task<InputFormatterResult> ReadAsync(InputFormatterContext context)

private async Task<string> GetRequestBodyAsync(Stream bodyStream)
{
using var reader = new StreamReader(bodyStream);
using var reader = new StreamReader(bodyStream, leaveOpen: true);
return await reader.ReadToEndAsync();
}

Expand Down
2 changes: 2 additions & 0 deletions test/TestBuildingBlocks/IntegrationTest.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using JsonApiDotNetCore.Middleware;
using Newtonsoft.Json;
Expand Down Expand Up @@ -60,6 +61,7 @@ public abstract class IntegrationTest
{
requestText = requestText.Replace("atomic__", "atomic:");
request.Content = new StringContent(requestText);
request.Content.Headers.ContentLength = Encoding.UTF8.GetByteCount(requestText);

if (contentType != null)
{
Expand Down