fix(server): detect a missing API-key pepper by type, not message text (mxaccessgw#195)
Auth.ApiKeys 0.3.0 throws a plain InvalidOperationException("pepper unavailable")
with no typed exception to catch, so take the issue's second option: check
IApiKeyPepperProvider before Create/Rotate and drop the message-matching catch.
Adds create/rotate missing-pepper tests.
This commit is contained in:
@@ -3,6 +3,7 @@ using System.Text.Json;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using ZB.MOM.WW.Audit;
|
||||
using ZB.MOM.WW.Auth.Abstractions.ApiKeys;
|
||||
using ZB.MOM.WW.Auth.ApiKeys;
|
||||
using ZB.MOM.WW.Auth.ApiKeys.Admin;
|
||||
using ZB.MOM.WW.MxGateway.Server.Security.Audit;
|
||||
using ZB.MOM.WW.MxGateway.Server.Security.Authentication;
|
||||
@@ -14,12 +15,13 @@ public sealed class DashboardApiKeyManagementService(
|
||||
DashboardApiKeyAuthorization authorization,
|
||||
ApiKeyAdminCommands adminCommands,
|
||||
IApiKeyAdminStore adminStore,
|
||||
IApiKeyPepperProvider pepperProvider,
|
||||
IAuditWriter auditWriter,
|
||||
IHttpContextAccessor httpContextAccessor,
|
||||
IApiKeyCacheInvalidator? cacheInvalidator = null) : IDashboardApiKeyManagementService
|
||||
{
|
||||
private const string UnauthorizedMessage = "Sign in with an authorized LDAP account to manage API keys.";
|
||||
private const string PepperUnavailableMarker = "pepper unavailable";
|
||||
private const string PepperNotConfiguredMessage = "API key pepper is not configured.";
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool CanManage(ClaimsPrincipal user)
|
||||
@@ -46,6 +48,13 @@ public sealed class DashboardApiKeyManagementService(
|
||||
|
||||
string keyId = request.KeyId.Trim();
|
||||
|
||||
// Checked up front by type (IApiKeyPepperProvider) rather than by matching the library's
|
||||
// InvalidOperationException message text (mxaccessgw#195).
|
||||
if (IsPepperMissing())
|
||||
{
|
||||
return DashboardApiKeyManagementResult.Fail(PepperNotConfiguredMessage);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
// The shared command set generates the secret, hashes it with the pepper, persists the
|
||||
@@ -69,10 +78,6 @@ public sealed class DashboardApiKeyManagementService(
|
||||
"API key created. Copy the key now; it will not be shown again.",
|
||||
created.Token);
|
||||
}
|
||||
catch (InvalidOperationException exception) when (IsPepperUnavailable(exception))
|
||||
{
|
||||
return DashboardApiKeyManagementResult.Fail("API key pepper is not configured.");
|
||||
}
|
||||
catch (SqliteException exception) when (exception.SqliteErrorCode == 19)
|
||||
{
|
||||
return DashboardApiKeyManagementResult.Fail("An API key with that id already exists.");
|
||||
@@ -135,34 +140,32 @@ public sealed class DashboardApiKeyManagementService(
|
||||
|
||||
string normalizedKeyId = keyId.Trim();
|
||||
|
||||
try
|
||||
if (IsPepperMissing())
|
||||
{
|
||||
CreateKeyResult rotated = await adminCommands
|
||||
.RotateKeyAsync(normalizedKeyId, RemoteAddress(), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
cacheInvalidator?.Invalidate(normalizedKeyId);
|
||||
|
||||
bool succeeded = rotated.Token is not null;
|
||||
|
||||
await WriteDashboardAuditAsync(
|
||||
user,
|
||||
normalizedKeyId,
|
||||
"dashboard-rotate-key",
|
||||
succeeded ? "rotated" : "not-found",
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return succeeded
|
||||
? DashboardApiKeyManagementResult.Success(
|
||||
"API key rotated. Copy the key now; it will not be shown again.",
|
||||
rotated.Token)
|
||||
: DashboardApiKeyManagementResult.Fail("API key was not found.");
|
||||
}
|
||||
catch (InvalidOperationException exception) when (IsPepperUnavailable(exception))
|
||||
{
|
||||
return DashboardApiKeyManagementResult.Fail("API key pepper is not configured.");
|
||||
return DashboardApiKeyManagementResult.Fail(PepperNotConfiguredMessage);
|
||||
}
|
||||
|
||||
CreateKeyResult rotated = await adminCommands
|
||||
.RotateKeyAsync(normalizedKeyId, RemoteAddress(), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
cacheInvalidator?.Invalidate(normalizedKeyId);
|
||||
|
||||
bool succeeded = rotated.Token is not null;
|
||||
|
||||
await WriteDashboardAuditAsync(
|
||||
user,
|
||||
normalizedKeyId,
|
||||
"dashboard-rotate-key",
|
||||
succeeded ? "rotated" : "not-found",
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
|
||||
return succeeded
|
||||
? DashboardApiKeyManagementResult.Success(
|
||||
"API key rotated. Copy the key now; it will not be shown again.",
|
||||
rotated.Token)
|
||||
: DashboardApiKeyManagementResult.Fail("API key was not found.");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
@@ -285,8 +288,7 @@ public sealed class DashboardApiKeyManagementService(
|
||||
? null
|
||||
: JsonSerializer.Serialize(new Dictionary<string, string> { ["detail"] = detail });
|
||||
|
||||
private static bool IsPepperUnavailable(InvalidOperationException exception) =>
|
||||
exception.Message.Contains(PepperUnavailableMarker, StringComparison.OrdinalIgnoreCase);
|
||||
private bool IsPepperMissing() => string.IsNullOrWhiteSpace(pepperProvider.GetPepper());
|
||||
|
||||
private static string? ValidateCreateRequest(DashboardApiKeyManagementRequest request)
|
||||
{
|
||||
|
||||
+39
-2
@@ -280,6 +280,7 @@ public sealed class DashboardApiKeyManagementServiceTests : IDisposable
|
||||
new DashboardApiKeyAuthorization(),
|
||||
services.GetRequiredService<ApiKeyAdminCommands>(),
|
||||
services.GetRequiredService<IApiKeyAdminStore>(),
|
||||
services.GetRequiredService<ZB.MOM.WW.Auth.ApiKeys.IApiKeyPepperProvider>(),
|
||||
recordingWriter,
|
||||
new HttpContextAccessor { HttpContext = httpContext });
|
||||
|
||||
@@ -299,6 +300,41 @@ public sealed class DashboardApiKeyManagementServiceTests : IDisposable
|
||||
Assert.Equal(ZB.MOM.WW.Audit.AuditOutcome.Success, dashboardEvent.Outcome);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that create reports a missing pepper as a failure result without persisting a key (mxaccessgw#195).</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task CreateAsync_PepperNotConfigured_FailsWithoutCreating()
|
||||
{
|
||||
await using ServiceProvider services = BuildServices(pepper: null);
|
||||
DashboardApiKeyManagementService service = CreateService(services);
|
||||
|
||||
DashboardApiKeyManagementResult result = await service.CreateAsync(
|
||||
CreateAuthorizedUser(),
|
||||
CreateRequest(),
|
||||
CancellationToken.None);
|
||||
|
||||
Assert.False(result.Succeeded);
|
||||
Assert.Equal("API key pepper is not configured.", result.Message);
|
||||
Assert.Empty(await ListAsync(services));
|
||||
}
|
||||
|
||||
/// <summary>Verifies that rotate reports a missing pepper as a failure result (mxaccessgw#195).</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task RotateAsync_PepperNotConfigured_Fails()
|
||||
{
|
||||
await using ServiceProvider services = BuildServices(pepper: null);
|
||||
DashboardApiKeyManagementService service = CreateService(services);
|
||||
|
||||
DashboardApiKeyManagementResult result = await service.RotateAsync(
|
||||
CreateAuthorizedUser(),
|
||||
"operator01",
|
||||
CancellationToken.None);
|
||||
|
||||
Assert.False(result.Succeeded);
|
||||
Assert.Equal("API key pepper is not configured.", result.Message);
|
||||
}
|
||||
|
||||
private DashboardApiKeyManagementService CreateService(ServiceProvider services)
|
||||
{
|
||||
DefaultHttpContext httpContext = new();
|
||||
@@ -308,11 +344,12 @@ public sealed class DashboardApiKeyManagementServiceTests : IDisposable
|
||||
new DashboardApiKeyAuthorization(),
|
||||
services.GetRequiredService<ApiKeyAdminCommands>(),
|
||||
services.GetRequiredService<IApiKeyAdminStore>(),
|
||||
services.GetRequiredService<ZB.MOM.WW.Auth.ApiKeys.IApiKeyPepperProvider>(),
|
||||
services.GetRequiredService<ZB.MOM.WW.Audit.IAuditWriter>(),
|
||||
new HttpContextAccessor { HttpContext = httpContext });
|
||||
}
|
||||
|
||||
private ServiceProvider BuildServices()
|
||||
private ServiceProvider BuildServices(string? pepper = "test-pepper")
|
||||
{
|
||||
TempDatabaseDirectory directory = TempDatabaseDirectory.Create("mxgateway-dashboard-apikey-tests");
|
||||
_tempDirectories.Add(directory);
|
||||
@@ -322,7 +359,7 @@ public sealed class DashboardApiKeyManagementServiceTests : IDisposable
|
||||
new Dictionary<string, string?>
|
||||
{
|
||||
["MxGateway:Authentication:SqlitePath"] = directory.DatabasePath(),
|
||||
["MxGateway:ApiKeyPepper"] = "test-pepper"
|
||||
["MxGateway:ApiKeyPepper"] = pepper,
|
||||
})
|
||||
.Build();
|
||||
|
||||
|
||||
Reference in New Issue
Block a user