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>
61 lines
2.4 KiB
C#
61 lines
2.4 KiB
C#
#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;
|
|
}
|
|
}
|