diff --git a/API.IntegrationTests/Tests/OpenApiDocumentTests.cs b/API.IntegrationTests/Tests/OpenApiDocumentTests.cs index 69c00ad2..cd09657b 100644 --- a/API.IntegrationTests/Tests/OpenApiDocumentTests.cs +++ b/API.IntegrationTests/Tests/OpenApiDocumentTests.cs @@ -8,40 +8,81 @@ public sealed class OpenApiDocumentTests [ClassDataSource(Shared = SharedType.PerTestSession)] public required WebApplicationFactory WebApplicationFactory { get; init; } - [Test] - public async Task GetOpenApiDocument_ServesSingleDocumentWithEveryVersion() + /// Every operation in the document as "METHOD /path". + private async Task GetOperationsAsync(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() + .SelectMany(path => path.Value.EnumerateObject().Select(method => $"{method.Name.ToUpperInvariant()} {path.Name}")) + .ToArray(); + } + + [Test] + public async Task SdkDocument_HasTokenAndPublicEndpointsOnly() + { + var operations = await GetOperationsAsync("/openapi.json"); + var paths = operations.Select(operation => operation[(operation.IndexOf(' ') + 1)..]).ToArray(); + + 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"); + await Assert.That(paths).DoesNotContain("/1/sessions"); // session cookie only + await Assert.That(paths.Where(path => path.Contains("/admin/"))).IsEmpty(); + } - await Assert.That(paths).Contains("/1/account"); - await Assert.That(paths).Contains("/2/account/login"); + [Test] + public async Task FrontendDocument_IsSdkDocumentPlusFrontendOnlyAndAdminEndpoints() + { + 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] - public async Task GetOpenApiDocument_IncludesXmlDocsTheBuiltInSupportLeavesOut() + [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("/openapi.json")); - var root = doc.RootElement; + 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..0f6acff4 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. +// 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(); @@ -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..7901d19d --- /dev/null +++ b/Common.Tests/OpenApi/OpenApiAudiencesTests.cs @@ -0,0 +1,51 @@ +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(); + // 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 new file mode 100644 index 00000000..52128394 --- /dev/null +++ b/Common/OpenApi/OpenApiAudience.cs @@ -0,0 +1,100 @@ +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; + +/// +/// Who calls an endpoint. Decides whether it is in the SDK document; the frontend document has every documented endpoint. +/// +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 +} + +/// +/// 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. +/// +[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] +public sealed class OpenApiAudienceAttribute(OpenApiAudience audience) : Attribute +{ + public OpenApiAudience Audience { get; } = audience; +} + +public static class OpenApiAudiences +{ + /// + /// 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"; + + /// + /// 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"; + + /// + /// for the SDK document: only endpoints. + /// Register it in the host (see ConfigureOpenApi) under . + /// + public static void ConfigureSdkDocument(OpenApiOptions options) + { + OpenShockServiceHelper.ConfigureOpenApi(options); + options.ShouldInclude = description => Classify(description) == OpenApiAudience.Sdk; + } + + /// + /// 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 void ConfigureFrontendDocument(OpenApiOptions options) + { + OpenShockServiceHelper.ConfigureOpenApi(options); + options.ShouldInclude = description => + { + Classify(description); + return true; + }; + } + + 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) + { + if (metadata.OfType().Any()) return OpenApiAudience.Frontend; + if (metadata.OfType().LastOrDefault() is { } marked) return marked.Audience; + + 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."); + + // 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..74e87006 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 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") - ); + { + options + .WithOpenApiRoutePattern(OpenShockServiceHelper.OpenApiDocumentPath) + .AddDocument(OpenShockServiceHelper.OpenApiDocumentName, "OpenShock API (SDK)", isDefault: true); + + if (openApiAudienceDocuments) + 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 // 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..c179afd6 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` | 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`. + # Configuration The API can be configured using the following environment variables.