Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 53 additions & 12 deletions API.IntegrationTests/Tests/OpenApiDocumentTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,40 +8,81 @@ public sealed class OpenApiDocumentTests
[ClassDataSource<WebApplicationFactory>(Shared = SharedType.PerTestSession)]
public required WebApplicationFactory WebApplicationFactory { get; init; }

[Test]
public async Task GetOpenApiDocument_ServesSingleDocumentWithEveryVersion()
/// <summary>Every operation in the document as "METHOD /path".</summary>
private async Task<string[]> 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 <summary> 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 <response code="500"> 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");
}
Expand Down
2 changes: 2 additions & 0 deletions API/Controller/Account/_ApiController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -10,6 +11,7 @@ namespace OpenShock.API.Controller.Account;
/// </summary>
[ApiController]
[Tags("Account")]
[OpenApiAudience(OpenApiAudience.Frontend)]
[Route("/{version:apiVersion}/account")]
public sealed partial class AccountController : OpenShockControllerBase
{
Expand Down
2 changes: 2 additions & 0 deletions API/Controller/Device/Pair.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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<LegacyDataResponse<string>>(StatusCodes.Status200OK, MediaTypeNames.Application.Json)]
Expand Down
2 changes: 2 additions & 0 deletions API/Controller/Integrations/_ApiController.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using Microsoft.AspNetCore.Mvc;
using OpenShock.Common;
using OpenShock.Common.OpenShockDb;
using OpenShock.Common.OpenApi;

namespace OpenShock.API.Controller.Integrations;

Expand All @@ -10,6 +11,7 @@ namespace OpenShock.API.Controller.Integrations;
/// </summary>
[ApiController]
[Tags("Integrations")]
[OpenApiAudience(OpenApiAudience.Sdk)]
[Route("/{version:apiVersion}/integrations")]
public sealed partial class IntegrationsController : OpenShockControllerBase
{
Expand Down
2 changes: 2 additions & 0 deletions API/Controller/OAuth/_ApiController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -14,6 +15,7 @@ namespace OpenShock.API.Controller.OAuth;
/// </summary>
[ApiController]
[Tags("OAuth")]
[OpenApiAudience(OpenApiAudience.Frontend)]
[Route("/{version:apiVersion}/oauth")]
public sealed partial class OAuthController : OpenShockControllerBase
{
Expand Down
2 changes: 2 additions & 0 deletions API/Controller/Public/_ApiController.cs
Original file line number Diff line number Diff line change
@@ -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
{
Expand Down
2 changes: 2 additions & 0 deletions API/Controller/Version/_ApiController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -19,6 +20,7 @@ namespace OpenShock.API.Controller.Version;
/// </summary>
[ApiController]
[Tags("Meta")]
[OpenApiAudience(OpenApiAudience.Sdk)]
[Route("/{version:apiVersion}")]
public sealed partial class VersionController : OpenShockControllerBase
{
Expand Down
9 changes: 6 additions & 3 deletions API/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<IDeviceService, DeviceService>();
builder.Services.AddScoped<IControlSender, ControlSender>();
Expand Down Expand Up @@ -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<string>("OpenShock:Api:PathBase");

await app.UseCommonOpenShockMiddleware(apiPathBase);
await app.UseCommonOpenShockMiddleware(apiPathBase, openApiAudienceDocuments: true);

if (!databaseOptions.SkipMigration)
{
Expand Down
51 changes: 51 additions & 0 deletions Common.Tests/OpenApi/OpenApiAudiencesTests.cs
Original file line number Diff line number Diff line change
@@ -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<Func<(object[] Metadata, OpenApiAudience Expected)>> 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<InvalidOperationException>();
await Assert.That(() => OpenApiAudiences.Classify([Authorize(OpenShockAuthSchemes.ApiToken), new AllowAnonymousAttribute()], "GET /test"))
.Throws<InvalidOperationException>();
// Controller metadata precedes action metadata.
await Assert.That(() => OpenApiAudiences.Classify([new AllowAnonymousAttribute(), Authorize(OpenShockAuthSchemes.ApiToken)], "GET /test"))
.Throws<InvalidOperationException>();
}
}
100 changes: 100 additions & 0 deletions Common/OpenApi/OpenApiAudience.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// Who calls an endpoint. Decides whether it is in the SDK document; the frontend document has every documented endpoint.
/// </summary>
public enum OpenApiAudience
{
/// <summary>What a third-party client calls: endpoints taking an API or hub token, and anonymous endpoints marked public.</summary>
Sdk,

/// <summary>
/// What only the OpenShock frontend calls: session-only endpoints (admin ones included) and the signup, login and OAuth flows.
/// </summary>
Frontend
}

/// <summary>
/// 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.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class OpenApiAudienceAttribute(OpenApiAudience audience) : Attribute
{
public OpenApiAudience Audience { get; } = audience;
}

public static class OpenApiAudiences
{
/// <summary>
/// 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 <see cref="OpenShockServiceHelper.OpenApiDocumentPath"/>.
/// </summary>
public const string FrontendDocumentName = "frontend";

/// <summary>
/// Serves the frontend document at <c>/openapi/frontend.json</c>. MapOpenApi only serves a non-default document through the
/// <c>{documentName}</c> route value, so the path cannot be fixed.
/// </summary>
public const string DocumentPathPattern = "/openapi/{documentName}.json";

/// <summary>
/// <see cref="OpenShockServiceHelper.ConfigureOpenApi"/> for the SDK document: only <see cref="OpenApiAudience.Sdk"/> endpoints.
/// Register it in the host (see ConfigureOpenApi) under <see cref="OpenShockServiceHelper.OpenApiDocumentName"/>.
/// </summary>
public static void ConfigureSdkDocument(OpenApiOptions options)
{
OpenShockServiceHelper.ConfigureOpenApi(options);
options.ShouldInclude = description => Classify(description) == OpenApiAudience.Sdk;
}

/// <summary>
/// <see cref="OpenShockServiceHelper.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 <see cref="FrontendDocumentName"/>.
/// </summary>
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}");

/// <summary>
/// Classifies an endpoint by its metadata, ordered controller first and action last as MVC builds it.
/// </summary>
/// <exception cref="InvalidOperationException">The endpoint is anonymous and carries no <see cref="OpenApiAudienceAttribute"/>.</exception>
public static OpenApiAudience Classify(IList<object> metadata, string endpoint)
{
if (metadata.OfType<TrustedOriginAttribute>().Any()) return OpenApiAudience.Frontend;
if (metadata.OfType<OpenApiAudienceAttribute>().LastOrDefault() is { } marked) return marked.Audience;

var authorize = metadata.OfType<IAuthorizeData>().ToArray();
// ASP.NET Core honors [AllowAnonymous] regardless of its order relative to [Authorize].
if (authorize.Length == 0 || metadata.OfType<IAllowAnonymous>().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<string> Split(string? list)
=> string.IsNullOrEmpty(list) ? [] : list.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);
}
Loading