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
@@ -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;
}
}