Files
scadaproj/ZB.MOM.WW.Secrets/tests/ZB.MOM.WW.Secrets.Ui.Tests/RevealAuditFailureTests.cs
T

76 lines
3.2 KiB
C#

using Bunit;
using Bunit.TestDoubles;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using ZB.MOM.WW.Audit;
using ZB.MOM.WW.Secrets.Abstractions;
using ZB.MOM.WW.Secrets.Ui.Components;
using ZB.MOM.WW.Secrets.Ui.Tests.Fakes;
namespace ZB.MOM.WW.Secrets.Ui.Tests;
/// <summary>
/// Secrets-015: a reveal whose audit write fails must not show the plaintext (fail closed), and the
/// failure must be logged — actor and name, never the value.
/// </summary>
public class RevealAuditFailureTests : BunitContext
{
public RevealAuditFailureTests() => RevealInterop.Setup(JSInterop);
private const string PlainValue = "the-plaintext-value-42";
private sealed class CapturingLogger<T> : ILogger<T>
{
public List<(LogLevel Level, string Message)> Entries { get; } = new();
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception,
Func<TState, Exception?, string> formatter) => Entries.Add((logLevel, formatter(state, exception)));
}
[Fact]
public void A_reveal_whose_audit_fails_shows_nothing_and_logs_it()
{
var store = new RecordingSecretStore();
var audit = new CapturingAuditWriter { SuccessFault = new InvalidOperationException("audit sink down") };
var logger = new CapturingLogger<RevealButton>();
Services.AddSingleton<ISecretStore>(store);
Services.AddSingleton<IAuditWriter>(audit);
Services.AddSingleton<ISecretCipher>(new FakeCipher());
Services.AddSingleton<ILogger<RevealButton>>(logger);
var auth = this.AddAuthorization();
auth.SetAuthorized("mallory");
auth.SetPolicies(SecretsAuthorization.RevealPolicy);
var name = new SecretName("prod/db");
store.Seed(new FakeCipher().Encrypt(name, PlainValue, SecretContentType.Text) with
{
Revision = 1,
CreatedUtc = DateTimeOffset.UnixEpoch,
UpdatedUtc = DateTimeOffset.UnixEpoch,
});
var cut = Render<RevealButton>(p => p.Add(c => c.Name, name));
cut.Find("button.reveal-secret").Click();
Assert.DoesNotContain(PlainValue, cut.Markup);
Assert.Empty(cut.FindAll("[data-testid=revealed-value]"));
Assert.Contains("audit", cut.Find("[data-testid=reveal-error]").TextContent);
var status = cut.Find("[data-testid=reveal-status][role=status]");
Assert.Contains("Reveal failed", status.TextContent);
Assert.DoesNotContain(PlainValue, status.TextContent);
var described = cut.Find("[data-testid=hide-button]").GetAttribute("aria-describedby")!.Split(' ');
Assert.Contains(cut.Find("[data-testid=reveal-error]").Id, described);
Assert.All(described, id => Assert.NotNull(cut.Find($"[id='{id}']")));
(LogLevel level, string message) = Assert.Single(logger.Entries);
Assert.Equal(LogLevel.Warning, level);
Assert.Contains("prod/db", message);
Assert.Contains("mallory", message);
Assert.DoesNotContain(PlainValue, message);
}
}