From 8c5d70f68790e91e52f917ffa9b49255dc7ce0be Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 10:04:28 -0500 Subject: [PATCH] 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. --- docs/requirements/Component-CentralUI.md | 2 +- .../Component-ManagementService.md | 4 +- docs/requirements/Component-Transport.md | 6 +- .../Pages/Design/TransportExport.razor.cs | 47 ++++---- .../Interfaces/Transport/IBundleExporter.cs | 12 ++ .../ManagementActor.cs | 55 +++++++-- .../Export/BundleExporter.cs | 8 ++ .../Export/ExportSecretPolicy.cs | 39 +++++++ .../Pages/Design/TransportExportPageTests.cs | 36 ++++++ .../ManagementActorTests.cs | 105 +++++++++++++++++- .../RequiredRoleMatrixTests.cs | 9 +- .../Export/ExportSecretPolicyTests.cs | 55 +++++++++ 12 files changed, 335 insertions(+), 43 deletions(-) create mode 100644 src/ZB.MOM.WW.ScadaBridge.Transport/Export/ExportSecretPolicy.cs create mode 100644 tests/ZB.MOM.WW.ScadaBridge.Transport.Tests/Export/ExportSecretPolicyTests.cs diff --git a/docs/requirements/Component-CentralUI.md b/docs/requirements/Component-CentralUI.md index 96eff1dc..f3fe895b 100644 --- a/docs/requirements/Component-CentralUI.md +++ b/docs/requirements/Component-CentralUI.md @@ -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 = ` 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) diff --git a/docs/requirements/Component-ManagementService.md b/docs/requirements/Component-ManagementService.md index 7fb8a9d4..97799cd5 100644 --- a/docs/requirements/Component-ManagementService.md +++ b/docs/requirements/Component-ManagementService.md @@ -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. diff --git a/docs/requirements/Component-Transport.md b/docs/requirements/Component-Transport.md index 06ce579b..6a52e102 100644 --- a/docs/requirements/Component-Transport.md +++ b/docs/requirements/Component-Transport.md @@ -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 | diff --git a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/TransportExport.razor.cs b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/TransportExport.razor.cs index 517543dc..86594a99 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/TransportExport.razor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Components/Pages/Design/TransportExport.razor.cs @@ -315,33 +315,7 @@ public partial class TransportExport : ComponentBase /// /// The resolved export closure whose secret fields are counted. /// The total number of non-empty secret fields across all external systems, SMTP configs, and database connections. - 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); diff --git a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Transport/IBundleExporter.cs b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Transport/IBundleExporter.cs index 3e5a884c..309b7cfe 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Transport/IBundleExporter.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Commons/Interfaces/Transport/IBundleExporter.cs @@ -19,4 +19,16 @@ public interface IBundleExporter string sourceEnvironment, string? passphrase, CancellationToken cancellationToken = default); + + /// + /// Resolves exactly as 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). + /// + /// The export selection. + /// Cancellation token. + /// The number of non-empty secret fields in the resolved export. + Task CountSecretsAsync(ExportSelection selection, CancellationToken cancellationToken = default); } diff --git a/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs b/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs index 1a396ed8..c3f31632 100644 --- a/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.ManagementService/ManagementActor.cs @@ -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. /// private static async Task 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(); + 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) { } } +/// +/// 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 ManagementUnauthorized; the +/// message is caller-safe. +/// +public class ManagementAuthorizationException : Exception +{ + /// Initializes a new instance with the given caller-safe message. + /// The message describing the missing authority. + public ManagementAuthorizationException(string message) : base(message) { } +} + /// /// Thrown by a command handler to signal a curated, caller-safe failure. Its /// is intended to be diff --git a/src/ZB.MOM.WW.ScadaBridge.Transport/Export/BundleExporter.cs b/src/ZB.MOM.WW.ScadaBridge.Transport/Export/BundleExporter.cs index 8a54e9f6..f2bc4ad9 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Transport/Export/BundleExporter.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Transport/Export/BundleExporter.cs @@ -64,6 +64,14 @@ public sealed class BundleExporter : IBundleExporter _signer = signer; } + /// + public async Task CountSecretsAsync(ExportSelection selection, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(selection); + var resolved = await _resolver.ResolveAsync(selection, cancellationToken).ConfigureAwait(false); + return ExportSecretPolicy.CountSecrets(resolved); + } + /// public async Task ExportAsync( ExportSelection selection, diff --git a/src/ZB.MOM.WW.ScadaBridge.Transport/Export/ExportSecretPolicy.cs b/src/ZB.MOM.WW.ScadaBridge.Transport/Export/ExportSecretPolicy.cs new file mode 100644 index 00000000..694c1e81 --- /dev/null +++ b/src/ZB.MOM.WW.ScadaBridge.Transport/Export/ExportSecretPolicy.cs @@ -0,0 +1,39 @@ +namespace ZB.MOM.WW.ScadaBridge.Transport.Export; + +/// +/// 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 +/// SecretsBlocks — 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 *PublicShape-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. +/// +public static class ExportSecretPolicy +{ + /// + /// Counts the non-empty secret fields the bundle would carry — the same fields the + /// serializer puts in a SecretsBlock: external-system auth configuration, SMTP + /// credentials, the SMS auth token, database connection strings and data-connection + /// protocol configuration (primary and backup). + /// + /// The resolved export closure (dependencies included). + /// The number of non-empty secret fields. + 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; + } +} diff --git a/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Pages/Design/TransportExportPageTests.cs b/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Pages/Design/TransportExportPageTests.cs index f83b95ea..d6b7333f 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Pages/Design/TransportExportPageTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Pages/Design/TransportExportPageTests.cs @@ -328,6 +328,42 @@ public class TransportExportPageTests : BunitContext Arg.Any()); } + // ───────────────────────────────────────────────────────────────────── + // Code review 2026-12-02 MGT-3: a Designer-only user cannot export a selection + // whose resolved closure carries stored secrets; nothing is exported. + // ───────────────────────────────────────────────────────────────────── + /// Verifies that a Designer without Administrator cannot export a secret-bearing selection. + /// A task that represents the asynchronous operation. + [Fact] + public async Task Step4_SecretBearingSelection_RequiresAdministrator() + { + var template = new Template("Pump") { Id = 1 }; + _templateRepo.GetTemplateStubsAsync(Arg.Any()) + .Returns(Task.FromResult>( + (new List