diff --git a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardApiKeyManagementService.cs b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardApiKeyManagementService.cs
index 3dd3447f..41e773bc 100644
--- a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardApiKeyManagementService.cs
+++ b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardApiKeyManagementService.cs
@@ -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.";
///
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.");
}
///
@@ -285,8 +288,7 @@ public sealed class DashboardApiKeyManagementService(
? null
: JsonSerializer.Serialize(new Dictionary { ["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)
{
diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/DashboardApiKeyManagementServiceTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/DashboardApiKeyManagementServiceTests.cs
index f9c4a9db..4aecc340 100644
--- a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/DashboardApiKeyManagementServiceTests.cs
+++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/DashboardApiKeyManagementServiceTests.cs
@@ -280,6 +280,7 @@ public sealed class DashboardApiKeyManagementServiceTests : IDisposable
new DashboardApiKeyAuthorization(),
services.GetRequiredService(),
services.GetRequiredService(),
+ services.GetRequiredService(),
recordingWriter,
new HttpContextAccessor { HttpContext = httpContext });
@@ -299,6 +300,41 @@ public sealed class DashboardApiKeyManagementServiceTests : IDisposable
Assert.Equal(ZB.MOM.WW.Audit.AuditOutcome.Success, dashboardEvent.Outcome);
}
+ /// Verifies that create reports a missing pepper as a failure result without persisting a key (mxaccessgw#195).
+ /// A task that represents the asynchronous operation.
+ [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));
+ }
+
+ /// Verifies that rotate reports a missing pepper as a failure result (mxaccessgw#195).
+ /// A task that represents the asynchronous operation.
+ [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(),
services.GetRequiredService(),
+ services.GetRequiredService(),
services.GetRequiredService(),
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
{
["MxGateway:Authentication:SqlitePath"] = directory.DatabasePath(),
- ["MxGateway:ApiKeyPepper"] = "test-pepper"
+ ["MxGateway:ApiKeyPepper"] = pepper,
})
.Build();