Skip to content

Add logging for OpenAPI schema default value type mismatches #63027

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

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all 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
22 changes: 17 additions & 5 deletions src/OpenApi/src/Extensions/JsonNodeSchemaExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Routing.Constraints;
using Microsoft.Extensions.Logging;

namespace Microsoft.AspNetCore.OpenApi;

Expand Down Expand Up @@ -170,7 +171,8 @@ internal static void ApplyValidationAttributes(this JsonNode schema, IEnumerable
/// <param name="schema">The <see cref="JsonNode"/> produced by the underlying schema generator.</param>
/// <param name="defaultValue">An object representing the <see cref="object"/> associated with the default value.</param>
/// <param name="jsonTypeInfo">The <see cref="JsonTypeInfo"/> associated with the target type.</param>
internal static void ApplyDefaultValue(this JsonNode schema, object? defaultValue, JsonTypeInfo? jsonTypeInfo)
/// <param name="logger">The logger to use for warning messages when default value type mismatches occur.</param>
internal static void ApplyDefaultValue(this JsonNode schema, object? defaultValue, JsonTypeInfo? jsonTypeInfo, ILogger? logger = null)
{
if (jsonTypeInfo is null)
{
Expand All @@ -183,7 +185,16 @@ internal static void ApplyDefaultValue(this JsonNode schema, object? defaultValu
}
else
{
schema[OpenApiSchemaKeywords.DefaultKeyword] = JsonSerializer.SerializeToNode(defaultValue, jsonTypeInfo);
try
{
schema[OpenApiSchemaKeywords.DefaultKeyword] = JsonSerializer.SerializeToNode(defaultValue, jsonTypeInfo);
}
catch (Exception ex) when (ex is InvalidCastException or NotSupportedException or InvalidOperationException)
{
// Log warning when there's a type mismatch that prevents serialization
logger?.DefaultValueTypeMismatch(defaultValue.GetType().Name, jsonTypeInfo.Type.Name);
// Do not apply the default value when there's a type mismatch
}
}
}

Expand Down Expand Up @@ -305,7 +316,8 @@ internal static void ApplyRouteConstraints(this JsonNode schema, IEnumerable<IRo
/// <param name="schema">The <see cref="JsonNode"/> produced by the underlying schema generator.</param>
/// <param name="parameterDescription">The <see cref="ApiParameterDescription"/> associated with the <see paramref="schema"/>.</param>
/// <param name="jsonTypeInfo">The <see cref="JsonTypeInfo"/> associated with the <see paramref="schema"/>.</param>
internal static void ApplyParameterInfo(this JsonNode schema, ApiParameterDescription parameterDescription, JsonTypeInfo? jsonTypeInfo)
/// <param name="logger">The logger to use for warning messages when default value type mismatches occur.</param>
internal static void ApplyParameterInfo(this JsonNode schema, ApiParameterDescription parameterDescription, JsonTypeInfo? jsonTypeInfo, ILogger? logger = null)
{
// This is special handling for parameters that are not bound from the body but represented in a complex type.
// For example:
Expand Down Expand Up @@ -338,11 +350,11 @@ internal static void ApplyParameterInfo(this JsonNode schema, ApiParameterDescri
{
if (parameterInfo.HasDefaultValue)
{
schema.ApplyDefaultValue(parameterInfo.DefaultValue, jsonTypeInfo);
schema.ApplyDefaultValue(parameterInfo.DefaultValue, jsonTypeInfo, logger);
}
else if (parameterInfo.GetCustomAttributes<DefaultValueAttribute>().LastOrDefault() is { } defaultValueAttribute)
{
schema.ApplyDefaultValue(defaultValueAttribute.Value, jsonTypeInfo);
schema.ApplyDefaultValue(defaultValueAttribute.Value, jsonTypeInfo, logger);
}

if (parameterInfo.GetCustomAttributes<ValidationAttribute>() is { } validationAttributes)
Expand Down
12 changes: 12 additions & 0 deletions src/OpenApi/src/Extensions/OpenApiLoggingExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.Extensions.Logging;

namespace Microsoft.AspNetCore.OpenApi;

internal static partial class OpenApiLoggingExtensions
{
[LoggerMessage(1, LogLevel.Warning, "Failed to apply default value for parameter due to type mismatch. Default value type: '{DefaultValueType}', Parameter type: '{ParameterType}'. Default value will be omitted from the OpenAPI schema.", EventName = "DefaultValueTypeMismatch")]
public static partial void DefaultValueTypeMismatch(this ILogger logger, string defaultValueType, string parameterType);
}
8 changes: 5 additions & 3 deletions src/OpenApi/src/Services/Schemas/OpenApiSchemaService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace Microsoft.AspNetCore.OpenApi;
Expand All @@ -28,7 +29,8 @@ namespace Microsoft.AspNetCore.OpenApi;
internal sealed class OpenApiSchemaService(
[ServiceKey] string documentName,
IOptions<JsonOptions> jsonOptions,
IOptionsMonitor<OpenApiOptions> optionsMonitor)
IOptionsMonitor<OpenApiOptions> optionsMonitor,
ILogger<OpenApiSchemaService>? logger = null)
{
private readonly ConcurrentDictionary<Type, string?> _schemaIdCache = new();
private readonly OpenApiJsonSchemaContext _jsonSchemaContext = new(new(jsonOptions.Value.SerializerOptions));
Expand Down Expand Up @@ -105,7 +107,7 @@ internal sealed class OpenApiSchemaService(
}
if (attributeProvider.GetCustomAttributes(inherit: false).OfType<DefaultValueAttribute>().LastOrDefault() is DefaultValueAttribute defaultValueAttribute)
{
schema.ApplyDefaultValue(defaultValueAttribute.Value, context.TypeInfo);
schema.ApplyDefaultValue(defaultValueAttribute.Value, context.TypeInfo, logger);
}
if (attributeProvider.GetCustomAttributes(inherit: false).OfType<DescriptionAttribute>().LastOrDefault() is DescriptionAttribute descriptionAttribute)
{
Expand All @@ -125,7 +127,7 @@ internal async Task<OpenApiSchema> GetOrCreateUnresolvedSchemaAsync(OpenApiDocum
var schemaAsJsonObject = CreateSchema(key);
if (parameterDescription is not null)
{
schemaAsJsonObject.ApplyParameterInfo(parameterDescription, _jsonSerializerOptions.GetTypeInfo(type));
schemaAsJsonObject.ApplyParameterInfo(parameterDescription, _jsonSerializerOptions.GetTypeInfo(type), logger);
}
// Use _jsonSchemaContext constructed from _jsonSerializerOptions to respect shared config set by end-user,
// particularly in the case of maxDepth.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Routing.Constraints;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Microsoft.Net.Http.Headers;
using Moq;
Expand Down Expand Up @@ -88,7 +90,8 @@ internal static OpenApiDocumentService CreateDocumentService(IEndpointRouteBuild
// Set strict number handling by default to make integer type checks more straightforward
jsonOptions.SerializerOptions.NumberHandling = System.Text.Json.Serialization.JsonNumberHandling.Strict;

var schemaService = new OpenApiSchemaService("Test", Options.Create(jsonOptions), openApiOptions.Object);
var logger = builder.ServiceProvider.GetService<ILogger<OpenApiSchemaService>>() ?? NullLogger<OpenApiSchemaService>.Instance;
var schemaService = new OpenApiSchemaService("Test", Options.Create(jsonOptions), openApiOptions.Object, logger);
((TestServiceProvider)builder.ServiceProvider).TestSchemaService = schemaService;
var documentService = new OpenApiDocumentService("Test", apiDescriptionGroupCollectionProvider, hostEnvironment, openApiOptions.Object, builder.ServiceProvider, new OpenApiTestServer());
((TestServiceProvider)builder.ServiceProvider).TestDocumentService = documentService;
Expand Down Expand Up @@ -134,7 +137,8 @@ internal static OpenApiDocumentService CreateDocumentService(IEndpointRouteBuild
defaultJsonOptions.SerializerOptions.NumberHandling = System.Text.Json.Serialization.JsonNumberHandling.Strict;
var jsonOptions = builder.ServiceProvider.GetService<IOptions<Microsoft.AspNetCore.Http.Json.JsonOptions>>() ?? Options.Create(defaultJsonOptions);

var schemaService = new OpenApiSchemaService("Test", jsonOptions, options.Object);
var logger = builder.ServiceProvider.GetService<ILogger<OpenApiSchemaService>>() ?? NullLogger<OpenApiSchemaService>.Instance;
var schemaService = new OpenApiSchemaService("Test", jsonOptions, options.Object, logger);
((TestServiceProvider)builder.ServiceProvider).TestSchemaService = schemaService;
var documentService = new OpenApiDocumentService("Test", apiDescriptionGroupCollectionProvider, hostEnvironment, options.Object, builder.ServiceProvider, new OpenApiTestServer());
((TestServiceProvider)builder.ServiceProvider).TestDocumentService = documentService;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

public partial class OpenApiSchemaServiceTests : OpenApiDocumentServiceTestBase
{
Expand Down Expand Up @@ -642,6 +643,50 @@ await VerifyOpenApiDocument(builder, document =>
});
}

public static object[][] RouteParametersWithDefaultValueTypeMismatch =>
[
// F# scenarios where type mismatch causes InvalidCastException and logging should occur
[([DefaultValue(10)] ulong id) => { }, (Action<string[]>)((logMessages) =>
{
Assert.Single(logMessages);
Assert.Contains("Failed to apply default value for parameter due to type mismatch", logMessages[0]);
Assert.Contains("Default value type: 'Int32', Parameter type: 'UInt64'", logMessages[0]);
})],
[([DefaultValue(10u)] ulong id) => { }, (Action<string[]>)((logMessages) =>
{
Assert.Single(logMessages);
Assert.Contains("Failed to apply default value for parameter due to type mismatch", logMessages[0]);
Assert.Contains("Default value type: 'UInt32', Parameter type: 'UInt64'", logMessages[0]);
})],
];

[Theory]
[MemberData(nameof(RouteParametersWithDefaultValueTypeMismatch))]
public async Task GetOpenApiParameters_LogsWarningForDefaultValueTypeMismatch(Delegate requestHandler, Action<string[]> assertLogMessages)
{
// Arrange
var logMessages = new List<string>();
var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton<ILoggerProvider>(new TestLoggerProvider(logMessages));
serviceCollection.AddLogging();

var builder = CreateBuilder(serviceCollection);
builder.MapGet("/api/{id}", requestHandler);

// Act & Assert
await VerifyOpenApiDocument(builder, document =>
{
var operation = document.Paths["/api/{id}"].Operations[HttpMethod.Get];
var parameter = Assert.Single(operation.Parameters);

// Verify that no default value is set when there's a type mismatch
Assert.Null(parameter.Schema.Default);

// Verify the warning log was emitted
assertLogMessages(logMessages.ToArray());
});
}

public struct CustomType { }

public class CustomTypeConverter : JsonConverter<CustomType>
Expand Down Expand Up @@ -890,6 +935,48 @@ public override void Write(Utf8JsonWriter writer, EnumArrayType value, JsonSeria
}
}

public class TestLoggerProvider : ILoggerProvider
{
private readonly List<string> _logMessages;

public TestLoggerProvider(List<string> logMessages)
{
_logMessages = logMessages;
}

public ILogger CreateLogger(string categoryName)
{
return new TestLogger(_logMessages);
}

public void Dispose() { }
}

public class TestLogger : ILogger
{
private readonly List<string> _logMessages;

public TestLogger(List<string> logMessages)
{
_logMessages = logMessages;
}

public IDisposable BeginScope<TState>(TState state) => NullScope.Instance;

public bool IsEnabled(LogLevel logLevel) => true;

public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
_logMessages.Add(formatter(state, exception));
}

private class NullScope : IDisposable
{
public static NullScope Instance { get; } = new();
public void Dispose() { }
}
}

[ApiController]
[Route("[controller]/[action]")]
private class TestFromQueryController : ControllerBase
Expand Down
Loading