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:
2026-11-10 13:07:28 +01:00
co-authored by Claude Sonnet 5.5
parent ce06fad727
commit f8d45eef54
9 changed files with 1968 additions and 13 deletions
@@ -88,7 +88,7 @@ public class ContactMessagesControllerTests
var result = await Create(new ContactOptions { Enabled = true, ProblemTypeBase = "https://example.test/problems/" })
.Submit(new ContactMessageRequest(null, null, null, null, null, null, null), CancellationToken.None);
var problem = result.Should().BeOfType<BadRequestObjectResult>().Subject.Value.Should().BeOfType<ValidationProblemDetails>().Subject;
var problem = result.Should().BeOfType<ObjectResult>().Subject.Value.Should().BeOfType<ValidationProblemDetails>().Subject;
problem.Status.Should().Be(400);
problem.Type.Should().Be("https://example.test/problems/validation");
problem.Errors["email"].Should().Equal("invalid");
@@ -102,7 +102,7 @@ public class ContactMessagesControllerTests
var result = await Create().Submit(null, CancellationToken.None);
((ValidationProblemDetails)((BadRequestObjectResult)result).Value!).Type.Should().Be("about:blank");
((ValidationProblemDetails)((ObjectResult)result).Value!).Type.Should().Be("about:blank");
}
[Fact]
@@ -0,0 +1,160 @@
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Nodes;
using FluentAssertions;
namespace SlpModularCms.Modules.Contact.Tests.Pipeline;
/// <summary>
/// Keeps the committed OpenAPI document of the SlpSoftware host (<c>openapi/slpsoftware.v1.json</c>)
/// equal to what the real, composed host serves, and checks the contact contract inside it.
/// </summary>
/// <remarks>
/// The document is the single source from which the frontend client (<c>cms-client</c>)
/// generates its types. To regenerate after an intended API change run:
/// <c>UPDATE_OPENAPI=1 dotnet test --filter OpenApiSnapshot</c>.
/// </remarks>
public class OpenApiSnapshotTests(DisabledContactHostFactory factory) : IClassFixture<DisabledContactHostFactory>
{
private const string FileName = "slpsoftware.v1.json";
private static string RepositoryRoot()
{
var directory = new DirectoryInfo(AppContext.BaseDirectory);
while (directory is not null && !File.Exists(Path.Combine(directory.FullName, "SlpModularCms.sln")))
{
directory = directory.Parent;
}
return directory?.FullName ?? throw new InvalidOperationException("SlpModularCms.sln not found above the test output.");
}
private static string SnapshotPath() => Path.Combine(RepositoryRoot(), "openapi", FileName);
private async Task<string> FetchAsync()
{
var response = await factory.CreateClient().GetAsync("/openapi/v1.json");
response.IsSuccessStatusCode.Should().BeTrue();
return await response.Content.ReadAsStringAsync();
}
/// <summary>
/// A stable form: no request-derived <c>servers</c>, every object's keys in ordinal order (the
/// generator's order depends on assembly discovery), 2-space indentation, LF, trailing newline.
/// </summary>
internal static string Normalize(string json)
{
var root = JsonNode.Parse(json)!.AsObject();
root.Remove("servers");
var text = Sort(root)!.ToJsonString(new JsonSerializerOptions
{
WriteIndented = true,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
});
return text.Replace("\r\n", "\n") + "\n";
}
private static JsonNode? Sort(JsonNode? node) => node switch
{
JsonObject obj => new JsonObject(obj
.OrderBy(p => p.Key, StringComparer.Ordinal)
.Select(p => new KeyValuePair<string, JsonNode?>(p.Key, Sort(p.Value)))),
JsonArray array => new JsonArray(array.Select(Sort).ToArray()),
_ => node?.DeepClone(),
};
[Fact]
public async Task TheCommittedDocument_EqualsWhatTheHostServes()
{
var current = Normalize(await FetchAsync());
var path = SnapshotPath();
if (Environment.GetEnvironmentVariable("UPDATE_OPENAPI") == "1")
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
await File.WriteAllTextAsync(path, current, new System.Text.UTF8Encoding(false));
return;
}
File.Exists(path).Should().BeTrue($"{path} is missing. Generate it with: UPDATE_OPENAPI=1 dotnet test --filter OpenApiSnapshot");
var committed = (await File.ReadAllTextAsync(path)).Replace("\r\n", "\n");
committed.Should().Be(
current,
"the OpenAPI document changed. If that is intended, regenerate the committed file with: " +
"UPDATE_OPENAPI=1 dotnet test --filter OpenApiSnapshot");
}
[Fact]
public async Task TheDocument_ContainsTheContactContract()
{
var doc = JsonNode.Parse(Normalize(await FetchAsync()))!;
var paths = doc["paths"]!.AsObject();
paths.Select(p => p.Key).Should().Contain(["/api/v1/contact-messages", "/api/v1/contact-messages/token"]);
// POST /contact-messages
var post = doc["paths"]!["/api/v1/contact-messages"]!["post"]!;
var header = post["parameters"]!.AsArray().Single(p => p!["name"]!.GetValue<string>() == "Idempotency-Key")!;
header["in"]!.GetValue<string>().Should().Be("header");
header["required"]!.GetValue<bool>().Should().BeTrue();
header["schema"]!["format"]!.GetValue<string>().Should().Be("uuid");
post["requestBody"]!["required"]!.GetValue<bool>().Should().BeTrue();
post["requestBody"]!["content"]!["application/json"]!["schema"]!["$ref"]!.GetValue<string>()
.Should().EndWith("/ContactMessageRequest");
post["responses"]!.AsObject().Select(p => p.Key).Should().BeEquivalentTo(["202", "400", "404", "413", "429"]);
post["responses"]!["400"]!["$ref"]!.GetValue<string>().Should().EndWith("/Validation");
post["responses"]!["413"]!["$ref"]!.GetValue<string>().Should().EndWith("/TooLarge");
post["responses"]!["429"]!["$ref"]!.GetValue<string>().Should().EndWith("/RateLimited");
// GET /contact-messages/token
var token = doc["paths"]!["/api/v1/contact-messages/token"]!["get"]!;
token["responses"]!.AsObject().Select(p => p.Key).Should().BeEquivalentTo(["200", "404", "429"]);
// Request schema: the contract's required fields and limits.
var request = doc["components"]!["schemas"]!["ContactMessageRequest"]!;
request["required"]!.AsArray().Select(n => n!.GetValue<string>())
.Should().BeEquivalentTo(["name", "email", "subject", "message", "hpCheck", "token"]);
var properties = request["properties"]!;
properties["name"]!["maxLength"]!.GetValue<int>().Should().Be(100);
properties["email"]!["maxLength"]!.GetValue<int>().Should().Be(254);
properties["subject"]!["maxLength"]!.GetValue<int>().Should().Be(100);
properties["message"]!["maxLength"]!.GetValue<int>().Should().Be(2000);
properties["hpCheck"]!["maxLength"]!.GetValue<int>().Should().Be(0);
// Reusable responses.
var responses = doc["components"]!["responses"]!;
responses["RateLimited"]!["headers"]!["Retry-After"].Should().NotBeNull();
responses["Validation"]!["content"]!["application/problem+json"].Should().NotBeNull();
responses["TooLarge"]!["content"]!["application/problem+json"].Should().NotBeNull();
var codes = doc["components"]!["schemas"]!["ValidationProblem"]!["properties"]!["errors"]!["additionalProperties"]!["items"]!["enum"]!
.AsArray().Select(n => n!.GetValue<string>());
codes.Should().BeEquivalentTo(["required", "tooLong", "invalid", "expired"]);
}
[Fact]
public async Task TheDocument_HoldsNoHostNamesAddressesOrSecrets()
{
var text = Normalize(await FetchAsync());
text.Should().NotContain("127.0.0.1").And.NotContain("localhost");
text.Should().NotContain("@", "no e-mail addresses (not even examples)");
text.ToLowerInvariant().Should().NotContain("secret\":").And.NotContain("password\":\"");
JsonNode.Parse(text)!.AsObject().ContainsKey("servers").Should().BeFalse();
}
[Fact]
public void Normalize_IsDeterministic_RegardlessOfKeyOrder()
{
const string a = """{"servers":[{"url":"http://x"}],"b":1,"a":{"z":1,"y":[{"d":1,"c":2}]}}""";
const string b = """{"a":{"y":[{"c":2,"d":1}],"z":1},"b":1}""";
Normalize(a).Should().Be(Normalize(b));
Normalize(a).Should().EndWith("\n").And.NotContain("\r");
}
}
@@ -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;
}
}
}