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;
///
/// 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.
///
public class RevealAuditFailureTests : TestContext
{
private const string PlainValue = "the-plaintext-value-42";
private sealed class CapturingLogger : ILogger
{
public List<(LogLevel Level, string Message)> Entries { get; } = new();
public IDisposable? BeginScope(TState state) where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception,
Func 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();
Services.AddSingleton(store);
Services.AddSingleton(audit);
Services.AddSingleton(new FakeCipher());
Services.AddSingleton>(logger);
var auth = this.AddTestAuthorization();
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 = RenderComponent(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);
(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);
}
}