Skip to content

Commit

Permalink
ported domaindrivendev#2842 filter illegar header fields.
Browse files Browse the repository at this point in the history
  • Loading branch information
Havunen committed May 5, 2024
1 parent 6038bdb commit 96912e1
Show file tree
Hide file tree
Showing 6 changed files with 183 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
Expand All @@ -7,11 +8,19 @@
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Net.Http.Headers;

namespace DotSwashbuckle.AspNetCore.SwaggerGen
{
public static class ApiParameterDescriptionExtensions
{
private static readonly HashSet<string> IllegalHeaderParameters = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
HeaderNames.Accept,
HeaderNames.Authorization,
HeaderNames.ContentType
};

public static bool IsRequiredParameter(this ApiParameterDescription apiParameter)
{
// From the OpenAPI spec:
Expand Down Expand Up @@ -96,5 +105,12 @@ internal static bool IsFromForm(this ApiParameterDescription apiParameter)
return source == BindingSource.Form || source == BindingSource.FormFile
|| (elementType != null && typeof(IFormFile).IsAssignableFrom(elementType));
}

internal static bool IsIllegalHeaderParameter(this ApiParameterDescription apiParameter)
{
// Certain header parameters are not allowed and should be described using the corresponding OpenAPI keywords
// https://swagger.io/docs/specification/describing-parameters/#header-parameters
return apiParameter.Source == BindingSource.Header && IllegalHeaderParameters.Contains(apiParameter.Name);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ private OpenApiOperation GenerateOpenApiOperationFromMetadata(ApiDescription api
// Schemas will be generated via DotSwashbuckle by default.
foreach (var parameter in operation.Parameters)
{
var apiParameter = apiDescription.ParameterDescriptions.SingleOrDefault(desc => desc.Name == parameter.Name && !desc.IsFromBody() && !desc.IsFromForm());
var apiParameter = apiDescription.ParameterDescriptions.SingleOrDefault(desc => desc.Name == parameter.Name && !desc.IsFromBody() && !desc.IsFromForm() && !desc.IsIllegalHeaderParameter());
if (apiParameter is not null)
{
var propInfo = apiParameter.PropertyInfo();
Expand Down Expand Up @@ -392,7 +392,8 @@ private IList<OpenApiParameter> GenerateParameters(ApiDescription apiDescription
{
return !apiParam.IsFromBody() && !apiParam.IsFromForm()
&& !apiParam.CustomAttributes().OfType<BindNeverAttribute>().Any()
&& (apiParam.ModelMetadata == null || apiParam.ModelMetadata.IsBindingAllowed);
&& (apiParam.ModelMetadata == null || apiParam.ModelMetadata.IsBindingAllowed)
&& !apiParam.IsIllegalHeaderParameter(); ;
});

return applicableApiParameters
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1759,6 +1759,28 @@
"x-purpose": "test"
}
},
"/country/validate": {
"get": {
"tags": [
"FromHeaderParams"
],
"parameters": [
{
"name": "country",
"in": "query",
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "Success"
}
},
"x-purpose": "test"
}
},
"/addresses/validate": {
"get": {
"tags": [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,15 @@ public void ActionWithParameterWithCustomRequiredAttribute([CustomRequiredAttrib
public void ActionWithParameterWithBindRequiredAttribute([BindRequired]string param)
{ }

public void ActionWithAcceptFromHeaderParameter([FromHeader] string accept, string param)
{ }

public void ActionWithContentTypeFromHeaderParameter([FromHeader(Name = "Content-Type")] string contentType, string param)
{ }

public void ActionWithAuthorizationFromHeaderParameter([FromHeader] string authorization, string param)
{ }

public void ActionWithIntParameter(int param)
{ }

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.Json;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
Expand All @@ -14,6 +15,7 @@
using Xunit;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata;
using Microsoft.Extensions.Options;

Expand Down Expand Up @@ -90,6 +92,118 @@ public void GetSwagger_GeneratesSwaggerDocument_ForApiDescriptionsWithConstraine
Assert.Equal(expectedPath, actualPath);
}

[Theory]
[InlineData(nameof(FakeController.ActionWithAcceptFromHeaderParameter))]
[InlineData(nameof(FakeController.ActionWithContentTypeFromHeaderParameter))]
[InlineData(nameof(FakeController.ActionWithAuthorizationFromHeaderParameter))]
public void GetSwagger_IgnoresParameters_IfActionParameterIsIllegalHeaderParameter(string action)
{
var illegalParameter = typeof(FakeController).GetMethod(action).GetParameters()[0];
var fromHeaderAttribute = illegalParameter.GetCustomAttribute<FromHeaderAttribute>();

var subject = Subject(
new[]
{
ApiDescriptionFactory.Create<FakeController>(
c => action,
groupName: "v1",
httpMethod: "GET",
relativePath: "resource",
parameterDescriptions: new[]
{
new ApiParameterDescription
{
Name = fromHeaderAttribute?.Name ?? illegalParameter.Name,
Source = BindingSource.Header,
ModelMetadata = ModelMetadataFactory.CreateForParameter(illegalParameter)
},
new ApiParameterDescription
{
Name = "param",
Source = BindingSource.Header
}
}
)
}
);

var document = subject.GetSwagger("v1");

var operation = document.Paths["/resource"].Operations[OperationType.Get];
var parameter = Assert.Single(operation.Parameters);
Assert.Equal("param", parameter.Name);
}

[Theory]
[InlineData(nameof(FakeController.ActionWithAcceptFromHeaderParameter))]
[InlineData(nameof(FakeController.ActionWithContentTypeFromHeaderParameter))]
[InlineData(nameof(FakeController.ActionWithAuthorizationFromHeaderParameter))]
public void GetSwagger_GenerateParametersSchemas_IfActionParameterIsIllegalHeaderParameterWithProvidedOpenApiOperation(string action)
{
var illegalParameter = typeof(FakeController).GetMethod(action).GetParameters()[0];
var fromHeaderAttribute = illegalParameter.GetCustomAttribute<FromHeaderAttribute>();
var illegalParameterName = fromHeaderAttribute?.Name ?? illegalParameter.Name;
var methodInfo = typeof(FakeController).GetMethod(action);
var actionDescriptor = new ActionDescriptor
{
EndpointMetadata = new List<object>()
{
new OpenApiOperation
{
OperationId = "OperationIdSetInMetadata",
Parameters = new List<OpenApiParameter>()
{
new OpenApiParameter
{
Name = illegalParameterName,
},
new OpenApiParameter
{
Name = "param",
}
}
}
},
RouteValues = new Dictionary<string, string>
{
["controller"] = methodInfo.DeclaringType.Name.Replace("Controller", string.Empty)
}
};
var subject = Subject(
apiDescriptions: new[]
{
ApiDescriptionFactory.Create(
actionDescriptor,
methodInfo,
groupName: "v1",
httpMethod: "GET",
relativePath: "resource",
parameterDescriptions: new[]
{
new ApiParameterDescription
{
Name = illegalParameterName,
Source = BindingSource.Header,
ModelMetadata = ModelMetadataFactory.CreateForParameter(illegalParameter)
},
new ApiParameterDescription
{
Name = "param",
Source = BindingSource.Header,
ModelMetadata = ModelMetadataFactory.CreateForType(typeof(string))
}
}),
}
);

var document = subject.GetSwagger("v1");

var operation = document.Paths["/resource"].Operations[OperationType.Get];
Assert.Null(operation.Parameters.Single(p => p.Name == illegalParameterName).Schema);
Assert.NotNull(operation.Parameters.Single(p => p.Name == "param").Schema);
}


[Fact]
public void GetSwagger_SetsOperationIdToNull_ByDefault()
{
Expand Down
18 changes: 18 additions & 0 deletions test/WebSites/Basic/Controllers/FormHeaderParamsController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using Microsoft.AspNetCore.Mvc;

namespace Basic.Controllers
{
[Produces("application/json")]
public class FromHeaderParamsController
{
[HttpGet("country/validate")]
public IActionResult Get(
[FromHeader] string accept,
[FromHeader(Name = "Content-Type")] string contentType,
[FromHeader] string authorization,
[FromQuery] string country)
{
return new NoContentResult();
}
}
}

0 comments on commit 96912e1

Please sign in to comment.