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>
This commit is contained in:
17
SVSim.EmulatedEntrypoint/Configuration/AdminOptions.cs
Normal file
17
SVSim.EmulatedEntrypoint/Configuration/AdminOptions.cs
Normal file
@@ -0,0 +1,17 @@
|
||||
namespace SVSim.EmulatedEntrypoint.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Config for the /admin/* util endpoints. Bound from the "Admin" section of appsettings.
|
||||
/// </summary>
|
||||
public class AdminOptions
|
||||
{
|
||||
public const string SectionName = "Admin";
|
||||
|
||||
/// <summary>
|
||||
/// Shared secret required in the <c>X-Admin-Secret</c> header on protected admin endpoints
|
||||
/// (see <see cref="Infrastructure.RequireAdminSecretAttribute"/>). Empty / whitespace means
|
||||
/// the endpoint is disabled — the filter fails closed so an unconfigured deployment never
|
||||
/// exposes the admin surface.
|
||||
/// </summary>
|
||||
public string ImportSecret { get; set; } = string.Empty;
|
||||
}
|
||||
@@ -16,8 +16,10 @@ using SVSim.EmulatedEntrypoint.Services;
|
||||
namespace SVSim.EmulatedEntrypoint.Controllers;
|
||||
|
||||
/// <summary>
|
||||
/// Util endpoints for bootstrapping the dev environment. Anonymous-allowed today — security
|
||||
/// audit pending (don't expose these to the public internet).
|
||||
/// Util endpoints for bootstrapping the dev environment. Actions are gated by
|
||||
/// <see cref="RequireAdminSecretAttribute"/>: callers must send the shared secret from
|
||||
/// <c>Admin:ImportSecret</c> in the <c>X-Admin-Secret</c> header. Missing/blank config
|
||||
/// disables the endpoint (fail-closed).
|
||||
/// </summary>
|
||||
public class AdminController : SVSimController
|
||||
{
|
||||
@@ -41,6 +43,7 @@ public class AdminController : SVSimController
|
||||
/// Only essential fields are imported today — extend as needed.
|
||||
/// </summary>
|
||||
[AllowAnonymous]
|
||||
[RequireAdminSecret]
|
||||
[HttpPost("import_viewer")]
|
||||
public async Task<ActionResult<ImportViewerResponse>> ImportViewer(ImportViewerRequest request)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
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>()
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using SVSim.EmulatedEntrypoint.Configuration;
|
||||
|
||||
namespace SVSim.EmulatedEntrypoint.Infrastructure;
|
||||
|
||||
/// <summary>
|
||||
/// Gates a controller or action on a shared secret carried in the <c>X-Admin-Secret</c> header,
|
||||
/// compared against <see cref="AdminOptions.ImportSecret"/>. Runs as an authorization filter so
|
||||
/// unauthorized requests short-circuit before model binding.
|
||||
///
|
||||
/// Fail-closed: if the configured secret is null/empty the endpoint is treated as disabled and
|
||||
/// every request gets a 401 (with a warning logged once per request). This means a deployment
|
||||
/// that forgets to set the secret leaves the endpoint locked, not open.
|
||||
/// </summary>
|
||||
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true)]
|
||||
public sealed class RequireAdminSecretAttribute : Attribute, IAuthorizationFilter
|
||||
{
|
||||
public const string HeaderName = "X-Admin-Secret";
|
||||
|
||||
public void OnAuthorization(AuthorizationFilterContext context)
|
||||
{
|
||||
var services = context.HttpContext.RequestServices;
|
||||
var options = services.GetRequiredService<IOptions<AdminOptions>>().Value;
|
||||
var logger = services.GetRequiredService<ILogger<RequireAdminSecretAttribute>>();
|
||||
|
||||
if (string.IsNullOrWhiteSpace(options.ImportSecret))
|
||||
{
|
||||
logger.LogWarning(
|
||||
"Rejecting request to {Path}: Admin:ImportSecret is not configured. " +
|
||||
"Set it in appsettings (or the NPGSQL_ADMIN__IMPORTSECRET env var) to enable the endpoint.",
|
||||
context.HttpContext.Request.Path);
|
||||
context.Result = new UnauthorizedResult();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!context.HttpContext.Request.Headers.TryGetValue(HeaderName, out var provided)
|
||||
|| provided.Count == 0
|
||||
|| string.IsNullOrEmpty(provided[0]))
|
||||
{
|
||||
context.Result = new UnauthorizedResult();
|
||||
return;
|
||||
}
|
||||
|
||||
var providedBytes = Encoding.UTF8.GetBytes(provided[0]!);
|
||||
var expectedBytes = Encoding.UTF8.GetBytes(options.ImportSecret);
|
||||
if (!CryptographicOperations.FixedTimeEquals(providedBytes, expectedBytes))
|
||||
{
|
||||
context.Result = new UnauthorizedResult();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ using SVSim.Database.Services.Friend;
|
||||
using SVSim.Database.Services.Replay;
|
||||
using SVSim.EmulatedEntrypoint.Configuration;
|
||||
using SVSim.EmulatedEntrypoint.Extensions;
|
||||
using SVSim.EmulatedEntrypoint.Infrastructure;
|
||||
using SVSim.EmulatedEntrypoint.Matching;
|
||||
using SVSim.EmulatedEntrypoint.Middlewares;
|
||||
using SVSim.EmulatedEntrypoint.Security.SteamSessionAuthentication;
|
||||
@@ -64,6 +65,19 @@ public class Program
|
||||
// Disambiguate same-named DTOs across families (e.g. Story.StartRequest vs
|
||||
// BasicPuzzle.StartRequest) by qualifying schema ids with the full type name.
|
||||
c.CustomSchemaIds(t => t.FullName?.Replace("+", "."));
|
||||
|
||||
// Register the X-Admin-Secret shared-secret header so the Swagger UI shows an
|
||||
// Authorize dialog for it. AdminSecretOperationFilter then attaches the requirement
|
||||
// only to endpoints that carry [RequireAdminSecret], keeping the padlock off
|
||||
// ordinary game endpoints.
|
||||
c.AddSecurityDefinition(AdminSecretOperationFilter.SchemeId, new Microsoft.OpenApi.Models.OpenApiSecurityScheme
|
||||
{
|
||||
Name = RequireAdminSecretAttribute.HeaderName,
|
||||
In = Microsoft.OpenApi.Models.ParameterLocation.Header,
|
||||
Type = Microsoft.OpenApi.Models.SecuritySchemeType.ApiKey,
|
||||
Description = "Shared secret for /admin/* endpoints (matches Admin:ImportSecret in appsettings).",
|
||||
});
|
||||
c.OperationFilter<AdminSecretOperationFilter>();
|
||||
});
|
||||
builder.Services.AddHttpLogging(opt =>
|
||||
{
|
||||
@@ -71,6 +85,7 @@ public class Program
|
||||
});
|
||||
|
||||
builder.Services.Configure<DeckOptions>(builder.Configuration.GetSection(DeckOptions.SectionName));
|
||||
builder.Services.Configure<AdminOptions>(builder.Configuration.GetSection(AdminOptions.SectionName));
|
||||
|
||||
#region Database Services
|
||||
|
||||
|
||||
@@ -6,5 +6,10 @@
|
||||
"Microsoft.AspNetCore.HttpLogging.HttpLoggingMiddleware": "Warning",
|
||||
"Microsoft.EntityFrameworkCore": "Warning"
|
||||
}
|
||||
},
|
||||
"Admin": {
|
||||
// Fixed secret so AdminControllerTests can send X-Admin-Secret without going through
|
||||
// a per-test config knob. Tests read it back via AdminControllerTests.TestSecret.
|
||||
"ImportSecret": "test-admin-secret"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,6 +27,13 @@
|
||||
"Deck": {
|
||||
"MaxDeckSlots": 36
|
||||
},
|
||||
"Admin": {
|
||||
// Shared secret required in the X-Admin-Secret header on /admin/* util endpoints
|
||||
// (see RequireAdminSecretAttribute). Leaving this blank disables the endpoint entirely
|
||||
// — fail-closed so an unconfigured deployment never exposes admin surface. Override with
|
||||
// the ADMIN__IMPORTSECRET env var.
|
||||
"ImportSecret": "replaceme"
|
||||
},
|
||||
"BattleNode": {
|
||||
// Socket.IO v2 endpoint URL echoed to the client on /*/do_matching success.
|
||||
// Wire format: "host[:port]/socket.io/" — no scheme prefix, trailing slash REQUIRED.
|
||||
|
||||
Reference in New Issue
Block a user