feat(api): #287 OpenAPI contract honesty by construction
ApiKey security scheme + per-op security/401 via shared EndpointRequiresKey predicate (no drift from enforcement); synthesized stable operationIds; 400 ValidationProblemDetails on binding ops; DayOfWeek as string enum. Refs #287 #197 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,115 @@
|
||||
using ErsatzTV.Serialization;
|
||||
using ErsatzTV.Tests.Support;
|
||||
using Microsoft.OpenApi;
|
||||
using NUnit.Framework;
|
||||
using Shouldly;
|
||||
|
||||
namespace ErsatzTV.Tests.Controllers;
|
||||
|
||||
/// <summary>
|
||||
/// Pins the #287 "contract honesty by construction" transformers against the document the app would
|
||||
/// actually serve (generated in-process; see <see cref="GeneratedOpenApiDocument" />): the ApiKey
|
||||
/// security scheme + per-operation security/401, a stable operationId on every operation, and the
|
||||
/// DayOfWeek string enum. If a transformer regresses (or is dropped from the "v1" registration) these
|
||||
/// go red without needing the committed v1.json to be regenerated first.
|
||||
/// </summary>
|
||||
[TestFixture]
|
||||
public class OpenApiContractHonestyTests
|
||||
{
|
||||
private static OpenApiDocument _document = null!;
|
||||
|
||||
[OneTimeSetUp]
|
||||
public async Task BuildDocument() => _document = await GeneratedOpenApiDocument.BuildV1Async();
|
||||
|
||||
[Test]
|
||||
public void Should_Declare_ApiKey_Security_Scheme_In_Header()
|
||||
{
|
||||
_document.Components.ShouldNotBeNull();
|
||||
_document.Components!.SecuritySchemes.ShouldNotBeNull();
|
||||
_document.Components!.SecuritySchemes!.TryGetValue("ApiKey", out IOpenApiSecurityScheme? scheme)
|
||||
.ShouldBeTrue();
|
||||
|
||||
var concrete = scheme.ShouldBeOfType<OpenApiSecurityScheme>();
|
||||
concrete.Type.ShouldBe(SecuritySchemeType.ApiKey);
|
||||
concrete.In.ShouldBe(ParameterLocation.Header);
|
||||
concrete.Name.ShouldBe("X-Api-Key");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Every_Operation_Should_Have_A_NonEmpty_OperationId()
|
||||
{
|
||||
List<string> missing = EnumerateOperations()
|
||||
.Where(op => string.IsNullOrEmpty(op.Operation.OperationId))
|
||||
.Select(op => $"{op.Method} {op.Path}")
|
||||
.ToList();
|
||||
|
||||
missing.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Operation_Ids_Should_Be_Unique()
|
||||
{
|
||||
List<string> ids = EnumerateOperations()
|
||||
.Select(op => op.Operation.OperationId!)
|
||||
.ToList();
|
||||
|
||||
ids.Count.ShouldBeGreaterThan(150);
|
||||
ids.Distinct(StringComparer.Ordinal).Count().ShouldBe(ids.Count);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Gated_Operations_Should_Declare_Security_And_401()
|
||||
{
|
||||
// Under the default posture (Api:RequireKeyForReads=true) every documented operation requires the
|
||||
// key, so each must carry the ApiKey security requirement AND a documented 401.
|
||||
foreach ((string method, string path, OpenApiOperation operation) in EnumerateOperations())
|
||||
{
|
||||
operation.Security.ShouldNotBeNull($"{method} {path} should declare security");
|
||||
operation.Security!.Count.ShouldBeGreaterThan(0, $"{method} {path} should declare security");
|
||||
operation.Responses.ShouldNotBeNull();
|
||||
operation.Responses!.ContainsKey("401").ShouldBeTrue($"{method} {path} should document 401");
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ValidationProblemDetails_Schema_And_400_Should_Be_Documented_For_Binding_Operations()
|
||||
{
|
||||
_document.Components!.Schemas!.ContainsKey(
|
||||
ApiSecuritySchemeDocumentTransformer.ValidationProblemDetailsSchemaId).ShouldBeTrue();
|
||||
|
||||
// Any operation that binds a body or parameters must document a 400 (model-binding / validation).
|
||||
foreach ((string method, string path, OpenApiOperation operation) in EnumerateOperations())
|
||||
{
|
||||
bool binds = operation.RequestBody is not null || operation.Parameters is { Count: > 0 };
|
||||
if (binds)
|
||||
{
|
||||
operation.Responses!.ContainsKey("400").ShouldBeTrue($"{method} {path} should document 400");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DayOfWeek_Schema_Should_Be_A_String_Enum()
|
||||
{
|
||||
_document.Components!.Schemas!.TryGetValue("DayOfWeek", out IOpenApiSchema? schema).ShouldBeTrue();
|
||||
schema!.Type.ShouldBe(JsonSchemaType.String);
|
||||
schema.Enum.ShouldNotBeNull();
|
||||
schema.Enum!.Select(n => n!.GetValue<string>()).ShouldContain("Sunday");
|
||||
}
|
||||
|
||||
private static IEnumerable<(string Method, string Path, OpenApiOperation Operation)> EnumerateOperations()
|
||||
{
|
||||
foreach (KeyValuePair<string, IOpenApiPathItem> path in _document.Paths)
|
||||
{
|
||||
if (path.Value.Operations is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (KeyValuePair<HttpMethod, OpenApiOperation> operation in path.Value.Operations)
|
||||
{
|
||||
yield return (operation.Key.Method, path.Key, operation.Value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
using System.Collections.Generic;
|
||||
using ErsatzTV.Filters;
|
||||
using ErsatzTV.Services;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Abstractions;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using Microsoft.AspNetCore.Routing;
|
||||
using NUnit.Framework;
|
||||
using Shouldly;
|
||||
|
||||
namespace ErsatzTV.Tests.Filters;
|
||||
|
||||
/// <summary>
|
||||
/// Proves the shared <see cref="ApiKeyAuthorizationFilter.EndpointRequiresKey" /> predicate — the one
|
||||
/// the OpenAPI security/401 transformer consumes — agrees with what the filter actually enforces at
|
||||
/// runtime, across a representative matrix. If the two ever diverged, the spec could claim an endpoint
|
||||
/// is open while the filter gates it (or vice-versa); this test is the anti-drift guard (#287).
|
||||
/// </summary>
|
||||
[TestFixture]
|
||||
public class ApiKeyEndpointRequiresKeyTests
|
||||
{
|
||||
private const string Key = "secret";
|
||||
|
||||
private sealed class FakeApiKeyProvider(bool requireKeyForReads) : IApiKeyProvider
|
||||
{
|
||||
public string ApiKey => Key;
|
||||
public bool RequireKeyForReads { get; } = requireKeyForReads;
|
||||
}
|
||||
|
||||
// (method, requiresApiKey, skip, requireKeyForReads, expectedRequiresKey)
|
||||
private static readonly object[] Matrix =
|
||||
[
|
||||
new object[] { "POST", false, false, false, true }, // write always gated
|
||||
new object[] { "PUT", false, false, false, true },
|
||||
new object[] { "PATCH", false, false, false, true },
|
||||
new object[] { "DELETE", false, false, false, true },
|
||||
new object[] { "GET", false, false, true, true }, // read gated when reads-required
|
||||
new object[] { "GET", false, false, false, false }, // read open when reads-not-required
|
||||
new object[] { "GET", true, false, false, true }, // [RequiresApiKey] gates read even so
|
||||
new object[] { "HEAD", false, false, false, false }, // read verb, open
|
||||
new object[] { "OPTIONS", false, false, true, false },// preflight always exempt
|
||||
new object[] { "POST", false, true, false, false } // [SkipApiKeyAuthorization] exempt
|
||||
];
|
||||
|
||||
[TestCaseSource(nameof(Matrix))]
|
||||
public void Predicate_Matches_Expected(
|
||||
string method,
|
||||
bool requiresApiKey,
|
||||
bool skip,
|
||||
bool requireKeyForReads,
|
||||
bool expected)
|
||||
{
|
||||
var metadata = new List<object>();
|
||||
if (requiresApiKey)
|
||||
{
|
||||
metadata.Add(new RequiresApiKeyAttribute());
|
||||
}
|
||||
|
||||
if (skip)
|
||||
{
|
||||
metadata.Add(new SkipApiKeyAuthorizationAttribute());
|
||||
}
|
||||
|
||||
ApiKeyAuthorizationFilter.EndpointRequiresKey(method, metadata, requireKeyForReads)
|
||||
.ShouldBe(expected);
|
||||
}
|
||||
|
||||
[TestCaseSource(nameof(Matrix))]
|
||||
public void Predicate_Agrees_With_Filter_Enforcement(
|
||||
string method,
|
||||
bool requiresApiKey,
|
||||
bool skip,
|
||||
bool requireKeyForReads,
|
||||
bool expected)
|
||||
{
|
||||
// The filter, on an /api path with the header MISSING, produces a 401 exactly when the predicate
|
||||
// says the endpoint requires a key. Drive the real filter and compare its decision to the predicate.
|
||||
AuthorizationFilterContext context = MakeContext(method, requiresApiKey, skip);
|
||||
new ApiKeyAuthorizationFilter(new FakeApiKeyProvider(requireKeyForReads)).OnAuthorization(context);
|
||||
|
||||
bool filterGated = context.Result is not null;
|
||||
filterGated.ShouldBe(expected);
|
||||
filterGated.ShouldBe(
|
||||
ApiKeyAuthorizationFilter.EndpointRequiresKey(method, Metadata(requiresApiKey, skip), requireKeyForReads));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Filter_Never_Gates_Non_Api_Paths_Even_When_Predicate_Would()
|
||||
{
|
||||
// The predicate assumes an /api endpoint; the filter's path scoping precedes it. A mutating request
|
||||
// outside /api must pass untouched even though the predicate (given the same method) returns true.
|
||||
ApiKeyAuthorizationFilter.EndpointRequiresKey("POST", new List<object>(), requireKeyForReads: true)
|
||||
.ShouldBeTrue();
|
||||
|
||||
AuthorizationFilterContext context = MakeContext("POST", requiresApiKey: false, skip: false, path: "/iptv/x.m3u");
|
||||
new ApiKeyAuthorizationFilter(new FakeApiKeyProvider(requireKeyForReads: true)).OnAuthorization(context);
|
||||
|
||||
context.Result.ShouldBeNull();
|
||||
}
|
||||
|
||||
private static List<object> Metadata(bool requiresApiKey, bool skip)
|
||||
{
|
||||
var metadata = new List<object>();
|
||||
if (requiresApiKey)
|
||||
{
|
||||
metadata.Add(new RequiresApiKeyAttribute());
|
||||
}
|
||||
|
||||
if (skip)
|
||||
{
|
||||
metadata.Add(new SkipApiKeyAuthorizationAttribute());
|
||||
}
|
||||
|
||||
return metadata;
|
||||
}
|
||||
|
||||
private static AuthorizationFilterContext MakeContext(
|
||||
string method,
|
||||
bool requiresApiKey,
|
||||
bool skip,
|
||||
string path = "/api/channels")
|
||||
{
|
||||
var httpContext = new DefaultHttpContext();
|
||||
httpContext.Request.Method = method;
|
||||
httpContext.Request.Path = path;
|
||||
|
||||
var actionDescriptor = new ActionDescriptor { EndpointMetadata = Metadata(requiresApiKey, skip) };
|
||||
var actionContext = new ActionContext(httpContext, new RouteData(), actionDescriptor);
|
||||
return new AuthorizationFilterContext(actionContext, new List<IFilterMetadata>());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
using ErsatzTV;
|
||||
using ErsatzTV.Controllers.Api;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Mvc.ApplicationParts;
|
||||
using Microsoft.AspNetCore.OpenApi;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.FileProviders;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.OpenApi;
|
||||
using NSubstitute;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace ErsatzTV.Tests.Support;
|
||||
|
||||
/// <summary>
|
||||
/// Builds the "v1" OpenAPI document in-process from the real <see cref="Startup.ConfigureServices" />
|
||||
/// registrations, so contract tests validate the document the running app would actually serve —
|
||||
/// including every registered document/operation/schema transformer — rather than a stale committed
|
||||
/// <c>wwwroot/openapi/v1.json</c> that is regenerated out-of-band. Mirrors the DI-only bootstrap that
|
||||
/// <c>ApiControllerSecurityTests</c> uses to inspect <c>MvcOptions</c>.
|
||||
/// </summary>
|
||||
public static class GeneratedOpenApiDocument
|
||||
{
|
||||
public static async Task<OpenApiDocument> BuildV1Async()
|
||||
{
|
||||
var settings = new Dictionary<string, string?>
|
||||
{
|
||||
["provider"] = "sqlite",
|
||||
["ConnectionStrings:Data"] = "Data Source=:memory:"
|
||||
};
|
||||
|
||||
IConfiguration configuration = new ConfigurationBuilder().AddInMemoryCollection(settings).Build();
|
||||
|
||||
var environment = Substitute.For<IWebHostEnvironment>();
|
||||
environment.ApplicationName.Returns("ErsatzTV");
|
||||
environment.EnvironmentName.Returns("Development");
|
||||
environment.ContentRootPath.Returns(TestContext.CurrentContext.TestDirectory);
|
||||
environment.WebRootPath.Returns(TestContext.CurrentContext.TestDirectory);
|
||||
environment.ContentRootFileProvider.Returns(new NullFileProvider());
|
||||
environment.WebRootFileProvider.Returns(new NullFileProvider());
|
||||
|
||||
var services = new ServiceCollection();
|
||||
|
||||
// The host normally provides these; supply them so the OpenAPI document service and the
|
||||
// API-key provider (an operation-transformer dependency) can be constructed.
|
||||
services.AddSingleton(configuration);
|
||||
services.AddLogging();
|
||||
services.AddSingleton(environment);
|
||||
services.AddSingleton<IHostEnvironment>(environment);
|
||||
|
||||
new Startup(configuration, environment).ConfigureServices(services);
|
||||
|
||||
// In the running app ErsatzTV is the entry assembly and its controllers are discovered
|
||||
// automatically; under the test runner it is not, so register it as an application part.
|
||||
ApplicationPartManager? partManager = services
|
||||
.FirstOrDefault(d => d.ServiceType == typeof(ApplicationPartManager))?.ImplementationInstance
|
||||
as ApplicationPartManager;
|
||||
if (partManager is not null &&
|
||||
!partManager.ApplicationParts.OfType<AssemblyPart>()
|
||||
.Any(p => p.Assembly == typeof(CollectionController).Assembly))
|
||||
{
|
||||
partManager.ApplicationParts.Add(new AssemblyPart(typeof(CollectionController).Assembly));
|
||||
}
|
||||
|
||||
await using ServiceProvider provider = services.BuildServiceProvider();
|
||||
IOpenApiDocumentProvider documentProvider = provider.GetRequiredKeyedService<IOpenApiDocumentProvider>("v1");
|
||||
return await documentProvider.GetOpenApiDocumentAsync();
|
||||
}
|
||||
}
|
||||
@@ -32,19 +32,7 @@ public class ApiKeyAuthorizationFilter(IApiKeyProvider apiKeyProvider) : IAuthor
|
||||
return;
|
||||
}
|
||||
|
||||
// CORS preflight carries no custom headers and is handled by the CORS middleware.
|
||||
if (HttpMethods.IsOptions(request.Method))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Explicit opt-out for internal, separately-guarded endpoints (e.g. the scanner callback).
|
||||
if (HasMetadata<SkipApiKeyAuthorizationAttribute>(context))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!RequiresKey(context, request))
|
||||
if (!EndpointRequiresKey(request.Method, context.ActionDescriptor.EndpointMetadata, apiKeyProvider.RequireKeyForReads))
|
||||
{
|
||||
return;
|
||||
}
|
||||
@@ -61,18 +49,43 @@ public class ApiKeyAuthorizationFilter(IApiKeyProvider apiKeyProvider) : IAuthor
|
||||
}
|
||||
}
|
||||
|
||||
private bool RequiresKey(AuthorizationFilterContext context, HttpRequest request)
|
||||
/// <summary>
|
||||
/// The single decision shared between runtime enforcement (this filter) and the OpenAPI
|
||||
/// document generation (<c>ApiSecurityOperationTransformer</c>), so the spec's declared
|
||||
/// <c>security</c>/<c>401</c> can never drift from what is actually enforced. Assumes the
|
||||
/// endpoint is already known to be under <c>/api</c> (the caller's responsibility). Returns
|
||||
/// <see langword="true" /> when the endpoint requires a valid <c>X-Api-Key</c>: any mutating
|
||||
/// verb (POST/PUT/PATCH/DELETE) is always fail-closed; reads are gated when
|
||||
/// <paramref name="requireKeyForReads" /> is set or the endpoint carries
|
||||
/// <see cref="RequiresApiKeyAttribute" />. <c>OPTIONS</c> preflight and endpoints marked
|
||||
/// <see cref="SkipApiKeyAuthorizationAttribute" /> are exempt.
|
||||
/// </summary>
|
||||
public static bool EndpointRequiresKey(
|
||||
string httpMethod,
|
||||
IEnumerable<object> endpointMetadata,
|
||||
bool requireKeyForReads)
|
||||
{
|
||||
string method = request.Method;
|
||||
bool isMutating = HttpMethods.IsPost(method)
|
||||
|| HttpMethods.IsPut(method)
|
||||
|| HttpMethods.IsPatch(method)
|
||||
|| HttpMethods.IsDelete(method);
|
||||
// CORS preflight carries no custom headers and is handled by the CORS middleware.
|
||||
if (HttpMethods.IsOptions(httpMethod))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Explicit opt-out for internal, separately-guarded endpoints (e.g. the scanner callback).
|
||||
if (endpointMetadata.OfType<SkipApiKeyAuthorizationAttribute>().Any())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
bool isMutating = HttpMethods.IsPost(httpMethod)
|
||||
|| HttpMethods.IsPut(httpMethod)
|
||||
|| HttpMethods.IsPatch(httpMethod)
|
||||
|| HttpMethods.IsDelete(httpMethod);
|
||||
|
||||
// Writes are always fail-closed; reads are gated by the global flag or a per-endpoint opt-in.
|
||||
return isMutating
|
||||
|| apiKeyProvider.RequireKeyForReads
|
||||
|| HasMetadata<RequiresApiKeyAttribute>(context);
|
||||
|| requireKeyForReads
|
||||
|| endpointMetadata.OfType<RequiresApiKeyAttribute>().Any();
|
||||
}
|
||||
|
||||
// Compare in constant time so a remote attacker cannot use response-timing to recover the
|
||||
@@ -82,9 +95,4 @@ public class ApiKeyAuthorizationFilter(IApiKeyProvider apiKeyProvider) : IAuthor
|
||||
CryptographicOperations.FixedTimeEquals(
|
||||
Encoding.UTF8.GetBytes(provided),
|
||||
Encoding.UTF8.GetBytes(configured));
|
||||
|
||||
private static bool HasMetadata<TAttribute>(AuthorizationFilterContext context)
|
||||
where TAttribute : class =>
|
||||
context.Filters.OfType<TAttribute>().Any()
|
||||
|| context.ActionDescriptor.EndpointMetadata.OfType<TAttribute>().Any();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
#nullable enable
|
||||
using ErsatzTV.Filters;
|
||||
using ErsatzTV.Services;
|
||||
using Microsoft.AspNetCore.OpenApi;
|
||||
using Microsoft.OpenApi;
|
||||
|
||||
namespace ErsatzTV.Serialization;
|
||||
|
||||
/// <summary>
|
||||
/// OpenAPI operation transformer that documents the API-key contract <b>by construction</b>: for
|
||||
/// every operation that actually requires the <c>X-Api-Key</c> header it injects the
|
||||
/// <c>ApiKey</c> security requirement and a documented <c>401</c> response. The "requires a key"
|
||||
/// decision is the exact same predicate the runtime filter enforces
|
||||
/// (<see cref="ApiKeyAuthorizationFilter.EndpointRequiresKey" />), so the spec can never claim an
|
||||
/// endpoint is open when it is gated (or vice-versa). The <c>ApiKey</c> scheme itself and the
|
||||
/// <c>ProblemDetails</c> schema the <c>401</c> references are declared by
|
||||
/// <see cref="ApiSecuritySchemeDocumentTransformer" />. See issues #286/#287.
|
||||
/// </summary>
|
||||
public sealed class ApiSecurityOperationTransformer(IApiKeyProvider apiKeyProvider) : IOpenApiOperationTransformer
|
||||
{
|
||||
public const string SchemeName = "ApiKey";
|
||||
|
||||
public Task TransformAsync(
|
||||
OpenApiOperation operation,
|
||||
OpenApiOperationTransformerContext context,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
string method = context.Description.HttpMethod ?? string.Empty;
|
||||
IEnumerable<object> metadata = context.Description.ActionDescriptor.EndpointMetadata;
|
||||
|
||||
if (!ApiKeyAuthorizationFilter.EndpointRequiresKey(method, metadata, apiKeyProvider.RequireKeyForReads))
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
operation.Security ??= new List<OpenApiSecurityRequirement>();
|
||||
operation.Security.Add(new OpenApiSecurityRequirement
|
||||
{
|
||||
[new OpenApiSecuritySchemeReference(SchemeName)] = new List<string>()
|
||||
});
|
||||
|
||||
operation.Responses ??= new OpenApiResponses();
|
||||
if (!operation.Responses.ContainsKey("401"))
|
||||
{
|
||||
operation.Responses["401"] = new OpenApiResponse
|
||||
{
|
||||
Description = "API key missing or invalid.",
|
||||
Content = new Dictionary<string, OpenApiMediaType>
|
||||
{
|
||||
["application/json"] = new OpenApiMediaType
|
||||
{
|
||||
Schema = new OpenApiSchemaReference("ProblemDetails")
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
#nullable enable
|
||||
using ErsatzTV.Filters;
|
||||
using Microsoft.AspNetCore.OpenApi;
|
||||
using Microsoft.OpenApi;
|
||||
|
||||
namespace ErsatzTV.Serialization;
|
||||
|
||||
/// <summary>
|
||||
/// OpenAPI document transformer that declares the components the per-operation transformers reference:
|
||||
/// the <c>ApiKey</c> security scheme (<c>X-Api-Key</c> request header) used by
|
||||
/// <see cref="ApiSecurityOperationTransformer" />, and the <c>ValidationProblemDetails</c> schema used
|
||||
/// by <see cref="ValidationProblemOperationTransformer" /> for documented <c>400</c> responses. Runs on
|
||||
/// the "v1" document only. See issues #286/#287.
|
||||
/// </summary>
|
||||
public static class ApiSecuritySchemeDocumentTransformer
|
||||
{
|
||||
public const string ValidationProblemDetailsSchemaId = "ValidationProblemDetails";
|
||||
|
||||
public static Task TransformAsync(
|
||||
OpenApiDocument document,
|
||||
OpenApiDocumentTransformerContext context,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
document.Components ??= new OpenApiComponents();
|
||||
|
||||
document.Components.SecuritySchemes ??= new Dictionary<string, IOpenApiSecurityScheme>();
|
||||
document.Components.SecuritySchemes[ApiSecurityOperationTransformer.SchemeName] = new OpenApiSecurityScheme
|
||||
{
|
||||
Type = SecuritySchemeType.ApiKey,
|
||||
Name = ApiKeyAuthorizationFilter.HeaderName,
|
||||
In = ParameterLocation.Header,
|
||||
Description =
|
||||
"API key sent in the 'X-Api-Key' request header. Required for all mutating requests and, " +
|
||||
"under the default posture (Api:RequireKeyForReads=true), for reads as well."
|
||||
};
|
||||
|
||||
document.Components.Schemas ??= new Dictionary<string, IOpenApiSchema>();
|
||||
if (!document.Components.Schemas.ContainsKey(ValidationProblemDetailsSchemaId))
|
||||
{
|
||||
document.Components.Schemas[ValidationProblemDetailsSchemaId] = BuildValidationProblemDetailsSchema();
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
// The RFC 7807 shape ASP.NET Core's [ApiController] + FluentValidation return on a model-binding /
|
||||
// validation failure: the standard ProblemDetails members plus an "errors" map of field -> messages.
|
||||
private static OpenApiSchema BuildValidationProblemDetailsSchema() =>
|
||||
new()
|
||||
{
|
||||
Type = JsonSchemaType.Object,
|
||||
Properties = new Dictionary<string, IOpenApiSchema>
|
||||
{
|
||||
["type"] = new OpenApiSchema { Type = JsonSchemaType.String | JsonSchemaType.Null },
|
||||
["title"] = new OpenApiSchema { Type = JsonSchemaType.String | JsonSchemaType.Null },
|
||||
["status"] = new OpenApiSchema
|
||||
{
|
||||
Type = JsonSchemaType.Integer | JsonSchemaType.Null,
|
||||
Format = "int32"
|
||||
},
|
||||
["detail"] = new OpenApiSchema { Type = JsonSchemaType.String | JsonSchemaType.Null },
|
||||
["instance"] = new OpenApiSchema { Type = JsonSchemaType.String | JsonSchemaType.Null },
|
||||
["errors"] = new OpenApiSchema
|
||||
{
|
||||
Type = JsonSchemaType.Object,
|
||||
AdditionalProperties = new OpenApiSchema
|
||||
{
|
||||
Type = JsonSchemaType.Array,
|
||||
Items = new OpenApiSchema { Type = JsonSchemaType.String }
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
#nullable enable
|
||||
using Microsoft.AspNetCore.Mvc.Controllers;
|
||||
using Microsoft.AspNetCore.OpenApi;
|
||||
using Microsoft.OpenApi;
|
||||
|
||||
namespace ErsatzTV.Serialization;
|
||||
|
||||
/// <summary>
|
||||
/// OpenAPI operation transformer that guarantees every operation carries a stable, non-empty
|
||||
/// <c>operationId</c>. Only actions with <c>Name = "..."</c> on their HTTP-method attribute get an
|
||||
/// id from the framework; the rest (~90 of ~240) would ship without one, which breaks generated
|
||||
/// clients that key methods off <c>operationId</c>. Here we synthesize one from the
|
||||
/// <see cref="ControllerActionDescriptor" /> (<c>ControllerName</c> + <c>ActionName</c>) whenever the
|
||||
/// id is null/empty, and never rename an id the developer set explicitly.
|
||||
/// <para>
|
||||
/// A single instance is created per document generation and reused across every operation, so the
|
||||
/// <see cref="_used" /> set gives whole-document uniqueness: a synthesized id that collides is
|
||||
/// disambiguated deterministically (append the HTTP method, then a counter). Explicit ids are also
|
||||
/// recorded so a later synthesized id can't shadow one.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public sealed class OperationIdOpenApiTransformer : IOpenApiOperationTransformer
|
||||
{
|
||||
private readonly System.Collections.Generic.HashSet<string> _used = new(StringComparer.Ordinal);
|
||||
|
||||
public Task TransformAsync(
|
||||
OpenApiOperation operation,
|
||||
OpenApiOperationTransformerContext context,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(operation.OperationId))
|
||||
{
|
||||
// Keep developer-assigned ids verbatim; just reserve them so nothing synthesized collides.
|
||||
_used.Add(operation.OperationId);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
if (context.Description.ActionDescriptor is not ControllerActionDescriptor controllerAction)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
string baseId = controllerAction.ControllerName + controllerAction.ActionName;
|
||||
string candidate = baseId;
|
||||
|
||||
if (_used.Contains(candidate))
|
||||
{
|
||||
// Overloaded action (same controller+action name, different verb/route): qualify by verb.
|
||||
candidate = baseId + (context.Description.HttpMethod ?? string.Empty);
|
||||
}
|
||||
|
||||
int suffix = 2;
|
||||
while (!_used.Add(candidate))
|
||||
{
|
||||
candidate = baseId + (context.Description.HttpMethod ?? string.Empty) + suffix;
|
||||
suffix++;
|
||||
}
|
||||
|
||||
operation.OperationId = candidate;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
#nullable enable
|
||||
using Microsoft.AspNetCore.OpenApi;
|
||||
using Microsoft.OpenApi;
|
||||
|
||||
namespace ErsatzTV.Serialization;
|
||||
|
||||
/// <summary>
|
||||
/// OpenAPI operation transformer that documents the <c>400</c> a model-binding / FluentValidation
|
||||
/// failure actually returns. ASP.NET Core's <c>[ApiController]</c> convention emits a
|
||||
/// <c>ValidationProblemDetails</c> (an <c>errors</c> map) for any operation that binds a request body
|
||||
/// or parameters, but that response was undocumented. This adds a <c>400</c> referencing the
|
||||
/// <c>ValidationProblemDetails</c> schema (declared by
|
||||
/// <see cref="ApiSecuritySchemeDocumentTransformer" />) to every operation that binds something and
|
||||
/// does not already document a <c>400</c>. See issues #286/#287.
|
||||
/// </summary>
|
||||
public static class ValidationProblemOperationTransformer
|
||||
{
|
||||
public static Task TransformAsync(
|
||||
OpenApiOperation operation,
|
||||
OpenApiOperationTransformerContext context,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
bool bindsSomething = operation.RequestBody is not null
|
||||
|| operation.Parameters is { Count: > 0 };
|
||||
|
||||
if (!bindsSomething)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
operation.Responses ??= new OpenApiResponses();
|
||||
if (operation.Responses.ContainsKey("400"))
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
operation.Responses["400"] = new OpenApiResponse
|
||||
{
|
||||
Description = "Request validation failed (model binding or FluentValidation).",
|
||||
Content = new Dictionary<string, OpenApiMediaType>
|
||||
{
|
||||
["application/json"] = new OpenApiMediaType
|
||||
{
|
||||
Schema = new OpenApiSchemaReference(
|
||||
ApiSecuritySchemeDocumentTransformer.ValidationProblemDetailsSchemaId)
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -139,6 +139,7 @@ public class Startup
|
||||
Dictionary<string, Type> enumTypes = typeof(Core.Domain.PlayoutMode).Assembly.GetTypes()
|
||||
.Where(type => type.IsEnum)
|
||||
.Concat([
|
||||
typeof(DayOfWeek),
|
||||
typeof(FFmpeg.OutputFormat.OutputFormatKind),
|
||||
typeof(FFmpeg.State.WatermarkLocation),
|
||||
typeof(FFmpeg.State.WatermarkSize),
|
||||
@@ -229,6 +230,15 @@ public class Startup
|
||||
UseStringEnumSchemas(document);
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
|
||||
// Contract-honesty transformers (#287): document the API surface the way it actually
|
||||
// behaves at runtime — the ApiKey security scheme + per-operation security/401 (shared
|
||||
// with the enforcing filter's predicate), a synthesized operationId for every action,
|
||||
// and the 400 ValidationProblemDetails a binding failure returns. "v1" document only.
|
||||
options.AddDocumentTransformer(ApiSecuritySchemeDocumentTransformer.TransformAsync);
|
||||
options.AddOperationTransformer<ApiSecurityOperationTransformer>();
|
||||
options.AddOperationTransformer<OperationIdOpenApiTransformer>();
|
||||
options.AddOperationTransformer(ValidationProblemOperationTransformer.TransformAsync);
|
||||
});
|
||||
|
||||
services.AddOpenApi(
|
||||
|
||||
Reference in New Issue
Block a user