fix(transport): secret-bearing bundle export needs Administrator; scrub data-connection move reply (MGT-3, MGT-4, WP1 task 1.5)

MGT-3: a Designer could read SMTP/SMS credentials, external-system auth,
DB connection strings and data-connection configuration through bundle
export, values the management API returns to no one. Both export
surfaces now resolve the selection (dependencies included) via the new
IBundleExporter.CountSecretsAsync / ExportSecretPolicy and require
Administrator when it carries any secret; a secret-free export stays a
Designer operation. The ExportBundle gate becomes any-of [Designer,
Administrator] - a deliberate change to the frozen authz matrix. A new
ManagementAuthorizationException maps to ManagementUnauthorized.

MGT-4: data-connection move replies with DataConnectionPublicShape like
its siblings (the audit after-state switched with task 1.4).

Tests: matrix entry, Designer+secrets refused (nothing exported), Admin
and secret-free Designer succeed, UI wizard refuses a Designer, policy
counts every SecretsBlock field, move reply carries no secret.
This commit is contained in:
Joseph Doherty
2026-12-03 10:04:28 -05:00
parent 5ca998dc56
commit 8c5d70f687
12 changed files with 335 additions and 43 deletions
@@ -328,6 +328,42 @@ public class TransportExportPageTests : BunitContext
Arg.Any<CancellationToken>());
}
// ─────────────────────────────────────────────────────────────────────
// Code review 2026-12-02 MGT-3: a Designer-only user cannot export a selection
// whose resolved closure carries stored secrets; nothing is exported.
// ─────────────────────────────────────────────────────────────────────
/// <summary>Verifies that a Designer without Administrator cannot export a secret-bearing selection.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Step4_SecretBearingSelection_RequiresAdministrator()
{
var template = new Template("Pump") { Id = 1 };
_templateRepo.GetTemplateStubsAsync(Arg.Any<CancellationToken>())
.Returns(Task.FromResult<IReadOnlyList<TemplateStub>>(
(new List<Template> { template }).Select(t => new TemplateStub(t.Id, t.Name, t.ParentTemplateId, t.FolderId, t.IsDerived, t.OwnerCompositionId)).ToList()));
_templateRepo.GetTemplateWithChildrenAsync(1, Arg.Any<CancellationToken>())
.Returns(Task.FromResult<Template?>(template));
_exporter.CountSecretsAsync(Arg.Any<ExportSelection>(), Arg.Any<CancellationToken>()).Returns(3);
var cut = Render<TransportExportPage>();
cut.WaitForState(() => cut.Markup.Contains("Pump"));
cut.FindAll("li[role='treeitem']")
.First(li => li.TextContent.Contains("Pump"))
.QuerySelector("input.tv-checkbox")!.Change(true);
await cut.FindAll("button").First(b => b.TextContent.Trim() == "Next").ClickAsync(new());
cut.WaitForAssertion(() => Assert.Contains("Selected by you", cut.Markup));
await cut.FindAll("button").First(b => b.TextContent.Trim() == "Next").ClickAsync(new());
cut.WaitForAssertion(() => Assert.Contains("Passphrase", cut.Markup));
cut.Find("#passphrase").Input("hunter2hunter2");
cut.Find("#passphrase-confirm").Input("hunter2hunter2");
await cut.FindAll("button").First(b => b.TextContent.Trim() == "Export").ClickAsync(new());
cut.WaitForAssertion(() => Assert.Contains("requires the Administrator role", cut.Markup));
await _exporter.DidNotReceive().ExportAsync(
Arg.Any<ExportSelection>(), Arg.Any<string>(), Arg.Any<string>(),
Arg.Any<string?>(), Arg.Any<CancellationToken>());
}
// ─────────────────────────────────────────────────────────────────────
// Test 4: A user without the Design role fails the RequireDesign policy.
// The router enforces [Authorize(Policy=...)] at request time — bUnit
@@ -4116,14 +4116,15 @@ public class ManagementActorTests : TestKit, IDisposable
IncludeDependencies: false, Passphrase: null,
SourceEnvironment: "test-env");
/// <summary>Verifies that export bundle command, when with admin role, returns unauthorized.</summary>
/// <summary>Verifies that export bundle command, when with deployer role, returns unauthorized.</summary>
[Fact]
public void ExportBundleCommand_WithAdminRole_ReturnsUnauthorized()
public void ExportBundleCommand_WithDeployerRole_ReturnsUnauthorized()
{
// ExportBundle requires the Design role; an Admin-only caller is rejected.
// ExportBundle requires Designer or Administrator (code review 2026-12-02 MGT-3
// widened the gate from Designer-only); a Deployer is rejected at the gate.
AddBundleSubstitutes();
var actor = CreateActor();
var envelope = Envelope(AllExportCommand(), "Administrator");
var envelope = Envelope(AllExportCommand(), "Deployer");
actor.Tell(envelope);
@@ -4131,6 +4132,69 @@ public class ManagementActorTests : TestKit, IDisposable
Assert.Contains("Designer", response.Message);
}
// ── Code review 2026-12-02 MGT-3: secret-bearing export needs Administrator ──
/// <summary>
/// A Designer whose resolved export carries stored secrets is refused with
/// <c>ManagementUnauthorized</c>, and nothing is exported.
/// </summary>
[Fact]
public void ExportBundleCommand_WithSecrets_AsDesigner_ReturnsUnauthorized()
{
var (exporter, _) = AddBundleSubstitutes();
exporter.CountSecretsAsync(Arg.Any<Commons.Types.Transport.ExportSelection>(), Arg.Any<CancellationToken>())
.Returns(2);
var actor = CreateActor();
actor.Tell(Envelope(AllExportCommand(), "Designer"));
var response = ExpectMsg<ManagementUnauthorized>(TimeSpan.FromSeconds(5));
Assert.Contains("Administrator", response.Message);
Assert.Contains("2 stored secret", response.Message);
exporter.DidNotReceive().ExportAsync(
Arg.Any<Commons.Types.Transport.ExportSelection>(), Arg.Any<string>(), Arg.Any<string>(),
Arg.Any<string?>(), Arg.Any<CancellationToken>());
}
/// <summary>An Administrator may export secret-bearing configuration (no secret probe needed).</summary>
/// <param name="roles">Comma-separated roles of the caller.</param>
[Theory]
[InlineData("Administrator")]
[InlineData("Designer,Administrator")]
public void ExportBundleCommand_WithSecrets_AsAdministrator_Succeeds(string roles)
{
var (exporter, _) = AddBundleSubstitutes();
exporter.CountSecretsAsync(Arg.Any<Commons.Types.Transport.ExportSelection>(), Arg.Any<CancellationToken>())
.Returns(2);
exporter.ExportAsync(
Arg.Any<Commons.Types.Transport.ExportSelection>(), Arg.Any<string>(), Arg.Any<string>(),
Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(_ => Task.FromResult<Stream>(new MemoryStream(new byte[] { 1 })));
var actor = CreateActor();
actor.Tell(Envelope(AllExportCommand(), roles.Split(',')));
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
}
/// <summary>A Designer may still export a secret-free selection.</summary>
[Fact]
public void ExportBundleCommand_WithoutSecrets_AsDesigner_Succeeds()
{
var (exporter, _) = AddBundleSubstitutes();
exporter.CountSecretsAsync(Arg.Any<Commons.Types.Transport.ExportSelection>(), Arg.Any<CancellationToken>())
.Returns(0);
exporter.ExportAsync(
Arg.Any<Commons.Types.Transport.ExportSelection>(), Arg.Any<string>(), Arg.Any<string>(),
Arg.Any<string?>(), Arg.Any<CancellationToken>())
.Returns(_ => Task.FromResult<Stream>(new MemoryStream(new byte[] { 1 })));
var actor = CreateActor();
actor.Tell(Envelope(AllExportCommand(), "Designer"));
ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
}
/// <summary>Verifies that preview bundle command, when with design role, returns unauthorized.</summary>
[Fact]
public void PreviewBundleCommand_WithDesignRole_ReturnsUnauthorized()
@@ -5295,6 +5359,39 @@ public class ManagementActorTests : TestKit, IDisposable
Arg.Any<object?>(), Arg.Any<CancellationToken>());
}
/// <summary>
/// Code review 2026-12-02 MGT-4: <c>data-connection move</c> replies with the scrubbed
/// public shape like its siblings, never the raw entity's stored credentials.
/// </summary>
[Fact]
public void MoveDataConnection_Reply_IsScrubbed()
{
var conn = new Commons.Entities.Sites.DataConnection("Opc1", "OpcUa", 1)
{
Id = 5,
PrimaryConfiguration = """{"endpointUrl":"opc.tcp://plc:4840","password":"hunter2-primary"}""",
BackupConfiguration = """{"endpointUrl":"opc.tcp://plc2:4840","apiKey":"hunter2-backup"}""",
};
var siteRepo = Substitute.For<ISiteRepository>();
siteRepo.GetDataConnectionByIdAsync(5, Arg.Any<CancellationToken>()).Returns(conn);
siteRepo.GetSiteByIdAsync(2, Arg.Any<CancellationToken>()).Returns(new Commons.Entities.Sites.Site("Target", "SITE-B") { Id = 2 });
siteRepo.GetDataConnectionsBySiteIdAsync(2, Arg.Any<CancellationToken>())
.Returns(new List<Commons.Entities.Sites.DataConnection>());
siteRepo.GetInstancesReferencingDataConnectionAsync(5, Arg.Any<CancellationToken>()).Returns(new List<Instance>());
siteRepo.GetInstancesWithNativeAlarmOverridesBySiteIdAsync(1, Arg.Any<CancellationToken>()).Returns(new List<Instance>());
siteRepo.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(1);
_services.AddScoped(_ => siteRepo);
var actor = CreateActor();
actor.Tell(Envelope(new MoveDataConnectionCommand(5, 2), "Designer"));
var response = ExpectMsg<ManagementSuccess>(TimeSpan.FromSeconds(5));
Assert.DoesNotContain("hunter2", response.JsonData);
Assert.Contains(ConfigSecretScrubber.Sentinel, response.JsonData);
Assert.Contains("opc.tcp://plc:4840", response.JsonData); // non-secret fields survive
Assert.Contains("\"siteId\":2", response.JsonData);
}
/// <summary>Verifies that move data connection, when target site missing, returns error.</summary>
[Fact]
public void MoveDataConnection_TargetSiteMissing_ReturnsError()
@@ -63,6 +63,14 @@ public class RequiredRoleMatrixTests
["PreviewBundle"] = [Roles.Administrator],
["ImportBundle"] = [Roles.Administrator],
// ---- Bundle export: any-of [Designer, Administrator] ------------------------
// Code review 2026-12-02 MGT-3 (deliberate change, was [Designer]): the gate admits
// Administrator too, and the handler additionally requires Administrator whenever the
// resolved export carries a stored secret (SMTP/SMS credentials, external-system auth,
// DB connection strings, data-connection configuration). Content-dependent, so it is
// pinned by ManagementActorTests.ExportBundleCommand_WithSecrets_* rather than here.
["ExportBundle"] = [Roles.Designer, Roles.Administrator],
// ---- Area management: any-of [Designer, Deployer] ---------------------------
["CreateArea"] = AreaManagers,
["UpdateArea"] = AreaManagers,
@@ -128,7 +136,6 @@ public class RequiredRoleMatrixTests
["BrowseNode"] = [Roles.Designer],
["SearchAddressSpace"] = [Roles.Designer],
["VerifyEndpoint"] = [Roles.Designer],
["ExportBundle"] = [Roles.Designer],
// ---- Deployer-only ----------------------------------------------------------
["CreateInstance"] = [Roles.Deployer],
@@ -0,0 +1,55 @@
using ZB.MOM.WW.ScadaBridge.Commons.Entities.ExternalSystems;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.InboundApi;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Notifications;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Scripts;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Transport;
using ZB.MOM.WW.ScadaBridge.Transport.Export;
namespace ZB.MOM.WW.ScadaBridge.Transport.Tests.Export;
/// <summary>
/// Code review 2026-12-02 MGT-3: <see cref="ExportSecretPolicy.CountSecrets"/> decides whether
/// an export needs the Administrator role, on both the management API and the Central UI. It
/// must count exactly the fields the serializer puts in a <c>SecretsBlock</c>.
/// </summary>
public class ExportSecretPolicyTests
{
private static ResolvedExport Resolved(
IReadOnlyList<ExternalSystemDefinition>? es = null,
IReadOnlyList<DatabaseConnectionDefinition>? db = null,
IReadOnlyList<SmtpConfiguration>? smtp = null,
IReadOnlyList<SmsConfiguration>? sms = null,
IReadOnlyList<DataConnection>? dc = null) =>
new(Array.Empty<TemplateFolder>(), Array.Empty<Template>(), Array.Empty<SharedScript>(),
es ?? Array.Empty<ExternalSystemDefinition>(), Array.Empty<ExternalSystemMethod>(),
db ?? Array.Empty<DatabaseConnectionDefinition>(), Array.Empty<NotificationList>(),
smtp ?? Array.Empty<SmtpConfiguration>(), Array.Empty<ApiMethod>(), Array.Empty<ManifestContentEntry>())
{
SmsConfigs = sms ?? Array.Empty<SmsConfiguration>(),
DataConnections = dc ?? Array.Empty<DataConnection>(),
};
/// <summary>A secret-free closure needs no Administrator.</summary>
[Fact]
public void SecretFreeExport_CountsZero()
{
var es = new ExternalSystemDefinition("ERP", "https://erp", "None");
var dc = new DataConnection("Plc", "OpcUa", 1);
Assert.Equal(0, ExportSecretPolicy.CountSecrets(Resolved(es: [es], dc: [dc])));
}
/// <summary>Every secret-bearing category contributes one per non-empty secret field.</summary>
[Fact]
public void EverySecretCategory_IsCounted()
{
var es = new ExternalSystemDefinition("ERP", "https://erp", "ApiKey") { AuthConfiguration = "{\"key\":\"k\"}" };
var db = new DatabaseConnectionDefinition("Mes", "Server=x;Password=y");
var smtp = new SmtpConfiguration("smtp.example.com", "Basic", "a@b") { Credentials = "u:p" };
var sms = new SmsConfiguration("AC1", "+15550000000") { AuthToken = "tok" };
var dc = new DataConnection("Plc", "OpcUa", 1) { PrimaryConfiguration = "{}", BackupConfiguration = "{}" };
Assert.Equal(6, ExportSecretPolicy.CountSecrets(Resolved([es], [db], [smtp], [sms], [dc])));
}
}