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
+1 -1
View File
@@ -133,7 +133,7 @@ Central cluster only. Sites have no user interface.
- The API key detail page includes a **"Recent calls"** link that opens the Audit Log page pre-filtered to `Actor = <key name>` and `Channel = ApiInbound` — surfacing the key's recent inbound-call audit history.
### Bundle Export / Import (Design Role for export, Admin Role for import)
- `Export Bundle` (`/design/transport/export`) — multi-step wizard for exporting a `.scadabundle` artifact containing templates, shared scripts, external systems, and central-only configuration. Visible to users with `RequireDesign`.
- `Export Bundle` (`/design/transport/export`) — multi-step wizard for exporting a `.scadabundle` artifact containing templates, shared scripts, external systems, and central-only configuration. Visible to users with `RequireDesign`; exporting a selection whose resolved closure carries stored secrets additionally requires the Administrator role (code review 2026-12-02 MGT-3).
- `Import Bundle` (`/design/transport/import`) — multi-step wizard for uploading and applying a `.scadabundle` into the current environment, with per-artifact diff review and conflict resolution. Visible to users with `RequireAdmin`.
### Area Management (Designer or Deployer Role)
@@ -145,7 +145,7 @@ The whole folder surface is reachable from the CLI as `template folder list|crea
- **CreateDataConnection** / **UpdateDataConnection** / **DeleteDataConnection**: Manage data connection definitions.
- **AssignDataConnectionToSite** / **UnassignDataConnectionFromSite**: Manage site assignments.
> **Secret elision (arch-review C3).** The `PrimaryConfiguration`/`BackupConfiguration` JSON blobs can embed OPC UA user and certificate passwords, yet List/Get are readable by any authenticated user. All command responses **and** audit `afterState` are projected through a secret-elided shape (`DataConnectionPublicShape`): secret-bearing values inside the config JSON are replaced with a redaction sentinel and a `hasSecrets` flag is surfaced (mirrors the SMTP/SMS `HasCredentials` pattern). **Update** merges the sentinel via `ConfigSecretScrubber.MergeSentinels` — a client that round-trips a scrubbed config keeps the stored secret rather than wiping it.
> **Secret elision (arch-review C3).** The `PrimaryConfiguration`/`BackupConfiguration` JSON blobs can embed OPC UA user and certificate passwords, yet List/Get are readable by any authenticated user. All command responses **and** audit `afterState` — including `MoveDataConnection`, which returned and audited the raw entity until code review 2026-12-02 MGT-4 — are projected through a secret-elided shape (`DataConnectionPublicShape`): secret-bearing values inside the config JSON are replaced with a redaction sentinel and a `hasSecrets` flag is surfaced (mirrors the SMTP/SMS `HasCredentials` pattern). **Update** merges the sentinel via `ConfigSecretScrubber.MergeSentinels` — a client that round-trips a scrubbed config keeps the stored secret rather than wiping it.
### Deployments
@@ -205,7 +205,7 @@ The two-person authorization workflow for writes through the MxAccess Gateway. B
### Transport (Bundle Import / Export)
- **ExportBundle**: Build an encrypted bundle (templates, system artifacts, central-only configuration). Gated to the `Design` role. Returns base64-encoded bundle bytes plus a byte count.
- **ExportBundle**: Build an encrypted bundle (templates, system artifacts, central-only configuration). Gated to any-of `Designer`/`Administrator`; when the resolved selection carries a stored secret (SMTP/SMS credentials, external-system auth, DB connection strings, data-connection configuration) the handler additionally requires `Administrator` and otherwise answers `ManagementUnauthorized` (code review 2026-12-02 MGT-3; see `Component-Transport.md` → Authorization). Returns base64-encoded bundle bytes plus a byte count.
- **PreviewBundle**: Unlock and inspect a previously uploaded bundle session, returning the per-entity preview (adds, modifies, identicals, blockers). Gated to the `Admin` role.
- **ImportBundle**: Apply a previewed bundle with per-conflict resolutions inside a single audit-correlated session. Gated to the `Admin` role.
+5 -1
View File
@@ -458,8 +458,12 @@ Exit codes follow the project convention: `0` = success, `1` = command failure (
| Operation | Required role | Enforced at |
|---|---|---|
| Open Export page / `bundle export` CLI | `RequireDesign` | Razor page authorize attribute + `ManagementActor.GetRequiredRole` |
| Open Export page | `RequireDesign` | Razor page authorize attribute |
| `bundle export` CLI | Designer **or** Administrator | `ManagementActor.GetRequiredRole` |
| Export of a **secret-bearing** selection (UI and CLI) | **Administrator** (in addition to the gate above) | `IBundleExporter.CountSecretsAsync` over the resolved closure, checked by the export page and the `ExportBundle` handler |
| `IBundleExporter.ExportAsync` | `RequireDesign` | Service entrypoint |
**Secret-bearing export needs Administrator (code review 2026-12-02 MGT-3).** A bundle carries every stored secret in its selection — SMTP credentials, the Twilio auth token, external-system auth configuration, database connection strings, data-connection protocol configuration — encrypted under a passphrase the exporter chooses, or in plaintext for an unencrypted export. Nothing else in the management API returns those values to anyone (SMTP/SMS replies are public-shape scrubbed and only an Administrator may write them), so a Designer could read them only through export. Both export surfaces therefore resolve the selection exactly as the export would (`IncludeDependencies` can pull an external system or DB connection into a template-only selection) and, when `ExportSecretPolicy.CountSecrets` is non-zero, require the Administrator role; the refusal names the secret count and suggests narrowing the selection. A secret-free export stays a Designer operation, and the management gate admits an Administrator as well (the frozen authz matrix entry is `ExportBundle = [Designer, Administrator]`).
| Open Import page / `bundle preview` + `bundle import` CLI | `RequireAdmin` | Razor page authorize attribute + `ManagementActor.GetRequiredRole` |
| `IBundleImporter.LoadAsync` / `PreviewAsync` / `ApplyAsync` | `RequireAdmin` | Service entrypoint |
| Configuration Audit Log "Bundle Import" filter | `RequireAdmin` or `Audit` | Existing audit page logic |
@@ -315,33 +315,7 @@ public partial class TransportExport : ComponentBase
/// </summary>
/// <param name="resolved">The resolved export closure whose secret fields are counted.</param>
/// <returns>The total number of non-empty secret fields across all external systems, SMTP configs, and database connections.</returns>
internal static int CountSecrets(ResolvedExport resolved)
{
var count = 0;
foreach (var es in resolved.ExternalSystems)
{
if (!string.IsNullOrEmpty(es.AuthConfiguration)) count++;
}
foreach (var smtp in resolved.SmtpConfigs)
{
if (!string.IsNullOrEmpty(smtp.Credentials)) count++;
}
// SMS provider AuthToken is a secret, mirroring SMTP Credentials above.
foreach (var sms in resolved.SmsConfigs)
{
if (!string.IsNullOrEmpty(sms.AuthToken)) count++;
}
foreach (var db in resolved.DatabaseConnections)
{
if (!string.IsNullOrEmpty(db.ConnectionString)) count++;
}
foreach (var dc in resolved.DataConnections)
{
if (!string.IsNullOrEmpty(dc.PrimaryConfiguration)) count++;
if (!string.IsNullOrEmpty(dc.BackupConfiguration)) count++;
}
return count;
}
internal static int CountSecrets(ResolvedExport resolved) => ExportSecretPolicy.CountSecrets(resolved);
private void BackToSelect() => _step = ExportWizardStep.Select;
private void BackToReview() => _step = ExportWizardStep.Review;
@@ -391,6 +365,25 @@ public partial class TransportExport : ComponentBase
}
var selection = BuildSelection();
// Code review 2026-12-02 MGT-3: a bundle carrying stored secrets (SMTP/SMS
// credentials, external-system auth, DB connection strings, data-connection
// configuration) needs Administrator — the same rule the management API applies.
// Re-counted from a fresh resolution, not the Review step's cached closure.
var secretCount = await BundleExporter.CountSecretsAsync(selection, CancellationToken.None);
if (secretCount > 0)
{
try
{
await Auth.RequireRoleAsync(ZB.MOM.WW.ScadaBridge.Security.Roles.Administrator);
}
catch (UnauthorizedAccessException)
{
throw new UnauthorizedAccessException(
$"This export carries {secretCount} stored secret(s) and requires the Administrator role. " +
"Go back and narrow the selection (or turn off dependencies) to export without secrets.");
}
}
await using var stream = await BundleExporter.ExportAsync(
selection, user, sourceEnv, passphrase, CancellationToken.None);
@@ -19,4 +19,16 @@ public interface IBundleExporter
string sourceEnvironment,
string? passphrase,
CancellationToken cancellationToken = default);
/// <summary>
/// Resolves <paramref name="selection"/> exactly as <see cref="ExportAsync"/> would
/// (dependencies included) and counts the stored secret fields the bundle would carry —
/// external-system auth, SMTP/SMS credentials, DB connection strings, data-connection
/// configuration. A non-zero count means the export needs the Administrator role
/// (code review 2026-12-02 MGT-3).
/// </summary>
/// <param name="selection">The export selection.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>The number of non-empty secret fields in the resolved export.</returns>
Task<int> CountSecretsAsync(ExportSelection selection, CancellationToken cancellationToken = default);
}
@@ -174,8 +174,8 @@ public class ManagementActor : ReceiveActor
// PipeTo wraps continuation exceptions; unwrap to find the real cause.
var cause = ex is AggregateException agg ? agg.Flatten().InnerException ?? ex : ex;
if (cause is SiteScopeViolationException scope)
return new ManagementUnauthorized(correlationId, scope.Message);
if (cause is SiteScopeViolationException or ManagementAuthorizationException)
return new ManagementUnauthorized(correlationId, cause.Message);
_logger.LogError(cause, "Management command {Command} failed (CorrelationId={CorrelationId})",
command.GetType().Name, correlationId);
@@ -236,6 +236,7 @@ public class ManagementActor : ReceiveActor
// Static readonly role sets for the authorization gate. Single-role arms
// stay one-element arrays so every arm has the uniform any-of shape.
private static readonly string[] AdminOnly = [Roles.Administrator];
private static readonly string[] BundleExporters = [Roles.Designer, Roles.Administrator];
private static readonly string[] DesignerOnly = [Roles.Designer];
private static readonly string[] DeployerOnly = [Roles.Deployer];
private static readonly string[] OperatorOnly = [Roles.Operator];
@@ -342,8 +343,15 @@ public class ManagementActor : ReceiveActor
// browse the address space, run a bounded search, and probe/verify an
// endpoint. Read-only against the live site server; gated Design to
// match the connection editor these back.
or BrowseNodeCommand or SearchAddressSpaceCommand or VerifyEndpointCommand
or ExportBundleCommand => DesignerOnly,
or BrowseNodeCommand or SearchAddressSpaceCommand or VerifyEndpointCommand => DesignerOnly,
// Bundle export (code review 2026-12-02 MGT-3): any-of [Designer, Administrator]
// at the gate. The handler then requires Administrator when the RESOLVED selection
// (dependencies included) carries a stored secret — SMTP/SMS credentials,
// external-system auth, DB connection strings, data-connection configuration —
// which no other management read returns to anyone. A secret-free export stays a
// Designer operation.
ExportBundleCommand => BundleExporters,
// Transport import operations (mirror the Central UI gating:
// Administrator for inbound bundle handling because they mutate
@@ -595,7 +603,7 @@ public class ManagementActor : ReceiveActor
ListSecuredWritesCommand cmd => await HandleListSecuredWrites(sp, cmd, user),
// Transport bundle operations
ExportBundleCommand cmd => await HandleExportBundle(sp, cmd, user.Username),
ExportBundleCommand cmd => await HandleExportBundle(sp, cmd, user),
PreviewBundleCommand cmd => await HandlePreviewBundle(sp, cmd, clientIp),
ImportBundleCommand cmd => await HandleImportBundle(sp, cmd, user.Username, clientIp),
@@ -2400,7 +2408,9 @@ public class ManagementActor : ReceiveActor
// was never saved. The after-state is the scrubbed public shape (MGT-4) — the raw
// entity carries the decrypted protocol configuration, credentials included.
await AuditAndSaveAsync(sp, user, "Move", "DataConnection", conn.Id.ToString(), conn.Name, DataConnectionPublicShape(conn));
return conn;
// MGT-4: reply with the scrubbed public shape like every sibling handler — the raw
// entity printed the stored credentials to the terminal and any CI log.
return DataConnectionPublicShape(conn);
}
@@ -4390,8 +4400,9 @@ public class ManagementActor : ReceiveActor
/// and returns the encrypted ZIP as base64.
/// </summary>
private static async Task<object?> HandleExportBundle(
IServiceProvider sp, ExportBundleCommand cmd, string username)
IServiceProvider sp, ExportBundleCommand cmd, AuthenticatedUser user)
{
var username = user.Username;
await TransportGate.WaitAsync();
try
{
@@ -4480,7 +4491,24 @@ public class ManagementActor : ReceiveActor
// the bundle preview row shows AccountSid, so the CLI uses AccountSid too.
SmsConfigurationIds: ResolveIds(smsConfigs, cmd.SmsConfigurationNames, s => s.AccountSid, s => s.Id, "SMS configuration"));
// Code review 2026-12-02 MGT-3: a bundle carries stored secrets the management API
// never returns to anyone, so a secret-bearing export needs Administrator. Judge the
// RESOLVED closure — IncludeDependencies can pull an external system or DB connection
// into a template-only selection.
var exporter = sp.GetRequiredService<IBundleExporter>();
if (!user.Roles.Contains(Roles.Administrator, StringComparer.OrdinalIgnoreCase))
{
var secretCount = await exporter.CountSecretsAsync(selection);
if (secretCount > 0)
{
throw new ManagementAuthorizationException(
$"This export carries {secretCount} stored secret(s) (external-system auth, SMTP/SMS " +
"credentials, database connection strings or data-connection configuration) and requires " +
"the Administrator role. Narrow the selection (or drop --include-dependencies) to export " +
"without secrets.");
}
}
await using var stream = await exporter.ExportAsync(
selection, user: username, sourceEnvironment: cmd.SourceEnvironment,
passphrase: cmd.Passphrase);
@@ -4831,6 +4859,19 @@ public class SiteScopeViolationException : Exception
public SiteScopeViolationException(string message) : base(message) { }
}
/// <summary>
/// Thrown by a handler when an authorization decision depends on the command's content and
/// so cannot be made at the role gate (e.g. a bundle export that turns out to carry stored
/// secrets — code review 2026-12-02 MGT-3). Mapped to <c>ManagementUnauthorized</c>; the
/// message is caller-safe.
/// </summary>
public class ManagementAuthorizationException : Exception
{
/// <summary>Initializes a new instance with the given caller-safe message.</summary>
/// <param name="message">The message describing the missing authority.</param>
public ManagementAuthorizationException(string message) : base(message) { }
}
/// <summary>
/// Thrown by a command handler to signal a curated, caller-safe failure. Its
/// <see cref="Exception.Message"/> is intended to be
@@ -64,6 +64,14 @@ public sealed class BundleExporter : IBundleExporter
_signer = signer;
}
/// <inheritdoc />
public async Task<int> CountSecretsAsync(ExportSelection selection, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(selection);
var resolved = await _resolver.ResolveAsync(selection, cancellationToken).ConfigureAwait(false);
return ExportSecretPolicy.CountSecrets(resolved);
}
/// <inheritdoc />
public async Task<Stream> ExportAsync(
ExportSelection selection,
@@ -0,0 +1,39 @@
namespace ZB.MOM.WW.ScadaBridge.Transport.Export;
/// <summary>
/// Which parts of a resolved export carry stored secrets, and therefore who may export
/// them (code review 2026-12-02 MGT-3). A bundle carries secrets in its
/// <c>SecretsBlock</c>s — encrypted under the exporter's passphrase, or in plaintext for an
/// unencrypted export — so whoever runs the export can read them. The management API never
/// returns these values to anyone (SMTP/SMS are <c>*PublicShape</c>-scrubbed and
/// Administrator-only to write), so exporting them requires the Administrator role on every
/// export surface (management API / CLI and the Central UI wizard). A secret-free export stays
/// available to a Designer.
/// </summary>
public static class ExportSecretPolicy
{
/// <summary>
/// Counts the non-empty secret fields the bundle would carry — the same fields the
/// serializer puts in a <c>SecretsBlock</c>: external-system auth configuration, SMTP
/// credentials, the SMS auth token, database connection strings and data-connection
/// protocol configuration (primary and backup).
/// </summary>
/// <param name="resolved">The resolved export closure (dependencies included).</param>
/// <returns>The number of non-empty secret fields.</returns>
public static int CountSecrets(ResolvedExport resolved)
{
ArgumentNullException.ThrowIfNull(resolved);
var count = 0;
count += resolved.ExternalSystems.Count(es => !string.IsNullOrEmpty(es.AuthConfiguration));
count += resolved.SmtpConfigs.Count(smtp => !string.IsNullOrEmpty(smtp.Credentials));
count += resolved.SmsConfigs.Count(sms => !string.IsNullOrEmpty(sms.AuthToken));
count += resolved.DatabaseConnections.Count(db => !string.IsNullOrEmpty(db.ConnectionString));
foreach (var dc in resolved.DataConnections)
{
if (!string.IsNullOrEmpty(dc.PrimaryConfiguration)) count++;
if (!string.IsNullOrEmpty(dc.BackupConfiguration)) count++;
}
return count;
}
}
@@ -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])));
}
}