diff --git a/src/Arcus.WebApi.Hosting.AzureFunctions/Arcus.WebApi.Hosting.AzureFunctions.csproj b/src/Arcus.WebApi.Hosting.AzureFunctions/Arcus.WebApi.Hosting.AzureFunctions.csproj index b6e4bc4e..fac533cd 100644 --- a/src/Arcus.WebApi.Hosting.AzureFunctions/Arcus.WebApi.Hosting.AzureFunctions.csproj +++ b/src/Arcus.WebApi.Hosting.AzureFunctions/Arcus.WebApi.Hosting.AzureFunctions.csproj @@ -26,7 +26,6 @@ - diff --git a/src/Arcus.WebApi.Hosting.AzureFunctions/Formatting/AzureFunctionsJsonFormattingMiddleware.cs b/src/Arcus.WebApi.Hosting.AzureFunctions/Formatting/AzureFunctionsJsonFormattingMiddleware.cs index 4610d8cd..7d481c2d 100644 --- a/src/Arcus.WebApi.Hosting.AzureFunctions/Formatting/AzureFunctionsJsonFormattingMiddleware.cs +++ b/src/Arcus.WebApi.Hosting.AzureFunctions/Formatting/AzureFunctionsJsonFormattingMiddleware.cs @@ -44,6 +44,7 @@ public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next private static async Task DetermineHttpRequestAsync(FunctionContext context) { HttpRequestData request = await context.GetHttpRequestDataAsync(); + if (request is null) { throw new InvalidOperationException( diff --git a/src/Arcus.WebApi.Hosting.AzureFunctions/Formatting/Extensions/IFunctionsWorkerApplicationBuilderExtensions.cs b/src/Arcus.WebApi.Hosting.AzureFunctions/Formatting/Extensions/IFunctionsWorkerApplicationBuilderExtensions.cs index d45a7387..02915ee9 100644 --- a/src/Arcus.WebApi.Hosting.AzureFunctions/Formatting/Extensions/IFunctionsWorkerApplicationBuilderExtensions.cs +++ b/src/Arcus.WebApi.Hosting.AzureFunctions/Formatting/Extensions/IFunctionsWorkerApplicationBuilderExtensions.cs @@ -1,6 +1,5 @@ using System; using Arcus.WebApi.Hosting.AzureFunctions.Formatting; -using GuardNet; using Microsoft.Azure.Functions.Worker; // ReSharper disable once CheckNamespace @@ -20,7 +19,10 @@ public static class IFunctionsWorkerApplicationBuilderExtensions public static IFunctionsWorkerApplicationBuilder UseOnlyJsonFormatting( this IFunctionsWorkerApplicationBuilder builder) { - Guard.NotNull(builder, nameof(builder), "Requires a function worker builder instance to add the JSON formatting middleware"); + if (builder is null) + { + throw new ArgumentNullException(nameof(builder), "Requires a function worker builder instance to add the JSON formatting middleware"); + } builder.UseMiddleware(); return builder; diff --git a/src/Arcus.WebApi.Hosting.AzureFunctions/Formatting/Extensions/IServiceCollectionExtensions.cs b/src/Arcus.WebApi.Hosting.AzureFunctions/Formatting/Extensions/IServiceCollectionExtensions.cs index e982a74d..71dc1cf8 100644 --- a/src/Arcus.WebApi.Hosting.AzureFunctions/Formatting/Extensions/IServiceCollectionExtensions.cs +++ b/src/Arcus.WebApi.Hosting.AzureFunctions/Formatting/Extensions/IServiceCollectionExtensions.cs @@ -1,7 +1,6 @@ using System; using System.Text.Json; using Azure.Core.Serialization; -using GuardNet; using Microsoft.Azure.Functions.Worker; using Microsoft.Extensions.DependencyInjection; @@ -24,8 +23,15 @@ public static IServiceCollection ConfigureJsonFormatting( this IFunctionsWorkerApplicationBuilder builder, Action configureOptions) { - Guard.NotNull(builder, nameof(builder), "Requires an Azure Functions application builder instance to add the JSON serializer to the application services"); - Guard.NotNull(configureOptions, nameof(configureOptions), "Requires a function to configure the JSON serialization options to add the JSON serializer to the application services"); + if (builder is null) + { + throw new ArgumentNullException(nameof(builder), "Requires an Azure Functions application builder instance to add the JSON serializer to the application services"); + } + + if (configureOptions is null) + { + throw new ArgumentNullException(nameof(configureOptions), "Requires a function to configure the JSON serialization options to add the JSON serializer to the application services"); + } var options = new JsonSerializerOptions(); configureOptions(options); diff --git a/src/Arcus.WebApi.Hosting/Arcus.WebApi.Hosting.csproj b/src/Arcus.WebApi.Hosting/Arcus.WebApi.Hosting.csproj index 7c0576a7..bd0eebf2 100644 --- a/src/Arcus.WebApi.Hosting/Arcus.WebApi.Hosting.csproj +++ b/src/Arcus.WebApi.Hosting/Arcus.WebApi.Hosting.csproj @@ -28,8 +28,4 @@ - - - - diff --git a/src/Arcus.WebApi.Hosting/Formatting/Extensions/MvcOptionsExtensions.cs b/src/Arcus.WebApi.Hosting/Formatting/Extensions/MvcOptionsExtensions.cs index bf41937e..ed08c869 100644 --- a/src/Arcus.WebApi.Hosting/Formatting/Extensions/MvcOptionsExtensions.cs +++ b/src/Arcus.WebApi.Hosting/Formatting/Extensions/MvcOptionsExtensions.cs @@ -1,7 +1,6 @@ using System; using System.Linq; using System.Text.Json; -using GuardNet; using Microsoft.AspNetCore.Mvc.Formatters; using Microsoft.Extensions.DependencyInjection; @@ -20,7 +19,10 @@ public static class MvcOptionsExtensions /// Thrown when the is null. public static MvcOptions OnlyAllowJsonFormatting(this MvcOptions options) { - Guard.NotNull(options, nameof(options), "Requires MVC options to restrict the formatting to only JSON formatting"); + if (options is null) + { + throw new ArgumentNullException(nameof(options), "Requires MVC options to restrict the formatting to only JSON formatting"); + } IInputFormatter[] allButJsonInputFormatters = options.InputFormatters.Where(formatter => !(formatter is SystemTextJsonInputFormatter)) @@ -46,8 +48,15 @@ public static MvcOptions OnlyAllowJsonFormatting(this MvcOptions options) [Obsolete("Use the " + nameof(MvcCoreMvcBuilderExtensions) + "." + nameof(MvcCoreMvcBuilderExtensions.AddJsonOptions) + " instead to configure the JSON formatters")] public static MvcOptions ConfigureJsonFormatting(this MvcOptions options, Action configureOptions) { - Guard.NotNull(options, nameof(options), "Requires MVC options to configure the JSON formatters"); - Guard.NotNull(configureOptions, nameof(configureOptions), "Requires a function to configure the JSON formatters in the MVC options"); + if (options is null) + { + throw new ArgumentNullException(nameof(options), "Requires MVC options to configure the JSON formatters"); + } + + if (configureOptions is null) + { + throw new ArgumentNullException(nameof(configureOptions), "Requires a function to configure the JSON formatters in the MVC options"); + } SystemTextJsonInputFormatter[] onlyJsonInputFormatters = options.InputFormatters.OfType() diff --git a/src/Arcus.WebApi.Logging.AzureFunctions/AzureFunctionsRequestTrackingMiddleware.cs b/src/Arcus.WebApi.Logging.AzureFunctions/AzureFunctionsRequestTrackingMiddleware.cs index b10be58d..ebed2409 100644 --- a/src/Arcus.WebApi.Logging.AzureFunctions/AzureFunctionsRequestTrackingMiddleware.cs +++ b/src/Arcus.WebApi.Logging.AzureFunctions/AzureFunctionsRequestTrackingMiddleware.cs @@ -37,6 +37,7 @@ public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next ILogger logger = context.GetLogger(); HttpRequestData request = await context.GetHttpRequestDataAsync(); + if (request is null || IsRequestPathOmitted(PathString.FromUriComponent(request.Url), logger)) { await next(context); @@ -60,12 +61,12 @@ public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next HttpResponseData response = context.GetHttpResponseData(); var attributeTrackedStatusCodes = Enumerable.Empty(); - if (response != null && AllowedToTrackStatusCode((int) response.StatusCode, attributeTrackedStatusCodes, logger)) + if (response != null && AllowedToTrackStatusCode((int)response.StatusCode, attributeTrackedStatusCodes, logger)) { string responseBody = await GetPotentialResponseBodyAsync(response, logger); - LogRequest(requestBody, responseBody, request, response, measurement, logger); + LogRequest(requestBody, responseBody, request, response, measurement, logger); } - } + } } } } @@ -150,7 +151,7 @@ private void LogRequest(string requestBody, string responseBody, HttpRequestData request.Url.Host, request.Url.AbsolutePath, operationName: null, - (int) response.StatusCode, + (int)response.StatusCode, duration.StartTime, duration.Elapsed, logContext)); diff --git a/src/Arcus.WebApi.Logging.AzureFunctions/Correlation/AzureFunctionsCorrelationMiddleware.cs b/src/Arcus.WebApi.Logging.AzureFunctions/Correlation/AzureFunctionsCorrelationMiddleware.cs index 207d272c..272965cd 100644 --- a/src/Arcus.WebApi.Logging.AzureFunctions/Correlation/AzureFunctionsCorrelationMiddleware.cs +++ b/src/Arcus.WebApi.Logging.AzureFunctions/Correlation/AzureFunctionsCorrelationMiddleware.cs @@ -2,7 +2,6 @@ using System.Net; using System.Threading.Tasks; using Arcus.WebApi.Logging.Core.Correlation; -using GuardNet; using Microsoft.Azure.Functions.Worker; using Microsoft.Azure.Functions.Worker.Http; using Microsoft.Azure.Functions.Worker.Middleware; @@ -25,8 +24,15 @@ public class AzureFunctionsCorrelationMiddleware : IFunctionsWorkerMiddleware /// Thrown when the or is nul. public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next) { - Guard.NotNull(context, nameof(context), "Requires a function context instance of the current Azure Function invocation to HTTP correlate the HTTP request"); - Guard.NotNull(next, nameof(next), "Requires a 'next' function to chain this HTTP correlation middleware to the next action in the HTTP request pipeline"); + if (context is null) + { + throw new ArgumentNullException(nameof(context), "Requires a function context instance of the current Azure Function invocation to HTTP correlate the HTTP request"); + } + + if (next is null) + { + throw new ArgumentNullException(nameof(next), "Requires a 'next' function to chain this HTTP correlation middleware to the next action in the HTTP request pipeline"); + } var service = context.InstanceServices.GetRequiredService(); HttpRequestData request = await DetermineHttpRequestAsync(context); diff --git a/src/Arcus.WebApi.Logging.AzureFunctions/Correlation/AzureFunctionsHttpCorrelation.cs b/src/Arcus.WebApi.Logging.AzureFunctions/Correlation/AzureFunctionsHttpCorrelation.cs index 7d02cfc4..f2af1692 100644 --- a/src/Arcus.WebApi.Logging.AzureFunctions/Correlation/AzureFunctionsHttpCorrelation.cs +++ b/src/Arcus.WebApi.Logging.AzureFunctions/Correlation/AzureFunctionsHttpCorrelation.cs @@ -4,7 +4,6 @@ using System.Linq; using Arcus.Observability.Correlation; using Arcus.WebApi.Logging.Core.Correlation; -using GuardNet; using Microsoft.ApplicationInsights; using Microsoft.AspNetCore.Http; using Microsoft.Azure.Functions.Worker.Http; @@ -63,7 +62,10 @@ public AzureFunctionsHttpCorrelation( /// Thrown when the is null. protected override IHeaderDictionary GetRequestHeaders(HttpRequestData request) { - Guard.NotNull(request, nameof(request), "Requires a HTTP request instance to retrieve the HTTP request headers"); + if (request is null) + { + throw new ArgumentNullException(nameof(request), "Requires a HTTP request instance to retrieve the HTTP request headers"); + } Dictionary dictionary = request.Headers.ToDictionary( @@ -128,9 +130,20 @@ protected override HttpCorrelationResult CorrelateW3CForExistingParent(IHeaderDi /// Thrown when the or is blank. protected override void SetHttpResponseHeader(HttpResponseData response, string headerName, string headerValue) { - Guard.NotNull(response, nameof(response), "Requires a HTTP response to set the HTTP correlation headers"); - Guard.NotNullOrWhitespace(headerName, nameof(headerName), "Requires a non-blank HTTP correlation header name to set the HTTP correlation header in the HTTP request"); - Guard.NotNullOrWhitespace(headerValue, nameof(headerValue), "Requires a non-blank HTTP correlation header value to set the HTTP correlation header in the HTTP request"); + if (response is null) + { + throw new ArgumentNullException(nameof(response), "Requires a HTTP response to set the HTTP correlation headers"); + } + + if (string.IsNullOrWhiteSpace(headerName)) + { + throw new ArgumentException("Requires a non-blank HTTP correlation header name to set the HTTP correlation header in the HTTP request", nameof(headerName)); + } + + if (string.IsNullOrWhiteSpace(headerValue)) + { + throw new ArgumentException("Requires a non-blank HTTP correlation header value to set the HTTP correlation header in the HTTP request", nameof(headerValue)); + } response.Headers.Add(headerName, headerValue); } diff --git a/src/Arcus.WebApi.Logging.AzureFunctions/Correlation/AzureFunctionsHttpCorrelationInfoAccessor.cs b/src/Arcus.WebApi.Logging.AzureFunctions/Correlation/AzureFunctionsHttpCorrelationInfoAccessor.cs index e8958943..3c15e266 100644 --- a/src/Arcus.WebApi.Logging.AzureFunctions/Correlation/AzureFunctionsHttpCorrelationInfoAccessor.cs +++ b/src/Arcus.WebApi.Logging.AzureFunctions/Correlation/AzureFunctionsHttpCorrelationInfoAccessor.cs @@ -1,7 +1,6 @@ using System; using Arcus.Observability.Correlation; using Arcus.WebApi.Logging.Core.Correlation; -using GuardNet; using Microsoft.Azure.Functions.Worker; namespace Arcus.WebApi.Logging.AzureFunctions.Correlation @@ -20,8 +19,7 @@ public class AzureFunctionsHttpCorrelationInfoAccessor : IHttpCorrelationInfoAcc /// Thrown when the is null. public AzureFunctionsHttpCorrelationInfoAccessor(IFunctionContextAccessor contextAccessor) { - Guard.NotNull(contextAccessor, nameof(contextAccessor), "Requires a function context accessor instance to get/set the correlation information in the function context"); - _contextAccessor = contextAccessor; + _contextAccessor = contextAccessor ?? throw new ArgumentNullException(nameof(contextAccessor), "Requires a function context accessor instance to get/set the correlation information in the function context"); } /// diff --git a/src/Arcus.WebApi.Logging.AzureFunctions/Correlation/AzureFunctionsInProcessHttpCorrelation.cs b/src/Arcus.WebApi.Logging.AzureFunctions/Correlation/AzureFunctionsInProcessHttpCorrelation.cs index 7959ae8c..a3b0d0ac 100644 --- a/src/Arcus.WebApi.Logging.AzureFunctions/Correlation/AzureFunctionsInProcessHttpCorrelation.cs +++ b/src/Arcus.WebApi.Logging.AzureFunctions/Correlation/AzureFunctionsInProcessHttpCorrelation.cs @@ -2,7 +2,6 @@ using System.Threading.Tasks; using Arcus.Observability.Correlation; using Arcus.WebApi.Logging.Core.Correlation; -using GuardNet; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Primitives; @@ -33,9 +32,20 @@ public AzureFunctionsInProcessHttpCorrelation( IHttpCorrelationInfoAccessor correlationInfoAccessor, ILogger logger) { - Guard.NotNull(options, nameof(options), "Requires a set of HTTP correlation options to determine where the correlation information should be added to the HTTP response headers"); - Guard.NotNull(correlationInfoAccessor, nameof(correlationInfoAccessor), "Requires a HTTP correlation accessor to retrieve the current correlation information"); - Guard.NotNull(logger, nameof(logger), "Requires a logging instance to write diagnostic trace messages while adding the correlation information to the HTTP response headers"); + if (options is null) + { + throw new ArgumentNullException(nameof(options), "Requires a set of HTTP correlation options to determine where the correlation information should be added to the HTTP response headers"); + } + + if (correlationInfoAccessor is null) + { + throw new ArgumentNullException(nameof(correlationInfoAccessor), "Requires a HTTP correlation accessor to retrieve the current correlation information"); + } + + if (logger is null) + { + throw new ArgumentNullException(nameof(logger), "Requires a logging instance to write diagnostic trace messages while adding the correlation information to the HTTP response headers"); + } _options = options; _correlationInfoAccessor = correlationInfoAccessor; @@ -57,8 +67,15 @@ public CorrelationInfo GetCorrelationInfo() /// Thrown when the is null or does not have a response present. public void AddCorrelationResponseHeaders(HttpContext httpContext) { - Guard.NotNull(httpContext, nameof(httpContext), "Requires a HTTP context to add the correlation information to the response headers"); - Guard.NotNull(httpContext.Response, nameof(httpContext), "Requires a HTTP response in the HTTP context to add the correlation information to the response headers"); + if (httpContext is null) + { + throw new ArgumentNullException(nameof(httpContext), "Requires a HTTP context to add the correlation information to the response headers"); + } + + if (httpContext.Response is null) + { + throw new ArgumentNullException(nameof(httpContext), "Requires a HTTP response in the HTTP context to add the correlation information to the response headers"); + } if (_options.Operation.IncludeInResponse) { diff --git a/src/Arcus.WebApi.Logging.AzureFunctions/Extensions/IFunctionsWorkerApplicationBuilderExtensions.cs b/src/Arcus.WebApi.Logging.AzureFunctions/Extensions/IFunctionsWorkerApplicationBuilderExtensions.cs index ad7ae63e..eb2b02ce 100644 --- a/src/Arcus.WebApi.Logging.AzureFunctions/Extensions/IFunctionsWorkerApplicationBuilderExtensions.cs +++ b/src/Arcus.WebApi.Logging.AzureFunctions/Extensions/IFunctionsWorkerApplicationBuilderExtensions.cs @@ -4,7 +4,6 @@ using Arcus.WebApi.Logging.AzureFunctions; using Arcus.WebApi.Logging.AzureFunctions.Correlation; using Arcus.WebApi.Logging.Core.Correlation; -using GuardNet; using Microsoft.ApplicationInsights; using Microsoft.Azure.Functions.Worker; using Microsoft.Extensions.DependencyInjection; @@ -27,7 +26,10 @@ public static class IFunctionsWorkerApplicationBuilderExtensions public static IFunctionsWorkerApplicationBuilder UseFunctionContext( this IFunctionsWorkerApplicationBuilder builder) { - Guard.NotNull(builder, nameof(builder), "Requires a function worker builder instance to add the function context middleware"); + if (builder is null) + { + throw new ArgumentNullException(nameof(builder), "Requires a function worker builder instance to add the function context middleware"); + } builder.Services.AddSingleton(); builder.UseMiddleware(); @@ -42,11 +44,7 @@ public static IFunctionsWorkerApplicationBuilder UseFunctionContext( /// Thrown when the is null. public static IFunctionsWorkerApplicationBuilder UseHttpCorrelation( this IFunctionsWorkerApplicationBuilder builder) - { - Guard.NotNull(builder, nameof(builder), "Requires a function worker builder instance to add the HTTP correlation middleware"); - - return UseHttpCorrelation(builder, options => { }); - } + => UseHttpCorrelation(builder, options => { }); /// /// Adds a middleware component that exposes the in a scoped service . @@ -58,7 +56,10 @@ public static IFunctionsWorkerApplicationBuilder UseHttpCorrelation( this IFunctionsWorkerApplicationBuilder builder, Action configureOptions) { - Guard.NotNull(builder, nameof(builder), "Requires a function worker builder instance to add the HTTP correlation middleware"); + if (builder is null) + { + throw new ArgumentNullException(nameof(builder), "Requires a function worker builder instance to add the HTTP correlation middleware"); + } builder.Services.AddApplicationInsightsTelemetryWorkerService(); builder.Services.ConfigureFunctionsApplicationInsights(); @@ -98,8 +99,12 @@ public static IFunctionsWorkerApplicationBuilder UseHttpCorrelation( /// Thrown when the is null. public static IFunctionsWorkerApplicationBuilder UseExceptionHandling(this IFunctionsWorkerApplicationBuilder builder) { - Guard.NotNull(builder, nameof(builder), "Requires a function worker builder instance to add the HTTP exception handling middleware"); - return builder.UseMiddleware(); + if (builder is null) + { + throw new ArgumentNullException(nameof(builder), "Requires a function worker builder instance to add the HTTP exception handling middleware"); + } + + return builder.UseMiddleware(); } /// @@ -111,7 +116,11 @@ public static IFunctionsWorkerApplicationBuilder UseExceptionHandling(this IFunc public static IFunctionsWorkerApplicationBuilder UseExceptionHandling(this IFunctionsWorkerApplicationBuilder builder) where TMiddleware : AzureFunctionsExceptionHandlingMiddleware { - Guard.NotNull(builder, nameof(builder), "Requires a function worker builder instance to add the HTTP exception handling middleware"); + if (builder is null) + { + throw new ArgumentNullException(nameof(builder), "Requires a function worker builder instance to add the HTTP exception handling middleware"); + } + return builder.UseMiddleware(); } @@ -123,7 +132,11 @@ public static IFunctionsWorkerApplicationBuilder UseExceptionHandling configureOptions) { - Guard.NotNull(builder, nameof(builder), "Requires a function worker builder instance to add the HTTP request tracking middleware"); + if (builder is null) + { + throw new ArgumentNullException(nameof(builder), "Requires a function worker builder instance to add the HTTP request tracking middleware"); + } return UseRequestTracking(builder, configureOptions); } @@ -152,7 +168,10 @@ public static IFunctionsWorkerApplicationBuilder UseRequestTracking this IFunctionsWorkerApplicationBuilder builder) where TMiddleware : AzureFunctionsRequestTrackingMiddleware { - Guard.NotNull(builder, nameof(builder), "Requires a function worker builder instance to add the HTTP request tracking middleware"); + if (builder is null) + { + throw new ArgumentNullException(nameof(builder), "Requires a function worker builder instance to add the HTTP request tracking middleware"); + } return UseRequestTracking(builder, configureOptions: null); } @@ -169,7 +188,10 @@ public static IFunctionsWorkerApplicationBuilder UseRequestTracking Action configureOptions) where TMiddleware : AzureFunctionsRequestTrackingMiddleware { - Guard.NotNull(builder, nameof(builder), "Requires a function worker builder instance to add the HTTP request tracking middleware"); + if (builder is null) + { + throw new ArgumentNullException(nameof(builder), "Requires a function worker builder instance to add the HTTP request tracking middleware"); + } var options = new RequestTrackingOptions(); configureOptions?.Invoke(options); diff --git a/src/Arcus.WebApi.Logging.AzureFunctions/Extensions/IServiceCollectionExtensions.cs b/src/Arcus.WebApi.Logging.AzureFunctions/Extensions/IServiceCollectionExtensions.cs index d3a19aef..eca0ce13 100644 --- a/src/Arcus.WebApi.Logging.AzureFunctions/Extensions/IServiceCollectionExtensions.cs +++ b/src/Arcus.WebApi.Logging.AzureFunctions/Extensions/IServiceCollectionExtensions.cs @@ -3,7 +3,6 @@ using Arcus.WebApi.Logging.AzureFunctions.Correlation; using Arcus.WebApi.Logging.Core.Correlation; using Arcus.WebApi.Logging.Correlation; -using GuardNet; using Microsoft.AspNetCore.Http; using Microsoft.Azure.Functions.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; @@ -24,11 +23,7 @@ public static class IServiceCollectionExtensions /// The functions host builder containing the dependency injection services. /// Thrown when the is null. public static IServiceCollection AddHttpCorrelation(this IFunctionsHostBuilder builder) - { - Guard.NotNull(builder, nameof(builder), "Requires a function host builder instance to add the HTTP correlation services"); - - return AddHttpCorrelation(builder, options => { }); - } + => AddHttpCorrelation(builder, options => { }); /// /// Adds operation and transaction correlation to the application. @@ -38,7 +33,10 @@ public static IServiceCollection AddHttpCorrelation(this IFunctionsHostBuilder b /// Thrown when the is null. public static IServiceCollection AddHttpCorrelation(this IFunctionsHostBuilder builder, Action configureOptions) { - Guard.NotNull(builder, nameof(builder), "Requires a function host builder instance to add the HTTP correlation services"); + if (builder is null) + { + throw new ArgumentNullException(nameof(builder), "Requires a function host builder instance to add the HTTP correlation services"); + } IServiceCollection services = builder.Services; diff --git a/src/Arcus.WebApi.Logging.AzureFunctions/FunctionContextMiddleware.cs b/src/Arcus.WebApi.Logging.AzureFunctions/FunctionContextMiddleware.cs index 5e6f2d95..5db35a18 100644 --- a/src/Arcus.WebApi.Logging.AzureFunctions/FunctionContextMiddleware.cs +++ b/src/Arcus.WebApi.Logging.AzureFunctions/FunctionContextMiddleware.cs @@ -1,6 +1,5 @@ using System; using System.Threading.Tasks; -using GuardNet; using Microsoft.Azure.Functions.Worker; using Microsoft.Azure.Functions.Worker.Middleware; @@ -19,9 +18,8 @@ public class FunctionContextMiddleware : IFunctionsWorkerMiddleware /// The instance to manage the in this request. /// Thrown when the is null. public FunctionContextMiddleware(IFunctionContextAccessor contextAccessor) - { - Guard.NotNull(contextAccessor, nameof(contextAccessor), "Requires a function context accessor to assign the current function context instance"); - _contextAccessor = contextAccessor; + { + _contextAccessor = contextAccessor ?? throw new ArgumentNullException(nameof(contextAccessor), "Requires a function context accessor to assign the current function context instance"); } /// @@ -32,8 +30,15 @@ public FunctionContextMiddleware(IFunctionContextAccessor contextAccessor) /// A that represents the asynchronous invocation. public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next) { - Guard.NotNull(context, nameof(context), "Requires a function context instance to assign the context to the function context accessor"); - Guard.NotNull(next, nameof(next), "Requires a 'next' function to chain this middleware to the next action in the HTTP request pipeline"); + if (context is null) + { + throw new ArgumentNullException(nameof(context), "Requires a function context instance to assign the context to the function context accessor"); + } + + if (next is null) + { + throw new ArgumentNullException(nameof(next), "Requires a 'next' function to chain this middleware to the next action in the HTTP request pipeline"); + } _contextAccessor.FunctionContext = context; await next(context); diff --git a/src/Arcus.WebApi.Logging.Core/Arcus.WebApi.Logging.Core.csproj b/src/Arcus.WebApi.Logging.Core/Arcus.WebApi.Logging.Core.csproj index c3cf166c..fe8921eb 100644 --- a/src/Arcus.WebApi.Logging.Core/Arcus.WebApi.Logging.Core.csproj +++ b/src/Arcus.WebApi.Logging.Core/Arcus.WebApi.Logging.Core.csproj @@ -38,7 +38,6 @@ - diff --git a/src/Arcus.WebApi.Logging.Core/Correlation/CorrelationInfoUpstreamServiceOptions.cs b/src/Arcus.WebApi.Logging.Core/Correlation/CorrelationInfoUpstreamServiceOptions.cs index 90f4ba3b..804b4ff8 100644 --- a/src/Arcus.WebApi.Logging.Core/Correlation/CorrelationInfoUpstreamServiceOptions.cs +++ b/src/Arcus.WebApi.Logging.Core/Correlation/CorrelationInfoUpstreamServiceOptions.cs @@ -1,7 +1,4 @@ using System; -using Arcus.Observability.Correlation; -using GuardNet; -using Microsoft.Net.Http.Headers; namespace Arcus.WebApi.Logging.Core.Correlation { @@ -41,7 +38,11 @@ public string HeaderName get => _headerName; set { - Guard.NotNullOrWhitespace(value, nameof(value), "Requires a non-blank value for the operation parent ID request header name"); + if (string.IsNullOrWhiteSpace(value)) + { + throw new ArgumentException("Requires a non-blank value for the operation parent ID request header name", nameof(value)); + } + _headerName = value; } } @@ -58,7 +59,11 @@ public Func GenerateId get => _generateId; set { - Guard.NotNull(value, nameof (value), "Requires a function to generate the operation parent ID"); + if (value is null) + { + throw new ArgumentNullException(nameof(value), "Requires a function to generate the operation parent ID"); + } + _generateId = value; } } diff --git a/src/Arcus.WebApi.Logging.Core/Correlation/HttpCorrelation.cs b/src/Arcus.WebApi.Logging.Core/Correlation/HttpCorrelation.cs index 28276ff1..0ba67e67 100644 --- a/src/Arcus.WebApi.Logging.Core/Correlation/HttpCorrelation.cs +++ b/src/Arcus.WebApi.Logging.Core/Correlation/HttpCorrelation.cs @@ -2,7 +2,6 @@ using System.Threading.Tasks; using Arcus.Observability.Correlation; using Arcus.WebApi.Logging.Core.Correlation; -using GuardNet; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; @@ -39,14 +38,16 @@ public HttpCorrelation( ILogger logger) : base(options?.Value, correlationInfoAccessor, logger) { - Guard.NotNull(httpContextAccessor, nameof(httpContextAccessor), "Requires a HTTP context accessor to get the current HTTP context"); - Guard.NotNull(correlationInfoAccessor, nameof(correlationInfoAccessor), "Requires a correlation info instance to set and retrieve the correlation information"); - Guard.NotNull(options, nameof(options), "Requires a value in the set of options to configure the correlation process"); - Guard.NotNull(options.Value, nameof(options), "Requires a value in the set of options to configure the correlation process"); - - _httpContextAccessor = httpContextAccessor; - _options = options.Value; - _correlationInfoAccessor = correlationInfoAccessor; + if (options is null) + { + throw new ArgumentNullException(nameof(options), "Requires a value in the set of options to configure the correlation process"); + } + + _httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor), "Requires a HTTP context accessor to get the current HTTP context"); + _correlationInfoAccessor = correlationInfoAccessor ?? throw new ArgumentNullException(nameof(correlationInfoAccessor), "Requires a correlation info instance to set and retrieve the correlation information"); + _options = options.Value ?? throw new ArgumentNullException(nameof(options.Value), "Requires a value in the set of options to configure the correlation process"); + + _logger = logger ?? NullLogger.Instance; } @@ -65,7 +66,11 @@ public CorrelationInfo GetCorrelationInfo() /// Thrown when the is null. public void SetCorrelationInfo(CorrelationInfo correlationInfo) { - Guard.NotNull(correlationInfo, nameof(correlationInfo)); + if (_correlationInfoAccessor is null) + { + throw new ArgumentNullException(nameof(correlationInfo), "Requires a correlation info instance to set and retrieve the correlation information"); + } + _correlationInfoAccessor.SetCorrelationInfo(correlationInfo); } @@ -77,11 +82,17 @@ public void SetCorrelationInfo(CorrelationInfo correlationInfo) /// Thrown when the given doesn't have any response headers to set the correlation headers. public HttpCorrelationResult CorrelateHttpRequest() { - HttpContext httpContext = _httpContextAccessor.HttpContext; + HttpContext httpContext = _httpContextAccessor.HttpContext ?? throw new ArgumentNullException(nameof(HttpContext), "Requires a HTTP context from the HTTP context accessor to start correlating the HTTP request"); + + if (httpContext.Response is null) + { + throw new ArgumentException("Requires a 'Response'", nameof(httpContext.Response)); + } - Guard.NotNull(httpContext, nameof(httpContext), "Requires a HTTP context from the HTTP context accessor to start correlating the HTTP request"); - Guard.For(() => httpContext.Response is null, "Requires a 'Response'"); - Guard.For(() => httpContext.Response.Headers is null, "Requires a 'Response' object with headers"); + if (httpContext.Response.Headers is null) + { + throw new ArgumentException("Requires a 'Response' object with headers", nameof(httpContext.Response.Headers)); + } HttpCorrelationResult result = TrySettingCorrelationFromRequest(httpContext.Request, httpContext.TraceIdentifier); if (result.IsSuccess) diff --git a/src/Arcus.WebApi.Logging.Core/Correlation/HttpCorrelationClientOptions.cs b/src/Arcus.WebApi.Logging.Core/Correlation/HttpCorrelationClientOptions.cs index e2bf5ab3..68a26353 100644 --- a/src/Arcus.WebApi.Logging.Core/Correlation/HttpCorrelationClientOptions.cs +++ b/src/Arcus.WebApi.Logging.Core/Correlation/HttpCorrelationClientOptions.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Net.Http; -using GuardNet; using Microsoft.Extensions.Logging; namespace Arcus.WebApi.Logging.Core.Correlation @@ -25,7 +24,11 @@ public Func GenerateDependencyId get => _generateDependencyId; set { - Guard.NotNull(value, nameof(value), "Requires a function to generate the dependency ID used when tracking HTTP dependencies"); + if (value is null) + { + throw new ArgumentNullException(nameof(value), "Requires a function to generate the dependency ID used when tracking HTTP dependencies"); + } + _generateDependencyId = value; } } @@ -39,7 +42,11 @@ public string UpstreamServiceHeaderName get => _upstreamServiceHeaderName; set { - Guard.NotNullOrWhitespace(value, nameof(value), "Requires a non-blank value for the HTTP request header where the dependency ID should be added when tracking HTTP dependencies"); + if (string.IsNullOrWhiteSpace(value)) + { + throw new ArgumentException("Requires a non-blank value for the HTTP request header where the dependency ID should be added when tracking HTTP dependencies", nameof(value)); + } + _upstreamServiceHeaderName = value; } } @@ -53,7 +60,11 @@ public string TransactionIdHeaderName get => _transactionIdHeaderName; set { - Guard.NotNullOrWhitespace(value, nameof(value), "Requires a non-blank value for the HTTP request header where the transaction ID should be added when tracking HTTP dependencies"); + if (string.IsNullOrWhiteSpace(value)) + { + throw new ArgumentException("Requires a non-blank value for the HTTP request header where the transaction ID should be added when tracking HTTP dependencies", nameof(value)); + } + _transactionIdHeaderName = value; } } @@ -70,7 +81,11 @@ public string TransactionIdHeaderName /// Thrown when the is null. public void AddTelemetryContext(Dictionary telemetryContext) { - Guard.NotNull(telemetryContext, nameof(telemetryContext), "Requires a telemetry context dictionary to add to the HTTP dependency tracking"); + if (telemetryContext is null) + { + throw new ArgumentNullException(nameof(telemetryContext), "Requires a telemetry context dictionary to add to the HTTP dependency tracking"); + } + foreach (KeyValuePair item in telemetryContext) { TelemetryContext[item.Key] = item.Value; diff --git a/src/Arcus.WebApi.Logging.Core/Correlation/HttpCorrelationInfoAccessor.cs b/src/Arcus.WebApi.Logging.Core/Correlation/HttpCorrelationInfoAccessor.cs index c0567d67..f68acb79 100644 --- a/src/Arcus.WebApi.Logging.Core/Correlation/HttpCorrelationInfoAccessor.cs +++ b/src/Arcus.WebApi.Logging.Core/Correlation/HttpCorrelationInfoAccessor.cs @@ -1,7 +1,6 @@ using System; using Arcus.Observability.Correlation; using Arcus.WebApi.Logging.Core.Correlation; -using GuardNet; using Microsoft.AspNetCore.Http; // ReSharper disable once CheckNamespace @@ -21,7 +20,10 @@ public class HttpCorrelationInfoAccessor : IHttpCorrelationInfoAccessor, ICorrel /// Thrown when the is null. public HttpCorrelationInfoAccessor(IHttpContextAccessor contextAccessor) { - Guard.NotNull(contextAccessor, nameof(contextAccessor)); + if (contextAccessor is null) + { + throw new ArgumentNullException(nameof(contextAccessor)); + } _httpContextAccessor = contextAccessor; } @@ -42,7 +44,11 @@ public CorrelationInfo GetCorrelationInfo() /// Thrown when the is null. public void SetCorrelationInfo(CorrelationInfo correlationInfo) { - Guard.NotNull(correlationInfo, nameof(correlationInfo)); + if (correlationInfo is null) + { + throw new ArgumentNullException(nameof(correlationInfo)); + } + _httpContextAccessor.HttpContext?.Features?.Set(correlationInfo); } } diff --git a/src/Arcus.WebApi.Logging.Core/Correlation/HttpCorrelationInfoOperationOptions.cs b/src/Arcus.WebApi.Logging.Core/Correlation/HttpCorrelationInfoOperationOptions.cs index 4edcf393..efba65fe 100644 --- a/src/Arcus.WebApi.Logging.Core/Correlation/HttpCorrelationInfoOperationOptions.cs +++ b/src/Arcus.WebApi.Logging.Core/Correlation/HttpCorrelationInfoOperationOptions.cs @@ -1,5 +1,4 @@ using System; -using GuardNet; namespace Arcus.WebApi.Logging.Core.Correlation { @@ -27,7 +26,11 @@ public string HeaderName get => _headerName; set { - Guard.NotNullOrWhitespace(value, nameof (value), "Correlation operation header cannot be blank"); + if (string.IsNullOrWhiteSpace(value)) + { + throw new ArgumentException("Correlation operation header cannot be blank", nameof(value)); + } + _headerName = value; } } @@ -43,7 +46,11 @@ public Func GenerateId get => _generateId; set { - Guard.NotNull(value, nameof (value), "Correlation function to generate an operation ID cannot be 'null'"); + if (value is null) + { + throw new ArgumentNullException(nameof(value), "Correlation function to generate an operation ID cannot be 'null'"); + } + _generateId = value; } } diff --git a/src/Arcus.WebApi.Logging.Core/Correlation/HttpCorrelationInfoTransactionOptions.cs b/src/Arcus.WebApi.Logging.Core/Correlation/HttpCorrelationInfoTransactionOptions.cs index f81f669f..6b56078a 100644 --- a/src/Arcus.WebApi.Logging.Core/Correlation/HttpCorrelationInfoTransactionOptions.cs +++ b/src/Arcus.WebApi.Logging.Core/Correlation/HttpCorrelationInfoTransactionOptions.cs @@ -1,5 +1,4 @@ using System; -using GuardNet; namespace Arcus.WebApi.Logging.Core.Correlation { @@ -43,7 +42,11 @@ public string HeaderName get => _headerName; set { - Guard.NotNullOrWhitespace(value, nameof(value), "Correlation transaction header cannot be blank"); + if (string.IsNullOrWhiteSpace(value)) + { + throw new ArgumentException("Header name cannot be blank", nameof(value)); + } + _headerName = value; } } @@ -62,7 +65,11 @@ public Func GenerateId get => this._generateId; set { - Guard.NotNull(value, nameof(value), "Correlation function to generate an transaction ID cannot be 'null'"); + if (value is null) + { + throw new ArgumentNullException(nameof(value), "Correlation function to generate an transaction ID cannot be 'null'"); + } + _generateId = value; } } diff --git a/src/Arcus.WebApi.Logging.Core/Correlation/HttpCorrelationMessageHandler.cs b/src/Arcus.WebApi.Logging.Core/Correlation/HttpCorrelationMessageHandler.cs index 1f1912b0..13bb04f6 100644 --- a/src/Arcus.WebApi.Logging.Core/Correlation/HttpCorrelationMessageHandler.cs +++ b/src/Arcus.WebApi.Logging.Core/Correlation/HttpCorrelationMessageHandler.cs @@ -5,8 +5,6 @@ using System.Threading.Tasks; using Arcus.Observability.Correlation; using Arcus.Observability.Telemetry.Core; -using GuardNet; -using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; namespace Arcus.WebApi.Logging.Core.Correlation @@ -34,13 +32,9 @@ public HttpCorrelationMessageHandler( HttpCorrelationClientOptions options, ILogger logger) { - Guard.NotNull(correlationInfoAccessor, nameof(correlationInfoAccessor), "Requires a HTTP context accessor to retrieve the current HTTP correlation"); - Guard.NotNull(options, nameof(options), "Requires a set of additional user-configurable options to influence the HTTP dependency tracking"); - Guard.NotNull(logger, nameof(logger), "Requires a logger instance to write the HTTP dependency telemetry"); - - _correlationInfoAccessor = correlationInfoAccessor; - _options = options; - _logger = logger; + _correlationInfoAccessor = correlationInfoAccessor ?? throw new ArgumentNullException(nameof(correlationInfoAccessor), "Requires a HTTP context accessor to retrieve the current HTTP correlation"); + _options = options ?? throw new ArgumentNullException(nameof(options), "Requires a set of additional user-configurable options to influence the HTTP dependency tracking"); + _logger = logger ?? throw new ArgumentNullException(nameof(logger), "Requires a logger instance to write the HTTP dependency telemetry"); } /// diff --git a/src/Arcus.WebApi.Logging.Core/Correlation/HttpCorrelationResult.cs b/src/Arcus.WebApi.Logging.Core/Correlation/HttpCorrelationResult.cs index be4659cf..73fcab57 100644 --- a/src/Arcus.WebApi.Logging.Core/Correlation/HttpCorrelationResult.cs +++ b/src/Arcus.WebApi.Logging.Core/Correlation/HttpCorrelationResult.cs @@ -1,7 +1,6 @@ using System; using System.Diagnostics; using Arcus.Observability.Correlation; -using GuardNet; using Microsoft.ApplicationInsights; using Microsoft.ApplicationInsights.DataContracts; using Microsoft.ApplicationInsights.Extensibility; @@ -19,8 +18,15 @@ public class HttpCorrelationResult : IDisposable private HttpCorrelationResult(bool isSuccess, string requestId, string errorMessage) { - Guard.For(() => isSuccess && errorMessage != null, new ArgumentException("Cannot create a successful HTTP correlation result with an error user message", nameof(errorMessage))); - Guard.For(() => !isSuccess && requestId != null, new ArgumentException("Cannot create a failed HTTP correlation result with a request ID", nameof(requestId))); + if (isSuccess && errorMessage != null) + { + throw new ArgumentException("Cannot create a successful HTTP correlation result with an error user message", nameof(errorMessage)); + } + + if (!isSuccess && requestId != null) + { + throw new ArgumentException("Cannot create a failed HTTP correlation result with a request ID", nameof(requestId)); + } RequestId = requestId; ErrorMessage = errorMessage; @@ -82,7 +88,11 @@ public static HttpCorrelationResult Success(string requestId) /// Thrown when the is blank. public static HttpCorrelationResult Failure(string errorMessage) { - Guard.NotNullOrWhitespace(errorMessage, nameof(errorMessage), "Requires an error user message that describes why the HTTP correlation process failed on the current HTTP request"); + if (string.IsNullOrWhiteSpace(errorMessage)) + { + throw new ArgumentException("Requires an error user message that describes why the HTTP correlation process failed on the current HTTP request", nameof(errorMessage)); + } + return new HttpCorrelationResult(isSuccess: false, requestId: null, errorMessage); } @@ -95,8 +105,15 @@ public static HttpCorrelationResult Failure(string errorMessage) /// Thrown when the is blank. public static HttpCorrelationResult Success(TelemetryClient client, string transactionId) { - Guard.NotNull(client, nameof(client), "Requires a telemetry client instance to automatically track built-in Microsoft dependencies"); - Guard.NotNullOrWhitespace(transactionId, nameof(transactionId), "Requires a non-blank transaction ID for the pending HTTP correlation"); + if (client is null) + { + throw new ArgumentNullException(nameof(client), "Requires a telemetry client instance to automatically track built-in Microsoft dependencies"); + } + + if (string.IsNullOrWhiteSpace(transactionId)) + { + throw new ArgumentException("Requires a non-blank transaction ID for the pending HTTP correlation", nameof(transactionId)); + } return Success(client, transactionId, operationParentId: null, traceParent: null); } @@ -114,8 +131,15 @@ public static HttpCorrelationResult Success(TelemetryClient client, string trans /// public static HttpCorrelationResult Success(TelemetryClient client, string transactionId, string operationParentId, string traceParent) { - Guard.NotNull(client, nameof(client), "Requires a telemetry client instance to automatically track built-in Microsoft dependencies"); - Guard.NotNullOrWhitespace(transactionId, nameof(transactionId), "Requires a non-blank transaction ID for the pending HTTP correlation"); + if (client is null) + { + throw new ArgumentNullException(nameof(client), "Requires a telemetry client instance to automatically track built-in Microsoft dependencies"); + } + + if (string.IsNullOrWhiteSpace(transactionId)) + { + throw new ArgumentException("Requires a non-blank transaction ID for the pending HTTP correlation", nameof(transactionId)); + } var telemetry = new RequestTelemetry(); telemetry.Context.Operation.Id = transactionId; diff --git a/src/Arcus.WebApi.Logging.Core/Correlation/HttpCorrelationTemplate.cs b/src/Arcus.WebApi.Logging.Core/Correlation/HttpCorrelationTemplate.cs index bfd91112..9be97cd2 100644 --- a/src/Arcus.WebApi.Logging.Core/Correlation/HttpCorrelationTemplate.cs +++ b/src/Arcus.WebApi.Logging.Core/Correlation/HttpCorrelationTemplate.cs @@ -5,7 +5,6 @@ using Microsoft.Extensions.Primitives; using System.Text.RegularExpressions; using Arcus.Observability.Correlation; -using GuardNet; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using System.Collections.Generic; @@ -38,11 +37,8 @@ protected HttpCorrelationTemplate( IHttpCorrelationInfoAccessor correlationInfoAccessor, ILogger logger) { - Guard.NotNull(options, nameof(options), "Requires a set of options to configure the correlation process"); - Guard.NotNull(correlationInfoAccessor, nameof(correlationInfoAccessor), "Requires a correlation info instance to set and retrieve the correlation information"); - - _options = options; - _correlationInfoAccessor = correlationInfoAccessor; + _options = options ?? throw new ArgumentNullException(nameof(options), "Requires a set of options to configure the correlation process"); + _correlationInfoAccessor = correlationInfoAccessor ?? throw new ArgumentNullException(nameof(correlationInfoAccessor), "Requires a correlation info instance to set and retrieve the correlation information"); Logger = logger ?? NullLogger.Instance; } @@ -68,7 +64,10 @@ protected HttpCorrelationTemplate( /// Thrown when the is null. public HttpCorrelationResult TrySettingCorrelationFromRequest(THttpRequest request, string traceIdentifier) { - Guard.NotNull(request, nameof(request), "Requires a HTTP request to determine the HTTP correlation of the application"); + if (request is null) + { + throw new ArgumentNullException(nameof(request), "Requires a HTTP request to determine the HTTP correlation of the application"); + } IHeaderDictionary requestHeaders = GetRequestHeaders(request); if (requestHeaders is null) @@ -366,7 +365,7 @@ private string ExtractLatestOperationParentIdFromHeader(string requestId) // returns: def Logger.LogTrace("Extracting operation parent ID from request ID '{RequestId}' from the upstream service according to W3C Trace-Context standard", requestId); - if (requestId.Contains(".")) + if (requestId.Contains('.')) { string[] ids = requestId.Split('.'); string operationParentId = ids.LastOrDefault(id => !string.IsNullOrWhiteSpace(id)); @@ -405,8 +404,15 @@ private bool MatchesRequestIdFormat(string requestId, string headerName) /// Thrown when the or is null. public void SetCorrelationHeadersInResponse(THttpResponse response, HttpCorrelationResult result) { - Guard.NotNull(response, nameof(response), "Requires a HTTP response to set the HTTP correlation headers"); - Guard.NotNull(result, nameof(result), "Requires a HTTP correlation result to determine to set the HTTP correlation headers in the HTTP request"); + if (response is null) + { + throw new ArgumentNullException(nameof(response), "Requires a HTTP response to set the HTTP correlation headers"); + } + + if (result is null) + { + throw new ArgumentNullException(nameof(result), "Requires a HTTP correlation result to determine to set the HTTP correlation headers in the HTTP request"); + } string requestId = result.RequestId; CorrelationInfo correlationInfo = _correlationInfoAccessor.GetCorrelationInfo(); diff --git a/src/Arcus.WebApi.Logging.Core/Extensions/HttpClientExtensions.cs b/src/Arcus.WebApi.Logging.Core/Extensions/HttpClientExtensions.cs index 5ec264e0..7f0081a7 100644 --- a/src/Arcus.WebApi.Logging.Core/Extensions/HttpClientExtensions.cs +++ b/src/Arcus.WebApi.Logging.Core/Extensions/HttpClientExtensions.cs @@ -2,7 +2,6 @@ using Arcus.Observability.Correlation; using Arcus.Observability.Telemetry.Core; using Arcus.WebApi.Logging.Core.Correlation; -using GuardNet; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; @@ -36,14 +35,7 @@ public static async Task SendAsync( HttpRequestMessage request, IHttpCorrelationInfoAccessor correlationAccessor, ILogger logger) - { - Guard.NotNull(client, nameof(client), "Requires a HTTP client to track the HTTP request with HTTP correlation"); - Guard.NotNull(request, nameof(request), "Requires a HTTP request to enrich with HTTP correlation"); - Guard.NotNull(correlationAccessor, nameof(correlationAccessor), "Requires a HTTP correlation accessor instance to retrieve the current correlation to include in the HTTP request"); - Guard.NotNull(logger, nameof(logger), "Requires a logger instance to track the correlated HTTP request"); - - return await SendAsync(client, request, correlationAccessor, logger, configureOptions: null); - } + => await SendAsync(client, request, correlationAccessor, logger, configureOptions: null); /// /// Sends an HTTP request as an asynchronous operation while tracking the HTTP correlation. @@ -70,10 +62,10 @@ public static async Task SendAsync( ILogger logger, Action configureOptions) { - Guard.NotNull(client, nameof(client), "Requires a HTTP client to track the HTTP request with HTTP correlation"); - Guard.NotNull(request, nameof(request), "Requires a HTTP request to enrich with HTTP correlation"); - Guard.NotNull(correlationAccessor, nameof(correlationAccessor), "Requires a HTTP correlation accessor instance to retrieve the current correlation to include in the HTTP request"); - Guard.NotNull(logger, nameof(logger), "Requires a logger instance to track the correlated HTTP request"); + if (correlationAccessor is null) + { + throw new ArgumentNullException(nameof(correlationAccessor), "Requires a HTTP correlation accessor instance to retrieve the current correlation to include in the HTTP request"); + } CorrelationInfo correlation = correlationAccessor.GetCorrelationInfo(); return await SendAsync(client, request, correlation, logger, configureOptions); @@ -101,14 +93,7 @@ public static async Task SendAsync( HttpRequestMessage request, CorrelationInfo correlationInfo, ILogger logger) - { - Guard.NotNull(client, nameof(client), "Requires a HTTP client to track the HTTP request with HTTP correlation"); - Guard.NotNull(request, nameof(request), "Requires a HTTP request to enrich with HTTP correlation"); - Guard.NotNull(correlationInfo, nameof(correlationInfo), "Requires a HTTP correlation instance to include in the HTTP request"); - Guard.NotNull(logger, nameof(logger), "Requires a logger instance to track the correlated HTTP request"); - - return await SendAsync(client, request, correlationInfo, logger, configureOptions: null); - } + => await SendAsync(client, request, correlationInfo, logger, configureOptions: null); /// /// Sends an HTTP request as an asynchronous operation while tracking the HTTP correlation. @@ -135,10 +120,25 @@ public static async Task SendAsync( ILogger logger, Action configureOptions) { - Guard.NotNull(client, nameof(client), "Requires a HTTP client to track the HTTP request with HTTP correlation"); - Guard.NotNull(request, nameof(request), "Requires a HTTP request to enrich with HTTP correlation"); - Guard.NotNull(correlationInfo, nameof(correlationInfo), "Requires a HTTP correlation instance to include in the HTTP request"); - Guard.NotNull(logger, nameof(logger), "Requires a logger instance to track the correlated HTTP request"); + if (client is null) + { + throw new ArgumentNullException(nameof(client), "Requires a HTTP client to track the HTTP request with HTTP correlation"); + } + + if (request is null) + { + throw new ArgumentNullException(nameof(request), "Requires a HTTP request to enrich with HTTP correlation"); + } + + if (correlationInfo is null) + { + throw new ArgumentNullException(nameof(correlationInfo), "Requires a HTTP correlation instance to include in the HTTP request"); + } + + if (logger is null) + { + throw new ArgumentNullException(nameof(logger), "Requires a logger instance to track the correlated HTTP request"); + } var options = new HttpCorrelationClientOptions(); configureOptions?.Invoke(options); diff --git a/src/Arcus.WebApi.Logging.Core/Extensions/HttpCorrelationEnricherExtensions.cs b/src/Arcus.WebApi.Logging.Core/Extensions/HttpCorrelationEnricherExtensions.cs index 72c4f6e3..93a389f0 100644 --- a/src/Arcus.WebApi.Logging.Core/Extensions/HttpCorrelationEnricherExtensions.cs +++ b/src/Arcus.WebApi.Logging.Core/Extensions/HttpCorrelationEnricherExtensions.cs @@ -3,7 +3,6 @@ using Arcus.Observability.Telemetry.Serilog.Enrichers; using Arcus.WebApi.Logging.Core.Correlation; using Arcus.WebApi.Logging.Correlation; -using GuardNet; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; @@ -27,8 +26,15 @@ public static class HttpCorrelationEnricherExtensions /// Thrown when the or is null. public static LoggerConfiguration WithHttpCorrelationInfo(this LoggerEnrichmentConfiguration enrichmentConfiguration, IServiceProvider serviceProvider) { - Guard.NotNull(enrichmentConfiguration, nameof(enrichmentConfiguration), "Requires a Serilog logger enrichment configuration to register the HTTP correlation as enrichment"); - Guard.NotNull(serviceProvider, nameof(serviceProvider), "Requires a service provider to retrieve the HTTP correlation from the registered services when enriching the Serilog with the HTTP correlation"); + if (enrichmentConfiguration is null) + { + throw new ArgumentNullException(nameof(enrichmentConfiguration), "Requires a Serilog logger enrichment configuration to register the HTTP correlation as enrichment"); + } + + if (serviceProvider is null) + { + throw new ArgumentNullException(nameof(serviceProvider), "Requires a service provider to retrieve the HTTP correlation from the registered services when enriching the Serilog with the HTTP correlation"); + } var correlationInfoAccessor = serviceProvider.GetService(); if (correlationInfoAccessor is null) diff --git a/src/Arcus.WebApi.Logging.Core/Extensions/IDictionaryExtensions.cs b/src/Arcus.WebApi.Logging.Core/Extensions/IDictionaryExtensions.cs index bf5c67ae..137fd248 100644 --- a/src/Arcus.WebApi.Logging.Core/Extensions/IDictionaryExtensions.cs +++ b/src/Arcus.WebApi.Logging.Core/Extensions/IDictionaryExtensions.cs @@ -1,5 +1,4 @@ using System.Linq; -using GuardNet; // ReSharper disable once CheckNamespace namespace System.Collections.Generic @@ -22,8 +21,15 @@ public static class IDictionaryExtensions /// public static IDictionary Where(this IDictionary dictionary, Func, bool> predicate) { - Guard.NotNull(dictionary, nameof(dictionary)); - Guard.NotNull(predicate, nameof(predicate)); + if (dictionary is null) + { + throw new ArgumentNullException(nameof(dictionary)); + } + + if (predicate is null) + { + throw new ArgumentNullException(nameof(predicate)); + } return Enumerable.Where(dictionary, predicate) .ToDictionary(item => item.Key, item => item.Value); diff --git a/src/Arcus.WebApi.Logging.Core/Extensions/IHeaderDictionaryExtensions.cs b/src/Arcus.WebApi.Logging.Core/Extensions/IHeaderDictionaryExtensions.cs index 5879c488..f436abed 100644 --- a/src/Arcus.WebApi.Logging.Core/Extensions/IHeaderDictionaryExtensions.cs +++ b/src/Arcus.WebApi.Logging.Core/Extensions/IHeaderDictionaryExtensions.cs @@ -1,5 +1,4 @@ using System; -using GuardNet; using Microsoft.Extensions.Primitives; // ReSharper disable once CheckNamespace @@ -18,7 +17,10 @@ public static class IHeaderDictionaryExtensions /// Thrown when the is null. public static StringValues GetTraceParent(this IHeaderDictionary headers) { - Guard.NotNull(headers, nameof(headers), "Requires a HTTP request headers dictionary instance to retrieve the 'traceparent' header value"); + if (headers is null) + { + throw new ArgumentNullException(nameof(headers), "Requires a HTTP request headers dictionary instance to retrieve the 'traceparent' header value"); + } #if NET6_0 StringValues traceParent = headers.TraceParent; #else @@ -40,7 +42,10 @@ public static StringValues GetTraceParent(this IHeaderDictionary headers) /// Thrown when the is null. internal static StringValues GetTraceState(this IHeaderDictionary headers) { - Guard.NotNull(headers, nameof(headers), "Requires a HTTP request headers dictionary instance to retrieve the 'tracestate' header value"); + if (headers is null) + { + throw new ArgumentNullException(nameof(headers), "Requires a HTTP request headers dictionary instance to retrieve the 'tracestate' header value"); + } #if NET6_0 return headers.TraceState; #else diff --git a/src/Arcus.WebApi.Logging.Core/Extensions/IHttpClientBuilderExtensions.cs b/src/Arcus.WebApi.Logging.Core/Extensions/IHttpClientBuilderExtensions.cs index 5e2f27af..90ead07a 100644 --- a/src/Arcus.WebApi.Logging.Core/Extensions/IHttpClientBuilderExtensions.cs +++ b/src/Arcus.WebApi.Logging.Core/Extensions/IHttpClientBuilderExtensions.cs @@ -1,6 +1,5 @@ using System; using Arcus.WebApi.Logging.Core.Correlation; -using GuardNet; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; @@ -24,7 +23,11 @@ public static class IHttpClientBuilderExtensions /// Thrown when the no was found in the dependency injection container. public static IHttpClientBuilder WithHttpCorrelationTracking(this IHttpClientBuilder builder) { - Guard.NotNull(builder, nameof(builder), "Requires a HTTP client builder instance to add the HTTP correlation message handler"); + if (builder is null) + { + throw new ArgumentNullException(nameof(builder), "Requires a HTTP client builder instance to add the HTTP correlation message handler"); + } + return WithHttpCorrelationTracking(builder, configureOptions: null); } @@ -40,7 +43,10 @@ public static IHttpClientBuilder WithHttpCorrelationTracking(this IHttpClientBui /// Thrown when the no was found in the dependency injection container. public static IHttpClientBuilder WithHttpCorrelationTracking(this IHttpClientBuilder builder, Action configureOptions) { - Guard.NotNull(builder, nameof(builder), "Requires a HTTP client builder instance to add the HTTP correlation message handler"); + if (builder is null) + { + throw new ArgumentNullException(nameof(builder), "Requires a HTTP client builder instance to add the HTTP correlation message handler"); + } return builder.AddHttpMessageHandler(serviceProvider => { diff --git a/src/Arcus.WebApi.Logging.Core/RequestTracking/RequestTrackingOptions.cs b/src/Arcus.WebApi.Logging.Core/RequestTracking/RequestTrackingOptions.cs index 50bf967c..9325c864 100644 --- a/src/Arcus.WebApi.Logging.Core/RequestTracking/RequestTrackingOptions.cs +++ b/src/Arcus.WebApi.Logging.Core/RequestTracking/RequestTrackingOptions.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Net; -using GuardNet; namespace Arcus.WebApi.Logging { @@ -33,7 +32,11 @@ public int? RequestBodyBufferSize get => _requestBodyBufferSize; set { - Guard.For(() => value < 0, "Requires a request body buffer size greater than zero"); + if (value < 0) + { + throw new ArgumentOutOfRangeException(nameof(value), "Requires a request body buffer size greater than zero"); + } + _requestBodyBufferSize = value; } } @@ -52,7 +55,11 @@ public int? ResponseBodyBufferSize get => _responseBodyBufferSize; set { - Guard.For(() => value < 0, "Requires a response body buffer size greater than zero"); + if (value < 0) + { + throw new ArgumentOutOfRangeException(nameof(value), "Requires a response body buffer size greater than zero"); + } + _responseBodyBufferSize = value; } } diff --git a/src/Arcus.WebApi.Logging.Core/RequestTracking/RequestTrackingTemplate.cs b/src/Arcus.WebApi.Logging.Core/RequestTracking/RequestTrackingTemplate.cs index a4783dfe..ab5518b4 100644 --- a/src/Arcus.WebApi.Logging.Core/RequestTracking/RequestTrackingTemplate.cs +++ b/src/Arcus.WebApi.Logging.Core/RequestTracking/RequestTrackingTemplate.cs @@ -5,7 +5,6 @@ using System.Linq; using System.Net; using System.Threading.Tasks; -using GuardNet; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; @@ -25,8 +24,7 @@ public class RequestTrackingTemplate /// Thrown when the is null. protected RequestTrackingTemplate(RequestTrackingOptions options) { - Guard.NotNull(options, nameof(options), "Requires a set of additional user-configurable options to influence the behavior of the HTTP request tracking"); - Options = options; + Options = options ?? throw new ArgumentNullException(nameof(options), "Requires a set of additional user-configurable options to influence the behavior of the HTTP request tracking"); } /// @@ -46,7 +44,7 @@ protected bool IsRequestPathOmitted(PathString requestPath, ILogger logger) IEnumerable allOmittedRoutes = Options.OmittedRoutes ?? new Collection(); string[] matchedOmittedRoutes = allOmittedRoutes - .Select(omittedRoute => omittedRoute?.StartsWith("/") == true ? omittedRoute : "/" + omittedRoute) + .Select(omittedRoute => omittedRoute?.StartsWith('/') == true ? omittedRoute : "/" + omittedRoute) .Where(omittedRoute => requestPath.StartsWithSegments(omittedRoute, StringComparison.OrdinalIgnoreCase)) .ToArray(); @@ -120,12 +118,12 @@ protected Dictionary CreateTelemetryContext(string requestBody, IDictionary headers = GetSanitizedRequestHeaders(requestHeaders, logger); Dictionary telemetryContext = headers.ToDictionary(header => header.Key, header => string.Join(",", header.Value)); - if (string.IsNullOrWhiteSpace(requestBody) == false) + if (!string.IsNullOrWhiteSpace(requestBody)) { telemetryContext.Add("RequestBody", requestBody); } - if (string.IsNullOrWhiteSpace(responseBody) == false) + if (!string.IsNullOrWhiteSpace(responseBody)) { telemetryContext.Add("ResponseBody", responseBody); } @@ -182,7 +180,11 @@ protected virtual IDictionary SanitizeRequestHeaders(IDict /// Thrown when the is null. protected async Task GetBodyAsync(Stream body, int? maxLength, string targetName, ILogger logger) { - Guard.NotNull(body, nameof(body), $"Requires a streamed body to read the string representation of the {targetName}"); + if (body is null) + { + throw new ArgumentNullException(nameof(body), $"Requires a streamed body to read the string representation of the {targetName}"); + } + logger = logger ?? NullLogger.Instance; logger.LogTrace("Prepare for {Target} body to be tracked...", targetName); diff --git a/src/Arcus.WebApi.Logging.Core/RequestTracking/StatusCodeRange.cs b/src/Arcus.WebApi.Logging.Core/RequestTracking/StatusCodeRange.cs index 0c28fcfb..eb688caa 100644 --- a/src/Arcus.WebApi.Logging.Core/RequestTracking/StatusCodeRange.cs +++ b/src/Arcus.WebApi.Logging.Core/RequestTracking/StatusCodeRange.cs @@ -1,5 +1,4 @@ using System; -using GuardNet; namespace Arcus.WebApi.Logging { @@ -30,9 +29,20 @@ public StatusCodeRange(int minimum) : this(minimum, minimum) /// public StatusCodeRange(int minimum, int maximum) { - Guard.NotLessThan(minimum, 100, nameof(minimum), "Requires the minimum HTTP status code threshold not be less than 100"); - Guard.NotGreaterThan(maximum, 599, nameof(maximum), "Requires the maximum HTTP status code threshold not be greater than 599"); - Guard.NotGreaterThan(minimum, maximum, nameof(minimum), "Requires the minimum HTTP status code threshold to be less than the maximum HTTP status code threshold"); + if (minimum < 100) + { + throw new ArgumentOutOfRangeException(nameof(minimum), "Requires the minimum HTTP status code threshold to not be less than 100"); + } + + if (maximum > 599) + { + throw new ArgumentOutOfRangeException(nameof(maximum), "Requires the maximum HTTP status code threshold to not be greater than 599"); + } + + if (minimum > maximum) + { + throw new ArgumentOutOfRangeException(nameof(minimum), "Requires the minimum HTTP status code threshold to be less than the maximum HTTP status code threshold"); + } Minimum = minimum; Maximum = maximum; @@ -58,8 +68,15 @@ public StatusCodeRange(int minimum, int maximum) /// Thrown when the is less than 100 or greater than 599. public bool IsWithinRange(int statusCode) { - Guard.NotLessThan(statusCode, 100, nameof(statusCode), "Requires the response HTTP status code not be less than 100"); - Guard.NotGreaterThan(statusCode, 599, nameof(statusCode), "Requires the response HTTP status code not be greater than 599"); + if (statusCode < 100) + { + throw new ArgumentOutOfRangeException(nameof(statusCode), "Requires the response HTTP status code to not be less than 100"); + } + + if (statusCode > 599) + { + throw new ArgumentOutOfRangeException(nameof(statusCode), "Requires the response HTTP status code to not be greater than 599"); + } return Minimum <= statusCode && statusCode <= Maximum; } diff --git a/src/Arcus.WebApi.Logging/Arcus.WebApi.Logging.csproj b/src/Arcus.WebApi.Logging/Arcus.WebApi.Logging.csproj index 1fc6c463..06cce636 100644 --- a/src/Arcus.WebApi.Logging/Arcus.WebApi.Logging.csproj +++ b/src/Arcus.WebApi.Logging/Arcus.WebApi.Logging.csproj @@ -37,7 +37,6 @@ - diff --git a/src/Arcus.WebApi.Logging/Correlation/CorrelationMiddleware.cs b/src/Arcus.WebApi.Logging/Correlation/CorrelationMiddleware.cs index 124c182d..645f30e2 100644 --- a/src/Arcus.WebApi.Logging/Correlation/CorrelationMiddleware.cs +++ b/src/Arcus.WebApi.Logging/Correlation/CorrelationMiddleware.cs @@ -1,7 +1,6 @@ using System; using System.Threading.Tasks; using Arcus.WebApi.Logging.Core.Correlation; -using GuardNet; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; @@ -25,11 +24,8 @@ public CorrelationMiddleware( RequestDelegate next, ILogger logger) { - Guard.NotNull(next, nameof(next), "Requires a continuation delegate"); - Guard.NotNull(logger, nameof(logger), "Requires a logger instance"); - - _next = next; - _logger = logger; + _next = next ?? throw new ArgumentNullException(nameof(next), "Requires a continuation delegate"); + _logger = logger ?? throw new ArgumentNullException(nameof(logger), "Requires a logger instance"); } /// @@ -44,10 +40,25 @@ public CorrelationMiddleware( /// Thrown when the response headers are null. public async Task Invoke(HttpContext httpContext, HttpCorrelation service) { - Guard.NotNull(httpContext, nameof(httpContext)); - Guard.NotNull(service, nameof(service), "Requires the HTTP correlation service"); - Guard.For(() => httpContext.Response is null, "Requires a 'Response'"); - Guard.For(() => httpContext.Response.Headers is null, "Requires a 'Response' object with headers"); + if (httpContext is null) + { + throw new ArgumentNullException(nameof(httpContext), "Requires a HTTP context"); + } + + if (service is null) + { + throw new ArgumentNullException(nameof(service), "Requires the HTTP correlation service"); + } + + if (httpContext.Response is null) + { + throw new ArgumentException("Requires a 'Response'", nameof(httpContext)); + } + + if (httpContext.Response.Headers is null) + { + throw new ArgumentException("Requires a 'Response' object with headers", nameof(httpContext)); + } using (HttpCorrelationResult result = service.CorrelateHttpRequest()) { diff --git a/src/Arcus.WebApi.Logging/ExceptionHandlingMiddleware.cs b/src/Arcus.WebApi.Logging/ExceptionHandlingMiddleware.cs index bba462ba..5ef28f96 100644 --- a/src/Arcus.WebApi.Logging/ExceptionHandlingMiddleware.cs +++ b/src/Arcus.WebApi.Logging/ExceptionHandlingMiddleware.cs @@ -3,7 +3,6 @@ using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; -using GuardNet; using Microsoft.Extensions.Logging.Abstractions; // ReSharper disable once CheckNamespace @@ -45,11 +44,8 @@ public ExceptionHandlingMiddleware(RequestDelegate next, string categoryName) /// When the is null. public ExceptionHandlingMiddleware(RequestDelegate next, Func getLoggingCategory) { - Guard.NotNull(next, nameof(next), "The next request delegate in the application request pipeline cannot be null"); - Guard.NotNull(getLoggingCategory, nameof(getLoggingCategory), "The retrieval of the logging category function cannot be null"); - - _next = next; - _getLoggingCategory = getLoggingCategory; + _next = next ?? throw new ArgumentNullException(nameof(next), "The next request delegate in the application request pipeline cannot be null"); + _getLoggingCategory = getLoggingCategory ?? throw new ArgumentNullException(nameof(getLoggingCategory), "The retrieval of the logging category function cannot be null"); } /// diff --git a/src/Arcus.WebApi.Logging/Extensions/IApplicationBuilderExtensions.cs b/src/Arcus.WebApi.Logging/Extensions/IApplicationBuilderExtensions.cs index 5d81ba0a..92896acc 100644 --- a/src/Arcus.WebApi.Logging/Extensions/IApplicationBuilderExtensions.cs +++ b/src/Arcus.WebApi.Logging/Extensions/IApplicationBuilderExtensions.cs @@ -1,7 +1,6 @@ using System; using Arcus.WebApi.Logging; using Arcus.WebApi.Logging.Correlation; -using GuardNet; // ReSharper disable once CheckNamespace namespace Microsoft.AspNetCore.Builder @@ -19,7 +18,10 @@ public static class IApplicationBuilderExtensions /// Thrown when the is null. public static IApplicationBuilder UseExceptionHandling(this IApplicationBuilder app) { - Guard.NotNull(app, nameof(app), "Requires an application builder instance to add the exception middleware component"); + if (app is null) + { + throw new ArgumentNullException(nameof(app), "Requires an application builder instance to add the exception middleware component"); + } return app.UseMiddleware(); } @@ -33,7 +35,10 @@ public static IApplicationBuilder UseExceptionHandling(this IApplicationBuilder public static IApplicationBuilder UseExceptionHandling(this IApplicationBuilder app) where TMiddleware : ExceptionHandlingMiddleware { - Guard.NotNull(app, nameof(app), "Requires an application builder instance to add the exception middleware component"); + if (app is null) + { + throw new ArgumentNullException(nameof(app), "Requires an application builder instance to add the exception middleware component"); + } return app.UseMiddleware(); } @@ -47,7 +52,10 @@ public static IApplicationBuilder UseRequestTracking( this IApplicationBuilder app, Action configureOptions = null) { - Guard.NotNull(app, nameof(app)); + if (app is null) + { + throw new ArgumentNullException(nameof(app), "Requires an application builder instance to add the request tracking middleware component"); + } return UseRequestTracking(app, configureOptions); } @@ -62,7 +70,10 @@ public static IApplicationBuilder UseRequestTracking( Action configureOptions = null) where TMiddleware : RequestTrackingMiddleware { - Guard.NotNull(app, nameof(app)); + if (app is null) + { + throw new ArgumentNullException(nameof(app), "Requires an application builder instance to add the request tracking middleware component"); + } var options = new RequestTrackingOptions(); configureOptions?.Invoke(options); @@ -76,7 +87,10 @@ public static IApplicationBuilder UseRequestTracking( /// The builder to configure the application's request pipeline. public static IApplicationBuilder UseHttpCorrelation(this IApplicationBuilder app) { - Guard.NotNull(app, nameof(app)); + if (app is null) + { + throw new ArgumentNullException(nameof(app), "Requires an application builder instance to add the request tracking middleware component"); + } return app.UseMiddleware(); } @@ -94,7 +108,10 @@ public static IApplicationBuilder UseHttpCorrelation(this IApplicationBuilder ap /// public static IApplicationBuilder UseVersionTracking(this IApplicationBuilder app, Action configureOptions = null) { - Guard.NotNull(app, nameof(app), "Requires an application builder to add the version tracking middleware"); + if (app is null) + { + throw new ArgumentNullException(nameof(app), "Requires an application builder instance to add the request tracking middleware component"); + } var options = new VersionTrackingOptions(); configureOptions?.Invoke(options); diff --git a/src/Arcus.WebApi.Logging/Extensions/IServiceCollectionExtensions.cs b/src/Arcus.WebApi.Logging/Extensions/IServiceCollectionExtensions.cs index 5666437c..65e26d94 100644 --- a/src/Arcus.WebApi.Logging/Extensions/IServiceCollectionExtensions.cs +++ b/src/Arcus.WebApi.Logging/Extensions/IServiceCollectionExtensions.cs @@ -2,7 +2,6 @@ using Arcus.Observability.Correlation; using Arcus.WebApi.Logging.Core.Correlation; using Arcus.WebApi.Logging.Correlation; -using GuardNet; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; @@ -20,11 +19,7 @@ public static class IServiceCollectionExtensions /// /// The services collection containing the dependency injection services. public static IServiceCollection AddHttpCorrelation(this IServiceCollection services) - { - Guard.NotNull(services, nameof(services), "Requires a services collection to add the HTTP correlation services"); - - return AddHttpCorrelation(services, configureOptions: (HttpCorrelationInfoOptions options) => { }); - } + => AddHttpCorrelation(services, configureOptions: (HttpCorrelationInfoOptions options) => { }); /// /// Adds operation and transaction correlation to the application. @@ -36,7 +31,10 @@ public static IServiceCollection AddHttpCorrelation( this IServiceCollection services, Action configureOptions) { - Guard.NotNull(services, nameof(services), "Requires a services collection to add the HTTP correlation services"); + if (services is null) + { + throw new ArgumentNullException(nameof(services), "Requires a services collection to add the HTTP correlation services"); + } services.AddHttpContextAccessor(); services.AddSingleton(serviceProvider => diff --git a/src/Arcus.WebApi.Logging/RequestTrackingAttribute.cs b/src/Arcus.WebApi.Logging/RequestTrackingAttribute.cs index dd16b4a9..6fc5b192 100644 --- a/src/Arcus.WebApi.Logging/RequestTrackingAttribute.cs +++ b/src/Arcus.WebApi.Logging/RequestTrackingAttribute.cs @@ -1,7 +1,6 @@ using System; using System.Linq; using System.Net; -using GuardNet; namespace Arcus.WebApi.Logging { @@ -21,9 +20,10 @@ public class RequestTrackingAttribute : Attribute /// Thrown when the is outside the range of the enumeration. public RequestTrackingAttribute(Exclude filter) { - Guard.For( - () => !Enum.IsDefined(typeof(Exclude), filter) || filter is Exclude.None, - $"Requires the exclusion filter to be within these bounds of the enumeration '{ExcludeFilterNames}'; 'None' is not allowed"); + if (!Enum.IsDefined(typeof(Exclude), filter) || filter is Exclude.None) + { + throw new ArgumentOutOfRangeException(nameof(filter), $"Requires the exclusion filter to be within these bounds of the enumeration '{ExcludeFilterNames}'; 'None' is not allowed"); + } Filter = filter; } @@ -44,8 +44,10 @@ public RequestTrackingAttribute(HttpStatusCode trackedStatusCode) : this((int) t /// Thrown when the is outside the expected range (100-599). public RequestTrackingAttribute(int trackedStatusCode) { - Guard.NotLessThan(trackedStatusCode, 100, nameof(trackedStatusCode), "Requires the allowed tracked HTTP status code to not be less than 100"); - Guard.NotGreaterThan(trackedStatusCode, 599, nameof(trackedStatusCode), "Requires the allowed tracked HTTP status code to not be greater than 599"); + if (trackedStatusCode < 100 || trackedStatusCode > 599) + { + throw new ArgumentOutOfRangeException(nameof(trackedStatusCode), "Requires the allowed tracked HTTP status code to be within the range of 100-599"); + } StatusCodeRange = new StatusCodeRange(trackedStatusCode); } @@ -62,9 +64,20 @@ public RequestTrackingAttribute(int trackedStatusCode) /// public RequestTrackingAttribute(int minimumStatusCode, int maximumStatusCode) { - Guard.NotLessThan(minimumStatusCode, 100, nameof(minimumStatusCode), "Requires the minimum HTTP status code threshold not be less than 100"); - Guard.NotGreaterThan(maximumStatusCode, 599, nameof(maximumStatusCode), "Requires the maximum HTTP status code threshold not be greater than 599"); - Guard.NotGreaterThan(minimumStatusCode, maximumStatusCode, nameof(minimumStatusCode), "Requires the minimum HTTP status code threshold to be less than the maximum HTTP status code threshold"); + if (minimumStatusCode < 100) + { + throw new ArgumentOutOfRangeException(nameof(minimumStatusCode), "Requires the minimum HTTP status code threshold to not be less than 100"); + } + + if (maximumStatusCode > 599) + { + throw new ArgumentOutOfRangeException(nameof(maximumStatusCode), "Requires the maximum HTTP status code threshold to not be greater than 599"); + } + + if (minimumStatusCode >= maximumStatusCode) + { + throw new ArgumentOutOfRangeException(nameof(minimumStatusCode), "Requires the minimum HTTP status code threshold to be less than the maximum HTTP status code threshold"); + } StatusCodeRange = new StatusCodeRange(minimumStatusCode, maximumStatusCode); } diff --git a/src/Arcus.WebApi.Logging/RequestTrackingMiddleware.cs b/src/Arcus.WebApi.Logging/RequestTrackingMiddleware.cs index ae37f83d..f8813ee4 100644 --- a/src/Arcus.WebApi.Logging/RequestTrackingMiddleware.cs +++ b/src/Arcus.WebApi.Logging/RequestTrackingMiddleware.cs @@ -5,7 +5,6 @@ using System.Threading.Tasks; using Arcus.Observability.Telemetry.Core; using Arcus.WebApi.Logging.Core.RequestTracking; -using GuardNet; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Routing; @@ -34,9 +33,20 @@ public RequestTrackingMiddleware( ILogger logger) : base(options) { - Guard.NotNull(options, nameof(options), "Requires a set of options to control the behavior of the HTTP tracking middleware"); - Guard.NotNull(next, nameof(next), "Requires a function pipeline to delegate the remainder of the request processing"); - Guard.NotNull(logger, nameof(logger), "Requires a logger instance to write telemetry tracking during the request processing"); + if (options is null) + { + throw new ArgumentNullException(nameof(options), "Requires a set of options to control the behavior of the HTTP tracking middleware"); + } + + if (next is null) + { + throw new ArgumentNullException(nameof(next), "Requires a function pipeline to delegate the remainder of the request processing"); + } + + if (logger is null) + { + throw new ArgumentNullException(nameof(logger), "Requires a logger instance to write telemetry tracking during the request processing"); + } _next = next; _logger = logger; @@ -50,9 +60,20 @@ public RequestTrackingMiddleware( /// Thrown when the is null. public async Task Invoke(HttpContext httpContext) { - Guard.NotNull(httpContext, nameof(httpContext), "Requires a HTTP context instance to track the incoming request and outgoing response"); - Guard.NotNull(httpContext.Request, nameof(httpContext), "Requires a HTTP request in the context to track the request"); - Guard.NotNull(httpContext.Response, nameof(httpContext), "Requires a HTTP response in the context to track the request"); + if (httpContext is null) + { + throw new ArgumentNullException(nameof(httpContext), "Requires a HTTP context instance to track the incoming request and outgoing response"); + } + + if (httpContext.Request is null) + { + throw new ArgumentNullException(nameof(httpContext), "Requires a HTTP request in the context to track the request"); + } + + if (httpContext.Response is null) + { + throw new ArgumentNullException(nameof(httpContext), "Requires a HTTP response in the context to track the request"); + } if (IsRequestPathOmitted(httpContext.Request.Path, _logger)) { diff --git a/src/Arcus.WebApi.Logging/VersionTrackingMiddleware.cs b/src/Arcus.WebApi.Logging/VersionTrackingMiddleware.cs index 086d7142..4a02d363 100644 --- a/src/Arcus.WebApi.Logging/VersionTrackingMiddleware.cs +++ b/src/Arcus.WebApi.Logging/VersionTrackingMiddleware.cs @@ -1,7 +1,6 @@ using System; using System.Threading.Tasks; using Arcus.Observability.Telemetry.Core; -using GuardNet; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; @@ -35,9 +34,20 @@ public VersionTrackingMiddleware( RequestDelegate next, ILogger logger) { - Guard.NotNull(appVersion, nameof(appVersion), "Requires an instance to retrieve the current application version to add the version to the response"); - Guard.NotNull(next, nameof(next), "Requires a continuation delegate to move towards the next functionality in the request pipeline"); - Guard.NotNull(options, nameof(options), "Requires version tracking options to specify how the application version should be tracked in the response"); + if (appVersion is null) + { + throw new ArgumentNullException(nameof(appVersion), "Requires an instance to retrieve the current application version to add the version to the response"); + } + + if (next is null) + { + throw new ArgumentNullException(nameof(next), "Requires a continuation delegate to move towards the next functionality in the request pipeline"); + } + + if (options is null) + { + throw new ArgumentNullException(nameof(options), "Requires version tracking options to specify how the application version should be tracked in the response"); + } _appVersion = appVersion; _options = options; @@ -53,8 +63,15 @@ public VersionTrackingMiddleware( /// Thrown when the doesn't contain a response. public async Task Invoke(HttpContext context) { - Guard.NotNull(context, nameof(context), "Requires a HTTP context to add the application version to the response"); - Guard.For(() => context.Response is null, new ArgumentException("Requires a HTTP context with a response to add the application version", nameof(context))); + if (context is null) + { + throw new ArgumentNullException(nameof(context), "Requires a HTTP context to add the application version to the response"); + } + + if (context.Response is null) + { + throw new ArgumentException("Requires a HTTP context with a response to add the application version", nameof(context)); + } context.Response.OnStarting(() => { diff --git a/src/Arcus.WebApi.Logging/VersionTrackingOptions.cs b/src/Arcus.WebApi.Logging/VersionTrackingOptions.cs index 0ecb5652..a3d5aeb9 100644 --- a/src/Arcus.WebApi.Logging/VersionTrackingOptions.cs +++ b/src/Arcus.WebApi.Logging/VersionTrackingOptions.cs @@ -1,4 +1,4 @@ -using GuardNet; +using System; namespace Arcus.WebApi.Logging { @@ -17,7 +17,11 @@ public string HeaderName get => _headerName; set { - Guard.NotNullOrWhitespace(value, nameof(value), "Requires a non-blank header name to add the current application version to the response"); + if (string.IsNullOrWhiteSpace(value)) + { + throw new ArgumentException("Requires a non-blank header name to add the current application version to the response", nameof(value)); + } + _headerName = value; } } diff --git a/src/Arcus.WebApi.OpenApi.Extensions/Arcus.WebApi.OpenApi.Extensions.csproj b/src/Arcus.WebApi.OpenApi.Extensions/Arcus.WebApi.OpenApi.Extensions.csproj index 10bc60a1..b866e09a 100644 --- a/src/Arcus.WebApi.OpenApi.Extensions/Arcus.WebApi.OpenApi.Extensions.csproj +++ b/src/Arcus.WebApi.OpenApi.Extensions/Arcus.WebApi.OpenApi.Extensions.csproj @@ -31,10 +31,6 @@ - - - - diff --git a/src/Arcus.WebApi.OpenApi.Extensions/CertificateAuthenticationOperationFilter.cs b/src/Arcus.WebApi.OpenApi.Extensions/CertificateAuthenticationOperationFilter.cs index 49a1da3c..53697aa1 100644 --- a/src/Arcus.WebApi.OpenApi.Extensions/CertificateAuthenticationOperationFilter.cs +++ b/src/Arcus.WebApi.OpenApi.Extensions/CertificateAuthenticationOperationFilter.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using Arcus.WebApi.Security.Authentication.Certificates; -using GuardNet; #if !NETSTANDARD2_1 using Microsoft.OpenApi.Models; #endif @@ -44,16 +43,18 @@ public CertificateAuthenticationOperationFilter( #endif ) { - Guard.NotNullOrWhitespace(securitySchemeName, - nameof(securitySchemeName), - "Requires a name for the Certificate security scheme"); + if (string.IsNullOrWhiteSpace(securitySchemeName)) + { + throw new ArgumentNullException(nameof(securitySchemeName), "Requires a name for the Certificate security scheme"); + } _securitySchemeName = securitySchemeName; #if !NETSTANDARD2_1 - Guard.For( - () => !Enum.IsDefined(typeof(SecuritySchemeType), securitySchemeType), - "Requires a security scheme type for the Certificate authentication that is within the bounds of the enumeration"); + if (!Enum.IsDefined(typeof(SecuritySchemeType), securitySchemeType)) + { + throw new ArgumentException("Requires a security scheme type for the Certificate authentication that is within the bounds of the enumeration", nameof(securitySchemeType)); + } _securitySchemeType = securitySchemeType; #endif diff --git a/src/Arcus.WebApi.OpenApi.Extensions/OAuthAuthorizeOperationFilter.cs b/src/Arcus.WebApi.OpenApi.Extensions/OAuthAuthorizeOperationFilter.cs index 5c7bf446..6b8fd88f 100644 --- a/src/Arcus.WebApi.OpenApi.Extensions/OAuthAuthorizeOperationFilter.cs +++ b/src/Arcus.WebApi.OpenApi.Extensions/OAuthAuthorizeOperationFilter.cs @@ -3,7 +3,6 @@ using Swashbuckle.AspNetCore.SwaggerGen; using System.Collections.Generic; using System.Linq; -using GuardNet; using Swashbuckle.AspNetCore.Swagger; #if !NETSTANDARD2_1 using Microsoft.OpenApi.Models; @@ -31,12 +30,18 @@ public class OAuthAuthorizeOperationFilter : IOperationFilter /// public OAuthAuthorizeOperationFilter(IEnumerable scopes, string securitySchemaName = "oauth2") { - Guard.NotNull(scopes, nameof(scopes), "Requires a list of API scopes"); - Guard.For(() => scopes.Any(String.IsNullOrWhiteSpace), "Requires a list of non-blank API scopes"); - Guard.NotNullOrWhitespace(securitySchemaName, nameof(securitySchemaName), "Requires a name for the OAuth2 security scheme"); + if (scopes.Any(String.IsNullOrWhiteSpace)) + { + throw new ArgumentException("Requires a list of non-blank API scopes", nameof(scopes)); + } + + if (string.IsNullOrWhiteSpace(securitySchemaName)) + { + throw new ArgumentException("Requires a name for the OAuth2 security scheme", nameof(securitySchemaName)); + } _securitySchemaName = securitySchemaName; - _scopes = scopes; + _scopes = scopes ?? throw new ArgumentNullException(nameof(scopes), "Requires a list of API scopes"); } /// diff --git a/src/Arcus.WebApi.OpenApi.Extensions/SharedAccessKeyAuthenticationOperationFilter.cs b/src/Arcus.WebApi.OpenApi.Extensions/SharedAccessKeyAuthenticationOperationFilter.cs index b612b1ba..4500eaef 100644 --- a/src/Arcus.WebApi.OpenApi.Extensions/SharedAccessKeyAuthenticationOperationFilter.cs +++ b/src/Arcus.WebApi.OpenApi.Extensions/SharedAccessKeyAuthenticationOperationFilter.cs @@ -1,11 +1,11 @@ using System.Collections.Generic; using System.Linq; using Arcus.WebApi.Security.Authentication.SharedAccessKey; -using GuardNet; #if !NETSTANDARD2_1 using System; using Microsoft.OpenApi.Models; #else +using System; using Swashbuckle.AspNetCore.Swagger; #endif using Swashbuckle.AspNetCore.SwaggerGen; @@ -34,10 +34,15 @@ public SharedAccessKeyAuthenticationOperationFilter( string securitySchemeName = DefaultSecuritySchemeName, SecuritySchemeType securitySchemeType = SecuritySchemeType.ApiKey) { - Guard.NotNullOrWhitespace(securitySchemeName, nameof(securitySchemeName), "Requires a name for the Shared Access Key security scheme"); - Guard.For( - () => !Enum.IsDefined(typeof(SecuritySchemeType), securitySchemeType), - "Requires a security scheme type for the Shared Access Key authentication that is within the bounds of the enumeration"); + if (string.IsNullOrWhiteSpace(securitySchemeName)) + { + throw new ArgumentException("Requires a name for the Shared Access Key security scheme", nameof(securitySchemeName)); + } + + if (!Enum.IsDefined(typeof(SecuritySchemeType), securitySchemeType)) + { + throw new ArgumentException("Requires a security scheme type for the Shared Access Key authentication that is within the bounds of the enumeration", nameof(securitySchemeType)); + } _securitySchemeName = securitySchemeName; _securitySchemeType = securitySchemeType; @@ -49,7 +54,10 @@ public SharedAccessKeyAuthenticationOperationFilter( /// The name of the security scheme. Default value is "sharedaccesskey". public SharedAccessKeyAuthenticationOperationFilter(string securitySchemeName) { - Guard.NotNullOrWhitespace(securitySchemeName, nameof(securitySchemeName), "Requires a name for the Shared Access Key security scheme"); + if (string.IsNullOrWhiteSpace(securitySchemeName)) + { + throw new ArgumentException("Requires a name for the Shared Access Key security scheme", nameof(securitySchemeName)); + } _securitySchemeName = securitySchemeName; } diff --git a/src/Arcus.WebApi.Security/Arcus.WebApi.Security.csproj b/src/Arcus.WebApi.Security/Arcus.WebApi.Security.csproj index 3dc15716..baf2c9c5 100644 --- a/src/Arcus.WebApi.Security/Arcus.WebApi.Security.csproj +++ b/src/Arcus.WebApi.Security/Arcus.WebApi.Security.csproj @@ -36,7 +36,6 @@ - diff --git a/src/Arcus.WebApi.Security/Authentication/Certificates/CertificateAuthenticationConfig.cs b/src/Arcus.WebApi.Security/Authentication/Certificates/CertificateAuthenticationConfig.cs index 60ba5456..173f9e3e 100644 --- a/src/Arcus.WebApi.Security/Authentication/Certificates/CertificateAuthenticationConfig.cs +++ b/src/Arcus.WebApi.Security/Authentication/Certificates/CertificateAuthenticationConfig.cs @@ -4,7 +4,6 @@ using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using Arcus.WebApi.Security.Authentication.Certificates.Interfaces; -using GuardNet; using Microsoft.Extensions.Logging; namespace Arcus.WebApi.Security.Authentication.Certificates @@ -27,10 +26,15 @@ public class CertificateAuthenticationConfig internal CertificateAuthenticationConfig( IDictionary locationAndKeyByRequirement) { - Guard.NotNull(locationAndKeyByRequirement, nameof(locationAndKeyByRequirement), "Location and key by certificate requirement dictionary cannot be 'null'"); - Guard.For( - () => locationAndKeyByRequirement.Any(keyValue => keyValue.Value.location is null || keyValue.Value.configuredKey is null), - "All locations and configured keys by certificate requirement cannot be 'null'"); + if (locationAndKeyByRequirement is null) + { + throw new ArgumentNullException(nameof(locationAndKeyByRequirement), "Location and key by certificate requirement dictionary cannot be 'null'"); + } + + if (locationAndKeyByRequirement.Any(keyValue => keyValue.Value.location is null || keyValue.Value.configuredKey is null)) + { + throw new ArgumentException("All locations and configured keys by certificate requirement cannot be 'null'"); + } _locationAndKeyByRequirement = locationAndKeyByRequirement; } @@ -45,8 +49,15 @@ internal CertificateAuthenticationConfig( /// Thrown when the is null. internal async Task> GetAllExpectedCertificateValuesAsync(IServiceProvider services, ILogger logger) { - Guard.NotNull(services, nameof(services), "Request services cannot be 'null'"); - Guard.NotNull(logger, nameof(logger), "Logger cannot be 'null'"); + if (services is null) + { + throw new ArgumentNullException(nameof(services), "Request services cannot be 'null'"); + } + + if (logger is null) + { + throw new ArgumentNullException(nameof(logger), "Logger cannot be 'null'"); + } var expectedValuesByRequirement = await Task.WhenAll( diff --git a/src/Arcus.WebApi.Security/Authentication/Certificates/CertificateAuthenticationConfigBuilder.cs b/src/Arcus.WebApi.Security/Authentication/Certificates/CertificateAuthenticationConfigBuilder.cs index 03b24d43..139f878a 100644 --- a/src/Arcus.WebApi.Security/Authentication/Certificates/CertificateAuthenticationConfigBuilder.cs +++ b/src/Arcus.WebApi.Security/Authentication/Certificates/CertificateAuthenticationConfigBuilder.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Security.Cryptography.X509Certificates; using Arcus.WebApi.Security.Authentication.Certificates.Interfaces; -using GuardNet; namespace Arcus.WebApi.Security.Authentication.Certificates { @@ -28,11 +27,7 @@ public CertificateAuthenticationConfigBuilder() /// The configured key that the requires to retrieve the expected subject name. /// Thrown when the is blank. public CertificateAuthenticationConfigBuilder WithSubject(X509ValidationLocation location, string configuredKey) - { - Guard.NotNullOrWhitespace(configuredKey, nameof(configuredKey), "Configured key to retrieve expected subject cannot be blank"); - - return WithSubject(GetValidationLocationImplementation(location), configuredKey); - } + => WithSubject(GetValidationLocationImplementation(location), configuredKey); /// /// Configures the validation for the from a given using a specified . @@ -42,12 +37,7 @@ public CertificateAuthenticationConfigBuilder WithSubject(X509ValidationLocation /// Thrown when the is null. /// Thrown when the is blank. public CertificateAuthenticationConfigBuilder WithSubject(IX509ValidationLocation location, string configuredKey) - { - Guard.NotNull(location, nameof(location), "Location implementation to retrieve the expected subject cannot be 'null'"); - Guard.NotNullOrWhitespace(configuredKey, nameof(configuredKey), "Configured key to retrieve expected subject cannot be blank"); - - return AddCertificateRequirement(X509ValidationRequirement.SubjectName, location, configuredKey); - } + => AddCertificateRequirement(X509ValidationRequirement.SubjectName, location, configuredKey); /// /// Configures the validation for the from a given using a specified . @@ -56,11 +46,7 @@ public CertificateAuthenticationConfigBuilder WithSubject(IX509ValidationLocatio /// The configured key that the requires to retrieve the expected issuer name. /// Thrown when the is blank. public CertificateAuthenticationConfigBuilder WithIssuer(X509ValidationLocation location, string configuredKey) - { - Guard.NotNullOrWhitespace(configuredKey, nameof(configuredKey), "Configured key to retrieve expected issuer cannot be blank"); - - return WithIssuer(GetValidationLocationImplementation(location), configuredKey); - } + => WithIssuer(GetValidationLocationImplementation(location), configuredKey); /// /// Configures the validation for the from a given using a specified . @@ -70,12 +56,7 @@ public CertificateAuthenticationConfigBuilder WithIssuer(X509ValidationLocation /// Thrown when the is null. /// Thrown when the is blank. public CertificateAuthenticationConfigBuilder WithIssuer(IX509ValidationLocation location, string configuredKey) - { - Guard.NotNull(location, nameof(location), "Location implementation to retrieve the expected issuer cannot be 'null'"); - Guard.NotNullOrWhitespace(configuredKey, nameof(configuredKey), "Configured key to retrieve expected issuer cannot be blank"); - - return AddCertificateRequirement(X509ValidationRequirement.IssuerName, location, configuredKey); - } + => AddCertificateRequirement(X509ValidationRequirement.IssuerName, location, configuredKey); /// /// Configures the validation for the from a given using a specified . @@ -84,11 +65,7 @@ public CertificateAuthenticationConfigBuilder WithIssuer(IX509ValidationLocation /// The configured key that the requires to retrieve the expected thumbprint. /// Thrown when the is blank. public CertificateAuthenticationConfigBuilder WithThumbprint(X509ValidationLocation location, string configuredKey) - { - Guard.NotNullOrWhitespace(configuredKey, nameof(configuredKey), "Configured key to retrieve expected thumbprint cannot be blank"); - - return WithThumbprint(GetValidationLocationImplementation(location), configuredKey); - } + => WithThumbprint(GetValidationLocationImplementation(location), configuredKey); /// /// Configures the validation for the from a given using a specified . @@ -98,20 +75,22 @@ public CertificateAuthenticationConfigBuilder WithThumbprint(X509ValidationLocat /// Thrown when the is null. /// Thrown when the is blank. public CertificateAuthenticationConfigBuilder WithThumbprint(IX509ValidationLocation location, string configuredKey) - { - Guard.NotNull(location, nameof(location), "Location implementation to retrieve the expected thumbprint cannot be 'null'"); - Guard.NotNullOrWhitespace(configuredKey, nameof(configuredKey), "Configured key to retrieve expected thumbprint cannot be blank"); - - return AddCertificateRequirement(X509ValidationRequirement.Thumbprint, location, configuredKey); - } + => AddCertificateRequirement(X509ValidationRequirement.Thumbprint, location, configuredKey); private CertificateAuthenticationConfigBuilder AddCertificateRequirement( X509ValidationRequirement requirement, IX509ValidationLocation location, string configuredKey) { - Guard.NotNull(location, nameof(location), "Location cannot be 'null'"); - Guard.NotNullOrWhitespace(configuredKey, nameof(configuredKey), "Configured key cannot be blank"); + if (location is null) + { + throw new ArgumentNullException(nameof(location), "Location cannot be 'null'"); + } + + if (string.IsNullOrWhiteSpace(configuredKey)) + { + throw new ArgumentException("Configured key cannot be blank", nameof(configuredKey)); + } // Overwrites existing requirements. _locationAndKeyByRequirement[requirement] = (location, configuredKey); diff --git a/src/Arcus.WebApi.Security/Authentication/Certificates/CertificateAuthenticationFilter.cs b/src/Arcus.WebApi.Security/Authentication/Certificates/CertificateAuthenticationFilter.cs index edab5b68..d799292d 100644 --- a/src/Arcus.WebApi.Security/Authentication/Certificates/CertificateAuthenticationFilter.cs +++ b/src/Arcus.WebApi.Security/Authentication/Certificates/CertificateAuthenticationFilter.cs @@ -5,7 +5,6 @@ using System.Security.Cryptography.X509Certificates; using System.Text.RegularExpressions; using System.Threading.Tasks; -using GuardNet; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; @@ -47,8 +46,7 @@ public CertificateAuthenticationFilter() : this(new CertificateAuthenticationOpt [Obsolete("Use the new constructor with the certificate authentication filter instead")] public CertificateAuthenticationFilter(CertificateAuthenticationOptions options) { - Guard.NotNull(options, nameof(options), "Requires a set of additional consumer-configurable options to determine the behavior of the certificate authentication"); - _options = options; + _options = options ?? throw new ArgumentNullException(nameof(options), "Requires a set of additional consumer-configurable options to determine the behavior of the certificate authentication"); } /// @@ -61,11 +59,8 @@ public CertificateAuthenticationFilter( CertificateAuthenticationValidator validator, CertificateAuthenticationOptions options) { - Guard.NotNull(validator, nameof(validator), "Requires an instance to validate the incoming client certificate of the HTTP request"); - Guard.NotNull(options, nameof(options), "Requires a set of additional consumer-configurable options to determine the behavior of the certificate authentication"); - - _validator = validator; - _options = options; + _validator = validator ?? throw new ArgumentNullException(nameof(validator), "Requires an instance to validate the incoming client certificate of the HTTP request"); + _options = options ?? throw new ArgumentNullException(nameof(options), "Requires a set of additional consumer-configurable options to determine the behavior of the certificate authentication"); } /// @@ -74,10 +69,25 @@ public CertificateAuthenticationFilter( /// The . public async Task OnAuthorizationAsync(AuthorizationFilterContext context) { - Guard.NotNull(context, nameof(context)); - Guard.NotNull(context.HttpContext, nameof(context.HttpContext)); - Guard.For(() => context.HttpContext.Connection is null, "Invalid action context given without any HTTP connection"); - Guard.For(() => context.HttpContext.RequestServices is null, "Invalid action context given without any HTTP request services"); + if (context is null) + { + throw new ArgumentNullException(nameof(context)); + } + + if (context.HttpContext is null) + { + throw new ArgumentNullException(nameof(context)); + } + + if (context.HttpContext.Connection is null) + { + throw new ArgumentException("Invalid action context given without any HTTP connection"); + } + + if (context.HttpContext.RequestServices is null) + { + throw new ArgumentException("Invalid action context given without any HTTP request services"); + } IServiceProvider services = context.HttpContext.RequestServices; ILogger logger = services.GetLoggerOrDefault(); diff --git a/src/Arcus.WebApi.Security/Authentication/Certificates/CertificateAuthenticationValidator.cs b/src/Arcus.WebApi.Security/Authentication/Certificates/CertificateAuthenticationValidator.cs index 41c290bd..0e07a4c0 100644 --- a/src/Arcus.WebApi.Security/Authentication/Certificates/CertificateAuthenticationValidator.cs +++ b/src/Arcus.WebApi.Security/Authentication/Certificates/CertificateAuthenticationValidator.cs @@ -3,7 +3,6 @@ using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; -using GuardNet; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; @@ -24,9 +23,7 @@ public class CertificateAuthenticationValidator /// When the is null. public CertificateAuthenticationValidator(CertificateAuthenticationConfig certificateAuthenticationConfig) { - Guard.NotNull(certificateAuthenticationConfig, nameof(certificateAuthenticationConfig), "Certificate authentication configuration cannot be 'null'"); - - _certificateAuthenticationConfig = certificateAuthenticationConfig; + _certificateAuthenticationConfig = certificateAuthenticationConfig ?? throw new ArgumentNullException(nameof(certificateAuthenticationConfig), "Certificate authentication configuration cannot be 'null'"); } /// @@ -42,8 +39,15 @@ public CertificateAuthenticationValidator(CertificateAuthenticationConfig certif /// Thrown when the is null. internal async Task IsCertificateAllowedAsync(X509Certificate2 clientCertificate, IServiceProvider services) { - Guard.NotNull(clientCertificate, nameof(clientCertificate), "Certificate authentication validation requires a client certificate"); - Guard.NotNull(services, nameof(services), "Certificate authentication validation requires a service object to retrieve registered services"); + if (clientCertificate is null) + { + throw new ArgumentNullException(nameof(clientCertificate), "Certificate authentication validation requires a client certificate"); + } + + if (services is null) + { + throw new ArgumentNullException(nameof(services), "Certificate authentication validation requires a service object to retrieve registered services"); + } ILogger logger = services.GetService>() diff --git a/src/Arcus.WebApi.Security/Authentication/Certificates/ConfigurationValidationLocation.cs b/src/Arcus.WebApi.Security/Authentication/Certificates/ConfigurationValidationLocation.cs index 9e6de5b1..cc5e6a70 100644 --- a/src/Arcus.WebApi.Security/Authentication/Certificates/ConfigurationValidationLocation.cs +++ b/src/Arcus.WebApi.Security/Authentication/Certificates/ConfigurationValidationLocation.cs @@ -3,11 +3,10 @@ using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using Arcus.WebApi.Security.Authentication.Certificates.Interfaces; -using GuardNet; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -namespace Arcus.WebApi.Security.Authentication.Certificates +namespace Arcus.WebApi.Security.Authentication.Certificates { /// /// Certificate location implementation to retrieve the expected value from an @@ -34,11 +33,18 @@ public Task GetExpectedCertificateValueForConfiguredKeyAsync(string conf { try { - Guard.NotNullOrWhitespace(configurationKey, nameof(configurationKey), "Configured key cannot be blank"); - Guard.NotNull(services, nameof(services), "Registered services cannot be 'null'"); + if (string.IsNullOrWhiteSpace(configurationKey)) + { + throw new ArgumentException("Configured key cannot be blank", nameof(configurationKey)); + } + + if (services is null) + { + throw new ArgumentNullException(nameof(services), "Registered services cannot be 'null'"); + } var configuration = services.GetService(); - if (configuration == null) + if (configuration is null) { throw new KeyNotFoundException( $"No configured {nameof(IConfiguration)} implementation found in the request service container. " diff --git a/src/Arcus.WebApi.Security/Authentication/Certificates/Extensions/IServiceCollectionExtensions.cs b/src/Arcus.WebApi.Security/Authentication/Certificates/Extensions/IServiceCollectionExtensions.cs index a9da81c7..b975542f 100644 --- a/src/Arcus.WebApi.Security/Authentication/Certificates/Extensions/IServiceCollectionExtensions.cs +++ b/src/Arcus.WebApi.Security/Authentication/Certificates/Extensions/IServiceCollectionExtensions.cs @@ -1,6 +1,5 @@ using System; using Arcus.WebApi.Security.Authentication.Certificates; -using GuardNet; // ReSharper disable once CheckNamespace namespace Microsoft.Extensions.DependencyInjection @@ -33,8 +32,15 @@ public static IServiceCollection AddCertificateAuthenticationValidation( this IServiceCollection services, Action configureAuthentication) { - Guard.NotNull(services, nameof(services), "Requires a set of application services to register the certificate authentication validator"); - Guard.NotNull(configureAuthentication, nameof(configureAuthentication), "Requires a function to configure the certificate validation locations"); + if (services is null) + { + throw new ArgumentNullException(nameof(services), "Requires a set of application services to register the certificate authentication validator"); + } + + if (configureAuthentication is null) + { + throw new ArgumentNullException(nameof(configureAuthentication), "Requires a function to configure the certificate validation locations"); + } var builder = new CertificateAuthenticationConfigBuilder(); configureAuthentication(builder); diff --git a/src/Arcus.WebApi.Security/Authentication/Certificates/Extensions/MvcOptionsExtensions.cs b/src/Arcus.WebApi.Security/Authentication/Certificates/Extensions/MvcOptionsExtensions.cs index da937122..92a28b14 100644 --- a/src/Arcus.WebApi.Security/Authentication/Certificates/Extensions/MvcOptionsExtensions.cs +++ b/src/Arcus.WebApi.Security/Authentication/Certificates/Extensions/MvcOptionsExtensions.cs @@ -1,6 +1,5 @@ using System; using Arcus.WebApi.Security.Authentication.Certificates; -using GuardNet; using Microsoft.AspNetCore.Mvc; // ReSharper disable once CheckNamespace @@ -23,12 +22,8 @@ public static partial class MvcOptionsExtensions /// Thrown when the is null. [Obsolete("Use the " + nameof(AddCertificateAuthenticationFilter) + " overload where the certificate validation locations are configured directly")] public static MvcOptions AddCertificateAuthenticationFilter(this MvcOptions options) - { - Guard.NotNull(options, nameof(options), "Requires a set of MVC filters to add the certificate authentication MVC filter"); + => AddCertificateAuthenticationFilter(options, configureOptions: null); - return AddCertificateAuthenticationFilter(options, configureOptions: null); - } - /// /// Adds an certificate authentication MVC filter to the given that authenticates the incoming HTTP request. /// @@ -46,7 +41,10 @@ public static MvcOptions AddCertificateAuthenticationFilter( this MvcOptions options, Action configureOptions) { - Guard.NotNull(options, nameof(options), "Requires a set of MVC filters to add the certificate authentication MVC filter"); + if (options is null) + { + throw new ArgumentNullException(nameof(options), "Requires a set of MVC filters to add the certificate authentication MVC filter"); + } var authOptions = new CertificateAuthenticationOptions(); configureOptions?.Invoke(authOptions); @@ -76,12 +74,7 @@ public static MvcOptions AddCertificateAuthenticationFilter( public static MvcOptions AddCertificateAuthenticationFilter( this MvcOptions options, Action configureAuthentication) - { - Guard.NotNull(options, nameof(options), "Requires a set of MVC filters to add the certificate authentication MVC filter"); - Guard.NotNull(configureAuthentication, nameof(configureAuthentication), "Requires a function to configure the certificate validation locations"); - - return AddCertificateAuthenticationFilter(options, configureAuthentication, configureOptions: null); - } + => AddCertificateAuthenticationFilter(options, configureAuthentication, configureOptions: null); /// /// Adds an certificate authentication MVC filter to the given that authenticates the incoming HTTP request. @@ -109,8 +102,15 @@ public static MvcOptions AddCertificateAuthenticationFilter( Action configureAuthentication, Action configureOptions) { - Guard.NotNull(options, nameof(options), "Requires a set of MVC filters to add the certificate authentication MVC filter"); - Guard.NotNull(configureAuthentication, nameof(configureAuthentication), "Requires a function to configure the certificate validation locations"); + if (options is null) + { + throw new ArgumentNullException(nameof(options), "Requires a set of MVC filters to add the certificate authentication MVC filter"); + } + + if (configureAuthentication is null) + { + throw new ArgumentNullException(nameof(configureAuthentication), "Requires a function to configure the certificate validation locations"); + } var builder = new CertificateAuthenticationConfigBuilder(); configureAuthentication(builder); diff --git a/src/Arcus.WebApi.Security/Authentication/Certificates/SecretProviderValidationLocation.cs b/src/Arcus.WebApi.Security/Authentication/Certificates/SecretProviderValidationLocation.cs index 8c4fae08..22fa90ff 100644 --- a/src/Arcus.WebApi.Security/Authentication/Certificates/SecretProviderValidationLocation.cs +++ b/src/Arcus.WebApi.Security/Authentication/Certificates/SecretProviderValidationLocation.cs @@ -5,7 +5,6 @@ using Arcus.Security.Core; using Arcus.Security.Core.Caching; using Arcus.WebApi.Security.Authentication.Certificates.Interfaces; -using GuardNet; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; @@ -34,8 +33,16 @@ private SecretProviderValidationLocation() { } /// The services collections of the HTTP request pipeline to retrieve registered instances. public async Task GetExpectedCertificateValueForConfiguredKeyAsync(string configurationKey, IServiceProvider services) { - Guard.NotNullOrWhitespace(configurationKey, nameof(configurationKey), "Configured key cannot be blank"); - Guard.NotNull(services, nameof(services), "Registered services cannot be 'null'"); + if (string.IsNullOrWhiteSpace(configurationKey)) + { + throw new ArgumentException("Configured key cannot be blank", nameof(configurationKey)); + } + + if (services is null) + { + throw new ArgumentNullException(nameof(services), "Registered services cannot be 'null'"); + } + var userDefinedSecretProvider = services.GetService(); if (userDefinedSecretProvider is null) diff --git a/src/Arcus.WebApi.Security/Authentication/JwtBearer/Extensions/AuthenticationBuilderExtensions.cs b/src/Arcus.WebApi.Security/Authentication/JwtBearer/Extensions/AuthenticationBuilderExtensions.cs index d96bf796..2d7e0f4d 100644 --- a/src/Arcus.WebApi.Security/Authentication/JwtBearer/Extensions/AuthenticationBuilderExtensions.cs +++ b/src/Arcus.WebApi.Security/Authentication/JwtBearer/Extensions/AuthenticationBuilderExtensions.cs @@ -1,5 +1,4 @@ using System; -using GuardNet; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.Extensions.Options; @@ -21,7 +20,10 @@ public static class AuthenticationBuilderExtensions /// A reference to builder after the operation has completed. public static AuthenticationBuilder AddJwtBearer(this AuthenticationBuilder builder, Action configureOptions) { - Guard.NotNull(builder, nameof(builder), "Requires an authentication builder instance to add the JWT Bearer authentication"); + if (builder is null) + { + throw new ArgumentNullException(nameof(builder), "Requires an authentication builder instance to add the JWT Bearer authentication"); + } if (configureOptions != null) { diff --git a/src/Arcus.WebApi.Security/Authentication/SharedAccessKey/Extensions/MvcOptionsExtensions.cs b/src/Arcus.WebApi.Security/Authentication/SharedAccessKey/Extensions/MvcOptionsExtensions.cs index 508cbec2..0de1b620 100644 --- a/src/Arcus.WebApi.Security/Authentication/SharedAccessKey/Extensions/MvcOptionsExtensions.cs +++ b/src/Arcus.WebApi.Security/Authentication/SharedAccessKey/Extensions/MvcOptionsExtensions.cs @@ -1,7 +1,6 @@ using System; using Arcus.Security.Core; using Arcus.WebApi.Security.Authentication.SharedAccessKey; -using GuardNet; using Microsoft.AspNetCore.Mvc; // ReSharper disable once CheckNamespace @@ -25,12 +24,7 @@ public static partial class MvcOptionsExtensions /// Thrown when the is null. /// Thrown when the or is blank. public static MvcOptions AddSharedAccessKeyAuthenticationFilterOnHeader(this MvcOptions options, string headerName, string secretName) - { - Guard.NotNull(options, nameof(options), "Requires an MVC options instance to add the shared access key authenctication filter"); - Guard.NotNullOrWhitespace(headerName, nameof(headerName), "Requires a non-blank HTTP request header name to match the stored secret during the shared access key authentication"); - - return AddSharedAccessKeyAuthenticationFilterOnHeader(options, headerName, secretName, configureOptions: null); - } + => AddSharedAccessKeyAuthenticationFilterOnHeader(options, headerName, secretName, configureOptions: null); /// /// Adds an shared access key authentication MVC filter to the given that authenticates the incoming HTTP request on its header. @@ -53,8 +47,15 @@ public static MvcOptions AddSharedAccessKeyAuthenticationFilterOnHeader( string secretName, Action configureOptions) { - Guard.NotNull(options, nameof(options), "Requires an MVC options instance to add the shared access key authenctication filter"); - Guard.NotNullOrWhitespace(headerName, nameof(headerName), "Requires a non-blank HTTP request header name to match the stored secret during the shared access key authentication"); + if (options is null) + { + throw new ArgumentNullException(nameof(options), "Requires a MVC options instance to add the shared access key authentication filter"); + } + + if (string.IsNullOrWhiteSpace(headerName)) + { + throw new ArgumentException("Requires a non-blank HTTP request header name to match the stored secret during the shared access key authentication", nameof(headerName)); + } var authOptions = new SharedAccessKeyAuthenticationOptions(); configureOptions?.Invoke(authOptions); @@ -79,13 +80,7 @@ public static MvcOptions AddSharedAccessKeyAuthenticationFilterOnQuery( this MvcOptions options, string parameterName, string secretName) - { - Guard.NotNull(options, nameof(options), "Requires a set of MVC options to add the shared access authentication MVC filter"); - Guard.NotNullOrWhitespace(parameterName, nameof(parameterName), "Requires a non-blank HTTP request query parameter name name to match the stored secret during the shared access key authentication"); - Guard.NotNullOrWhitespace(secretName, nameof(secretName), "Requires a non-blank secret name to retrieve the stored access key in the secret store during the shared access key authentication"); - - return AddSharedAccessKeyAuthenticationFilterOnQuery(options, parameterName, secretName, configureOptions: null); - } + => AddSharedAccessKeyAuthenticationFilterOnQuery(options, parameterName, secretName, configureOptions: null); /// /// Adds an shared access key authentication MVC filter to the given that authenticates the incoming HTTP request on its query. @@ -108,9 +103,20 @@ public static MvcOptions AddSharedAccessKeyAuthenticationFilterOnQuery( string secretName, Action configureOptions) { - Guard.NotNull(options, nameof(options), "Requires a set of MVC options to add the shared access authentication MVC filter"); - Guard.NotNullOrWhitespace(parameterName, nameof(parameterName), "Requires a non-blank HTTP request query parameter name name to match the stored secret during the shared access key authentication"); - Guard.NotNullOrWhitespace(secretName, nameof(secretName), "Requires a non-blank secret name to retrieve the stored access key in the secret store during the shared access key authentication"); + if (options is null) + { + throw new ArgumentNullException(nameof(options), "Requires a set of MVC options to add the shared access authentication MVC filter"); + } + + if (string.IsNullOrWhiteSpace(parameterName)) + { + throw new ArgumentException("Requires a non-blank HTTP request query parameter name to match the stored secret during the shared access key authentication", nameof(parameterName)); + } + + if (string.IsNullOrWhiteSpace(secretName)) + { + throw new ArgumentException("Requires a non-blank secret name to retrieve the stored access key in the secret store during the shared access key authentication", nameof(secretName)); + } var authOptions = new SharedAccessKeyAuthenticationOptions(); configureOptions?.Invoke(authOptions); diff --git a/src/Arcus.WebApi.Security/Authentication/SharedAccessKey/SharedAccessKeyAuthenticationAttribute.cs b/src/Arcus.WebApi.Security/Authentication/SharedAccessKey/SharedAccessKeyAuthenticationAttribute.cs index e5160971..7eed9d77 100644 --- a/src/Arcus.WebApi.Security/Authentication/SharedAccessKey/SharedAccessKeyAuthenticationAttribute.cs +++ b/src/Arcus.WebApi.Security/Authentication/SharedAccessKey/SharedAccessKeyAuthenticationAttribute.cs @@ -1,6 +1,5 @@ using System; using Arcus.Security.Core; -using GuardNet; using Microsoft.AspNetCore.Mvc; namespace Arcus.WebApi.Security.Authentication.SharedAccessKey @@ -28,10 +27,15 @@ public class SharedAccessKeyAuthenticationAttribute : TypeFilterAttribute public SharedAccessKeyAuthenticationAttribute(string secretName, string headerName = null, string queryParameterName = null) : base(typeof(SharedAccessKeyAuthenticationFilter)) { - Guard.NotNullOrWhitespace(secretName, nameof(secretName), "Secret name cannot be blank"); - Guard.For( - () => String.IsNullOrWhiteSpace(headerName) && String.IsNullOrWhiteSpace(queryParameterName), - "Requires either a non-blank header name or query parameter name"); + if (string.IsNullOrWhiteSpace(secretName)) + { + throw new ArgumentException("Secret name cannot be blank", nameof(secretName)); + } + + if (string.IsNullOrWhiteSpace(headerName) && string.IsNullOrWhiteSpace(queryParameterName)) + { + throw new ArgumentException("Requires either a non-blank header name or query parameter name"); + } _options = new SharedAccessKeyAuthenticationOptions(); Arguments = new object[] { headerName?? String.Empty, queryParameterName?? String.Empty, secretName, _options }; diff --git a/src/Arcus.WebApi.Security/Authentication/SharedAccessKey/SharedAccessKeyAuthenticationFilter.cs b/src/Arcus.WebApi.Security/Authentication/SharedAccessKey/SharedAccessKeyAuthenticationFilter.cs index 20743355..1e257b6f 100644 --- a/src/Arcus.WebApi.Security/Authentication/SharedAccessKey/SharedAccessKeyAuthenticationFilter.cs +++ b/src/Arcus.WebApi.Security/Authentication/SharedAccessKey/SharedAccessKeyAuthenticationFilter.cs @@ -5,7 +5,6 @@ using System.Threading.Tasks; using Arcus.Security.Core; using Arcus.Security.Core.Caching; -using GuardNet; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; @@ -52,10 +51,15 @@ public SharedAccessKeyAuthenticationFilter(string headerName, string queryParame /// Thrown when the and are blank. public SharedAccessKeyAuthenticationFilter(string headerName, string queryParameterName, string secretName, SharedAccessKeyAuthenticationOptions options) { - Guard.NotNullOrWhitespace(secretName, nameof(secretName), "Requires a non-blank secret name"); - Guard.For( - () => String.IsNullOrWhiteSpace(headerName) && String.IsNullOrWhiteSpace(queryParameterName), - "Requires either a non-blank header name or query parameter name"); + if (string.IsNullOrWhiteSpace(secretName)) + { + throw new ArgumentException("Requires a non-blank secret name", nameof(secretName)); + } + + if (string.IsNullOrWhiteSpace(headerName) && string.IsNullOrWhiteSpace(queryParameterName)) + { + throw new ArgumentException("Requires either a non-blank header name or query parameter name"); + } _headerName = headerName; _queryParameterName = queryParameterName; @@ -72,11 +76,30 @@ public SharedAccessKeyAuthenticationFilter(string headerName, string queryParame /// public async Task OnAuthorizationAsync(AuthorizationFilterContext context) { - Guard.NotNull(context, nameof(context)); - Guard.NotNull(context.HttpContext, nameof(context.HttpContext)); - Guard.For(() => context.HttpContext.Request is null, "Invalid action context given without any HTTP request"); - Guard.For(() => context.HttpContext.Request.Headers is null, "Invalid action context given without any HTTP request headers"); - Guard.For(() => context.HttpContext.RequestServices is null, "Invalid action context given without any HTTP request services"); + if (context is null) + { + throw new ArgumentNullException(nameof(context)); + } + + if (context.HttpContext is null) + { + throw new ArgumentNullException(nameof(context.HttpContext)); + } + + if (context.HttpContext.Request is null) + { + throw new ArgumentException("Invalid action context given without any HTTP request"); + } + + if (context.HttpContext.Request.Headers is null) + { + throw new ArgumentException("Invalid action context given without any HTTP request headers"); + } + + if (context.HttpContext.RequestServices is null) + { + throw new ArgumentException("Invalid action context given without any HTTP request services"); + } ILogger logger = context.HttpContext.RequestServices.GetLoggerOrDefault(); @@ -106,23 +129,14 @@ public async Task OnAuthorizationAsync(AuthorizationFilterContext context) private async Task GetAuthorizationSecretAsync(AuthorizationFilterContext context) { - var userDefinedSecretProvider = context.HttpContext.RequestServices.GetService(); - if (userDefinedSecretProvider is null) - { - throw new InvalidOperationException( + var userDefinedSecretProvider = context.HttpContext.RequestServices.GetService() ?? throw new InvalidOperationException( "Cannot retrieve the shared access key to validate the HTTP request because no Arcus secret store was registered in the application," + $"please register the secret store with '{nameof(IHostBuilderExtensions.ConfigureSecretStore)}' on the '{nameof(IHostBuilder)}' or with 'AddSecretStore' on the '{nameof(IServiceCollection)}'," + "for more information on the Arcus secret store: https://security.arcus-azure.net/features/secret-store"); - } - - Task> rawSecretAsync = userDefinedSecretProvider.GetRawSecretsAsync(_secretName); - if (rawSecretAsync is null) - { - throw new InvalidOperationException( + Task> rawSecretAsync = userDefinedSecretProvider.GetRawSecretsAsync(_secretName) ?? throw new InvalidOperationException( $"Configured {nameof(ISecretProvider)} is not implemented correctly as it returns 'null' for a {nameof(Task)} value when calling {nameof(ISecretProvider.GetRawSecretAsync)}"); - } - IEnumerable foundSecrets = await rawSecretAsync; + if (foundSecrets is null) { throw new SecretNotFoundException(_secretName); diff --git a/src/Arcus.WebApi.Security/Authorization/Extensions/MvcOptionsExtensions.cs b/src/Arcus.WebApi.Security/Authorization/Extensions/MvcOptionsExtensions.cs index 617cc1bb..7c8cee38 100644 --- a/src/Arcus.WebApi.Security/Authorization/Extensions/MvcOptionsExtensions.cs +++ b/src/Arcus.WebApi.Security/Authorization/Extensions/MvcOptionsExtensions.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using Arcus.WebApi.Security.Authorization; -using GuardNet; using Microsoft.AspNetCore.Mvc; // ReSharper disable once CheckNamespace @@ -19,11 +18,7 @@ public static partial class MvcOptionsExtensions /// The options that are being applied to the request pipeline. /// Thrown when the is null. public static MvcOptions AddJwtTokenAuthorizationFilter(this MvcOptions options) - { - Guard.NotNull(options, nameof(options), "Requires a filter collection to add the JWT token authorization filter"); - - return AddJwtTokenAuthorizationFilter(options, configureOptions: null); - } + => AddJwtTokenAuthorizationFilter(options, configureOptions: null); /// /// Adds JWT token authorization. @@ -35,7 +30,10 @@ public static MvcOptions AddJwtTokenAuthorizationFilter( this MvcOptions options, Action configureOptions) { - Guard.NotNull(options, nameof(options), "Requires a filter collection to add the JWT token authorization filter"); + if (options is null) + { + throw new ArgumentNullException(nameof(options), "Requires a filter collection to add the JWT token authorization filter"); + } var authOptions= new JwtTokenAuthorizationOptions(); configureOptions?.Invoke(authOptions); @@ -53,15 +51,7 @@ public static MvcOptions AddJwtTokenAuthorizationFilter( public static MvcOptions AddJwtTokenAuthorizationFilter( this MvcOptions options, IDictionary claimCheck) - { - Guard.NotNull(options, nameof(options), "Requires a filter collection to add the JWT token authorization filter"); - Guard.NotNull(claimCheck, nameof(claimCheck), "Requires a set of claim checks to verify the claims request JWT"); - Guard.NotAny(claimCheck, nameof(claimCheck), "Requires at least one entry in the set of claim checks to verify the claims in the request JWT"); - Guard.For(() => claimCheck.Any(item => string.IsNullOrWhiteSpace(item.Key) || string.IsNullOrWhiteSpace(item.Value)), - "Requires all entries in the set of claim checks to be non-blank to correctly verify the claims in the request JWT"); - - return AddJwtTokenAuthorizationFilter(options, configureOptions: null, claimCheck: claimCheck); - } + => AddJwtTokenAuthorizationFilter(options, configureOptions: null, claimCheck: claimCheck); /// /// Adds JWT token authorization. @@ -76,11 +66,25 @@ public static MvcOptions AddJwtTokenAuthorizationFilter( Action configureOptions, IDictionary claimCheck) { - Guard.NotNull(options, nameof(options), "Requires a filter collection to add the JWT token authorization filter"); - Guard.NotNull(claimCheck, nameof(claimCheck), "Requires a set of claim checks to verify the claims request JWT"); - Guard.NotAny(claimCheck, nameof(claimCheck), "Requires at least one entry in the set of claim checks to verify the claims in the request JWT"); - Guard.For(() => claimCheck.Any(item => string.IsNullOrWhiteSpace(item.Key) || string.IsNullOrWhiteSpace(item.Value)), - "Requires all entries in the set of claim checks to be non-blank to correctly verify the claims in the request JWT"); + if (options is null) + { + throw new ArgumentNullException(nameof(options), "Requires a filter collection to add the JWT token authorization filter"); + } + + if (claimCheck is null) + { + throw new ArgumentNullException(nameof(claimCheck), "Requires a set of claim checks to verify the claims request JWT"); + } + + if (!claimCheck.Any()) + { + throw new ArgumentException("Requires at least one entry in the set of claim checks to verify the claims in the request JWT", nameof(claimCheck)); + } + + if (claimCheck.Any(item => string.IsNullOrWhiteSpace(item.Key) || string.IsNullOrWhiteSpace(item.Value))) + { + throw new ArgumentException("Requires all entries in the set of claim checks to be non-blank to correctly verify the claims in the request JWT"); + } var authOptions = new JwtTokenAuthorizationOptions(claimCheck); configureOptions?.Invoke(authOptions); diff --git a/src/Arcus.WebApi.Security/Authorization/Jwt/JwtTokenReader.cs b/src/Arcus.WebApi.Security/Authorization/Jwt/JwtTokenReader.cs index debf9a42..bf4e49b6 100644 --- a/src/Arcus.WebApi.Security/Authorization/Jwt/JwtTokenReader.cs +++ b/src/Arcus.WebApi.Security/Authorization/Jwt/JwtTokenReader.cs @@ -3,7 +3,6 @@ using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Threading.Tasks; -using GuardNet; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using IdentityModel; @@ -35,7 +34,10 @@ public class JwtTokenReader : IJwtTokenReader /// Thrown when the is blank. public JwtTokenReader(string audience) : this(audience, NullLogger.Instance) { - Guard.NotNullOrWhitespace(audience, nameof(audience), "Requires an audience to validate against"); + if (string.IsNullOrWhiteSpace(audience)) + { + throw new ArgumentException("Requires an audience to validate against", nameof(audience)); + } } /// @@ -47,7 +49,10 @@ public JwtTokenReader(string audience) : this(audience, NullLoggerThrown when the is blank. public JwtTokenReader(string audience, ILogger logger) : this(new Dictionary {{ JwtClaimTypes.Audience, audience}}, logger) { - Guard.NotNullOrWhitespace(audience, nameof(audience), "Requires an audience to validate against"); + if (string.IsNullOrWhiteSpace(audience)) + { + throw new ArgumentException("Requires an audience to validate against", nameof(audience)); + } } /// @@ -71,10 +76,20 @@ public JwtTokenReader(IDictionary claimCheck) : this(claimCheck, /// Thrown when the doesn't have any entries or one of the entries has blank key/value inputs. public JwtTokenReader(IDictionary claimCheck, ILogger logger) { - Guard.NotNull(claimCheck, nameof(claimCheck), "Requires a set of claim checks to verify the claims request JWT"); - Guard.NotAny(claimCheck, nameof(claimCheck), "Requires at least one entry in the set of claim checks to verify the claims in the request JWT"); - Guard.For(() => claimCheck.Any(item => String.IsNullOrWhiteSpace(item.Key) || String.IsNullOrWhiteSpace(item.Value)), - "Requires all entries in the set of claim checks to be non-blank to correctly verify the claims in the request JWT"); + if (claimCheck is null) + { + throw new ArgumentNullException(nameof(claimCheck), "Requires a set of claim checks to verify the claims request JWT"); + } + + if (!claimCheck.Any()) + { + throw new ArgumentException("Requires at least one entry in the set of claim checks to verify the claims in the request JWT", nameof(claimCheck)); + } + + if (claimCheck.Any(item => string.IsNullOrWhiteSpace(item.Key) || string.IsNullOrWhiteSpace(item.Value))) + { + throw new ArgumentException("Requires all entries in the set of claim checks to be non-blank to correctly verify the claims in the request JWT", nameof(claimCheck)); + } _claimCheck = claimCheck; _logger = logger ?? NullLogger.Instance; @@ -153,8 +168,15 @@ public JwtTokenReader(TokenValidationParameters tokenValidationParameters, strin /// Thrown when the is blank. public JwtTokenReader(TokenValidationParameters tokenValidationParameters, string openIdConnectDiscoveryUri, ILogger logger) { - Guard.NotNull(tokenValidationParameters, nameof(tokenValidationParameters), "Requires a collection of parameters to influence how the token validation is done"); - Guard.NotNullOrWhitespace(openIdConnectDiscoveryUri, nameof(openIdConnectDiscoveryUri), "Requires an non-blank OpenId URI connection endpoint for discovering the OpenId configuration"); + if (tokenValidationParameters is null) + { + throw new ArgumentNullException(nameof(tokenValidationParameters), "Requires a collection of parameters to influence how the token validation is done"); + } + + if (string.IsNullOrWhiteSpace(openIdConnectDiscoveryUri)) + { + throw new ArgumentException("Requires an non-blank OpenId URI connection endpoint for discovering the OpenId configuration", nameof(openIdConnectDiscoveryUri)); + } _tokenValidationParameters = tokenValidationParameters; _logger = logger ?? NullLogger.Instance; @@ -192,12 +214,31 @@ public JwtTokenReader( IDictionary claimCheck, ILogger logger) { - Guard.NotNullOrWhitespace(openIdConnectDiscoveryUri, nameof(openIdConnectDiscoveryUri), "Requires an non-blank OpenId URI connection endpoint for discovering the OpenId configuration"); - Guard.NotNull(tokenValidationParameters, nameof(tokenValidationParameters), "Requires a collection of parameters to influence how the token validation is done"); - Guard.NotNull(claimCheck, nameof(claimCheck), "Requires a set of claim checks to verify the claims request JWT"); - Guard.NotAny(claimCheck, nameof(claimCheck), "Requires at least one entry in the set of claim checks to verify the claims in the request JWT"); - Guard.For(() => claimCheck.Any(item => String.IsNullOrWhiteSpace(item.Key) || String.IsNullOrWhiteSpace(item.Value)), - "Requires all entries in the set of claim checks to be non-blank to correctly verify the claims in the request JWT"); + if (string.IsNullOrWhiteSpace(openIdConnectDiscoveryUri)) + { + throw new ArgumentException("Requires an non-blank OpenId URI connection endpoint for discovering the OpenId configuration", nameof(openIdConnectDiscoveryUri)); + } + + if (tokenValidationParameters is null) + { + throw new ArgumentNullException(nameof(tokenValidationParameters), "Requires a collection of parameters to influence how the token validation is done"); + } + + if (claimCheck is null) + { + throw new ArgumentNullException(nameof(claimCheck), "Requires a set of claim checks to verify the claims request JWT"); + } + + if (!claimCheck.Any()) + { + throw new ArgumentException("Requires at least one entry in the set of claim checks to verify the claims in the " + + "request JWT", nameof(claimCheck)); + } + + if (claimCheck.Any(item => string.IsNullOrWhiteSpace(item.Key) || string.IsNullOrWhiteSpace(item.Value))) + { + throw new ArgumentException("Requires all entries in the set of claim checks to be non-blank to correctly verify the claims in the request JWT", nameof(claimCheck)); + } _tokenValidationParameters = tokenValidationParameters; _claimCheck = claimCheck; diff --git a/src/Arcus.WebApi.Security/Authorization/JwtTokenAuthorizationFilter .cs b/src/Arcus.WebApi.Security/Authorization/JwtTokenAuthorizationFilter .cs index 4eff561e..265c7574 100644 --- a/src/Arcus.WebApi.Security/Authorization/JwtTokenAuthorizationFilter .cs +++ b/src/Arcus.WebApi.Security/Authorization/JwtTokenAuthorizationFilter .cs @@ -5,7 +5,6 @@ using System.Linq; using System.Threading.Tasks; using Arcus.WebApi.Security.Authorization.Jwt; -using GuardNet; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; @@ -32,8 +31,10 @@ public class JwtTokenAuthorizationFilter : IAsyncAuthorizationFilter /// Thrown when the is null. public JwtTokenAuthorizationFilter(JwtTokenAuthorizationOptions authorizationOptions) { - Guard.NotNull(authorizationOptions, nameof(authorizationOptions), - "Requires a set of options to configure how the JWT authorization filter should authorize requests"); + if (authorizationOptions is null) + { + throw new ArgumentNullException(nameof(authorizationOptions), "Requires a set of options to configure how the JWT authorization filter should authorize requests"); + } _authorizationOptions = authorizationOptions; } @@ -47,11 +48,30 @@ public JwtTokenAuthorizationFilter(JwtTokenAuthorizationOptions authorizationOpt /// public virtual async Task OnAuthorizationAsync(AuthorizationFilterContext context) { - Guard.NotNull(context, nameof(context)); - Guard.NotNull(context.HttpContext, nameof(context.HttpContext)); - Guard.For(() => context.HttpContext.Request is null, "Invalid action context given without any HTTP request"); - Guard.For(() => context.HttpContext.Request.Headers is null, "Invalid action context given without any HTTP request headers"); - Guard.For(() => context.HttpContext.RequestServices is null, "Invalid action context given without any HTTP request services"); + if (context is null) + { + throw new ArgumentNullException(nameof(context)); + } + + if (context.HttpContext is null) + { + throw new ArgumentNullException(nameof(context.HttpContext)); + } + + if (context.HttpContext.Request is null) + { + throw new ArgumentNullException(nameof(context), "INvalid action context given without any HTTP request"); + } + + if (context.HttpContext.Request.Headers is null) + { + throw new ArgumentNullException(nameof(context), "Invalid action context given without any HTTP request headers"); + } + + if (context.HttpContext.RequestServices is null) + { + throw new ArgumentNullException(nameof(context), "Invalid action context given without any HTTP request services"); + } ILogger logger = context.HttpContext.RequestServices.GetLoggerOrDefault(); diff --git a/src/Arcus.WebApi.Security/Authorization/JwtTokenAuthorizationOptions.cs b/src/Arcus.WebApi.Security/Authorization/JwtTokenAuthorizationOptions.cs index d47215c5..3f8a0244 100644 --- a/src/Arcus.WebApi.Security/Authorization/JwtTokenAuthorizationOptions.cs +++ b/src/Arcus.WebApi.Security/Authorization/JwtTokenAuthorizationOptions.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using Arcus.WebApi.Security.Authorization.Jwt; -using GuardNet; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.IdentityModel.Tokens; @@ -60,8 +59,15 @@ public JwtTokenAuthorizationOptions(IDictionary claimCheck) /// Thrown when the is blank. public JwtTokenAuthorizationOptions(IJwtTokenReader reader, string headerName) { - Guard.NotNull(reader, nameof(reader), $"Requires a valid {nameof(IJwtTokenReader)} to verify the JWT token"); - Guard.NotNullOrWhitespace(headerName, nameof(headerName), "Requires a non-blank request header name to look for the JWT token"); + if (reader is null) + { + throw new ArgumentNullException(nameof(reader), $"Requires a valid {nameof(IJwtTokenReader)} to verify the JWT token"); + } + + if (string.IsNullOrWhiteSpace(headerName)) + { + throw new ArgumentException("Requires a non-blank request header name to look for the JWT token", nameof(headerName)); + } JwtTokenReader = reader; HeaderName = headerName; @@ -76,7 +82,11 @@ public string HeaderName get => _headerName; set { - Guard.NotNullOrWhitespace(value, nameof(value), "Requires an non-blank request header name to look for the JWT token"); + if (string.IsNullOrWhiteSpace(value)) + { + throw new ArgumentException("Requires a non-blank request header name to look for the JWT token", nameof(value)); + } + _headerName = value; } } @@ -90,7 +100,11 @@ public IJwtTokenReader JwtTokenReader get => _jwtTokenReader; set { - Guard.NotNull(value, nameof(value), $"Requires a valid {nameof(IJwtTokenReader)} to verify the JWT token"); + if (value is null) + { + throw new ArgumentNullException(nameof(value), $"Requires a valid {nameof(IJwtTokenReader)} to verify the JWT token"); + } + _jwtTokenReader = value; _createJwtTokenReader = null; } @@ -119,10 +133,8 @@ public void AddJwtTokenReader() where TImplementation : IJwtTok /// Thrown when the is null. public void AddJwtTokenReader(Func createReader) { - Guard.NotNull(createReader, nameof(createReader), $"Requires an implementation function to create an {nameof(IJwtTokenReader)} instance"); - _jwtTokenReader = null; - _createJwtTokenReader = createReader; + _createJwtTokenReader = createReader ?? throw new ArgumentNullException(nameof(createReader), $"Requires an implementation function to create an {nameof(IJwtTokenReader)} instance"); } /// @@ -136,7 +148,11 @@ internal IJwtTokenReader GetOrCreateJwtTokenReader(IServiceProvider serviceProvi { try { - Guard.NotNull(serviceProvider, nameof(serviceProvider), $"Requires an collection of services to create an {nameof(IJwtTokenReader)} instance"); + if (serviceProvider is null) + { + throw new ArgumentNullException(nameof(serviceProvider), $"Requires a collection of services to create an {nameof(IJwtTokenReader)} instance"); + } + return _createJwtTokenReader(serviceProvider); } catch (Exception exception) diff --git a/src/Arcus.WebApi.Security/Extensions/IServiceProviderExtensions.cs b/src/Arcus.WebApi.Security/Extensions/IServiceProviderExtensions.cs index cd295456..625869a4 100644 --- a/src/Arcus.WebApi.Security/Extensions/IServiceProviderExtensions.cs +++ b/src/Arcus.WebApi.Security/Extensions/IServiceProviderExtensions.cs @@ -1,5 +1,4 @@ using System; -using GuardNet; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; @@ -23,7 +22,10 @@ public static class IServiceProviderExtensions /// Thrown when the is null. public static ILogger GetLoggerOrDefault(this IServiceProvider services) { - Guard.NotNull(services, nameof(services), "Requires a services collection to retrieve an logger instance"); + if (services is null) + { + throw new ArgumentNullException(nameof(services), "Requires a services collection to retrieve a logger instance"); + } var loggerFactory = services.GetService(); ILogger logger = loggerFactory?.CreateLogger(); diff --git a/src/Arcus.WebApi.Tests.Core/Arcus.WebApi.Tests.Core.csproj b/src/Arcus.WebApi.Tests.Core/Arcus.WebApi.Tests.Core.csproj index 77410530..4326c8cc 100644 --- a/src/Arcus.WebApi.Tests.Core/Arcus.WebApi.Tests.Core.csproj +++ b/src/Arcus.WebApi.Tests.Core/Arcus.WebApi.Tests.Core.csproj @@ -8,7 +8,6 @@ - diff --git a/src/Arcus.WebApi.Tests.Core/Logging/AzureFunctions/ReadOnceStream.cs b/src/Arcus.WebApi.Tests.Core/Logging/AzureFunctions/ReadOnceStream.cs index b2c9f4c4..f7f5cf7c 100644 --- a/src/Arcus.WebApi.Tests.Core/Logging/AzureFunctions/ReadOnceStream.cs +++ b/src/Arcus.WebApi.Tests.Core/Logging/AzureFunctions/ReadOnceStream.cs @@ -1,6 +1,5 @@ using System; using System.IO; -using GuardNet; namespace Arcus.WebApi.Tests.Unit.Logging.Fixture.AzureFunctions { @@ -14,8 +13,15 @@ public class ReadOnceStream : Stream /// public ReadOnceStream(Stream innerStream) { - Guard.NotNull(innerStream, nameof(innerStream)); - Guard.For(() => !innerStream.CanRead, "Requires a readable stream to represents a read-once stream"); + if (innerStream is null) + { + throw new ArgumentNullException(nameof(innerStream)); + } + + if (!innerStream.CanRead) + { + throw new ArgumentException("Requires a readable stream to represent a read-once stream", nameof(innerStream)); + } _innerStream = innerStream; } diff --git a/src/Arcus.WebApi.Tests.Integration/Fixture/HttpRequestBuilder.cs b/src/Arcus.WebApi.Tests.Integration/Fixture/HttpRequestBuilder.cs index 67c57cb5..b1de99c7 100644 --- a/src/Arcus.WebApi.Tests.Integration/Fixture/HttpRequestBuilder.cs +++ b/src/Arcus.WebApi.Tests.Integration/Fixture/HttpRequestBuilder.cs @@ -4,7 +4,7 @@ using System.Linq; using System.Net.Http; using System.Text; -using GuardNet; +using System.Threading; namespace Arcus.WebApi.Tests.Integration.Fixture { @@ -33,7 +33,11 @@ private HttpRequestBuilder(HttpMethod method, string path) /// Thrown when the is blank. public static HttpRequestBuilder Get(string route) { - Guard.NotNullOrWhitespace(route, nameof(route), "Requires a non-blank HTTP relative route to create a HTTP GET request builder instance"); + if (string.IsNullOrWhiteSpace(route)) + { + throw new ArgumentException("Requires a non-blank HTTP relative route to create a HTTP GET request builder instance", nameof(route)); + } + return new HttpRequestBuilder(HttpMethod.Get, route); } @@ -45,7 +49,11 @@ public static HttpRequestBuilder Get(string route) /// Thrown when the is blank. public static HttpRequestBuilder Post(string route) { - Guard.NotNullOrWhitespace(route, nameof(route), "Requires a non-blank HTTP relative route to create a HTTP POST request builder instance"); + if (string.IsNullOrWhiteSpace(route)) + { + throw new ArgumentException("Requires a non-blank HTTP relative route to create a HTTP POST request builder instance", nameof(route)); + } + return new HttpRequestBuilder(HttpMethod.Post, route); } @@ -57,7 +65,11 @@ public static HttpRequestBuilder Post(string route) /// Thrown when the is blank. public HttpRequestBuilder WithHeader(string headerName, object headerValue) { - Guard.NotNullOrWhitespace(headerName, nameof(headerName), "Requires a non-blank header name to add the header to the HTTP request builder instance"); + if (string.IsNullOrWhiteSpace(headerName)) + { + throw new ArgumentException("Requires a non-blank header name to add the header to the HTTP request builder instance", nameof(headerName)); + } + _headers.Add(new KeyValuePair(headerName, headerValue?.ToString())); return this; @@ -71,7 +83,11 @@ public HttpRequestBuilder WithHeader(string headerName, object headerValue) /// Thrown when the is blank. public HttpRequestBuilder WithParameter(string parameterName, object parameterValue) { - Guard.NotNullOrWhitespace(parameterName, nameof(parameterName), "Requires a non-blank query parameter name to add the parameter to the HTTP request builder instance"); + if (string.IsNullOrWhiteSpace(parameterName)) + { + throw new ArgumentException("Requires a non-blank query parameter to add the parameter to the HTTP request builder instance", nameof(parameterName)); + } + _parameters.Add(new KeyValuePair(parameterName, parameterValue.ToString())); return this; @@ -85,12 +101,16 @@ public HttpRequestBuilder WithParameter(string parameterName, object parameterVa /// Thrown when the is blank. public HttpRequestBuilder WithJsonText(string text) { - Guard.NotNullOrWhitespace(text, nameof(text), "Requires non-blank JSON request text to add the content to the HTTP request builder instance"); + if (string.IsNullOrWhiteSpace(text)) + { + throw new ArgumentException("Requires a non-blank JSON request text to add the content to the HTTP request builder instance", nameof(text)); + } + _createContent = () => new StringContent($"\"{text}\"", Encoding.UTF8, "application/json"); return this; } - + /// /// Adds a JSON json to the HTTP request. /// @@ -99,7 +119,11 @@ public HttpRequestBuilder WithJsonText(string text) /// Thrown when the is blank. public HttpRequestBuilder WithJsonBody(string json) { - Guard.NotNullOrWhitespace(json, nameof(json), "Requires non-blank JSON request body to add the content to the HTTP request builder instance"); + if (string.IsNullOrWhiteSpace(json)) + { + throw new ArgumentException("Requires a non-blank JSON request body to add the content to the HTTP request builder instance", nameof(json)); + } + _createContent = () => new StringContent(json, Encoding.UTF8, "application/json"); return this; @@ -113,7 +137,11 @@ public HttpRequestBuilder WithJsonBody(string json) /// Thrown when the is blank. public HttpRequestBuilder WithTextBody(string text) { - Guard.NotNullOrWhitespace(text, nameof(text), "Requires a non-blank text input for the request body"); + if (string.IsNullOrWhiteSpace(text)) + { + throw new ArgumentException("Requires a non-blank text input for the request body", nameof(text)); + } + _createContent = () => new StringContent(text, Encoding.UTF8, "text/plain"); return this; @@ -127,16 +155,22 @@ public HttpRequestBuilder WithTextBody(string text) /// Thrown when the is not in the correct HTTP format. internal HttpRequestMessage Build(string baseRoute) { - Guard.NotNullOrWhitespace(baseRoute, nameof(baseRoute), "Requires a non-blank base HTTP endpoint to create a HTTP request message from the HTTP request builder instance"); + if (string.IsNullOrWhiteSpace(baseRoute)) + { + throw new ArgumentException("Requires a non-blank base HTTP endpoint to create a HTTP request message from the HTTP request builder instance", nameof(baseRoute)); + } + string parameters = ""; + if (_parameters.Count > 0) { parameters = "?" + String.Join("&", _parameters.Select(p => $"{p.Key}={p.Value}")); } string path = _path; - if (path.StartsWith("/")) + + if (path.StartsWith('/')) { path = path.TrimStart('/'); } diff --git a/src/Arcus.WebApi.Tests.Integration/Fixture/TestApiServer.cs b/src/Arcus.WebApi.Tests.Integration/Fixture/TestApiServer.cs index c4ad7c15..4ea971d8 100644 --- a/src/Arcus.WebApi.Tests.Integration/Fixture/TestApiServer.cs +++ b/src/Arcus.WebApi.Tests.Integration/Fixture/TestApiServer.cs @@ -4,12 +4,12 @@ using System.Security.Cryptography; using System.Threading.Tasks; using Arcus.Testing.Logging; -using GuardNet; using Microsoft.ApplicationInsights.AspNetCore.Extensions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.ApplicationInsights; +using Microsoft.Extensions.Options; namespace Arcus.WebApi.Tests.Integration.Fixture { @@ -26,9 +26,7 @@ public class TestApiServer : IAsyncDisposable protected TestApiServer(IHost host, TestApiServerOptions options, ILogger logger) { - Guard.NotNull(host, nameof(host), "Requires a 'IHost' instance to start/stop the test API server"); - - _host = host; + _host = host ?? throw new ArgumentNullException(nameof(host), "Requires a 'IHost' instance to start/stop the test API server"); _options = options; _logger = logger; @@ -48,8 +46,15 @@ protected TestApiServer(IHost host, TestApiServerOptions options, ILogger logger /// Thrown when the or is null. public static async Task StartNewAsync(TestApiServerOptions options, ILogger logger) { - Guard.NotNull(options, nameof(options), "Requires a set of configurable options to control the behavior of the test API server"); - Guard.NotNull(logger, nameof(logger), "Requires a logger instance to write diagnostic messages during the lifetime of the test API server"); + if (options is null) + { + throw new ArgumentNullException(nameof(options), "Requires a set of configurable options to control the behavior of the test API server"); + } + + if (logger is null) + { + throw new ArgumentNullException(nameof(logger), "Requires a logger instance to write diagnostic messages during the lifetime of the test API server"); + } IHostBuilder builder = Host.CreateDefaultBuilder(); options.ApplyOptions(builder); @@ -88,7 +93,10 @@ public static async Task StartNewAsync(TestApiServerOptions optio /// Thrown when the is null. public async Task SendAsync(HttpRequestBuilder builder) { - Guard.NotNull(builder, nameof(builder), "Requires a HTTP request builder instance to create a HTTP request to the test API server"); + if (builder is null) + { + throw new ArgumentNullException(nameof(builder), "Requires a HTTP request builder instance to create a HTTP request to the test API server"); + } HttpRequestMessage request = builder.Build(_options.Url); diff --git a/src/Arcus.WebApi.Tests.Integration/Fixture/TestApiServerOptions.cs b/src/Arcus.WebApi.Tests.Integration/Fixture/TestApiServerOptions.cs index 4172b1ec..080f4264 100644 --- a/src/Arcus.WebApi.Tests.Integration/Fixture/TestApiServerOptions.cs +++ b/src/Arcus.WebApi.Tests.Integration/Fixture/TestApiServerOptions.cs @@ -3,7 +3,6 @@ using System.Collections.ObjectModel; using System.Linq; using Bogus; -using GuardNet; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Azure.Functions.Worker; @@ -47,7 +46,10 @@ public TestApiServerOptions() /// Thrown when the is null. public TestApiServerOptions ConfigureServices(Action configureServices) { - Guard.NotNull(configureServices, nameof(configureServices), "Requires a function to configure the dependency services on the test API server"); + if (configureServices is null) + { + throw new ArgumentNullException(nameof(configureServices), "Requires a function to configure the dependency services on the test API server"); + } _configureServices.Add(configureServices); return this; @@ -64,7 +66,10 @@ public TestApiServerOptions ConfigureServices(Action configu /// Thrown when the is null. public TestApiServerOptions PreConfigure(Action configure) { - Guard.NotNull(configure, nameof(configure), "Requires a function to configure the application on the test API server"); + if (configure is null) + { + throw new ArgumentNullException(nameof(configure), "Requires a function to configure the application on the test API server"); + } _preconfigures.Add(configure); return this; @@ -81,7 +86,10 @@ public TestApiServerOptions PreConfigure(Action configure) /// Thrown when the is null. public TestApiServerOptions Configure(Action configure) { - Guard.NotNull(configure, nameof(configure), "Requires a function to configure the application on the test API server"); + if (configure is null) + { + throw new ArgumentNullException(nameof(configure), "Requires a function to configure the application on the test API server"); + } _configures.Add(configure); return this; @@ -95,7 +103,10 @@ public TestApiServerOptions Configure(Action configure) /// Thrown when the is null. public TestApiServerOptions ConfigureHost(Action configure) { - Guard.NotNull(configure, nameof(configure), "Requires a function to configure the hosting configuration of the test API server"); + if (configure is null) + { + throw new ArgumentNullException(nameof(configure), "Requires a function to configure the hosting configuration of the test API server"); + } _hostingConfigures.Add(configure); return this; @@ -109,7 +120,11 @@ public TestApiServerOptions ConfigureHost(Action configure) /// Thrown when the is null. public TestApiServerOptions ConfigureAppConfiguration(Action configure) { - Guard.NotNull(configure, nameof(configure), "Requires a function to configure the application configuration of the test API server"); + if (configure is null) + { + throw new ArgumentNullException(nameof(configure), "Requires a function to configure the application configuration of the test API server"); + } + _appConfigures.Add(configure); return this; diff --git a/src/Arcus.WebApi.Tests.Integration/Fixture/TestConfig.cs b/src/Arcus.WebApi.Tests.Integration/Fixture/TestConfig.cs index 658cb152..aec8db4a 100644 --- a/src/Arcus.WebApi.Tests.Integration/Fixture/TestConfig.cs +++ b/src/Arcus.WebApi.Tests.Integration/Fixture/TestConfig.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using GuardNet; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Primitives; @@ -15,7 +14,11 @@ public class TestConfig : IConfigurationRoot private TestConfig(IConfigurationRoot config) { - Guard.NotNull(config, nameof(config)); + if (config is null) + { + throw new ArgumentNullException(nameof(config)); + } + _config = config; } diff --git a/src/Arcus.WebApi.Tests.Integration/Logging/Fixture/HttpAssert.cs b/src/Arcus.WebApi.Tests.Integration/Logging/Fixture/HttpAssert.cs index 6584cdf0..c07485c0 100644 --- a/src/Arcus.WebApi.Tests.Integration/Logging/Fixture/HttpAssert.cs +++ b/src/Arcus.WebApi.Tests.Integration/Logging/Fixture/HttpAssert.cs @@ -1,5 +1,4 @@ using System; -using GuardNet; using Microsoft.AspNetCore.Http; namespace Arcus.WebApi.Tests.Integration.Logging.Fixture @@ -13,7 +12,11 @@ public class HttpAssert private HttpAssert(Action assertion) { - Guard.NotNull(assertion, nameof(assertion), "Requires an assertion function to verify a HTTP context"); + if (assertion is null) + { + throw new ArgumentNullException(nameof(assertion), "Requires an assertion function to verify a HTTP context"); + } + _assertion = assertion; } @@ -24,7 +27,11 @@ private HttpAssert(Action assertion) /// Thrown when the is null. public static HttpAssert Create(Action assertion) { - Guard.NotNull(assertion, nameof(assertion), "Requires an assertion function to verify a HTTP context"); + if (assertion is null) + { + throw new ArgumentNullException(nameof(assertion), "Requires an assertion function to verify a HTTP context"); + } + return new HttpAssert(assertion); } @@ -35,7 +42,11 @@ public static HttpAssert Create(Action assertion) /// Thrown when the is null. public void Assert(HttpContext context) { - Guard.NotNull(context, nameof(context), "Requires a HTTP context to run an assertion function on it"); + if (context is null) + { + throw new ArgumentNullException(nameof(context), "Requires a HTTP context to run an assertion function to it"); + } + _assertion(context); } } diff --git a/src/Arcus.WebApi.Tests.Integration/Logging/Fixture/HttpAssertProvider.cs b/src/Arcus.WebApi.Tests.Integration/Logging/Fixture/HttpAssertProvider.cs index 73abd8fe..0120b499 100644 --- a/src/Arcus.WebApi.Tests.Integration/Logging/Fixture/HttpAssertProvider.cs +++ b/src/Arcus.WebApi.Tests.Integration/Logging/Fixture/HttpAssertProvider.cs @@ -1,7 +1,7 @@ -using System; +using Microsoft.AspNetCore.Mvc.ViewFeatures; +using System; using System.Collections.Generic; using System.Linq; -using GuardNet; using Xunit; using Xunit.Sdk; @@ -22,11 +22,20 @@ public class HttpAssertProvider /// Thrown when the contains null elements or has duplicate names. public HttpAssertProvider(IEnumerable> namedAssertions) { - Guard.NotNull(namedAssertions, nameof(namedAssertions), "Requires a series of named HTTP assertions to setup the HTTP assertion provider"); - Guard.For(() => namedAssertions.Any(item => item is null), - new ArgumentException("Requires a series of named HTTP assertions without any 'null' elements to setup the HTTP assertion provider", nameof(namedAssertions))); - Guard.For(() => namedAssertions.GroupBy(item => item.Item1).All(group => group.Count() != 1), - new ArgumentException("Requires a series of named HTTP assertions with unique names to setup the HTTP assertion provider", nameof(namedAssertions))); + if (namedAssertions is null) + { + throw new ArgumentNullException(nameof(namedAssertions), "Requires a series of named HTTP assertions to setup the HTTP assertion provider"); + } + + if (namedAssertions.Any(item => item is null)) + { + throw new ArgumentException("Requires a series of named HTTP assertions without any 'null' elements to setup the HTTP assertion provider", nameof(namedAssertions)); + } + + if (namedAssertions.GroupBy(item => item.Item1).All(group => group.Count() != 1)) + { + throw new ArgumentException("Requires a series of named HTTP assertions with unique names to setup the HTTP assertion provider", nameof(namedAssertions)); + } _namedAssertions = namedAssertions.ToArray(); } @@ -39,7 +48,11 @@ public HttpAssertProvider(IEnumerable> namedAssertions /// Thrown when more than one was registered under the given . public HttpAssert GetAssertion(string name) { - Guard.NotNullOrWhitespace(name, nameof(name), "Requires a non-blank name to retrieve the HTTP assertion"); + if (string.IsNullOrWhiteSpace(name)) + { + throw new ArgumentException("Requires a non-blank name to retrieve the HTTP assertion", nameof(name)); + } + return Assert.Single(_namedAssertions, item => item.Item1 == name).Item2; } } diff --git a/src/Arcus.WebApi.Tests.Integration/Logging/Fixture/HttpAssertServiceCollectionExtensions.cs b/src/Arcus.WebApi.Tests.Integration/Logging/Fixture/HttpAssertServiceCollectionExtensions.cs index 90f6da5d..b91eb137 100644 --- a/src/Arcus.WebApi.Tests.Integration/Logging/Fixture/HttpAssertServiceCollectionExtensions.cs +++ b/src/Arcus.WebApi.Tests.Integration/Logging/Fixture/HttpAssertServiceCollectionExtensions.cs @@ -1,5 +1,4 @@ using System; -using GuardNet; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; @@ -22,9 +21,20 @@ public static class HttpAssertServiceCollectionExtensions /// Thrown when the is blank. public static IServiceCollection AddHttpAssert(this IServiceCollection services, string name, Action assertion) { - Guard.NotNull(services, nameof(services), "Requires a set of services to add the HTTP assertion to"); - Guard.NotNullOrWhitespace(name, nameof(name), "Requires a non-blank name to register the HTTP assertion"); - Guard.NotNull(assertion, nameof(assertion), "Requires an assertion function to verify the currently available HTTP context"); + if (services is null) + { + throw new ArgumentNullException(nameof(services), "Requires a set of services to add the HTTP assertion to"); + } + + if (string.IsNullOrWhiteSpace(name)) + { + throw new ArgumentException("Requires a non-blank name to register the HTTP assertion", nameof(name)); + } + + if (assertion is null) + { + throw new ArgumentNullException(nameof(assertion), "Requires an assertion function to verify the currently available HTTP context"); + } services.TryAddSingleton(); return services.AddSingleton(Tuple.Create(name, HttpAssert.Create(assertion))); diff --git a/src/Arcus.WebApi.Tests.Integration/Logging/Fixture/TraceIdentifierMiddleware.cs b/src/Arcus.WebApi.Tests.Integration/Logging/Fixture/TraceIdentifierMiddleware.cs index f3f3d17d..e93cd501 100644 --- a/src/Arcus.WebApi.Tests.Integration/Logging/Fixture/TraceIdentifierMiddleware.cs +++ b/src/Arcus.WebApi.Tests.Integration/Logging/Fixture/TraceIdentifierMiddleware.cs @@ -1,6 +1,5 @@ using System; using System.Threading.Tasks; -using GuardNet; using Microsoft.AspNetCore.Http; namespace Arcus.WebApi.Tests.Integration.Logging.Fixture @@ -20,11 +19,8 @@ public TraceIdentifierMiddleware( RequestDelegate next, TraceIdentifierOptions options) { - _next = next; - Guard.NotNull(next, nameof(next), "Requires a continuation delegate"); - Guard.NotNull(options, nameof(options), $"Requires a non-null '{nameof(TraceIdentifierOptions)}' options"); - - _options = options; + _next = next ?? throw new ArgumentNullException(nameof(next), "Requires a continuation delegate"); + _options = options ?? throw new ArgumentNullException(nameof(options), $"Requires a non-null '{nameof(TraceIdentifierOptions)}' options instance"); } /// Request handling method. diff --git a/src/Arcus.WebApi.Tests.Integration/Security/Authentication/Fixture/CertificateConfiguration.cs b/src/Arcus.WebApi.Tests.Integration/Security/Authentication/Fixture/CertificateConfiguration.cs index ba13080c..ab0850e9 100644 --- a/src/Arcus.WebApi.Tests.Integration/Security/Authentication/Fixture/CertificateConfiguration.cs +++ b/src/Arcus.WebApi.Tests.Integration/Security/Authentication/Fixture/CertificateConfiguration.cs @@ -1,7 +1,6 @@ using System; using System.Security.Cryptography.X509Certificates; using Arcus.WebApi.Tests.Integration.Fixture; -using GuardNet; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; @@ -21,9 +20,7 @@ internal class CertificateConfiguration : IStartupFilter /// When the is null. public CertificateConfiguration(X509Certificate2 clientCertificate) { - Guard.NotNull(clientCertificate, nameof(clientCertificate)); - - _clientCertificate = clientCertificate; + _clientCertificate = clientCertificate ?? throw new ArgumentNullException(nameof(clientCertificate)); } /// diff --git a/src/Arcus.WebApi.Tests.Integration/Security/Authentication/Fixture/SelfSignedCertificate.cs b/src/Arcus.WebApi.Tests.Integration/Security/Authentication/Fixture/SelfSignedCertificate.cs index d79f14cc..9605d780 100644 --- a/src/Arcus.WebApi.Tests.Integration/Security/Authentication/Fixture/SelfSignedCertificate.cs +++ b/src/Arcus.WebApi.Tests.Integration/Security/Authentication/Fixture/SelfSignedCertificate.cs @@ -1,7 +1,6 @@ using System; using System.IO; using System.Security.Cryptography.X509Certificates; -using GuardNet; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Generators; @@ -36,7 +35,10 @@ public static X509Certificate2 Create() /// When the is null. public static X509Certificate2 CreateWithSubject(string subjectName) { - Guard.NotNullOrWhitespace(subjectName, nameof(subjectName), "Subject name should not be blank"); + if (string.IsNullOrWhiteSpace(subjectName)) + { + throw new ArgumentException("Subject name should not be blank", nameof(subjectName)); + } return CreateWithIssuerAndSubjectName("TestCA", subjectName); } @@ -50,8 +52,15 @@ public static X509Certificate2 CreateWithSubject(string subjectName) /// When the is null. public static X509Certificate2 CreateWithIssuerAndSubjectName(string issuerName, string subjectName) { - Guard.NotNullOrWhitespace(subjectName, nameof(subjectName), "Subject name should not be blank"); - Guard.NotNullOrWhitespace(issuerName, nameof(issuerName), "Issuer name should not be blank"); + if (string.IsNullOrWhiteSpace(subjectName)) + { + throw new ArgumentException("Subject name should not be blank", nameof(subjectName)); + } + + if (string.IsNullOrWhiteSpace(issuerName)) + { + throw new ArgumentException("Issuer name should not be blank", nameof(issuerName)); + } issuerName = issuerName.StartsWith("CN=") ? issuerName : "CN=" + issuerName; subjectName = subjectName.StartsWith("CN=") ? subjectName : "CN=" + subjectName; diff --git a/src/Arcus.WebApi.Tests.Runtimes.AzureFunction.Isolated/HttpTriggerFunction.cs b/src/Arcus.WebApi.Tests.Runtimes.AzureFunction.Isolated/HttpTriggerFunction.cs index ee26a47b..49cfee07 100644 --- a/src/Arcus.WebApi.Tests.Runtimes.AzureFunction.Isolated/HttpTriggerFunction.cs +++ b/src/Arcus.WebApi.Tests.Runtimes.AzureFunction.Isolated/HttpTriggerFunction.cs @@ -2,7 +2,6 @@ using Arcus.Observability.Correlation; using Arcus.WebApi.Logging.Core.Correlation; using Azure.Core.Serialization; -using GuardNet; using Microsoft.Azure.Functions.Worker; using Microsoft.Azure.Functions.Worker.Http; using Microsoft.Extensions.Logging; @@ -20,11 +19,8 @@ public HttpTriggerFunction( JsonObjectSerializer serializer, ILoggerFactory loggerFactory) { - Guard.NotNull(correlationAccessor, nameof(correlationAccessor)); - Guard.NotNull(serializer, nameof(serializer)); - - _correlationAccessor = correlationAccessor; - _serializer = serializer; + _correlationAccessor = correlationAccessor ?? throw new ArgumentNullException(nameof(correlationAccessor)); + _serializer = serializer ?? throw new ArgumentNullException(nameof(serializer)); _logger = loggerFactory.CreateLogger(); } diff --git a/src/Arcus.WebApi.Tests.Unit/Logging/Fixture/DefaultHttpMessageHandlerBuilder.cs b/src/Arcus.WebApi.Tests.Unit/Logging/Fixture/DefaultHttpMessageHandlerBuilder.cs index 54dc583e..ceba14ac 100644 --- a/src/Arcus.WebApi.Tests.Unit/Logging/Fixture/DefaultHttpMessageHandlerBuilder.cs +++ b/src/Arcus.WebApi.Tests.Unit/Logging/Fixture/DefaultHttpMessageHandlerBuilder.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Net.Http; -using GuardNet; using Microsoft.Extensions.Http; namespace Arcus.WebApi.Tests.Unit.Logging.Fixture @@ -18,8 +17,7 @@ public class DefaultHttpMessageHandlerBuilder : HttpMessageHandlerBuilder /// Thrown when the is null. public DefaultHttpMessageHandlerBuilder(IServiceProvider provider) { - Guard.NotNull(provider, nameof(provider), "Requires a service provider to retrieve the available application services when registering HTTP message handlers"); - Services = provider; + Services = provider ?? throw new ArgumentNullException(nameof(provider), "Requires a service provider to retrieve the available application services when registering HTTP message handlers"); } ///