From 9b5d6754fb1b18bf75b9777f53c5b0a070b8abab Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Fri, 4 Dec 2026 16:04:00 +0100 Subject: [PATCH 1/3] feat(openapi): split the OpenAPI document by audience /openapi.json now holds only the SDK surface: endpoints that accept an API token or hub token, plus anonymous endpoints explicitly marked as SDK. Everything else moves to /openapi/frontend.json: session-only endpoints (including the admin ones), trusted-origin flows and anonymous frontend flows. Scalar lists both. The audience is derived from each endpoint's authorization metadata; an anonymous endpoint without an [OpenApiAudience] marker makes document generation throw, so nothing lands in the SDK document by default. --- .../Tests/OpenApiDocumentTests.cs | 73 +++++++++++--- API/Controller/Account/_ApiController.cs | 2 + API/Controller/Device/Pair.cs | 2 + API/Controller/Integrations/_ApiController.cs | 2 + API/Controller/OAuth/_ApiController.cs | 2 + API/Controller/Public/_ApiController.cs | 2 + API/Controller/Version/_ApiController.cs | 2 + API/Program.cs | 9 +- Common.Tests/OpenApi/OpenApiAudiencesTests.cs | 48 +++++++++ Common/OpenApi/OpenApiAudience.cs | 99 +++++++++++++++++++ Common/OpenShockMiddlewareHelper.cs | 18 +++- Common/OpenShockServiceHelper.cs | 7 +- README.md | 9 ++ 13 files changed, 253 insertions(+), 22 deletions(-) create mode 100644 Common.Tests/OpenApi/OpenApiAudiencesTests.cs create mode 100644 Common/OpenApi/OpenApiAudience.cs diff --git a/API.IntegrationTests/Tests/OpenApiDocumentTests.cs b/API.IntegrationTests/Tests/OpenApiDocumentTests.cs index 69c00ad2..533bb166 100644 --- a/API.IntegrationTests/Tests/OpenApiDocumentTests.cs +++ b/API.IntegrationTests/Tests/OpenApiDocumentTests.cs @@ -5,43 +5,94 @@ namespace OpenShock.API.IntegrationTests.Tests; public sealed class OpenApiDocumentTests { + private static readonly string[] DocumentPaths = ["/openapi.json", "/openapi/frontend.json"]; + [ClassDataSource(Shared = SharedType.PerTestSession)] public required WebApplicationFactory WebApplicationFactory { get; init; } - [Test] - public async Task GetOpenApiDocument_ServesSingleDocumentWithEveryVersion() + private async Task GetPathsAsync(string documentPath) { using var client = WebApplicationFactory.CreateClient(); - var response = await client.GetAsync("/openapi.json"); - + var response = await client.GetAsync(documentPath); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); await Assert.That(response.Content.Headers.ContentType?.MediaType).IsEqualTo("application/json"); using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); - var paths = doc.RootElement.GetProperty("paths").EnumerateObject().Select(p => p.Name).ToArray(); + return doc.RootElement.GetProperty("paths").EnumerateObject().Select(p => p.Name).ToArray(); + } + + [Test] + public async Task SdkDocument_HasTokenAndPublicEndpointsOnly() + { + var paths = await GetPathsAsync("/openapi.json"); + + await Assert.That(paths).Contains("/1/shockers/own"); // API token + await Assert.That(paths).Contains("/2/shockers/control"); // API token, newest version only + await Assert.That(paths).Contains("/1/device/self"); // hub token + await Assert.That(paths).Contains("/1/public/shares/links/{publicShareId}"); // anonymous, marked Sdk + + await Assert.That(paths).DoesNotContain("/2/account/login"); + await Assert.That(paths).DoesNotContain("/1/account/username/check"); + await Assert.That(paths).DoesNotContain("/1/sessions"); // session cookie only + await Assert.That(paths.Where(path => path.Contains("/admin/"))).IsEmpty(); + } + + [Test] + public async Task FrontendDocument_HasSessionSignupAndAdminEndpoints() + { + var paths = await GetPathsAsync("/openapi/frontend.json"); - await Assert.That(paths).Contains("/1/account"); + await Assert.That(paths).Contains("/2/account/signup"); await Assert.That(paths).Contains("/2/account/login"); + await Assert.That(paths).Contains("/1/sessions"); + await Assert.That(paths).Contains("/1/admin/users"); + await Assert.That(paths).Contains("/1/admin/users/{userId}"); + await Assert.That(paths).DoesNotContain("/1/shockers/own"); } [Test] - public async Task GetOpenApiDocument_IncludesXmlDocsTheBuiltInSupportLeavesOut() + public async Task EveryOperationIsInExactlyOneDocument() { using var client = WebApplicationFactory.CreateClient(); - using var doc = JsonDocument.Parse(await client.GetStringAsync("/openapi.json")); - var root = doc.RootElement; + var operations = new List(); + foreach (var documentPath in DocumentPaths) + { + using var doc = JsonDocument.Parse(await client.GetStringAsync(documentPath)); + operations.AddRange(doc.RootElement.GetProperty("paths").EnumerateObject() + .SelectMany(path => path.Value.EnumerateObject().Select(method => $"{method.Name.ToUpperInvariant()} {path.Name}"))); + } + + await Assert.That(operations.GroupBy(operation => operation).Where(group => group.Count() > 1).Select(group => group.Key)).IsEmpty(); + } + + [Test] + [Arguments("/openapi.json")] + [Arguments("/openapi/frontend.json")] + public async Task GetOpenApiDocument_IncludesXmlDocsTheBuiltInSupportLeavesOut(string documentPath) + { + using var client = WebApplicationFactory.CreateClient(); + + using var doc = JsonDocument.Parse(await client.GetStringAsync(documentPath)); // Every tag is described by the of its controller - var undescribedTags = root.GetProperty("tags").EnumerateArray() + var undescribedTags = doc.RootElement.GetProperty("tags").EnumerateArray() .Where(tag => !tag.TryGetProperty("description", out var description) || string.IsNullOrWhiteSpace(description.GetString())) .Select(tag => tag.GetProperty("name").GetString()) .ToArray(); await Assert.That(undescribedTags).IsEmpty(); + } + + [Test] + public async Task GetOpenApiDocument_FillsDocumentedResponsesWithoutProducesResponseType() + { + using var client = WebApplicationFactory.CreateClient(); + + using var doc = JsonDocument.Parse(await client.GetStringAsync("/openapi/frontend.json")); // A documented without a [ProducesResponseType] - var linkShareCode = root.GetProperty("paths").GetProperty("/1/shares/code/{shareCodeId}").GetProperty("post"); + var linkShareCode = doc.RootElement.GetProperty("paths").GetProperty("/1/shares/code/{shareCodeId}").GetProperty("post"); var description = linkShareCode.GetProperty("responses").GetProperty("500").GetProperty("description").GetString(); await Assert.That(description).IsEqualTo("Error while linking share code to your account"); } diff --git a/API/Controller/Account/_ApiController.cs b/API/Controller/Account/_ApiController.cs index 9dd7a89d..07157afa 100644 --- a/API/Controller/Account/_ApiController.cs +++ b/API/Controller/Account/_ApiController.cs @@ -2,6 +2,7 @@ using OpenShock.API.Services.Signup; using OpenShock.API.Services.Account; using OpenShock.Common; +using OpenShock.Common.OpenApi; namespace OpenShock.API.Controller.Account; @@ -10,6 +11,7 @@ namespace OpenShock.API.Controller.Account; /// [ApiController] [Tags("Account")] +[OpenApiAudience(OpenApiAudience.Frontend)] [Route("/{version:apiVersion}/account")] public sealed partial class AccountController : OpenShockControllerBase { diff --git a/API/Controller/Device/Pair.cs b/API/Controller/Device/Pair.cs index 64b32b48..78afac0f 100644 --- a/API/Controller/Device/Pair.cs +++ b/API/Controller/Device/Pair.cs @@ -8,6 +8,7 @@ using OpenShock.Common.Models; using OpenShock.Common.Redis; using OpenShock.Internal.Common.Problems; +using OpenShock.Common.OpenApi; namespace OpenShock.API.Controller.Device; @@ -23,6 +24,7 @@ public sealed partial class DeviceController [HttpGet("pair/{pairCode}", Name = "Pair")] [ApiVersion(1)] [AllowAnonymous] + [OpenApiAudience(OpenApiAudience.Sdk)] [EnableRateLimiting("auth")] [EndpointName("PairDeviceByCode")] [ProducesResponseType>(StatusCodes.Status200OK, MediaTypeNames.Application.Json)] diff --git a/API/Controller/Integrations/_ApiController.cs b/API/Controller/Integrations/_ApiController.cs index 8a49e6ed..0448f829 100644 --- a/API/Controller/Integrations/_ApiController.cs +++ b/API/Controller/Integrations/_ApiController.cs @@ -1,6 +1,7 @@ using Microsoft.AspNetCore.Mvc; using OpenShock.Common; using OpenShock.Common.OpenShockDb; +using OpenShock.Common.OpenApi; namespace OpenShock.API.Controller.Integrations; @@ -10,6 +11,7 @@ namespace OpenShock.API.Controller.Integrations; /// [ApiController] [Tags("Integrations")] +[OpenApiAudience(OpenApiAudience.Sdk)] [Route("/{version:apiVersion}/integrations")] public sealed partial class IntegrationsController : OpenShockControllerBase { diff --git a/API/Controller/OAuth/_ApiController.cs b/API/Controller/OAuth/_ApiController.cs index 3ee75e3c..62d51403 100644 --- a/API/Controller/OAuth/_ApiController.cs +++ b/API/Controller/OAuth/_ApiController.cs @@ -6,6 +6,7 @@ using OpenShock.API.Services.Account; using OpenShock.Common; using OpenShock.Common.Results; +using OpenShock.Common.OpenApi; namespace OpenShock.API.Controller.OAuth; @@ -14,6 +15,7 @@ namespace OpenShock.API.Controller.OAuth; /// [ApiController] [Tags("OAuth")] +[OpenApiAudience(OpenApiAudience.Frontend)] [Route("/{version:apiVersion}/oauth")] public sealed partial class OAuthController : OpenShockControllerBase { diff --git a/API/Controller/Public/_ApiController.cs b/API/Controller/Public/_ApiController.cs index f15c46f6..424268db 100644 --- a/API/Controller/Public/_ApiController.cs +++ b/API/Controller/Public/_ApiController.cs @@ -1,10 +1,12 @@ using Microsoft.AspNetCore.Mvc; using OpenShock.Common; using OpenShock.Common.OpenShockDb; +using OpenShock.Common.OpenApi; namespace OpenShock.API.Controller.Public; [ApiController] +[OpenApiAudience(OpenApiAudience.Sdk)] [Route("/{version:apiVersion}/public")] public sealed partial class PublicController : OpenShockControllerBase { diff --git a/API/Controller/Version/_ApiController.cs b/API/Controller/Version/_ApiController.cs index 93fde37a..5fb907dc 100644 --- a/API/Controller/Version/_ApiController.cs +++ b/API/Controller/Version/_ApiController.cs @@ -10,6 +10,7 @@ using OpenShock.Common.Models; using OpenShock.Common.Options; using OpenShock.Internal.Common.Utils; +using OpenShock.Common.OpenApi; namespace OpenShock.API.Controller.Version; @@ -19,6 +20,7 @@ namespace OpenShock.API.Controller.Version; /// [ApiController] [Tags("Meta")] +[OpenApiAudience(OpenApiAudience.Sdk)] [Route("/{version:apiVersion}")] public sealed partial class VersionController : OpenShockControllerBase { diff --git a/API/Program.cs b/API/Program.cs index 79f03a3c..b05be6fd 100644 --- a/API/Program.cs +++ b/API/Program.cs @@ -15,6 +15,7 @@ using OpenShock.Common; using OpenShock.Common.Extensions; using OpenShock.Common.Hubs; +using OpenShock.Common.OpenApi; using OpenShock.Common.Services; using OpenShock.Common.Services.Device; using OpenShock.Common.Services.Ota; @@ -137,8 +138,10 @@ static void DefaultOptions(RemoteAuthenticationOptions options, string provider) }) .AddOpenShockSignalR(redisOptions); -// XML documentation comments are applied by a source generator that intercepts this call, so it has to be made here in the host -builder.Services.AddOpenApi(OpenShockServiceHelper.OpenApiDocumentName, OpenShockServiceHelper.ConfigureOpenApi); +// XML documentation comments are applied by a source generator that intercepts these calls, so they have to be made here in the host. +// One document per audience (see OpenApiAudiences): the SDK one is the default, served at /openapi.json. +builder.Services.AddOpenApi(OpenApiAudiences.DocumentName(OpenApiAudience.Sdk), OpenApiAudiences.Configure(OpenApiAudience.Sdk)); +builder.Services.AddOpenApi(OpenApiAudiences.DocumentName(OpenApiAudience.Frontend), OpenApiAudiences.Configure(OpenApiAudience.Frontend)); builder.Services.AddScoped(); builder.Services.AddScoped(); @@ -168,7 +171,7 @@ static void DefaultOptions(RemoteAuthenticationOptions options, string provider) // shared host). Empty by default -> served at root, unchanged behavior. var apiPathBase = builder.Configuration.GetValue("OpenShock:Api:PathBase"); -await app.UseCommonOpenShockMiddleware(apiPathBase); +await app.UseCommonOpenShockMiddleware(apiPathBase, openApiAudienceDocuments: true); if (!databaseOptions.SkipMigration) { diff --git a/Common.Tests/OpenApi/OpenApiAudiencesTests.cs b/Common.Tests/OpenApi/OpenApiAudiencesTests.cs new file mode 100644 index 00000000..2d4beeb3 --- /dev/null +++ b/Common.Tests/OpenApi/OpenApiAudiencesTests.cs @@ -0,0 +1,48 @@ +using Microsoft.AspNetCore.Authorization; +using OpenShock.Common.Authentication; +using OpenShock.Common.Authentication.Attributes; +using OpenShock.Common.OpenApi; + +namespace OpenShock.Common.Tests.OpenApi; + +public sealed class OpenApiAudiencesTests +{ + private static AuthorizeAttribute Authorize(string schemes, string? roles = null) + => new() { AuthenticationSchemes = schemes, Roles = roles }; + + private static OpenApiAudienceAttribute Marked(OpenApiAudience audience) => new(audience); + + public static IEnumerable> Cases() + { + yield return () => ([Authorize(OpenShockAuthSchemes.UserSessionCookie, "Admin")], OpenApiAudience.Frontend); // the admin controller + yield return () => ([Authorize(OpenShockAuthSchemes.ApiToken)], OpenApiAudience.Sdk); + yield return () => ([Authorize(OpenShockAuthSchemes.HubToken)], OpenApiAudience.Sdk); + yield return () => ([Authorize(OpenShockAuthSchemes.UserSessionApiTokenCombo)], OpenApiAudience.Sdk); + yield return () => ([Authorize(OpenShockAuthSchemes.UserSessionCookie)], OpenApiAudience.Frontend); + yield return () => ([new AuthorizeAttribute()], OpenApiAudience.Frontend); // default scheme is the session cookie + // Stacked [Authorize] (controller session-only, action adds the combo) accept the union of schemes + yield return () => ([Authorize(OpenShockAuthSchemes.UserSessionCookie), Authorize(OpenShockAuthSchemes.UserSessionApiTokenCombo)], OpenApiAudience.Sdk); + yield return () => ([new TrustedOriginAttribute(), Marked(OpenApiAudience.Sdk)], OpenApiAudience.Frontend); + yield return () => ([Marked(OpenApiAudience.Sdk)], OpenApiAudience.Sdk); + yield return () => ([Marked(OpenApiAudience.Frontend)], OpenApiAudience.Frontend); + yield return () => ([Marked(OpenApiAudience.Frontend), Marked(OpenApiAudience.Sdk)], OpenApiAudience.Sdk); // action wins + yield return () => ([Authorize(OpenShockAuthSchemes.UserSessionCookie), Marked(OpenApiAudience.Sdk)], OpenApiAudience.Sdk); + // [AllowAnonymous] on the action makes the controller's token scheme irrelevant: only the marker counts + yield return () => ([Authorize(OpenShockAuthSchemes.HubToken), new AllowAnonymousAttribute(), Marked(OpenApiAudience.Frontend)], OpenApiAudience.Frontend); + } + + [Test] + [MethodDataSource(nameof(Cases))] + public async Task Classify((object[] Metadata, OpenApiAudience Expected) testCase) + { + await Assert.That(OpenApiAudiences.Classify(testCase.Metadata, "GET /test")).IsEqualTo(testCase.Expected); + } + + [Test] + public async Task Classify_AnonymousWithoutMarker_Throws() + { + await Assert.That(() => OpenApiAudiences.Classify([], "GET /test")).Throws(); + await Assert.That(() => OpenApiAudiences.Classify([Authorize(OpenShockAuthSchemes.ApiToken), new AllowAnonymousAttribute()], "GET /test")) + .Throws(); + } +} diff --git a/Common/OpenApi/OpenApiAudience.cs b/Common/OpenApi/OpenApiAudience.cs new file mode 100644 index 00000000..22f4400f --- /dev/null +++ b/Common/OpenApi/OpenApiAudience.cs @@ -0,0 +1,99 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc.ApiExplorer; +using Microsoft.AspNetCore.OpenApi; +using OpenShock.Common.Authentication; +using OpenShock.Common.Authentication.Attributes; + +namespace OpenShock.Common.OpenApi; + +/// +/// Which OpenAPI document an endpoint is documented in. Every documented endpoint is in exactly one. +/// +public enum OpenApiAudience +{ + /// What a third-party client calls: endpoints taking an API or hub token, and anonymous endpoints marked public. + Sdk, + + /// + /// What only the OpenShock frontend calls: session-only endpoints (admin ones included) and the signup, login and OAuth flows. + /// + Frontend +} + +/// +/// Puts an endpoint in the given OpenAPI document. Required on every documented anonymous endpoint, where nothing else says who +/// calls it. On an authenticated endpoint it overrides the audience its authentication schemes imply. The action's wins over the +/// controller's. +/// +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] +public sealed class OpenApiAudienceAttribute(OpenApiAudience audience) : Attribute +{ + public OpenApiAudience Audience { get; } = audience; +} + +public static class OpenApiAudiences +{ + /// The SDK document is the default one, served at . + public const string FrontendDocumentName = "frontend"; + + /// + /// Serves the frontend document at /openapi/frontend.json. MapOpenApi only serves a non-default document through the + /// {documentName} route value, so the path cannot be fixed. + /// + public const string DocumentPathPattern = "/openapi/{documentName}.json"; + + public static string DocumentName(OpenApiAudience audience) => audience switch + { + OpenApiAudience.Sdk => OpenShockServiceHelper.OpenApiDocumentName, + OpenApiAudience.Frontend => FrontendDocumentName, + _ => throw new ArgumentOutOfRangeException(nameof(audience), audience, null) + }; + + /// + /// restricted to the endpoints of one audience. Register one document per + /// audience with services.AddOpenApi(DocumentName(audience), Configure(audience)), in the host (see ConfigureOpenApi). + /// + public static Action Configure(OpenApiAudience audience) => options => + { + OpenShockServiceHelper.ConfigureOpenApi(options); + options.ShouldInclude = description => Classify(description) == audience; + }; + + public static OpenApiAudience Classify(ApiDescription description) + => Classify(description.ActionDescriptor.EndpointMetadata, $"{description.HttpMethod} /{description.RelativePath}"); + + /// + /// Classifies an endpoint by its metadata, ordered controller first and action last as MVC builds it. + /// + /// The endpoint is anonymous and carries no . + public static OpenApiAudience Classify(IList metadata, string endpoint) + { + var lastAuthorize = -1; + var lastAllowAnonymous = -1; + for (var i = 0; i < metadata.Count; i++) + { + if (metadata[i] is IAuthorizeData) lastAuthorize = i; + if (metadata[i] is IAllowAnonymous) lastAllowAnonymous = i; + } + + // [AllowAnonymous] is ignored when a more specific [Authorize] follows it + var anonymous = lastAuthorize < 0 || lastAllowAnonymous > lastAuthorize; + var authorize = anonymous ? [] : metadata.OfType().ToArray(); + + if (metadata.OfType().Any()) return OpenApiAudience.Frontend; + if (metadata.OfType().LastOrDefault() is { } marked) return marked.Audience; + + if (anonymous) + throw new InvalidOperationException( + $"Anonymous endpoint {endpoint} has no [OpenApiAudience]: mark it Sdk if a third-party client would call it, Frontend otherwise."); + + // Stacked [Authorize] attributes accept the union of their schemes; none named means the default, the session cookie + var schemes = authorize.SelectMany(data => Split(data.AuthenticationSchemes)).ToArray(); + return schemes.Any(scheme => scheme is OpenShockAuthSchemes.ApiToken or OpenShockAuthSchemes.HubToken) + ? OpenApiAudience.Sdk + : OpenApiAudience.Frontend; + } + + private static IEnumerable Split(string? list) + => string.IsNullOrEmpty(list) ? [] : list.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries); +} diff --git a/Common/OpenShockMiddlewareHelper.cs b/Common/OpenShockMiddlewareHelper.cs index 19789d7a..37a5129d 100644 --- a/Common/OpenShockMiddlewareHelper.cs +++ b/Common/OpenShockMiddlewareHelper.cs @@ -11,6 +11,7 @@ using Npgsql; using OpenShock.Common.HealthChecks; using OpenShock.Common.Middleware; +using OpenShock.Common.OpenApi; using OpenShock.Common.OpenShockDb; using OpenShock.Common.Options; using OpenShock.Common.Redis; @@ -27,7 +28,8 @@ namespace OpenShock.Common; public static class OpenShockMiddlewareHelper { - public static async Task UseCommonOpenShockMiddleware(this WebApplication app, string? pathBase = null) + public static async Task UseCommonOpenShockMiddleware(this WebApplication app, string? pathBase = null, + bool openApiAudienceDocuments = false) { // Networks allowed to reach the operational endpoints (metrics, health). Defaults to the // private ranges, so in-cluster scrapers and container probes work without configuration. @@ -136,12 +138,18 @@ exception is null }); app.MapOpenApi(OpenShockServiceHelper.OpenApiDocumentPath); + // The frontend document, which only a host that registered it asks for (see OpenApiAudiences) + if (openApiAudienceDocuments) app.MapOpenApi(OpenApiAudiences.DocumentPathPattern); app.MapScalarApiReference("/scalar/viewer", options => - options - .WithOpenApiRoutePattern(OpenShockServiceHelper.OpenApiDocumentPath) - .AddDocument(OpenShockServiceHelper.OpenApiDocumentName, "OpenShock API") - ); + { + options + .WithOpenApiRoutePattern(OpenShockServiceHelper.OpenApiDocumentPath) + .AddDocument(OpenShockServiceHelper.OpenApiDocumentName, "OpenShock API", isDefault: true); + + if (openApiAudienceDocuments) + options.AddDocument(OpenApiAudiences.FrontendDocumentName, "OpenShock Frontend API", OpenApiAudiences.DocumentPathPattern); + }); // Reports whether every dependency this host needs to serve is reachable. The LCG gates its // self-onlining on the same set, so a probe sees exactly what the gateway acts on. diff --git a/Common/OpenShockServiceHelper.cs b/Common/OpenShockServiceHelper.cs index df29666a..8abe342e 100644 --- a/Common/OpenShockServiceHelper.cs +++ b/Common/OpenShockServiceHelper.cs @@ -47,13 +47,14 @@ namespace OpenShock.Common; public static class OpenShockServiceHelper { /// - /// Name of the single OpenAPI document. It must be the framework's default ("v1"): has no - /// {documentName} segment, so MapOpenApi serves the default document there. It never appears in a URL. + /// Name of the default OpenAPI document (in the API, the SDK one; see ). It must be the + /// framework's default ("v1"): has no {documentName} segment, so MapOpenApi serves the + /// default document there. /// public const string OpenApiDocumentName = "v1"; /// - /// Path the OpenAPI document is served at. + /// Path the default OpenAPI document is served at. /// public const string OpenApiDocumentPath = "/openapi.json"; diff --git a/README.md b/README.md index c92559a2..977cee5a 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,15 @@ You can access our Open API Doc here: https://api.openshock.app/scalar/viewer +The API is described by two OpenAPI documents, both listed in the viewer: + +| Document | URL | Contents | +|----------|-----|----------| +| SDK (default) | `/openapi.json` | Endpoints taking an API token or hub token, plus public anonymous ones (backend info, public shares, public profiles and stats, device pairing) | +| Frontend | `/openapi/frontend.json` | Endpoints only the OpenShock frontend uses: session-only account, session and token management, signup, login, password reset, OAuth, and the admin endpoints | + +Build third-party clients from `/openapi.json`. + # Configuration The API can be configured using the following environment variables. From ef061da066e0244b07a18973ee6076700b2744b6 Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Fri, 4 Dec 2026 16:29:06 +0100 Subject: [PATCH 2/3] feat(openapi): make the frontend document the complete API /openapi/frontend.json now contains every documented endpoint, so the frontend client can be generated from one document. /openapi.json stays the SDK subset. --- .../Tests/OpenApiDocumentTests.cs | 58 ++++++++----------- API/Program.cs | 6 +- Common/OpenApi/OpenApiAudience.cs | 37 +++++++----- Common/OpenShockMiddlewareHelper.cs | 6 +- README.md | 4 +- 5 files changed, 56 insertions(+), 55 deletions(-) diff --git a/API.IntegrationTests/Tests/OpenApiDocumentTests.cs b/API.IntegrationTests/Tests/OpenApiDocumentTests.cs index 533bb166..cd09657b 100644 --- a/API.IntegrationTests/Tests/OpenApiDocumentTests.cs +++ b/API.IntegrationTests/Tests/OpenApiDocumentTests.cs @@ -5,12 +5,11 @@ namespace OpenShock.API.IntegrationTests.Tests; public sealed class OpenApiDocumentTests { - private static readonly string[] DocumentPaths = ["/openapi.json", "/openapi/frontend.json"]; - [ClassDataSource(Shared = SharedType.PerTestSession)] public required WebApplicationFactory WebApplicationFactory { get; init; } - private async Task GetPathsAsync(string documentPath) + /// Every operation in the document as "METHOD /path". + private async Task GetOperationsAsync(string documentPath) { using var client = WebApplicationFactory.CreateClient(); @@ -19,18 +18,21 @@ private async Task GetPathsAsync(string documentPath) await Assert.That(response.Content.Headers.ContentType?.MediaType).IsEqualTo("application/json"); using var doc = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); - return doc.RootElement.GetProperty("paths").EnumerateObject().Select(p => p.Name).ToArray(); + return doc.RootElement.GetProperty("paths").EnumerateObject() + .SelectMany(path => path.Value.EnumerateObject().Select(method => $"{method.Name.ToUpperInvariant()} {path.Name}")) + .ToArray(); } [Test] public async Task SdkDocument_HasTokenAndPublicEndpointsOnly() { - var paths = await GetPathsAsync("/openapi.json"); + var operations = await GetOperationsAsync("/openapi.json"); + var paths = operations.Select(operation => operation[(operation.IndexOf(' ') + 1)..]).ToArray(); - await Assert.That(paths).Contains("/1/shockers/own"); // API token - await Assert.That(paths).Contains("/2/shockers/control"); // API token, newest version only - await Assert.That(paths).Contains("/1/device/self"); // hub token - await Assert.That(paths).Contains("/1/public/shares/links/{publicShareId}"); // anonymous, marked Sdk + await Assert.That(operations).Contains("GET /1/shockers/own"); // API token + await Assert.That(operations).Contains("POST /2/shockers/control"); // API token, newest version only + await Assert.That(operations).Contains("GET /1/device/self"); // hub token + await Assert.That(operations).Contains("GET /1/public/shares/links/{publicShareId}"); // anonymous, marked Sdk await Assert.That(paths).DoesNotContain("/2/account/login"); await Assert.That(paths).DoesNotContain("/1/account/username/check"); @@ -39,32 +41,20 @@ public async Task SdkDocument_HasTokenAndPublicEndpointsOnly() } [Test] - public async Task FrontendDocument_HasSessionSignupAndAdminEndpoints() + public async Task FrontendDocument_IsSdkDocumentPlusFrontendOnlyAndAdminEndpoints() { - var paths = await GetPathsAsync("/openapi/frontend.json"); - - await Assert.That(paths).Contains("/2/account/signup"); - await Assert.That(paths).Contains("/2/account/login"); - await Assert.That(paths).Contains("/1/sessions"); - await Assert.That(paths).Contains("/1/admin/users"); - await Assert.That(paths).Contains("/1/admin/users/{userId}"); - await Assert.That(paths).DoesNotContain("/1/shockers/own"); - } - - [Test] - public async Task EveryOperationIsInExactlyOneDocument() - { - using var client = WebApplicationFactory.CreateClient(); - - var operations = new List(); - foreach (var documentPath in DocumentPaths) - { - using var doc = JsonDocument.Parse(await client.GetStringAsync(documentPath)); - operations.AddRange(doc.RootElement.GetProperty("paths").EnumerateObject() - .SelectMany(path => path.Value.EnumerateObject().Select(method => $"{method.Name.ToUpperInvariant()} {path.Name}"))); - } - - await Assert.That(operations.GroupBy(operation => operation).Where(group => group.Count() > 1).Select(group => group.Key)).IsEmpty(); + var sdk = await GetOperationsAsync("/openapi.json"); + var frontend = await GetOperationsAsync("/openapi/frontend.json"); + + await Assert.That(sdk.Except(frontend)).IsEmpty(); + + var frontendOnly = frontend.Except(sdk).ToArray(); + await Assert.That(frontendOnly).Contains("POST /2/account/signup"); + await Assert.That(frontendOnly).Contains("POST /2/account/login"); + await Assert.That(frontendOnly).Contains("DELETE /1/account"); // session only, while GET /1/account also takes an API token + await Assert.That(frontendOnly).Contains("GET /1/sessions"); + await Assert.That(frontendOnly).Contains("GET /1/admin/users"); + await Assert.That(frontendOnly).Contains("GET /1/admin/users/{userId}"); } [Test] diff --git a/API/Program.cs b/API/Program.cs index b05be6fd..0f6acff4 100644 --- a/API/Program.cs +++ b/API/Program.cs @@ -139,9 +139,9 @@ static void DefaultOptions(RemoteAuthenticationOptions options, string provider) .AddOpenShockSignalR(redisOptions); // XML documentation comments are applied by a source generator that intercepts these calls, so they have to be made here in the host. -// One document per audience (see OpenApiAudiences): the SDK one is the default, served at /openapi.json. -builder.Services.AddOpenApi(OpenApiAudiences.DocumentName(OpenApiAudience.Sdk), OpenApiAudiences.Configure(OpenApiAudience.Sdk)); -builder.Services.AddOpenApi(OpenApiAudiences.DocumentName(OpenApiAudience.Frontend), OpenApiAudiences.Configure(OpenApiAudience.Frontend)); +// The SDK document (the default, served at /openapi.json) has what third-party clients call; the frontend document has everything. +builder.Services.AddOpenApi(OpenShockServiceHelper.OpenApiDocumentName, OpenApiAudiences.ConfigureSdkDocument); +builder.Services.AddOpenApi(OpenApiAudiences.FrontendDocumentName, OpenApiAudiences.ConfigureFrontendDocument); builder.Services.AddScoped(); builder.Services.AddScoped(); diff --git a/Common/OpenApi/OpenApiAudience.cs b/Common/OpenApi/OpenApiAudience.cs index 22f4400f..e2c460fa 100644 --- a/Common/OpenApi/OpenApiAudience.cs +++ b/Common/OpenApi/OpenApiAudience.cs @@ -7,7 +7,7 @@ namespace OpenShock.Common.OpenApi; /// -/// Which OpenAPI document an endpoint is documented in. Every documented endpoint is in exactly one. +/// Who calls an endpoint. Decides whether it is in the SDK document; the frontend document has every documented endpoint. /// public enum OpenApiAudience { @@ -21,7 +21,7 @@ public enum OpenApiAudience } /// -/// Puts an endpoint in the given OpenAPI document. Required on every documented anonymous endpoint, where nothing else says who +/// Sets an endpoint's audience. Required on every documented anonymous endpoint, where nothing else says who /// calls it. On an authenticated endpoint it overrides the audience its authentication schemes imply. The action's wins over the /// controller's. /// @@ -33,7 +33,10 @@ public sealed class OpenApiAudienceAttribute(OpenApiAudience audience) : Attribu public static class OpenApiAudiences { - /// The SDK document is the default one, served at . + /// + /// Name of the complete document, every documented endpoint, which the frontend generates its client from. The SDK document, + /// its third-party subset, is the default one, served at . + /// public const string FrontendDocumentName = "frontend"; /// @@ -42,22 +45,30 @@ public static class OpenApiAudiences /// public const string DocumentPathPattern = "/openapi/{documentName}.json"; - public static string DocumentName(OpenApiAudience audience) => audience switch + /// + /// for the SDK document: only endpoints. + /// Register it in the host (see ConfigureOpenApi) under . + /// + public static void ConfigureSdkDocument(OpenApiOptions options) { - OpenApiAudience.Sdk => OpenShockServiceHelper.OpenApiDocumentName, - OpenApiAudience.Frontend => FrontendDocumentName, - _ => throw new ArgumentOutOfRangeException(nameof(audience), audience, null) - }; + OpenShockServiceHelper.ConfigureOpenApi(options); + options.ShouldInclude = description => Classify(description) == OpenApiAudience.Sdk; + } /// - /// restricted to the endpoints of one audience. Register one document per - /// audience with services.AddOpenApi(DocumentName(audience), Configure(audience)), in the host (see ConfigureOpenApi). + /// for the frontend document: every documented endpoint. Each is still + /// classified, so this document fails to generate on an unmarked anonymous endpoint just like the SDK one. + /// Register it in the host (see ConfigureOpenApi) under . /// - public static Action Configure(OpenApiAudience audience) => options => + public static void ConfigureFrontendDocument(OpenApiOptions options) { OpenShockServiceHelper.ConfigureOpenApi(options); - options.ShouldInclude = description => Classify(description) == audience; - }; + options.ShouldInclude = description => + { + Classify(description); + return true; + }; + } public static OpenApiAudience Classify(ApiDescription description) => Classify(description.ActionDescriptor.EndpointMetadata, $"{description.HttpMethod} /{description.RelativePath}"); diff --git a/Common/OpenShockMiddlewareHelper.cs b/Common/OpenShockMiddlewareHelper.cs index 37a5129d..74e87006 100644 --- a/Common/OpenShockMiddlewareHelper.cs +++ b/Common/OpenShockMiddlewareHelper.cs @@ -138,17 +138,17 @@ exception is null }); app.MapOpenApi(OpenShockServiceHelper.OpenApiDocumentPath); - // The frontend document, which only a host that registered it asks for (see OpenApiAudiences) + // The complete frontend document, which only a host that registered it asks for (see OpenApiAudiences) if (openApiAudienceDocuments) app.MapOpenApi(OpenApiAudiences.DocumentPathPattern); app.MapScalarApiReference("/scalar/viewer", options => { options .WithOpenApiRoutePattern(OpenShockServiceHelper.OpenApiDocumentPath) - .AddDocument(OpenShockServiceHelper.OpenApiDocumentName, "OpenShock API", isDefault: true); + .AddDocument(OpenShockServiceHelper.OpenApiDocumentName, "OpenShock API (SDK)", isDefault: true); if (openApiAudienceDocuments) - options.AddDocument(OpenApiAudiences.FrontendDocumentName, "OpenShock Frontend API", OpenApiAudiences.DocumentPathPattern); + options.AddDocument(OpenApiAudiences.FrontendDocumentName, "OpenShock API (complete, frontend)", OpenApiAudiences.DocumentPathPattern); }); // Reports whether every dependency this host needs to serve is reachable. The LCG gates its diff --git a/README.md b/README.md index 977cee5a..c179afd6 100644 --- a/README.md +++ b/README.md @@ -28,8 +28,8 @@ The API is described by two OpenAPI documents, both listed in the viewer: | Document | URL | Contents | |----------|-----|----------| -| SDK (default) | `/openapi.json` | Endpoints taking an API token or hub token, plus public anonymous ones (backend info, public shares, public profiles and stats, device pairing) | -| Frontend | `/openapi/frontend.json` | Endpoints only the OpenShock frontend uses: session-only account, session and token management, signup, login, password reset, OAuth, and the admin endpoints | +| SDK (default) | `/openapi.json` | The third-party subset: endpoints taking an API token or hub token, plus public anonymous ones (backend info, public shares, public profiles and stats, device pairing) | +| Frontend | `/openapi/frontend.json` | The complete API: everything in the SDK document plus what only the OpenShock frontend uses (session-only account, session and token management, signup, login, password reset, OAuth, admin) | Build third-party clients from `/openapi.json`. From 46169bf63b9ebca655f304f7941831fe8bdb8090 Mon Sep 17 00:00:00 2001 From: "coderabbitai[bot]" <136622811+coderabbitai[bot]@users.noreply.github.com> Date: Fri, 4 Dec 2026 15:45:38 +0000 Subject: [PATCH 3/3] fix(openapi): honor AllowAnonymous regardless of metadata order --- Common.Tests/OpenApi/OpenApiAudiencesTests.cs | 3 +++ Common/OpenApi/OpenApiAudience.cs | 16 +++------------- 2 files changed, 6 insertions(+), 13 deletions(-) diff --git a/Common.Tests/OpenApi/OpenApiAudiencesTests.cs b/Common.Tests/OpenApi/OpenApiAudiencesTests.cs index 2d4beeb3..7901d19d 100644 --- a/Common.Tests/OpenApi/OpenApiAudiencesTests.cs +++ b/Common.Tests/OpenApi/OpenApiAudiencesTests.cs @@ -44,5 +44,8 @@ public async Task Classify_AnonymousWithoutMarker_Throws() await Assert.That(() => OpenApiAudiences.Classify([], "GET /test")).Throws(); await Assert.That(() => OpenApiAudiences.Classify([Authorize(OpenShockAuthSchemes.ApiToken), new AllowAnonymousAttribute()], "GET /test")) .Throws(); + // Controller metadata precedes action metadata. + await Assert.That(() => OpenApiAudiences.Classify([new AllowAnonymousAttribute(), Authorize(OpenShockAuthSchemes.ApiToken)], "GET /test")) + .Throws(); } } diff --git a/Common/OpenApi/OpenApiAudience.cs b/Common/OpenApi/OpenApiAudience.cs index e2c460fa..52128394 100644 --- a/Common/OpenApi/OpenApiAudience.cs +++ b/Common/OpenApi/OpenApiAudience.cs @@ -79,22 +79,12 @@ public static OpenApiAudience Classify(ApiDescription description) /// The endpoint is anonymous and carries no . public static OpenApiAudience Classify(IList metadata, string endpoint) { - var lastAuthorize = -1; - var lastAllowAnonymous = -1; - for (var i = 0; i < metadata.Count; i++) - { - if (metadata[i] is IAuthorizeData) lastAuthorize = i; - if (metadata[i] is IAllowAnonymous) lastAllowAnonymous = i; - } - - // [AllowAnonymous] is ignored when a more specific [Authorize] follows it - var anonymous = lastAuthorize < 0 || lastAllowAnonymous > lastAuthorize; - var authorize = anonymous ? [] : metadata.OfType().ToArray(); - if (metadata.OfType().Any()) return OpenApiAudience.Frontend; if (metadata.OfType().LastOrDefault() is { } marked) return marked.Audience; - if (anonymous) + var authorize = metadata.OfType().ToArray(); + // ASP.NET Core honors [AllowAnonymous] regardless of its order relative to [Authorize]. + if (authorize.Length == 0 || metadata.OfType().Any()) throw new InvalidOperationException( $"Anonymous endpoint {endpoint} has no [OpenApiAudience]: mark it Sdk if a third-party client would call it, Frontend otherwise.");