Files
SVSimServer/SVSim.EmulatedEntrypoint/Infrastructure/AdminSecretOperationFilter.cs
gamer147 c8e4bda6af feat(admin): shared-secret auth for /admin/import_viewer + Swagger authorize
Anonymous /admin/import_viewer was safe locally but exposed viewer-import surface
whenever the server was reachable off-box. Gate it on a shared secret carried in
X-Admin-Secret, sourced from Admin:ImportSecret in appsettings (override via
ADMIN__IMPORTSECRET env var). Fails closed: an unconfigured deployment 401s every
request (with a logged warning) instead of leaving the endpoint open.

Implementation is a plain IAuthorizationFilter attribute (RequireAdminSecret) that
runs before model binding — short-circuits the ImportViewerRequest deserialize on
unauthorized calls. Compare uses CryptographicOperations.FixedTimeEquals to avoid
timing signal. A companion Swagger IOperationFilter registers an ApiKey security
definition and attaches the requirement ONLY to actions carrying the attribute, so
the Swagger UI shows an Authorize dialog for admin endpoints without decorating
ordinary game routes with a padlock.

Tests: existing 27 AdminController tests routed through a new
SVSimTestFactory.CreateAdminClient() helper that bakes the header from
appsettings.Testing.json; added two negative-path tests
(missing_secret_header, wrong_secret) — 29/29 passing.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-07-04 18:24:59 -04:00

40 lines
1.5 KiB
C#

using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace SVSim.EmulatedEntrypoint.Infrastructure;
/// <summary>
/// Attaches the <see cref="RequireAdminSecretAttribute.HeaderName"/> security requirement to
/// Swagger operations whose action carries <see cref="RequireAdminSecretAttribute"/>. The
/// matching <see cref="OpenApiSecurityScheme"/> is registered by <c>Program.cs</c> under the
/// same scheme id (<see cref="SchemeId"/>) so the Swagger UI shows an Authorize dialog and,
/// once populated, sends the header on gated endpoints only.
/// </summary>
public sealed class AdminSecretOperationFilter : IOperationFilter
{
public const string SchemeId = "AdminSecret";
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
var hasAttribute = context.MethodInfo.GetCustomAttributes(true)
.OfType<RequireAdminSecretAttribute>().Any()
|| (context.MethodInfo.DeclaringType?.GetCustomAttributes(true)
.OfType<RequireAdminSecretAttribute>().Any() ?? false);
if (!hasAttribute) return;
operation.Security ??= new List<OpenApiSecurityRequirement>();
operation.Security.Add(new OpenApiSecurityRequirement
{
[new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = SchemeId,
}
}] = Array.Empty<string>()
});
}
}