The four rules, and the test that holds each
1. The admin surface is not in the document. OpenApiOptions.ShouldInclude answers false for
any route under /api/admin/, in one place, so the document never carries an operator endpoint
however many are added. That is a filter, and a filter is the kind of rule that breaks silently a
year later when somebody maps an admin endpoint under a new prefix, so ApiDocumentTests reads the
served document and fails if any path in it starts with /api/admin, and it reads the routing
table's own description of the host to prove the filter is doing work rather than passing because
there was nothing to filter.
public static bool IsPublic(ApiDescription description) =>
!(description.RelativePath ?? string.Empty)
.TrimStart('/')
.StartsWith(AdminPrefix, StringComparison.OrdinalIgnoreCase);
Live from api/TheYard.Api/Shared/Wire/ApiDocument.cs, region public-surface, read from this build at 99df7a8.
2. Every public endpoint is in it, and nothing else is. The same test compares the document's
paths and methods against every endpoint the host maps, minus the admin ones, in both directions.
An endpoint that somebody excludes from description by accident disappears from the document and
fails the build; a document that grew a path the host does not serve fails it too.
3. Every operation carries an operation id, a summary, and the responses it can actually
answer. The gate here is the one that stops the document rotting the way the README did. An
operation id, because a generated client and a search both key on it. A summary, because a list of
paths with no sentence beside each is a directory listing. And responses, including the failures:
a protected endpoint declares its 401, an endpoint with a route parameter declares its 404, and an
endpoint that reads a body declares its 400. A document that only shows 200s is the tell of a
generated document nobody read.
Declaring those responses honestly meant typing the endpoints. Every anonymous object became a named
record (VehiclePage, BidResult, HealthReport and the rest, in Replies.cs), the vehicle on
the wire became VehicleView rather than a JSON node with five fields added by hand, and the
handlers return TypedResults through Results<...> unions, so the generator reads the shape from
the type rather than inferring it. TypedResults.Ok rather than TypedResults.Json, because only
the first carries its type into the document; the second serialises the same bytes and declares
nothing. Where a handler answers text or a file, the endpoint says so with Produces. The wire did
not change: the same snake_case names, in the same order, with the derived auction facts last.
4. The bearer scheme is declared, and only the protected operations require it. The session is
a JWT that the browser carries in an httpOnly cookie and that a client can carry as a bearer header;
the handler reads either. The document declares both schemes, and an operation transformer marks
every endpoint that has RequireAuthorization as requiring one or the other, so the reference page
shows a lock on exactly the operations that will answer 401 without a session. The test reads the
routing table for the endpoints that carry authorization metadata and requires the set of
operations with a security requirement to be exactly that set.
public static void Configure(OpenApiOptions options, string version, string commit, string? siteUrl)
{
options.ShouldInclude = IsPublic;
options.OpenApiVersion = OpenApiSpecVersion.OpenApi3_2;
options.AddDocumentTransformer((document, _, _) =>
{
document.Servers = string.IsNullOrWhiteSpace(siteUrl)
? []
: [new OpenApiServer { Url = siteUrl.TrimEnd('/') }];
document.Info ??= new OpenApiInfo();
document.Info.Title = Title;
document.Info.Version = version;
document.Info.Description =
"A used-vehicle auction platform in .NET " + Environment.Version.Major + ": a hundred thousand listings with server-derived "
+ "auction windows, bidding against a simulated room, accounts, and two stores behind one set of "
+ "ports. Every response is snake_case, every instant is milliseconds since the epoch, every "
+ "amount is whole dollars, and every failure is an RFC 9457 problem. Built from commit "
+ commit + ". The decisions behind the API are served beside it, under Decision Records.";
document.Components ??= new OpenApiComponents();
document.Components.SecuritySchemes ??= new Dictionary<string, IOpenApiSecurityScheme>(StringComparer.Ordinal);
document.Components.SecuritySchemes[BearerScheme] = new OpenApiSecurityScheme
{
Type = SecuritySchemeType.Http,
Scheme = "bearer",
BearerFormat = "JWT",
Description = "The session token, issued by register, login and reset, sent as a bearer header.",
};
document.Components.SecuritySchemes[CookieScheme] = new OpenApiSecurityScheme
{
Type = SecuritySchemeType.ApiKey,
In = ParameterLocation.Cookie,
Name = TokenIssuer.CookieName,
Description = "The same token as the browser carries it: an httpOnly cookie set by register, login and reset.",
};
return Task.CompletedTask;
});
options.AddSchemaTransformer((schema, _, _) =>
{
if (schema.Type is { } type
&& type.HasFlag(JsonSchemaType.String)
&& (type.HasFlag(JsonSchemaType.Integer) || type.HasFlag(JsonSchemaType.Number)))
{
schema.Type = type & ~JsonSchemaType.String;
schema.Pattern = null;
}
return Task.CompletedTask;
});
options.AddOperationTransformer((operation, context, _) =>
{
var metadata = context.Description.ActionDescriptor.EndpointMetadata;
bool guarded = metadata.OfType<IAuthorizeData>().Any() && !metadata.OfType<IAllowAnonymous>().Any();
if (guarded)
{
operation.Security ??= [];
operation.Security.Add(new OpenApiSecurityRequirement
{
[new OpenApiSecuritySchemeReference(BearerScheme, context.Document)] = [],
});
operation.Security.Add(new OpenApiSecurityRequirement
{
[new OpenApiSecuritySchemeReference(CookieScheme, context.Document)] = [],
});
}
return Task.CompletedTask;
});
}
Live from api/TheYard.Api/Shared/Wire/ApiDocument.cs, region transformers, read from this build at 99df7a8.
The whole of the test class is the enforcement, and the rules table in ADR: The rules a change has
to pass names it beside the other seventeen:
private sealed record Mapped(string Method, string Path, bool Protected);
private IReadOnlyList<Mapped> Endpoints() =>
factory.Services.GetRequiredService<IApiDescriptionGroupCollectionProvider>()
.ApiDescriptionGroups.Items
.SelectMany(group => group.Items)
.Select(description => new Mapped(
description.HttpMethod ?? "",
"/" + (description.RelativePath ?? "").TrimStart('/'),
description.ActionDescriptor.EndpointMetadata.OfType<IAuthorizeData>().Any()
&& !description.ActionDescriptor.EndpointMetadata.OfType<IAllowAnonymous>().Any()))
.ToList();
private static bool IsAdmin(string path) =>
path.StartsWith("/" + ApiDocument.AdminPrefix, StringComparison.OrdinalIgnoreCase);
private async Task<JsonDocument> DocumentAsync()
{
var response = await _client.GetAsync(ApiDocument.DocumentRoute);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
return JsonDocument.Parse(await response.Content.ReadAsStringAsync());
}
private static List<(string Method, string Path, JsonElement Operation)> Operations(JsonDocument document)
{
var operations = new List<(string, string, JsonElement)>();
foreach (var path in document.RootElement.GetProperty("paths").EnumerateObject())
{
foreach (var operation in path.Value.EnumerateObject())
{
operations.Add((operation.Name.ToUpperInvariant(), path.Name, operation.Value));
}
}
return operations;
}
[Fact]
public async Task The_document_is_served_and_says_what_it_describes()
{
using var document = await DocumentAsync();
Assert.StartsWith("3.", document.RootElement.GetProperty("openapi").GetString(), StringComparison.Ordinal);
Assert.Equal(ApiDocument.Title, document.RootElement.GetProperty("info").GetProperty("title").GetString());
Assert.False(string.IsNullOrWhiteSpace(document.RootElement.GetProperty("info").GetProperty("description").GetString()));
}
[Fact]
public async Task The_document_is_written_in_the_version_the_code_sets()
{
using var document = await DocumentAsync();
Assert.StartsWith("3.2", document.RootElement.GetProperty("openapi").GetString(), StringComparison.Ordinal);
}
[Fact]
public async Task No_admin_route_is_in_the_public_document()
{
using var document = await DocumentAsync();
var leaked = Operations(document)
.Where(operation => IsAdmin(operation.Path))
.Select(operation => $"{operation.Method} {operation.Path}")
.ToList();
Assert.True(leaked.Count == 0, "these operator endpoints are in the public document: " + string.Join(", ", leaked));
int admin = Endpoints().Count(endpoint => IsAdmin(endpoint.Path));
Assert.True(admin >= 10, $"only {admin} admin endpoints are mapped, so this test is not exercising the filter");
}
[Fact]
public async Task Every_public_endpoint_is_in_the_document_and_nothing_else_is()
{
using var document = await DocumentAsync();
var mapped = Endpoints()
.Where(endpoint => !IsAdmin(endpoint.Path))
.Select(endpoint => $"{endpoint.Method} {endpoint.Path}")
.ToHashSet(StringComparer.Ordinal);
var documented = Operations(document)
.Select(operation => $"{operation.Method} {operation.Path}")
.ToHashSet(StringComparer.Ordinal);
Assert.True(mapped.Count >= 20, $"only {mapped.Count} public endpoints were read from the host");
Assert.True(
mapped.SetEquals(documented),
"mapped but not documented: [" + string.Join(", ", mapped.Except(documented))
+ "]; documented but not mapped: [" + string.Join(", ", documented.Except(mapped)) + "]");
}
[Fact]
public async Task Every_operation_carries_an_operation_id_a_summary_and_its_responses()
{
using var document = await DocumentAsync();
var wrong = new List<string>();
var ids = new HashSet<string>(StringComparer.Ordinal);
foreach ((string method, string path, JsonElement operation) in Operations(document))
{
string where = $"{method} {path}";
string? id = operation.TryGetProperty("operationId", out var idElement) ? idElement.GetString() : null;
if (string.IsNullOrWhiteSpace(id))
{
wrong.Add($"{where} has no operation id");
}
else if (!ids.Add(id))
{
wrong.Add($"{where} repeats the operation id {id}");
}
if (!operation.TryGetProperty("summary", out var summary) || string.IsNullOrWhiteSpace(summary.GetString()))
{
wrong.Add($"{where} has no summary");
}
if (!operation.TryGetProperty("responses", out var responses) || responses.ValueKind != JsonValueKind.Object)
{
wrong.Add($"{where} declares no responses");
continue;
}
bool success = false;
foreach (var response in responses.EnumerateObject())
{
if (!Regex.IsMatch(response.Name, @"^\d{3}$"))
{
wrong.Add($"{where} declares a response called '{response.Name}' rather than a status code");
continue;
}
if (response.Name[0] == '3')
{
success = true;
continue;
}
if (response.Name[0] != '2')
{
continue;
}
success = true;
if (response.Name != "204"
&& (!response.Value.TryGetProperty("content", out var content) || !content.EnumerateObject().Any()))
{
wrong.Add($"{where} declares a {response.Name} with no content type or shape");
}
}
if (!success)
{
wrong.Add($"{where} declares no success response");
}
}
Assert.True(wrong.Count == 0, string.Join(Environment.NewLine, wrong));
}
[Fact]
public async Task Every_operation_declares_the_failures_it_can_answer()
{
using var document = await DocumentAsync();
var guarded = Endpoints()
.Where(endpoint => endpoint.Protected && !IsAdmin(endpoint.Path))
.Select(endpoint => $"{endpoint.Method} {endpoint.Path}")
.ToHashSet(StringComparer.Ordinal);
var wrong = new List<string>();
foreach ((string method, string path, JsonElement operation) in Operations(document))
{
string where = $"{method} {path}";
var declared = operation.GetProperty("responses").EnumerateObject().Select(response => response.Name).ToHashSet(StringComparer.Ordinal);
if (guarded.Contains(where) && !declared.Contains("401"))
{
wrong.Add($"{where} needs a session and does not declare its 401");
}
if (path.Contains('{') && !declared.Contains("404"))
{
wrong.Add($"{where} takes a route parameter and does not declare its 404");
}
if (operation.TryGetProperty("requestBody", out _) && !declared.Contains("400"))
{
wrong.Add($"{where} reads a body and does not declare its 400");
}
}
Assert.True(wrong.Count == 0, string.Join(Environment.NewLine, wrong));
}
[Fact]
public async Task The_schemes_are_declared_and_only_the_protected_operations_require_one()
{
using var document = await DocumentAsync();
var schemes = document.RootElement.GetProperty("components").GetProperty("securitySchemes");
var bearer = schemes.GetProperty(ApiDocument.BearerScheme);
Assert.Equal("http", bearer.GetProperty("type").GetString());
Assert.Equal("bearer", bearer.GetProperty("scheme").GetString());
var cookie = schemes.GetProperty(ApiDocument.CookieScheme);
Assert.Equal("apiKey", cookie.GetProperty("type").GetString());
Assert.Equal("cookie", cookie.GetProperty("in").GetString());
Assert.Equal(TokenIssuer.CookieName, cookie.GetProperty("name").GetString());
var guarded = Endpoints()
.Where(endpoint => endpoint.Protected && !IsAdmin(endpoint.Path))
.Select(endpoint => $"{endpoint.Method} {endpoint.Path}")
.ToHashSet(StringComparer.Ordinal);
var locked = Operations(document)
.Where(operation => operation.Operation.TryGetProperty("security", out var security)
&& security.EnumerateArray().Any(requirement => requirement.TryGetProperty(ApiDocument.BearerScheme, out _)))
.Select(operation => $"{operation.Method} {operation.Path}")
.ToHashSet(StringComparer.Ordinal);
Assert.True(guarded.Count >= 5, $"only {guarded.Count} protected endpoints were read from the host");
Assert.True(
guarded.SetEquals(locked),
"protected but not locked in the document: [" + string.Join(", ", guarded.Except(locked))
+ "]; locked but not protected: [" + string.Join(", ", locked.Except(guarded)) + "]");
}
[Fact]
public async Task Every_number_in_the_document_is_a_number_and_nothing_else()
{
using var document = await DocumentAsync();
var wrong = new List<string>();
void Walk(JsonElement element, string where)
{
if (element.ValueKind == JsonValueKind.Object)
{
if (element.TryGetProperty("type", out var type) && type.ValueKind == JsonValueKind.Array)
{
var names = type.EnumerateArray().Select(name => name.GetString()).ToList();
if (names.Contains("string") && (names.Contains("integer") || names.Contains("number")))
{
wrong.Add($"{where} is typed [{string.Join(", ", names)}]");
}
}
foreach (var property in element.EnumerateObject())
{
Walk(property.Value, where + "/" + property.Name);
}
}
else if (element.ValueKind == JsonValueKind.Array)
{
int index = 0;
foreach (var item in element.EnumerateArray())
{
Walk(item, where + "/" + index++);
}
}
}
Walk(document.RootElement.GetProperty("components").GetProperty("schemas"), "schemas");
Walk(document.RootElement.GetProperty("paths"), "paths");
Assert.True(wrong.Count == 0, string.Join(Environment.NewLine, wrong));
}
[Fact]
public async Task The_document_names_the_site_as_its_server_only_when_the_site_has_an_address()
{
using var unnamed = await DocumentAsync();
Assert.False(
unnamed.RootElement.TryGetProperty("servers", out var none) && none.GetArrayLength() > 0,
"with no Site:Url the document should name no server");
using var named = factory.WithWebHostBuilder(host => host.UseSetting("Site:Url", "https://theyard.example/"));
using var response = await named.CreateClient().GetAsync(ApiDocument.DocumentRoute);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using var document = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
var servers = document.RootElement.GetProperty("servers");
Assert.Equal(1, servers.GetArrayLength());
Assert.Equal("https://theyard.example", servers[0].GetProperty("url").GetString());
}
[Fact]
public async Task The_reference_page_is_served_from_the_same_container()
{
var response = await _client.GetAsync(ApiDocument.ReferenceRoute);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("text/html", response.Content.Headers.ContentType?.MediaType);
Assert.Contains(ApiDocument.Title, await response.Content.ReadAsStringAsync(), StringComparison.Ordinal);
}
Live from api/TheYard.Tests/ApiDocumentTests.cs, region document, read from this build at 99df7a8.