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

Change OpenAPI document name resolution to be case-insensitive #59199

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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -30,16 +30,22 @@ public static IEndpointConventionBuilder MapOpenApi(this IEndpointRouteBuilder e
var options = endpoints.ServiceProvider.GetRequiredService<IOptionsMonitor<OpenApiOptions>>();
return endpoints.MapGet(pattern, async (HttpContext context, string documentName = OpenApiConstants.DefaultDocumentName) =>
{
// We need to retrieve the document name in a case-insensitive manner
// to support case-insensitive document name resolution.
// Keyed Services are case-sensitive by default, which doesn't work well for document names in ASP.NET Core
// as routing in ASP.NET Core is case-insensitive by default.
var lowercasedDocumentName = documentName.ToLowerInvariant();

// It would be ideal to use the `HttpResponseStreamWriter` to
// asynchronously write to the response stream here but Microsoft.OpenApi
// does not yet support async APIs on their writers.
// See https://github.com/microsoft/OpenAPI.NET/issues/421 for more info.
var documentService = context.RequestServices.GetKeyedService<OpenApiDocumentService>(documentName);
var documentService = context.RequestServices.GetKeyedService<OpenApiDocumentService>(lowercasedDocumentName);
if (documentService is null)
{
context.Response.StatusCode = StatusCodes.Status404NotFound;
context.Response.ContentType = "text/plain;charset=utf-8";
await context.Response.WriteAsync($"No OpenAPI document with the name '{documentName}' was found.");
await context.Response.WriteAsync($"No OpenAPI document with the name '{lowercasedDocumentName}' was found.");
}
else
{
Expand Down
43 changes: 25 additions & 18 deletions src/OpenApi/src/Extensions/OpenApiServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,13 +57,35 @@ public static IServiceCollection AddOpenApi(this IServiceCollection services, st
ArgumentNullException.ThrowIfNull(services);
ArgumentNullException.ThrowIfNull(configureOptions);

services.AddOpenApiCore(documentName);
services.Configure<OpenApiOptions>(documentName, options =>
// We need to store the document name in a case-insensitive manner
// to support case-insensitive document name resolution.
// Keyed Services are case-sensitive by default, which doesn't work well for document names in ASP.NET Core
// as routing in ASP.NET Core is case-insensitive by default.
var lowercasedDocumentName = documentName.ToLowerInvariant();

AddOpenApiCore(services, lowercasedDocumentName);
services.Configure<OpenApiOptions>(lowercasedDocumentName, options =>
{
options.DocumentName = documentName;
options.DocumentName = lowercasedDocumentName;
configureOptions(options);
});
return services;

// The reason this method is a local function is to prevent case-sensitive document names being passed into this method (from other methods) in the future.
sander1095 marked this conversation as resolved.
Show resolved Hide resolved
static IServiceCollection AddOpenApiCore(IServiceCollection services, string documentName)
{
services.AddEndpointsApiExplorer();
services.AddKeyedSingleton<OpenApiSchemaService>(documentName);
services.AddKeyedSingleton<OpenApiSchemaStore>(documentName);
services.AddKeyedSingleton<OpenApiDocumentService>(documentName);
// Required for build-time generation
services.AddSingleton<IDocumentProvider, OpenApiDocumentProvider>();
// Required to resolve document names for build-time generation
services.AddSingleton(new NamedService<OpenApiDocumentService>(documentName));
// Required to support JSON serializations
services.TryAddEnumerable(ServiceDescriptor.Singleton<IConfigureOptions<JsonOptions>, OpenApiSchemaJsonOptions>());
return services;
}
}

/// <summary>
Expand Down Expand Up @@ -99,19 +121,4 @@ public static IServiceCollection AddOpenApi(this IServiceCollection services, Ac
/// </example>
public static IServiceCollection AddOpenApi(this IServiceCollection services)
=> services.AddOpenApi(OpenApiConstants.DefaultDocumentName);

private static IServiceCollection AddOpenApiCore(this IServiceCollection services, string documentName)
{
services.AddEndpointsApiExplorer();
services.AddKeyedSingleton<OpenApiSchemaService>(documentName);
services.AddKeyedSingleton<OpenApiSchemaStore>(documentName);
services.AddKeyedSingleton<OpenApiDocumentService>(documentName);
// Required for build-time generation
services.AddSingleton<IDocumentProvider, OpenApiDocumentProvider>();
// Required to resolve document names for build-time generation
services.AddSingleton(new NamedService<OpenApiDocumentService>(documentName));
// Required to support JSON serializations
services.TryAddEnumerable(ServiceDescriptor.Singleton<IConfigureOptions<JsonOptions>, OpenApiSchemaJsonOptions>());
return services;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public async Task MapOpenApi_ReturnsRenderedDocument()
context.Response.Body = responseBodyStream;
context.RequestServices = serviceProvider;
context.Request.RouteValues.Add("documentName", "v1");
var endpoint = builder.DataSources.First().Endpoints.First();
var endpoint = builder.DataSources.First().Endpoints[0];
captainsafia marked this conversation as resolved.
Show resolved Hide resolved

// Act
var requestDelegate = endpoint.RequestDelegate;
Expand Down Expand Up @@ -89,7 +89,7 @@ public async Task MapOpenApi_ReturnsDefaultDocumentIfNoNameProvided(string expec
var responseBodyStream = new MemoryStream();
context.Response.Body = responseBodyStream;
context.RequestServices = serviceProvider;
var endpoint = builder.DataSources.First().Endpoints.First();
var endpoint = builder.DataSources.First().Endpoints[0];

// Act
var requestDelegate = endpoint.RequestDelegate;
Expand Down Expand Up @@ -121,7 +121,7 @@ public async Task MapOpenApi_Returns404ForUnresolvedDocument()
context.Response.Body = responseBodyStream;
context.RequestServices = serviceProvider;
context.Request.RouteValues.Add("documentName", "v2");
var endpoint = builder.DataSources.First().Endpoints.First();
var endpoint = builder.DataSources.First().Endpoints[0];

// Act
var requestDelegate = endpoint.RequestDelegate;
Expand All @@ -132,6 +132,30 @@ public async Task MapOpenApi_Returns404ForUnresolvedDocument()
Assert.Equal("No OpenAPI document with the name 'v2' was found.", Encoding.UTF8.GetString(responseBodyStream.ToArray()));
}

[Theory]
[InlineData("CaseSensitive", "casesensitive")]
[InlineData("casesensitive", "CaseSensitive")]
public async Task MapOpenApi_ReturnsDocumentWhenPathIsCaseSensitive(string registeredDocumentName, string requestedDocumentName)
{
// Arrange
var serviceProvider = CreateServiceProvider(registeredDocumentName);
var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(serviceProvider));
builder.MapOpenApi("/openapi/{documentName}.json");
var context = new DefaultHttpContext();
var responseBodyStream = new MemoryStream();
context.Response.Body = responseBodyStream;
context.RequestServices = serviceProvider;
context.Request.RouteValues.Add("documentName", requestedDocumentName);
var endpoint = builder.DataSources.First().Endpoints[0];

// Act
var requestDelegate = endpoint.RequestDelegate;
await requestDelegate(context);

// Assert
Assert.Equal(StatusCodes.Status200OK, context.Response.StatusCode);
}

[Theory]
[InlineData("/openapi.json", "application/json;charset=utf-8", false)]
[InlineData("/openapi.yaml", "text/plain+yaml;charset=utf-8", true)]
Expand All @@ -150,7 +174,7 @@ public async Task MapOpenApi_ReturnsDocumentIfNameProvidedInQuery(string expecte
context.Response.Body = responseBodyStream;
context.RequestServices = serviceProvider;
context.Request.QueryString = new QueryString($"?documentName={documentName}");
var endpoint = builder.DataSources.First().Endpoints.First();
var endpoint = builder.DataSources.First().Endpoints[0];

// Act
var requestDelegate = endpoint.RequestDelegate;
Expand Down
Loading