Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.ManagementService.Tests/ApiKeyCreationTests.cs
T
Joseph Doherty 5ca998dc56 fix(audit): persist config audit rows written after the final save (DEP-1, MGT-1, TPL-3, WP1 task 1.4)
IAuditService.LogAsync only stages the row; every caller that audited
after its last SaveChangesAsync, outside the configuration-command
transaction, lost the row with the DI scope (rig: zero Disable/Enable/
Delete/DeployArtifacts rows, 16 Deploy rows for 62 deployments, one
Create/Instance row for ids up to 3876).

- New IAuditService.LogAndSaveAsync: stage + save, best-effort (logs and
  swallows any failure incl. cancellation, detaches the unsaved row).
- DeploymentService (deploy/failed/reconciled/lifecycle + timeouts),
  ArtifactDeploymentService (DeployArtifacts now before the best-effort
  stamp, RetryArtifactDeployment, DeploySiteSecrets), InstanceService,
  AreaService, SiteService: post-save LogAsync -> LogAndSaveAsync.
- ManagementActor: AuditAndSaveAsync for the non-configuration handlers
  (API keys, shared schemas, ES methods, data-connection move); move now
  audits the scrubbed public shape (MGT-4) so the fix does not start
  writing protocol credentials into AuditLogEntries.
- HandleCreateInstance no longer stages a second Create row on top of
  InstanceService's own.

Tests: real-context (SQLite) tests per family read the row back through
a second context - DeploymentService, ArtifactDeploymentService,
InstanceService, ManagementActor; each fails against the old code.
Test projects gain a ConfigurationDatabase + EF Sqlite reference.
2026-12-03 09:59:19 -05:00

381 lines
17 KiB
C#

using System.Text.Json;
using Akka.Actor;
using Akka.TestKit.Xunit2;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using NSubstitute;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Security;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management;
using ZB.MOM.WW.ScadaBridge.ManagementService;
namespace ZB.MOM.WW.ScadaBridge.ManagementService.Tests;
/// <summary>
/// Inbound-API key re-arch (C2): the ManagementActor API-key management path now drives the
/// Commons <see cref="IInboundApiKeyAdmin"/> seam (added in C1) instead of the SQL Server
/// <c>IInboundApiRepository</c>. These tests exercise the actor against an in-memory fake of
/// the seam (the real <c>LibraryInboundApiKeyAdmin</c> + SQLite mapping is covered end-to-end
/// by the Security project's <c>LibraryInboundApiKeyAdminTests</c>). They verify the actor's
/// dispatch, response shapes (string keyId, one-time token, methods), the preserved ScadaBridge
/// management-audit calls, and that the "Administrator" role gate still applies to all five commands.
/// </summary>
public class ApiKeyCreationTests : TestKit, IDisposable
{
private readonly ServiceCollection _services = new();
private readonly FakeInboundApiKeyAdmin _admin = new();
private readonly IAuditService _auditService = Substitute.For<IAuditService>();
/// <summary>Initializes the test with a fake key admin and a substituted audit service.</summary>
public ApiKeyCreationTests()
{
_services.AddScoped<IInboundApiKeyAdmin>(_ => _admin);
_services.AddScoped(_ => _auditService);
}
private IActorRef CreateActor()
{
var sp = _services.BuildServiceProvider();
return Sys.ActorOf(Props.Create(() => new ManagementActor(sp, NullLogger<ManagementActor>.Instance)));
}
private static ManagementEnvelope Envelope(object command, params string[] roles) =>
new(new AuthenticatedUser("admin", "Admin User", roles, Array.Empty<string>()),
command, Guid.NewGuid().ToString("N"));
/// <inheritdoc />
void IDisposable.Dispose() => Shutdown();
/// <summary>Verifies that creating an API key returns the key id and a one-time token.</summary>
[Fact]
public void CreateApiKey_ReturnsKeyIdAndOneTimeToken()
{
var actor = CreateActor();
actor.Tell(Envelope(new CreateApiKeyCommand("MES-Production", new[] { "MethodA", "MethodB" }), "Administrator"));
var response = ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
using var doc = JsonDocument.Parse(response.JsonData);
var root = doc.RootElement;
var keyId = root.GetProperty("keyId").GetString();
var token = root.GetProperty("token").GetString();
var name = root.GetProperty("name").GetString();
Assert.False(string.IsNullOrWhiteSpace(keyId));
Assert.False(string.IsNullOrWhiteSpace(token));
Assert.StartsWith($"sbk_{keyId}_", token);
Assert.Equal("MES-Production", name);
// The seam was driven with the supplied name + methods.
var created = Assert.Single(_admin.Keys.Values);
Assert.Equal("MES-Production", created.Name);
Assert.Equal(new[] { "MethodA", "MethodB" }, created.Methods);
}
/// <summary>Verifies that creating an API key writes an audit entry.</summary>
[Fact]
public void CreateApiKey_AuditsTheCreate()
{
var actor = CreateActor();
actor.Tell(Envelope(new CreateApiKeyCommand("MES-Production", new[] { "MethodA" }), "Administrator"));
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
_auditService.Received(1).LogAndSaveAsync(
"admin", "Create", "ApiKey", Arg.Any<string>(), "MES-Production", Arg.Any<object?>());
}
/// <summary>Verifies that the create response does not echo a hash of the key.</summary>
[Fact]
public void CreateApiKey_ResponseDoesNotEchoAHash()
{
var actor = CreateActor();
actor.Tell(Envelope(new CreateApiKeyCommand("MES-Production", new[] { "MethodA" }), "Administrator"));
var response = ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
// The hash-free seam never surfaces a stored hash; the only secret in the body
// is the one-time token (sbk_<keyId>_<secret>).
Assert.DoesNotContain("hash", response.JsonData, StringComparison.OrdinalIgnoreCase);
}
/// <summary>Verifies that listing API keys returns each key with its methods.</summary>
[Fact]
public void ListApiKeys_ReturnsKeysWithMethods()
{
_admin.Seed("key-1", "Service A", enabled: true, "M1", "M2");
_admin.Seed("key-2", "Service B", enabled: false, "M3");
var actor = CreateActor();
actor.Tell(Envelope(new ListApiKeysCommand(), "Administrator"));
var response = ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
using var doc = JsonDocument.Parse(response.JsonData);
var items = doc.RootElement.EnumerateArray().ToList();
Assert.Equal(2, items.Count);
var first = items.Single(i => i.GetProperty("keyId").GetString() == "key-1");
Assert.Equal("Service A", first.GetProperty("name").GetString());
Assert.True(first.GetProperty("enabled").GetBoolean());
Assert.Equal(new[] { "M1", "M2" },
first.GetProperty("methods").EnumerateArray().Select(m => m.GetString()).ToArray());
// The list path must not surface a hash / token credential artifact.
Assert.DoesNotContain("token", response.JsonData, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("hash", response.JsonData, StringComparison.OrdinalIgnoreCase);
}
/// <summary>Verifies that updating an API key toggles its enabled flag and writes an audit entry.</summary>
[Fact]
public void UpdateApiKey_TogglesEnabled_AndAudits()
{
_admin.Seed("key-1", "Service A", enabled: true, "M1");
var actor = CreateActor();
actor.Tell(Envelope(new UpdateApiKeyCommand("key-1", false), "Administrator"));
var response = ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
Assert.False(_admin.Keys["key-1"].Enabled);
using var doc = JsonDocument.Parse(response.JsonData);
Assert.Equal("key-1", doc.RootElement.GetProperty("keyId").GetString());
Assert.False(doc.RootElement.GetProperty("isEnabled").GetBoolean());
_auditService.Received(1).LogAndSaveAsync(
"admin", "Update", "ApiKey", "key-1", Arg.Any<string>(), Arg.Any<object?>());
}
/// <summary>Verifies that deleting an API key removes it and writes an audit entry.</summary>
[Fact]
public void DeleteApiKey_RemovesKey_AndAudits()
{
_admin.Seed("key-1", "Service A", enabled: true, "M1");
var actor = CreateActor();
actor.Tell(Envelope(new DeleteApiKeyCommand("key-1"), "Administrator"));
var response = ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
Assert.DoesNotContain("key-1", _admin.Keys.Keys);
Assert.Equal("true", response.JsonData);
_auditService.Received(1).LogAndSaveAsync(
"admin", "Delete", "ApiKey", "key-1", "key-1", null);
}
/// <summary>Verifies that setting API key methods replaces the key's scopes and writes an audit entry.</summary>
[Fact]
public void SetApiKeyMethods_ReplacesScopes_AndAudits()
{
_admin.Seed("key-1", "Service A", enabled: true, "Old1", "Old2");
var actor = CreateActor();
actor.Tell(Envelope(new SetApiKeyMethodsCommand("key-1", new[] { "New1", "New2", "New3" }), "Administrator"));
var response = ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
Assert.Equal(new[] { "New1", "New2", "New3" }, _admin.Keys["key-1"].Methods);
// Fix 3 (review): response is now the richer { KeyId, Methods } shape.
using var doc = JsonDocument.Parse(response.JsonData);
Assert.Equal("key-1", doc.RootElement.GetProperty("keyId").GetString());
var methods = doc.RootElement.GetProperty("methods").EnumerateArray()
.Select(m => m.GetString()).ToArray();
Assert.Equal(new[] { "New1", "New2", "New3" }, methods);
_auditService.Received(1).LogAndSaveAsync(
"admin", "Update", "ApiKey", "key-1", Arg.Any<string>(), Arg.Any<object?>());
}
// =========================================================================
// Fix 1 (review): not-found on mutating ops → ManagementError, no audit
// =========================================================================
/// <summary>Verifies that updating an unknown API key returns a management error and writes no audit entry.</summary>
[Fact]
public void UpdateApiKey_UnknownKey_ReturnsManagementError_AndDoesNotAudit()
{
// No keys seeded — "key-unknown" does not exist.
var actor = CreateActor();
actor.Tell(Envelope(new UpdateApiKeyCommand("key-unknown", false), "Administrator"));
var response = ExpectMsg<ManagementError>(TimeSpan.FromSeconds(5));
Assert.Contains("key-unknown", response.Error);
// Seam returned false → audit must not have fired.
_auditService.DidNotReceive().LogAndSaveAsync(
Arg.Any<string>(), "Update", "ApiKey", Arg.Any<string>(), Arg.Any<string>(), Arg.Any<object?>());
}
/// <summary>Verifies that setting methods on an unknown API key returns a management error and writes no audit entry.</summary>
[Fact]
public void SetApiKeyMethods_UnknownKey_ReturnsManagementError_AndDoesNotAudit()
{
var actor = CreateActor();
actor.Tell(Envelope(new SetApiKeyMethodsCommand("key-unknown", new[] { "M1" }), "Administrator"));
var response = ExpectMsg<ManagementError>(TimeSpan.FromSeconds(5));
Assert.Contains("key-unknown", response.Error);
_auditService.DidNotReceive().LogAndSaveAsync(
Arg.Any<string>(), "Update", "ApiKey", Arg.Any<string>(), Arg.Any<string>(), Arg.Any<object?>());
}
/// <summary>Verifies that deleting an unknown API key returns a management error and writes no audit entry.</summary>
[Fact]
public void DeleteApiKey_UnknownKey_ReturnsManagementError_AndDoesNotAudit()
{
var actor = CreateActor();
actor.Tell(Envelope(new DeleteApiKeyCommand("key-unknown"), "Administrator"));
var response = ExpectMsg<ManagementError>(TimeSpan.FromSeconds(5));
Assert.Contains("key-unknown", response.Error);
_auditService.DidNotReceive().LogAndSaveAsync(
Arg.Any<string>(), "Delete", "ApiKey", Arg.Any<string>(), Arg.Any<string>(), Arg.Any<object?>());
}
// =========================================================================
// Fix 2 (review): empty methods set is rejected before seam + audit
// =========================================================================
/// <summary>Verifies that creating an API key with no methods returns a management error.</summary>
[Fact]
public void CreateApiKey_EmptyMethods_ReturnsManagementError()
{
var actor = CreateActor();
actor.Tell(Envelope(new CreateApiKeyCommand("MES-Production", Array.Empty<string>()), "Administrator"));
var response = ExpectMsg<ManagementError>(TimeSpan.FromSeconds(5));
Assert.Contains("method", response.Error, StringComparison.OrdinalIgnoreCase);
// No key should have been created.
Assert.Empty(_admin.Keys);
_auditService.DidNotReceive().LogAndSaveAsync(
Arg.Any<string>(), "Create", "ApiKey", Arg.Any<string>(), Arg.Any<string>(), Arg.Any<object?>());
}
/// <summary>Verifies that setting an empty method list on an API key returns a management error.</summary>
[Fact]
public void SetApiKeyMethods_EmptyMethods_ReturnsManagementError()
{
_admin.Seed("key-1", "Service A", enabled: true, "M1");
var actor = CreateActor();
actor.Tell(Envelope(new SetApiKeyMethodsCommand("key-1", Array.Empty<string>()), "Administrator"));
var response = ExpectMsg<ManagementError>(TimeSpan.FromSeconds(5));
Assert.Contains("method", response.Error, StringComparison.OrdinalIgnoreCase);
// Existing scope set must be unchanged.
Assert.Equal(new[] { "M1" }, _admin.Keys["key-1"].Methods);
_auditService.DidNotReceive().LogAndSaveAsync(
Arg.Any<string>(), "Update", "ApiKey", Arg.Any<string>(), Arg.Any<string>(), Arg.Any<object?>());
}
/// <summary>Verifies that every API key command is rejected for a caller without the Administrator role.</summary>
/// <param name="command">The API key command under test.</param>
[Theory]
[MemberData(nameof(AllApiKeyCommands))]
public void EveryApiKeyCommand_RequiresAdminRole(object command)
{
var actor = CreateActor();
// A Designer-role caller (not Administrator) must be rejected for every API-key command.
actor.Tell(Envelope(command, "Designer"));
var response = ExpectMsg<ManagementUnauthorized>(TimeSpan.FromSeconds(5));
Assert.Contains("Administrator", response.Message);
}
/// <summary>Supplies one instance of every API key command as test data.</summary>
/// <returns>The commands, each wrapped as a single-element argument array.</returns>
public static IEnumerable<object[]> AllApiKeyCommands() => new[]
{
new object[] { new ListApiKeysCommand() },
new object[] { new CreateApiKeyCommand("X", new[] { "M1" }) },
new object[] { new DeleteApiKeyCommand("key-1") },
new object[] { new UpdateApiKeyCommand("key-1", true) },
new object[] { new SetApiKeyMethodsCommand("key-1", new[] { "M1" }) },
};
/// <summary>
/// Minimal in-memory fake of the C1 management seam. Models only what the
/// ManagementActor handlers exercise: create (assigns a keyId + assembles a
/// <c>sbk_&lt;keyId&gt;_&lt;secret&gt;</c> token), list, toggle-enabled, replace-methods,
/// and delete. Mirrors the real seam's bool/return semantics (false when a key is absent).
/// </summary>
private sealed class FakeInboundApiKeyAdmin : IInboundApiKeyAdmin
{
public sealed record Entry(string KeyId, string Name, bool Enabled, IReadOnlyList<string> Methods);
/// <summary>Gets the keys currently held by the fake, indexed by key id.</summary>
public Dictionary<string, Entry> Keys { get; } = new(StringComparer.Ordinal);
/// <summary>Adds or replaces a key in the fake.</summary>
/// <param name="keyId">The key id.</param>
/// <param name="name">The key name.</param>
/// <param name="enabled">Whether the key is enabled.</param>
/// <param name="methods">The methods the key may call.</param>
public void Seed(string keyId, string name, bool enabled, params string[] methods) =>
Keys[keyId] = new Entry(keyId, name, enabled, methods.ToList());
/// <inheritdoc />
public Task<InboundApiKeyCreated> CreateAsync(
string name, IReadOnlyCollection<string> methods, CancellationToken ct = default)
{
var keyId = Guid.NewGuid().ToString("N");
Keys[keyId] = new Entry(keyId, name, Enabled: true, methods.ToList());
return Task.FromResult(new InboundApiKeyCreated(keyId, $"sbk_{keyId}_secret"));
}
/// <inheritdoc />
public Task<IReadOnlyList<InboundApiKeyInfo>> ListAsync(CancellationToken ct = default)
{
IReadOnlyList<InboundApiKeyInfo> result = Keys.Values
.Select(e => new InboundApiKeyInfo(
e.KeyId, e.Name, e.Enabled, e.Methods,
DateTimeOffset.UnixEpoch, LastUsedUtc: null))
.ToList();
return Task.FromResult(result);
}
/// <inheritdoc />
public Task<bool> SetEnabledAsync(string keyId, bool enabled, CancellationToken ct = default)
{
if (!Keys.TryGetValue(keyId, out var e)) return Task.FromResult(false);
Keys[keyId] = e with { Enabled = enabled };
return Task.FromResult(true);
}
/// <inheritdoc />
public Task<bool> SetMethodsAsync(string keyId, IReadOnlyCollection<string> methods, CancellationToken ct = default)
{
if (!Keys.TryGetValue(keyId, out var e)) return Task.FromResult(false);
Keys[keyId] = e with { Methods = methods.ToList() };
return Task.FromResult(true);
}
/// <inheritdoc />
public Task<bool> DeleteAsync(string keyId, CancellationToken ct = default) =>
Task.FromResult(Keys.Remove(keyId));
/// <inheritdoc />
public Task<IReadOnlyList<string>> GetMethodsForKeyAsync(string keyId, CancellationToken ct = default)
{
IReadOnlyList<string> methods = Keys.TryGetValue(keyId, out var e) ? e.Methods : Array.Empty<string>();
return Task.FromResult(methods);
}
/// <inheritdoc />
public Task<IReadOnlyList<string>> GetKeysForMethodAsync(string methodName, CancellationToken ct = default)
{
IReadOnlyList<string> keys = Keys.Values
.Where(e => e.Methods.Contains(methodName, StringComparer.Ordinal))
.Select(e => e.KeyId)
.ToList();
return Task.FromResult(keys);
}
}
}