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 Microsoft.Data.Sqlite;
|
||||||
using ZB.MOM.WW.Audit;
|
using ZB.MOM.WW.Audit;
|
||||||
using ZB.MOM.WW.Auth.Abstractions.ApiKeys;
|
using ZB.MOM.WW.Auth.Abstractions.ApiKeys;
|
||||||
|
using ZB.MOM.WW.Auth.ApiKeys;
|
||||||
using ZB.MOM.WW.Auth.ApiKeys.Admin;
|
using ZB.MOM.WW.Auth.ApiKeys.Admin;
|
||||||
using ZB.MOM.WW.MxGateway.Server.Security.Audit;
|
using ZB.MOM.WW.MxGateway.Server.Security.Audit;
|
||||||
using ZB.MOM.WW.MxGateway.Server.Security.Authentication;
|
using ZB.MOM.WW.MxGateway.Server.Security.Authentication;
|
||||||
@@ -14,12 +15,13 @@ public sealed class DashboardApiKeyManagementService(
|
|||||||
DashboardApiKeyAuthorization authorization,
|
DashboardApiKeyAuthorization authorization,
|
||||||
ApiKeyAdminCommands adminCommands,
|
ApiKeyAdminCommands adminCommands,
|
||||||
IApiKeyAdminStore adminStore,
|
IApiKeyAdminStore adminStore,
|
||||||
|
IApiKeyPepperProvider pepperProvider,
|
||||||
IAuditWriter auditWriter,
|
IAuditWriter auditWriter,
|
||||||
IHttpContextAccessor httpContextAccessor,
|
IHttpContextAccessor httpContextAccessor,
|
||||||
IApiKeyCacheInvalidator? cacheInvalidator = null) : IDashboardApiKeyManagementService
|
IApiKeyCacheInvalidator? cacheInvalidator = null) : IDashboardApiKeyManagementService
|
||||||
{
|
{
|
||||||
private const string UnauthorizedMessage = "Sign in with an authorized LDAP account to manage API keys.";
|
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 />
|
/// <inheritdoc />
|
||||||
public bool CanManage(ClaimsPrincipal user)
|
public bool CanManage(ClaimsPrincipal user)
|
||||||
@@ -46,6 +48,13 @@ public sealed class DashboardApiKeyManagementService(
|
|||||||
|
|
||||||
string keyId = request.KeyId.Trim();
|
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
|
try
|
||||||
{
|
{
|
||||||
// The shared command set generates the secret, hashes it with the pepper, persists the
|
// 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.",
|
"API key created. Copy the key now; it will not be shown again.",
|
||||||
created.Token);
|
created.Token);
|
||||||
}
|
}
|
||||||
catch (InvalidOperationException exception) when (IsPepperUnavailable(exception))
|
|
||||||
{
|
|
||||||
return DashboardApiKeyManagementResult.Fail("API key pepper is not configured.");
|
|
||||||
}
|
|
||||||
catch (SqliteException exception) when (exception.SqliteErrorCode == 19)
|
catch (SqliteException exception) when (exception.SqliteErrorCode == 19)
|
||||||
{
|
{
|
||||||
return DashboardApiKeyManagementResult.Fail("An API key with that id already exists.");
|
return DashboardApiKeyManagementResult.Fail("An API key with that id already exists.");
|
||||||
@@ -135,34 +140,32 @@ public sealed class DashboardApiKeyManagementService(
|
|||||||
|
|
||||||
string normalizedKeyId = keyId.Trim();
|
string normalizedKeyId = keyId.Trim();
|
||||||
|
|
||||||
try
|
if (IsPepperMissing())
|
||||||
{
|
{
|
||||||
CreateKeyResult rotated = await adminCommands
|
return DashboardApiKeyManagementResult.Fail(PepperNotConfiguredMessage);
|
||||||
.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.");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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 />
|
/// <inheritdoc />
|
||||||
@@ -285,8 +288,7 @@ public sealed class DashboardApiKeyManagementService(
|
|||||||
? null
|
? null
|
||||||
: JsonSerializer.Serialize(new Dictionary<string, string> { ["detail"] = detail });
|
: JsonSerializer.Serialize(new Dictionary<string, string> { ["detail"] = detail });
|
||||||
|
|
||||||
private static bool IsPepperUnavailable(InvalidOperationException exception) =>
|
private bool IsPepperMissing() => string.IsNullOrWhiteSpace(pepperProvider.GetPepper());
|
||||||
exception.Message.Contains(PepperUnavailableMarker, StringComparison.OrdinalIgnoreCase);
|
|
||||||
|
|
||||||
private static string? ValidateCreateRequest(DashboardApiKeyManagementRequest request)
|
private static string? ValidateCreateRequest(DashboardApiKeyManagementRequest request)
|
||||||
{
|
{
|
||||||
|
|||||||
+39
-2
@@ -280,6 +280,7 @@ public sealed class DashboardApiKeyManagementServiceTests : IDisposable
|
|||||||
new DashboardApiKeyAuthorization(),
|
new DashboardApiKeyAuthorization(),
|
||||||
services.GetRequiredService<ApiKeyAdminCommands>(),
|
services.GetRequiredService<ApiKeyAdminCommands>(),
|
||||||
services.GetRequiredService<IApiKeyAdminStore>(),
|
services.GetRequiredService<IApiKeyAdminStore>(),
|
||||||
|
services.GetRequiredService<ZB.MOM.WW.Auth.ApiKeys.IApiKeyPepperProvider>(),
|
||||||
recordingWriter,
|
recordingWriter,
|
||||||
new HttpContextAccessor { HttpContext = httpContext });
|
new HttpContextAccessor { HttpContext = httpContext });
|
||||||
|
|
||||||
@@ -299,6 +300,41 @@ public sealed class DashboardApiKeyManagementServiceTests : IDisposable
|
|||||||
Assert.Equal(ZB.MOM.WW.Audit.AuditOutcome.Success, dashboardEvent.Outcome);
|
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)
|
private DashboardApiKeyManagementService CreateService(ServiceProvider services)
|
||||||
{
|
{
|
||||||
DefaultHttpContext httpContext = new();
|
DefaultHttpContext httpContext = new();
|
||||||
@@ -308,11 +344,12 @@ public sealed class DashboardApiKeyManagementServiceTests : IDisposable
|
|||||||
new DashboardApiKeyAuthorization(),
|
new DashboardApiKeyAuthorization(),
|
||||||
services.GetRequiredService<ApiKeyAdminCommands>(),
|
services.GetRequiredService<ApiKeyAdminCommands>(),
|
||||||
services.GetRequiredService<IApiKeyAdminStore>(),
|
services.GetRequiredService<IApiKeyAdminStore>(),
|
||||||
|
services.GetRequiredService<ZB.MOM.WW.Auth.ApiKeys.IApiKeyPepperProvider>(),
|
||||||
services.GetRequiredService<ZB.MOM.WW.Audit.IAuditWriter>(),
|
services.GetRequiredService<ZB.MOM.WW.Audit.IAuditWriter>(),
|
||||||
new HttpContextAccessor { HttpContext = httpContext });
|
new HttpContextAccessor { HttpContext = httpContext });
|
||||||
}
|
}
|
||||||
|
|
||||||
private ServiceProvider BuildServices()
|
private ServiceProvider BuildServices(string? pepper = "test-pepper")
|
||||||
{
|
{
|
||||||
TempDatabaseDirectory directory = TempDatabaseDirectory.Create("mxgateway-dashboard-apikey-tests");
|
TempDatabaseDirectory directory = TempDatabaseDirectory.Create("mxgateway-dashboard-apikey-tests");
|
||||||
_tempDirectories.Add(directory);
|
_tempDirectories.Add(directory);
|
||||||
@@ -322,7 +359,7 @@ public sealed class DashboardApiKeyManagementServiceTests : IDisposable
|
|||||||
new Dictionary<string, string?>
|
new Dictionary<string, string?>
|
||||||
{
|
{
|
||||||
["MxGateway:Authentication:SqlitePath"] = directory.DatabasePath(),
|
["MxGateway:Authentication:SqlitePath"] = directory.DatabasePath(),
|
||||||
["MxGateway:ApiKeyPepper"] = "test-pepper"
|
["MxGateway:ApiKeyPepper"] = pepper,
|
||||||
})
|
})
|
||||||
.Build();
|
.Build();
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user