OpenAPI-document van de SlpSoftware-host vastgelegd met snapshot-test en contactcontract
openapi/slpsoftware.v1.json is de bron voor de gegenereerde frontend-types; een test haalt het document van de echte host op en faalt bij afwijking (UPDATE_OPENAPI=1 herschrijft het bestand). De contactmodule voegt de herbruikbare foutresponses, de verplichte Idempotency-Key en de verplichte velden met maximale lengtes toe via een documenttransformer, zodat Core ongemoeid blijft. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading.RateLimiting;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.OpenApi;
|
||||
using Microsoft.AspNetCore.RateLimiting;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
@@ -13,6 +14,7 @@ using SlpModularCms.Core.Modules;
|
||||
using SlpModularCms.Modules.Contact.Config;
|
||||
using SlpModularCms.Modules.Contact.Controllers;
|
||||
using SlpModularCms.Modules.Contact.Data;
|
||||
using SlpModularCms.Modules.Contact.OpenApi;
|
||||
using SlpModularCms.Modules.Contact.Repositories;
|
||||
using SlpModularCms.Modules.Contact.Services;
|
||||
|
||||
@@ -47,6 +49,10 @@ public class ContactModule : IModule
|
||||
services.AddScoped<ContactRouteFilter>();
|
||||
services.AddHostedService<ContactRetentionService>();
|
||||
|
||||
// The contact details of the OpenAPI document (named options of document 'v1', so the shared
|
||||
// AddOpenApi() call in Core stays untouched).
|
||||
services.Configure<OpenApiOptions>("v1", openApi => openApi.AddDocumentTransformer<ContactOpenApiDocumentTransformer>());
|
||||
|
||||
// Rate-limit policies live in this module so the shared limiter setup stays untouched.
|
||||
// The bucket key comes from one function; see ContactRateLimitPartition.
|
||||
services.AddOptions<RateLimiterOptions>()
|
||||
|
||||
@@ -15,6 +15,7 @@ namespace SlpModularCms.Modules.Contact.Controllers;
|
||||
/// bound must produce our own problem shape, never the framework's, and must not echo values.
|
||||
/// The management routes (list, read, delete, resend) are added with the admin unit.
|
||||
/// </summary>
|
||||
[ApiExplorerSettings(IgnoreApi = false)] // not an [ApiController], so visibility must be explicit for the OpenAPI document
|
||||
[Route("contact-messages")]
|
||||
[ServiceFilter(typeof(ContactRouteFilter))]
|
||||
public class ContactMessagesController(
|
||||
@@ -30,6 +31,9 @@ public class ContactMessagesController(
|
||||
[AllowAnonymous]
|
||||
[PublicSiteEndpoint]
|
||||
[EnableRateLimiting(TokenPolicy)]
|
||||
[ProducesResponseType(typeof(ContactTokenResponse), StatusCodes.Status200OK, "application/json")]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType(StatusCodes.Status429TooManyRequests)]
|
||||
public IActionResult GetToken()
|
||||
{
|
||||
var settings = options.Value;
|
||||
@@ -44,6 +48,12 @@ public class ContactMessagesController(
|
||||
[AllowAnonymous]
|
||||
[PublicSiteEndpoint]
|
||||
[EnableRateLimiting(FormPolicy)]
|
||||
[Consumes("application/json")]
|
||||
[ProducesResponseType(typeof(ReceivedResponse), StatusCodes.Status202Accepted, "application/json")]
|
||||
[ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest, "application/problem+json")]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status413PayloadTooLarge, "application/problem+json")]
|
||||
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status429TooManyRequests, "application/problem+json")]
|
||||
public async Task<IActionResult> Submit([FromBody] ContactMessageRequest? request, CancellationToken cancellationToken)
|
||||
{
|
||||
var key = Request.Headers[IdempotencyKeyHeader].FirstOrDefault();
|
||||
@@ -53,7 +63,12 @@ public class ContactMessagesController(
|
||||
|
||||
return result switch
|
||||
{
|
||||
SubmissionResult.Invalid invalid => BadRequest(Problem(invalid.Errors)),
|
||||
SubmissionResult.Invalid invalid => new ObjectResult(Problem(invalid.Errors))
|
||||
{
|
||||
StatusCode = StatusCodes.Status400BadRequest,
|
||||
// Explicit content type: problem details are served as problem+json, not as plain json.
|
||||
ContentTypes = { "application/problem+json" },
|
||||
},
|
||||
_ => new ObjectResult(new ReceivedResponse("received")) { StatusCode = StatusCodes.Status202Accepted },
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
using System.Net.Http;
|
||||
using Microsoft.AspNetCore.OpenApi;
|
||||
using Microsoft.OpenApi;
|
||||
using SlpModularCms.Modules.Contact.Controllers;
|
||||
using SlpModularCms.Modules.Contact.Services;
|
||||
|
||||
namespace SlpModularCms.Modules.Contact.OpenApi;
|
||||
|
||||
/// <summary>
|
||||
/// Adds what attributes cannot express to the generated OpenAPI document: the reusable problem
|
||||
/// responses of the contact contract, the required <c>Idempotency-Key</c> header, and the
|
||||
/// required fields / maximum lengths of the request body. It only touches the contact
|
||||
/// operations and schemas; everything else in the document is left as generated.
|
||||
/// </summary>
|
||||
public sealed class ContactOpenApiDocumentTransformer : IOpenApiDocumentTransformer
|
||||
{
|
||||
public const string RoutePath = "/api/v1/contact-messages";
|
||||
public const string TokenPath = "/api/v1/contact-messages/token";
|
||||
|
||||
private static readonly string[] Codes = ["required", "tooLong", "invalid", "expired"];
|
||||
|
||||
public Task TransformAsync(OpenApiDocument document, OpenApiDocumentTransformerContext context, CancellationToken cancellationToken)
|
||||
{
|
||||
AddComponents(document);
|
||||
|
||||
if (document.Paths.TryGetValue(RoutePath, out var route) && route.Operations is not null
|
||||
&& route.Operations.TryGetValue(HttpMethod.Post, out var submit))
|
||||
{
|
||||
DescribeSubmit(document, submit);
|
||||
}
|
||||
|
||||
if (document.Paths.TryGetValue(TokenPath, out var token) && token.Operations is not null
|
||||
&& token.Operations.TryGetValue(HttpMethod.Get, out var getToken))
|
||||
{
|
||||
getToken.Responses ??= [];
|
||||
getToken.Responses["404"] = new OpenApiResponse { Description = "The contact form is closed on this site (the website shows its mailto fallback)." };
|
||||
getToken.Responses["429"] = new OpenApiResponseReference("RateLimited", document);
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private static void AddComponents(OpenApiDocument document)
|
||||
{
|
||||
document.Components ??= new OpenApiComponents();
|
||||
document.Components.Schemas ??= new Dictionary<string, IOpenApiSchema>();
|
||||
document.Components.Responses ??= new Dictionary<string, IOpenApiResponse>();
|
||||
|
||||
document.Components.Schemas["Problem"] = new OpenApiSchema
|
||||
{
|
||||
Type = JsonSchemaType.Object,
|
||||
Description = "RFC 9457 problem details. Only the standard members are sent; nothing about the limiter, the policy or the caller.",
|
||||
Properties = new Dictionary<string, IOpenApiSchema>
|
||||
{
|
||||
["type"] = new OpenApiSchema { Type = JsonSchemaType.String },
|
||||
["title"] = new OpenApiSchema { Type = JsonSchemaType.String },
|
||||
["status"] = new OpenApiSchema { Type = JsonSchemaType.Integer, Format = "int32" },
|
||||
},
|
||||
};
|
||||
|
||||
document.Components.Schemas["ValidationProblem"] = new OpenApiSchema
|
||||
{
|
||||
Type = JsonSchemaType.Object,
|
||||
Description = "A 400 answer. 'errors' maps the JSON field name (name, email, subject, message, token, idempotencyKey, body) to its error codes; the client maps codes to texts.",
|
||||
Properties = new Dictionary<string, IOpenApiSchema>
|
||||
{
|
||||
["type"] = new OpenApiSchema { Type = JsonSchemaType.String },
|
||||
["title"] = new OpenApiSchema { Type = JsonSchemaType.String },
|
||||
["status"] = new OpenApiSchema { Type = JsonSchemaType.Integer, Format = "int32" },
|
||||
["errors"] = new OpenApiSchema
|
||||
{
|
||||
Type = JsonSchemaType.Object,
|
||||
AdditionalProperties = new OpenApiSchema
|
||||
{
|
||||
Type = JsonSchemaType.Array,
|
||||
Items = new OpenApiSchema
|
||||
{
|
||||
Type = JsonSchemaType.String,
|
||||
Enum = Codes.Select(c => (System.Text.Json.Nodes.JsonNode)System.Text.Json.Nodes.JsonValue.Create(c)!).ToList(),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
document.Components.Responses["Validation"] = ProblemResponse(
|
||||
"Validation failed (also an expired, forged or other-site token as errors.token=[\"expired\"], a missing or non-UUID Idempotency-Key, and an unreadable body as errors.body=[\"invalid\"]).",
|
||||
"ValidationProblem", document);
|
||||
document.Components.Responses["TooLarge"] = ProblemResponse("The request body is too large.", "Problem", document);
|
||||
document.Components.Responses["RateLimited"] = new OpenApiResponse
|
||||
{
|
||||
Description = "Too many requests. Retry after the number of seconds in the Retry-After header.",
|
||||
Headers = new Dictionary<string, IOpenApiHeader>
|
||||
{
|
||||
["Retry-After"] = new OpenApiHeader
|
||||
{
|
||||
Description = "Seconds to wait before retrying.",
|
||||
Schema = new OpenApiSchema { Type = JsonSchemaType.Integer, Format = "int32" },
|
||||
},
|
||||
},
|
||||
Content = new Dictionary<string, OpenApiMediaType>
|
||||
{
|
||||
["application/problem+json"] = new() { Schema = new OpenApiSchemaReference("Problem", document) },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
private static OpenApiResponse ProblemResponse(string description, string schema, OpenApiDocument document) => new()
|
||||
{
|
||||
Description = description,
|
||||
Content = new Dictionary<string, OpenApiMediaType>
|
||||
{
|
||||
["application/problem+json"] = new() { Schema = new OpenApiSchemaReference(schema, document) },
|
||||
},
|
||||
};
|
||||
|
||||
private static void DescribeSubmit(OpenApiDocument document, OpenApiOperation submit)
|
||||
{
|
||||
submit.Parameters ??= [];
|
||||
submit.Parameters.Add(new OpenApiParameter
|
||||
{
|
||||
Name = ContactMessagesController.IdempotencyKeyHeader,
|
||||
In = ParameterLocation.Header,
|
||||
Required = true,
|
||||
Description = "A UUID chosen by the client per attempt series. A replay within 24 hours is answered with the same 202 without storing the message twice.",
|
||||
Schema = new OpenApiSchema { Type = JsonSchemaType.String, Format = "uuid" },
|
||||
});
|
||||
|
||||
submit.Responses ??= [];
|
||||
submit.Responses["400"] = new OpenApiResponseReference("Validation", document);
|
||||
submit.Responses["404"] = new OpenApiResponse { Description = "The contact form is closed on this site (the website shows its mailto fallback)." };
|
||||
submit.Responses["413"] = new OpenApiResponseReference("TooLarge", document);
|
||||
submit.Responses["429"] = new OpenApiResponseReference("RateLimited", document);
|
||||
|
||||
// The body is required and is exactly one JSON object. (The action parameter is nullable
|
||||
// on purpose, which the generator would otherwise show as 'null or object'.)
|
||||
submit.RequestBody = new OpenApiRequestBody
|
||||
{
|
||||
Required = true,
|
||||
Content = new Dictionary<string, OpenApiMediaType>
|
||||
{
|
||||
["application/json"] = new() { Schema = new OpenApiSchemaReference(nameof(Models.ContactMessageRequest), document) },
|
||||
},
|
||||
};
|
||||
|
||||
// The body schema: our model is nullable on purpose (a missing field is reported as the
|
||||
// code 'required' in our own shape), so the contract's requirements are documented here.
|
||||
if (document.Components?.Schemas is { } schemas
|
||||
&& schemas.TryGetValue(nameof(Models.ContactMessageRequest), out var schemaRef)
|
||||
&& schemaRef is OpenApiSchema request)
|
||||
{
|
||||
request.Required = new HashSet<string> { "name", "email", "subject", "message", "hpCheck", "token" };
|
||||
SetMax(request, "name", ContactValidator.NameMax);
|
||||
SetMax(request, "email", ContactValidator.EmailMax);
|
||||
SetMax(request, "subject", ContactValidator.SubjectMax);
|
||||
SetMax(request, "message", ContactValidator.MessageMax);
|
||||
SetMax(request, "hpCheck", 0);
|
||||
if (request.Properties is not null && request.Properties.TryGetValue("token", out var tokenProperty)
|
||||
&& tokenProperty is OpenApiSchema tokenSchema)
|
||||
{
|
||||
tokenSchema.Type = JsonSchemaType.String;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void SetMax(OpenApiSchema request, string property, int max)
|
||||
{
|
||||
if (request.Properties is not null && request.Properties.TryGetValue(property, out var p) && p is OpenApiSchema schema)
|
||||
{
|
||||
// Required by the contract, so a plain string for generated client types (the C# model
|
||||
// is nullable only so that a missing field can be reported in our own error shape).
|
||||
schema.Type = JsonSchemaType.String;
|
||||
schema.MaxLength = max;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user