Skip to content

Commit

Permalink
Remove unused ILogger references from middleware and business logic
Browse files Browse the repository at this point in the history
  • Loading branch information
btungut committed Jan 24, 2025
1 parent 6d9b984 commit e8ac711
Show file tree
Hide file tree
Showing 6 changed files with 30 additions and 161 deletions.
1 change: 0 additions & 1 deletion src/AspNetHeaderReplicator.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.3.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.1" />
</ItemGroup>

<ItemGroup>
Expand Down
9 changes: 3 additions & 6 deletions src/HeaderReplicatorMiddleware.cs
Original file line number Diff line number Diff line change
@@ -1,31 +1,28 @@
/// <summary>
/// Represents the middleware that replicates headers from the request to the response.
/// </summary>



using AspNetHeaderReplicator.Internals;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace AspNetHeaderReplicator;

public class HeaderReplicatorMiddleware : IMiddleware
{
private readonly IHeaderReplicatorConfiguration _config;
private readonly ILogger _logger;

public HeaderReplicatorMiddleware(IHeaderReplicatorConfiguration config, ILogger<HeaderReplicatorMiddleware> logger = null)
public HeaderReplicatorMiddleware(IHeaderReplicatorConfiguration config)
{
_config = config ?? throw new ArgumentNullException(nameof(config));
_logger = logger;
}

public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
if (context == null) throw new ArgumentNullException(nameof(context));
if (next == null) throw new ArgumentNullException(nameof(next));

var business = new HeaderReplicationBusiness(_config, _logger);
var business = new HeaderReplicationBusiness(_config);

// Add the replicated headers from request to the response when the response is starting.
context.Response.OnStarting(() =>
Expand Down
27 changes: 4 additions & 23 deletions src/Internals/HeaderReplicationBusiness.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
/// </summary>

using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace AspNetHeaderReplicator.Internals;

Expand All @@ -12,16 +11,12 @@ internal class HeaderReplicationBusiness
public const string RedactedValue = $"REDACTED_By_{nameof(HeaderReplicationBusiness)}";

private readonly IHeaderReplicatorConfiguration _config;
private readonly ILogger _logger;

internal HeaderReplicationBusiness(IHeaderReplicatorConfiguration config, ILogger logger = null)
internal HeaderReplicationBusiness(IHeaderReplicatorConfiguration config)
{
_config = config ?? throw new ArgumentNullException(nameof(config));
if(_config.IgnoredHeaderSentences == null) throw new ArgumentNullException(nameof(config.IgnoredHeaderSentences));
if(_config.AllowedHeaderPrefixes == null) throw new ArgumentNullException(nameof(config.AllowedHeaderPrefixes));

_logger = logger;
_logger?.LogDebug("HeaderReplicationBusiness instance created with config {@config}", config);
if (_config.IgnoredHeaderSentences == null) throw new ArgumentNullException(nameof(config.IgnoredHeaderSentences));
if (_config.AllowedHeaderPrefixes == null) throw new ArgumentNullException(nameof(config.AllowedHeaderPrefixes));
}

internal IHeaderDictionary GetReplicatedHeaders(IHeaderDictionary requestHeaders)
Expand All @@ -38,17 +33,9 @@ internal IHeaderDictionary GetReplicatedHeaders(IHeaderDictionary requestHeaders
if (_config.AllowAll)
{
replicatedHeaders.AddOrReplaceRange(requestHeaders);
_logger?.LogDebug("AllowAll is true. All headers will be replicated {@logCtx}", new
{
sourceHeaders = requestHeaders,
replicatedHeaders = replicatedHeaders,
config = _config
});
return replicatedHeaders;
}

_logger?.LogDebug("AllowAll is false. Only the headers that match the allowed prefixes and also do not contain the ignored sentences will be replicated {@config}", _config);

// Iterate over each header in the request headers.
foreach (var header in requestHeaders)
{
Expand All @@ -70,7 +57,6 @@ internal IHeaderDictionary GetReplicatedHeaders(IHeaderDictionary requestHeaders
{
replicatedHeaders[key] = RedactedValue;
HeaderReplicationCache.Instance.AddIgnoredHeader(key);
_logger?.LogDebug("The header key is cached as ignored {@key}", key);
continue;
}

Expand All @@ -87,11 +73,8 @@ internal IHeaderDictionary GetReplicatedHeaders(IHeaderDictionary requestHeaders
{
replicatedHeaders[key] = value;
HeaderReplicationCache.Instance.AddAllowedHeader(key);
_logger?.LogDebug("The header key is cached as allowed {@key}", key);
continue;
}

_logger?.LogDebug("The header key is skipped {@key}", key);
}

return replicatedHeaders;
Expand All @@ -106,6 +89,4 @@ private string GetHeaderKeyPrefix(string key)

return key.Substring(0, indexOfDash + 1);
}

}

}
122 changes: 8 additions & 114 deletions tests/HeaderReplicationBusinessUnitTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,9 @@ public class HeaderReplicationBusinessUnitTests
public void Ctor_ShouldThrowException_WhenConfigIsNull()
{
// Arrange
var mockLogger = Mocked.GetLogger<HeaderReplicationBusiness>();

// Act
Action act = () => new HeaderReplicationBusiness(null, mockLogger);
Action act = () => new HeaderReplicationBusiness(null);

// Assert
Assert.Throws<ArgumentNullException>(act);
Expand All @@ -26,11 +25,10 @@ public void Ctor_ShouldThrowException_WhenConfigIsNull()
public void Ctor_ShouldThrowException_WhenConfigIgnoredHeaderSentencesIsNull()
{
// Arrange
var mockLogger = Mocked.GetLogger<HeaderReplicationBusiness>();
var mockConfig = Mocked.GetHeaderReplicatorConfiguration(false, Helpers.GetEmptyEnumerable(), null);

// Act
Action act = () => new HeaderReplicationBusiness(mockConfig, mockLogger);
Action act = () => new HeaderReplicationBusiness(mockConfig);

// Assert
Assert.Throws<ArgumentNullException>(act);
Expand All @@ -40,11 +38,10 @@ public void Ctor_ShouldThrowException_WhenConfigIgnoredHeaderSentencesIsNull()
public void Ctor_ShouldThrowException_WhenConfigAllowedHeaderPrefixesIsNull()
{
// Arrange
var mockLogger = Mocked.GetLogger<HeaderReplicationBusiness>();
var mockConfig = Mocked.GetHeaderReplicatorConfiguration(false, null, Helpers.GetEmptyEnumerable());

// Act
Action act = () => new HeaderReplicationBusiness(mockConfig, mockLogger);
Action act = () => new HeaderReplicationBusiness(mockConfig);

// Assert
Assert.Throws<ArgumentNullException>(act);
Expand All @@ -54,9 +51,8 @@ public void Ctor_ShouldThrowException_WhenConfigAllowedHeaderPrefixesIsNull()
public void GetReplicatedHeaders_ShouldThrowException_WhenRequestHeadersIsNull()
{
// Arrange
var mockLogger = Mocked.GetLogger<HeaderReplicationBusiness>();
var mockConfig = Mocked.GetHeaderReplicatorConfiguration(false, Helpers.GetEmptyEnumerable(), Helpers.GetEmptyEnumerable());
var business = new HeaderReplicationBusiness(mockConfig, mockLogger);
var business = new HeaderReplicationBusiness(mockConfig);

// Act
Action act = () => business.GetReplicatedHeaders(null);
Expand All @@ -69,9 +65,8 @@ public void GetReplicatedHeaders_ShouldThrowException_WhenRequestHeadersIsNull()
public void GetReplicatedHeaders_ShouldReturnEmptyDictionary_WhenRequestHeadersIsEmpty()
{
// Arrange
var mockLogger = Mocked.GetLogger<HeaderReplicationBusiness>();
var mockConfig = Mocked.GetHeaderReplicatorConfiguration(false, Helpers.GetEmptyEnumerable(), Helpers.GetEmptyEnumerable());
var business = new HeaderReplicationBusiness(mockConfig, mockLogger);
var business = new HeaderReplicationBusiness(mockConfig);
var requestHeaders = new HeaderDictionary();

// Act
Expand All @@ -85,9 +80,8 @@ public void GetReplicatedHeaders_ShouldReturnEmptyDictionary_WhenRequestHeadersI
public void GetReplicatedHeaders_ShouldReturnAllHeaders_WhenAllowAllIsTrue()
{
// Arrange
var mockLogger = Mocked.GetLogger<HeaderReplicationBusiness>();
var mockConfig = Mocked.GetHeaderReplicatorConfigurationWithDefaults(true);
var business = new HeaderReplicationBusiness(mockConfig, mockLogger);
var business = new HeaderReplicationBusiness(mockConfig);

// Arrange - Request Headers
var __requestHeaders_ignored = new HeaderDictionary
Expand Down Expand Up @@ -116,9 +110,8 @@ public void GetReplicatedHeaders_ShouldReturnAllHeaders_WhenAllowAllIsTrue()
public void GetReplicatedHeaders_ShouldReturnMatchedHeaders_WhenAllowAllIsFalse()
{
// Arrange
var mockLogger = Mocked.GetLogger<HeaderReplicationBusiness>();
var mockConfig = Mocked.GetHeaderReplicatorConfigurationWithDefaults(false);
var business = new HeaderReplicationBusiness(mockConfig, mockLogger);
var business = new HeaderReplicationBusiness(mockConfig);

// Arrange - Request Headers
var __requestHeaders_ignored = new HeaderDictionary
Expand Down Expand Up @@ -152,9 +145,8 @@ public void GetReplicatedHeaders_ShouldReturnMatchedHeaders_WhenAllowAllIsFalse(
public void GetReplicatedHeaders_ShouldReturnMatchedHeaders_WhenAllowAllIsFalseAndIgnoredSentencesAreProvided()
{
// Arrange
var mockLogger = Mocked.GetLogger<HeaderReplicationBusiness>();
var mockConfig = Mocked.GetHeaderReplicatorConfigurationWithDefaults(false);
var business = new HeaderReplicationBusiness(mockConfig, mockLogger);
var business = new HeaderReplicationBusiness(mockConfig);

// Arrange - Request Headers
var __requestHeaders_ignored = new HeaderDictionary
Expand Down Expand Up @@ -183,102 +175,4 @@ public void GetReplicatedHeaders_ShouldReturnMatchedHeaders_WhenAllowAllIsFalseA
Assert.Equal(__requestHeaders_allowed[header.Key], header.Value);
}
}



// Add some combined headers. These header keys will be ignored because they contain IgnoredHeaderSentence even if they start with AllowedHeaderPrefix
// for (int i = 0; i < toBeAddedCombinedHeader; i++)
// __requestHeaders_ignored.Add($"{Helpers.GetAllowedHeaderPrefix(mockConfig)}-{Helpers.GetIgnoredHeaderSentence(mockConfig)}-combined-{i}", GetRandomValue());
// [Fact]
// public void Ctor_Should_ThrowArgumentNullException_WhenIgnoredSentencesIsNull()
// {
// // Arrange
// IEnumerable<string> allowedPrefixes = GetEmptyEnumerable();
// IEnumerable<string> ignoredSentences = null;

// // Act
// Action act = () => new HeaderReplicationBusiness(false, allowedPrefixes, ignoredSentences);

// // Assert
// Assert.Throws<ArgumentNullException>(act);
// }


// [Fact]
// public void Ctor_Should_ReturnEmptyDictionary_WhenRequestHeadersIsEmpty()
// {
// // Arrange
// IEnumerable<string> allowedPrefixes = new List<string> { "X-", "Y-", "Z-" };
// IEnumerable<string> ignoredSentences = GetEmptyEnumerable();

// var business = new HeaderReplicationBusiness(false, allowedPrefixes, ignoredSentences);
// var requestHeaders = new HeaderDictionary();

// // Act
// var result = business.GetReplicatedHeaders(requestHeaders);

// // Assert
// Assert.Empty(result);
// }

// [Fact]
// public void Ctor_Should_ReturnAllowedHeaders_WhenAllowedPrefixesAreProvided()
// {
// // Arrange
// var allowedPrefixes = new List<string> { "X-", "Y-", "Z-" };
// var ignoredSentences = GetEmptyEnumerable();

// var business = new HeaderReplicationBusiness(false, allowedPrefixes, ignoredSentences);
// var requestHeaders = new HeaderDictionary
// {
// { "A-Test-Header", GetRandomValue() },
// { "B-Test-Header", GetRandomValue() },
// { "C-Test-Header", GetRandomValue() }
// };
// foreach (var prefix in allowedPrefixes)
// requestHeaders.Add(prefix + "Test-Header", GetRandomValue());

// // Act
// var responseHeaders = business.GetReplicatedHeaders(requestHeaders);

// // Assert
// Assert.Equal(allowedPrefixes.Count, responseHeaders.Count);
// foreach (var header in responseHeaders)
// {
// Assert.Contains(allowedPrefixes, header.Key.StartsWith);
// }
// }


// [Fact]
// public void Ctor_Should_ReturnMatchedHeaders_WhenAllowedPrefixesAndIgnoredSentencesAreProvided()
// {
// // Arrange
// var allowedPrefixes = new List<string> { "J-", "K-", "L-", "M-" };
// var ignoredSentences = new List<string> { "Test" };

// var business = new HeaderReplicationBusiness(false, allowedPrefixes, ignoredSentences);
// var requestHeaders = new HeaderDictionary
// {
// { $"A-{ignoredSentences.First()}-Header", GetRandomValue() },
// { $"B-{ignoredSentences.First()}-Header", GetRandomValue() },
// { $"C-{ignoredSentences.First()}-Header", GetRandomValue() },
// };
// foreach (var prefix in allowedPrefixes)
// requestHeaders.Add(prefix + "Header", GetRandomValue());

// var _ignoredList = requestHeaders.Where(h => ignoredSentences.Any(h.Key.Contains)).ToList();
// var _allowedList = requestHeaders.Except(_ignoredList).ToList();

// // Act
// var responseHeaders = business.GetReplicatedHeaders(requestHeaders);

// // Assert
// Assert.Equal(_allowedList.Count, responseHeaders.Count);
// foreach (var header in responseHeaders)
// {
// Assert.Contains(allowedPrefixes, header.Key.StartsWith);
// Assert.DoesNotContain(ignoredSentences, header.Key.Contains);
// }
// }
}
1 change: 0 additions & 1 deletion tests/HeaderReplicatorMiddlewareUnitTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
/// Represents the unit tests for the <see cref="HeaderReplicatorMiddleware"/> class only for ctor and InvokeAsync methods.
/// </summary>
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Moq;

namespace AspNetHeaderReplicator.Tests;
Expand Down
31 changes: 15 additions & 16 deletions tests/Mocked.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
/// Represents extension and helper methods for the tests.
/// </summary>
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Primitives;
using Moq;

Expand Down Expand Up @@ -132,21 +131,21 @@ public static string TrimDash(this string value)

internal static class Mocked
{
public static ILogger<T> GetLogger<T>()
{
// Can not create proxy for type Microsoft.Extensions.Logging.ILogger
var mockLogger = new Mock<ILogger<T>>();
mockLogger
.Setup(l => l.Log(
It.IsAny<LogLevel>(),
It.IsAny<EventId>(),
It.IsAny<object>(),
It.IsAny<Exception>(),
It.IsAny<Func<object, Exception, string>>()
));

return mockLogger.Object;
}
// public static ILogger<T> GetLogger<T>()
// {
// // Can not create proxy for type Microsoft.Extensions.Logging.ILogger
// var mockLogger = new Mock<ILogger<T>>();
// mockLogger
// .Setup(l => l.Log(
// It.IsAny<LogLevel>(),
// It.IsAny<EventId>(),
// It.IsAny<object>(),
// It.IsAny<Exception>(),
// It.IsAny<Func<object, Exception, string>>()
// ));

// return mockLogger.Object;
// }


public static IHeaderReplicatorConfiguration GetHeaderReplicatorConfigurationWithDefaults(bool allowAll)
Expand Down

0 comments on commit e8ac711

Please sign in to comment.