Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Filter illegal header fields #2842

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
martincostello marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Net.Http.Headers;

namespace Swashbuckle.AspNetCore.SwaggerGen
{
Expand All @@ -21,6 +22,13 @@ public static class ApiParameterDescriptionExtensions
#endif
};

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 @@ -111,5 +119,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 @@ -269,7 +269,7 @@ private OpenApiOperation GenerateOpenApiOperationFromMetadata(ApiDescription api
// Schemas will be generated via Swashbuckle 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)
{
parameter.Schema = GenerateSchema(
Expand Down Expand Up @@ -342,7 +342,8 @@ private IList<OpenApiParameter> GenerateParameters(ApiDescription apiDescription
return (!apiParam.IsFromBody() && !apiParam.IsFromForm())
&& (!apiParam.CustomAttributes().OfType<BindNeverAttribute>().Any())
&& (!apiParam.CustomAttributes().OfType<SwaggerIgnoreAttribute>().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 @@ -54,6 +54,15 @@ public void ActionWithIntParameterWithRequiredAttribute([Required]int param)
public void ActionWithIntParameterWithSwaggerIgnoreAttribute([SwaggerIgnore] int 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 ActionWithObjectParameter(XmlAnnotatedType param)
{ }

Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using System.Reflection;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
Expand Down Expand Up @@ -502,6 +504,117 @@ public void GetSwagger_IgnoresParameters_IfActionParameterHasSwaggerIgnoreAttrib
Assert.Empty(operation.Parameters);
}

[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_SetsParameterRequired_IfApiParameterIsBoundToPath()
{
Expand Down
18 changes: 18 additions & 0 deletions test/WebSites/Basic/Controllers/FromHeaderParamsController.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();
}
}
}