Compare commits

...

8 Commits

Author SHA1 Message Date
Joseph Doherty 128f159692 feat(secrets): resolve MxGateway ApiKey secret: refs at connect time (ScadaBridge G-3 T9) 2026-07-16 15:37:01 -04:00
Joseph Doherty 56b428d2ef docs(secrets): clustered master-key posture runbook + Central pointer (ScadaBridge G-5 T8) 2026-07-16 15:21:54 -04:00
Joseph Doherty 41e17d2ff8 feat(secrets): mount /admin/secrets + register secrets authz in CentralUI (ScadaBridge G-6 T7) 2026-07-16 15:09:34 -04:00
Joseph Doherty fbb3867cb3 chore(secrets): remove committed dev plaintext from docker central nodes + loose login files (ScadaBridge G-4 T5) 2026-07-16 14:55:31 -04:00
Joseph Doherty cf715b813b feat(secrets): switch Central config secrets to ${secret:} tokens (ScadaBridge G-4 T4)
Switch the three literal ${SCADABRIDGE_*} placeholders in appsettings.Central.json
to ${secret:} references resolved by the pre-host secrets expander, and update the
_secrets doc note. Fix Host.Tests fixtures that boot the real Program pipeline against
Central config: CentralDbTestEnvironment now also supplies the LDAP service-account
password and JWT signing key as whole-key env overrides (rollback path) so the expander
skips the tokens without a seeded store; the three fixtures that managed env vars
inline now use CentralDbTestEnvironment.
2026-07-16 14:42:28 -04:00
Joseph Doherty abc9c96af0 feat(secrets): register runtime AddZbSecrets on Central + Site roles (ScadaBridge T3) 2026-07-16 14:26:16 -04:00
Joseph Doherty ae62e650e9 feat(secrets): pre-host ${secret:} config expander (ScadaBridge G-4 T2) 2026-07-16 14:13:53 -04:00
Joseph Doherty 481d6d7265 build(secrets): add ZB.MOM.WW.Secrets 0.1.2 package refs (ScadaBridge G-3/4/5/6 T1) 2026-07-16 14:09:44 -04:00
24 changed files with 577 additions and 56 deletions
+3
View File
@@ -86,6 +86,9 @@
<PackageVersion Include="ZB.MOM.WW.Auth.AspNetCore" Version="0.1.3" />
<PackageVersion Include="ZB.MOM.WW.Audit" Version="0.1.0" />
<PackageVersion Include="ZB.MOM.WW.Theme" Version="0.3.1" />
<PackageVersion Include="ZB.MOM.WW.Secrets" Version="0.1.2" />
<PackageVersion Include="ZB.MOM.WW.Secrets.Abstractions" Version="0.1.2" />
<PackageVersion Include="ZB.MOM.WW.Secrets.Ui" Version="0.1.2" />
</ItemGroup>
<!--
@@ -18,8 +18,7 @@
"MinNrOfMembers": 1
},
"Database": {
"ConfigurationDb": "Server=scadabridge-mssql,1433;Database=ScadaBridgeConfig;User Id=scadabridge_app;Password=ScadaBridge_Dev1#;TrustServerCertificate=true",
"MachineDataDb": "Server=scadabridge-mssql,1433;Database=ScadaBridgeMachineData;User Id=scadabridge_app;Password=ScadaBridge_Dev1#;TrustServerCertificate=true"
"_comment": "ConfigurationDb/MachineDataDb (which carry the dev SQL password) are supplied as ScadaBridge__Database__* whole-key env overrides in docker/docker-compose.yml (dev-only-insecure, mirroring the ApiKeyPepper convention). The same dev password already ships committed for the sibling scadabridge-mssql container (infra/docker-compose.yml MSSQL_SA_PASSWORD) — this is consolidation, not new exposure. Env overrides layer over JSON before the ${secret:} expander runs, so the dev cluster boots with no KEK/secret store. Real/prod config uses ${secret:} tokens in src/.../appsettings.Central.json (T4)."
},
"Security": {
"Ldap": {
@@ -29,13 +28,13 @@
"AllowInsecure": true,
"SearchBase": "dc=zb,dc=local",
"ServiceAccountDn": "cn=serviceaccount,dc=zb,dc=local",
"ServiceAccountPassword": "serviceaccount123"
"_comment_ServiceAccountPassword": "Supplied as ScadaBridge__Security__Ldap__ServiceAccountPassword env override in docker-compose.yml (dev-only-insecure)."
},
"Auth": {
"DisableLogin": false,
"User": "multi-role"
},
"JwtSigningKey": "scadabridge-dev-jwt-signing-key-must-be-at-least-32-characters-long",
"_comment_JwtSigningKey": "Supplied as ScadaBridge__Security__JwtSigningKey env override in docker-compose.yml (dev-only-insecure).",
"JwtExpiryMinutes": 15,
"IdleTimeoutMinutes": 30,
"RequireHttpsCookie": false,
@@ -18,8 +18,7 @@
"MinNrOfMembers": 1
},
"Database": {
"ConfigurationDb": "Server=scadabridge-mssql,1433;Database=ScadaBridgeConfig;User Id=scadabridge_app;Password=ScadaBridge_Dev1#;TrustServerCertificate=true",
"MachineDataDb": "Server=scadabridge-mssql,1433;Database=ScadaBridgeMachineData;User Id=scadabridge_app;Password=ScadaBridge_Dev1#;TrustServerCertificate=true"
"_comment": "ConfigurationDb/MachineDataDb (which carry the dev SQL password) are supplied as ScadaBridge__Database__* whole-key env overrides in docker/docker-compose.yml (dev-only-insecure, mirroring the ApiKeyPepper convention). The same dev password already ships committed for the sibling scadabridge-mssql container (infra/docker-compose.yml MSSQL_SA_PASSWORD) — this is consolidation, not new exposure. Env overrides layer over JSON before the ${secret:} expander runs, so the dev cluster boots with no KEK/secret store. Real/prod config uses ${secret:} tokens in src/.../appsettings.Central.json (T4)."
},
"Security": {
"Ldap": {
@@ -29,13 +28,13 @@
"AllowInsecure": true,
"SearchBase": "dc=zb,dc=local",
"ServiceAccountDn": "cn=serviceaccount,dc=zb,dc=local",
"ServiceAccountPassword": "serviceaccount123"
"_comment_ServiceAccountPassword": "Supplied as ScadaBridge__Security__Ldap__ServiceAccountPassword env override in docker-compose.yml (dev-only-insecure)."
},
"Auth": {
"DisableLogin": false,
"User": "multi-role"
},
"JwtSigningKey": "scadabridge-dev-jwt-signing-key-must-be-at-least-32-characters-long",
"_comment_JwtSigningKey": "Supplied as ScadaBridge__Security__JwtSigningKey env override in docker-compose.yml (dev-only-insecure).",
"JwtExpiryMinutes": 15,
"IdleTimeoutMinutes": 30,
"RequireHttpsCookie": false,
+22
View File
@@ -16,6 +16,17 @@ services:
# out-of-band (env/secret store), never from source control — see
# docs/operations/inbound-api-key-reissue.md. Both Central nodes share one pepper.
ScadaBridge__InboundApi__ApiKeyPepper: "dev-only-insecure-pepper-docker-cluster-0001"
# DEV-ONLY local-cluster secrets — NOT real secrets. Relocated out of the mounted
# appsettings.Central.json (G-4 T5 secrets cleanup) so that app-config file carries no
# plaintext credentials. Env overrides layer over JSON BEFORE the ${secret:} pre-host
# expander runs, so the dev cluster boots with no KEK/secret store. The SQL password is
# the same value already committed for the sibling scadabridge-mssql container
# (infra/docker-compose.yml MSSQL_SA_PASSWORD) — consolidation, not new exposure. Real
# deployments use ${secret:} tokens (src/.../appsettings.Central.json) + a seeded store.
ScadaBridge__Database__ConfigurationDb: "Server=scadabridge-mssql,1433;Database=ScadaBridgeConfig;User Id=scadabridge_app;Password=ScadaBridge_Dev1#;TrustServerCertificate=true"
ScadaBridge__Database__MachineDataDb: "Server=scadabridge-mssql,1433;Database=ScadaBridgeMachineData;User Id=scadabridge_app;Password=ScadaBridge_Dev1#;TrustServerCertificate=true"
ScadaBridge__Security__Ldap__ServiceAccountPassword: "serviceaccount123"
ScadaBridge__Security__JwtSigningKey: "scadabridge-dev-jwt-signing-key-must-be-at-least-32-characters-long"
ports:
- "9001:5000" # Web UI + Inbound API
- "9011:8081" # Akka remoting (host access for CLI/debugging)
@@ -43,6 +54,17 @@ services:
# out-of-band (env/secret store), never from source control — see
# docs/operations/inbound-api-key-reissue.md. Both Central nodes share one pepper.
ScadaBridge__InboundApi__ApiKeyPepper: "dev-only-insecure-pepper-docker-cluster-0001"
# DEV-ONLY local-cluster secrets — NOT real secrets. Relocated out of the mounted
# appsettings.Central.json (G-4 T5 secrets cleanup) so that app-config file carries no
# plaintext credentials. Env overrides layer over JSON BEFORE the ${secret:} pre-host
# expander runs, so the dev cluster boots with no KEK/secret store. The SQL password is
# the same value already committed for the sibling scadabridge-mssql container
# (infra/docker-compose.yml MSSQL_SA_PASSWORD) — consolidation, not new exposure. Real
# deployments use ${secret:} tokens (src/.../appsettings.Central.json) + a seeded store.
ScadaBridge__Database__ConfigurationDb: "Server=scadabridge-mssql,1433;Database=ScadaBridgeConfig;User Id=scadabridge_app;Password=ScadaBridge_Dev1#;TrustServerCertificate=true"
ScadaBridge__Database__MachineDataDb: "Server=scadabridge-mssql,1433;Database=ScadaBridgeMachineData;User Id=scadabridge_app;Password=ScadaBridge_Dev1#;TrustServerCertificate=true"
ScadaBridge__Security__Ldap__ServiceAccountPassword: "serviceaccount123"
ScadaBridge__Security__JwtSigningKey: "scadabridge-dev-jwt-signing-key-must-be-at-least-32-characters-long"
ports:
- "9002:5000" # Web UI + Inbound API
- "9012:8081" # Akka remoting
@@ -0,0 +1,156 @@
# Secrets: Clustered Master-Key Posture (Central Pair)
## Purpose
`ZB.MOM.WW.Secrets` resolves `${secret:...}` tokens in `appsettings.*.json` via a
pre-host expander that runs at every Central-role boot, before `StartupValidator`
(Host-003). It reads rows from an envelope-encrypted SQLite store
(`Secrets:SqlitePath`) unwrapped with a key-encryption key (KEK) sourced per
`Secrets:MasterKey:Source`.
ScadaBridge's central role is an Akka.NET-clustered **pair** (`central-a` /
`central-b`, see [failover-procedures.md](./failover-procedures.md)) — either node
can be active, and both boot independently. This runbook covers what a production
deployment of the central pair (and any site node that is ever given a `${secret:}`
token) needs so that secret resolution behaves identically no matter which node is
running. It does **not** change any code; it is an operations/deployment posture,
delivered out-of-band from the committed config.
## The two hard requirements
For the pre-host expander to resolve the same plaintext secret on every node:
1. **Identical KEK on every node.** All central nodes must unwrap the store with
the exact same master key. A per-node KEK (e.g. two different DPAPI-protected
keys, one per Windows box) would make each node decrypt the *other* node's
ciphertext rows to garbage.
2. **Identical store rows on every node.** All central nodes must read the same
SQLite database (same file, or a replicated/shared copy with the same rows) —
not two independently-seeded stores that happen to use the same KEK.
`ZB.MOM.WW.Secrets` ships a SQLite-only `ISecretStore` with a `NoOpSecretReplicator`
— there is no built-in cross-node replication today. Meeting both requirements in
production is a deployment concern, covered below.
## Recommended interim posture (G-5)
Until real replication exists (G-7, below), the recommended production posture is:
- **`Secrets:MasterKey:Source = File`**, with `FilePath` pointing at a **read-only
key file that is identical on every central node** — a base64-encoded 32-byte
key, generated out-of-band (e.g. `openssl rand -base64 32`), distributed to each
node's filesystem/secret-mount by the deployment tooling, and **never committed**
to the repo. Treat it with the same discipline as any other production secret
(restrictive file ACLs, no logging, rotated via the KEK-rotation runbook — G-8,
not yet built).
- **`Secrets:SqlitePath`** pointing at a **single shared or replicated volume**
that both central nodes mount, so every node's `SqliteSecretsStoreMigrator` opens
and reads the same rows.
Writes to the store are rare and human-driven — an operator using the
`/admin/secrets` UI (G-6) or the `ZB.MOM.WW.Secrets` CLI on one node — while reads
happen on every boot and on the `ResolveCacheTtl` refresh cycle on both nodes. The
access pattern is read-mostly / effectively single-writer, which is what makes a
shared SQLite volume viable as an interim posture (see caveat below).
## How it's delivered (do NOT commit these values)
The File-KEK + shared-store posture is supplied per-node at deployment time —
**never** by editing the committed `appsettings.json` or
`appsettings.Central.json`. Two acceptable delivery mechanisms:
**Option A — environment variable overrides** (Windows Service / NSSM env block,
container `env_file`, etc.), applied identically on `central-a` and `central-b`:
```
# production deployment — do not commit to the dev appsettings
Secrets__MasterKey__Source=File
Secrets__MasterKey__FilePath=/run/secrets/scadabridge-master.key
Secrets__SqlitePath=/shared/secrets/scadabridge-secrets.db
```
**Option B — a production-only config layer** that is *not* the committed dev
base (e.g. an untracked `appsettings.Production.json` deployed alongside the
binaries, or an orchestrator-injected config mount):
```jsonc
// production deployment — do not commit to the dev appsettings
{
"Secrets": {
"MasterKey": {
"Source": "File",
"FilePath": "/run/secrets/scadabridge-master.key"
},
"SqlitePath": "/shared/secrets/scadabridge-secrets.db"
}
}
```
Either way, the file/path referenced must exist and be identical on every central
node **before** that node boots — the expander runs unconditionally and will throw
(`SecretNotFoundException` / migration failure) if the store or key is missing.
## Caveat: SQLite over a shared volume is not real replication
SQLite's file-locking model does not tolerate concurrent multi-writer access well
over network filesystems (SMB/NFS locking is unreliable, and even on a clustered
block volume only one writer should be active at a time). The interim posture
above is acceptable because:
- Reads dominate (every boot + cache-refresh cycle on both nodes).
- Writes are rare, human-initiated, and effectively single-writer in practice
(an operator runs the CLI/UI against one node at a time).
It is **not** a substitute for real replication, and it is not safe if both nodes
attempt concurrent writes. Do not build automation that writes secrets from both
central nodes simultaneously.
## Data Protection is independent — do not touch it here
ScadaBridge's cookie/session and hub-token protection already has its own
clustered-key story: `AddDataProtection().PersistKeysToDbContext<ScadaBridgeDbContext>()`
(see `docs/components/Security.md`), which shares the Data Protection key ring
across both central nodes via the existing MS SQL `ConfigurationDb`. That mechanism
is unrelated to `ZB.MOM.WW.Secrets`' envelope encryption (KEK + SQLite store) and
must **not** be reconfigured as part of secrets-adoption work — doing so risks
invalidating active sessions/cookies for an unrelated reason.
## The G-7 hand-off
The posture above is an interim, ops-only workaround. The long-term shape,
tracked as **G-7** in `scadaproj/components/secrets/GAPS.md`, is one of:
- A ConfigDb-backed `ISecretStore` — mirroring the pattern ScadaBridge already
uses for the Data Protection key ring (`PersistKeysToDbContext`), giving both
central nodes a single MS SQL-backed source of truth for secret rows instead of
a shared SQLite file; or
- The `ZB.MOM.WW.Secrets.Akka` replicator (LWW + anti-entropy resync +
tombstones) referenced in the library's SPEC.
Both require new library code that does not exist yet. This runbook's posture is
the bridge until one of those lands.
## Dev/test/default posture (unchanged)
The committed default in `appsettings.json` is:
```json
"Secrets": {
"SqlitePath": "scadabridge-secrets.db",
"MasterKey": { "Source": "Environment", "EnvVarName": "ZB_SECRETS_MASTER_KEY" },
"RunMigrationsOnStartup": true,
"ResolveCacheTtl": "00:00:30"
}
```
This is dev-safe: `Source=Environment` needs no filesystem key, and the SQLite
path is relative to the working directory, so local dev and the
`WebApplicationFactory<Program>` `Host.Tests` boot cleanly with no external mount.
Local dev and docker-compose environments supply concrete secret values via the
**whole-key environment override** (e.g. `ScadaBridge__Database__ConfigurationDb`),
which bypasses `${secret:...}` resolution entirely, so the expander is effectively
a no-op there. The File-KEK + shared-volume posture in this runbook applies only
to real clustered production deployments of the central pair — it must never be
baked into the committed dev base, because the expander runs unconditionally at
every Central boot and would break dev/CI if pointed at a nonexistent `/shared`
mount.
+2
View File
@@ -25,6 +25,8 @@
<package pattern="ZB.MOM.WW.Auth.*" />
<package pattern="ZB.MOM.WW.Audit" />
<package pattern="ZB.MOM.WW.Theme" />
<package pattern="ZB.MOM.WW.Secrets" />
<package pattern="ZB.MOM.WW.Secrets.*" />
</packageSource>
</packageSourceMapping>
<!--
@@ -18,6 +18,7 @@
<NavRailItem Href="/admin/ldap-mappings" Text="LDAP Mappings" />
<NavRailItem Href="/admin/sites" Text="Sites" />
<NavRailItem Href="/admin/api-keys" Text="API Keys" />
<NavRailItem Href="/admin/secrets" Text="Secrets" />
@* Import Bundle requires Administrator only — Designer role is not sufficient.
Export Bundle lives in the Design section (RequireDesign). *@
<NavRailItem Href="/design/transport/import" Text="Import Bundle" />
@@ -25,7 +25,9 @@ public static class EndpointExtensions
endpoints.MapRazorComponents<TApp>()
.AddInteractiveServerRenderMode()
.AddAdditionalAssemblies(typeof(MainLayout).Assembly);
.AddAdditionalAssemblies(
typeof(MainLayout).Assembly,
typeof(ZB.MOM.WW.Secrets.Ui.SecretsPage).Assembly);
return endpoints;
}
@@ -19,6 +19,7 @@
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Scripting" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" />
<PackageReference Include="ZB.MOM.WW.Theme" />
<PackageReference Include="ZB.MOM.WW.Secrets.Ui" />
</ItemGroup>
<ItemGroup>
@@ -3,6 +3,7 @@ using Microsoft.Extensions.Logging;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Protocol;
using ZB.MOM.WW.ScadaBridge.Commons.Serialization;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
using ZB.MOM.WW.Secrets.Abstractions;
namespace ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Adapters;
@@ -24,6 +25,7 @@ public class MxGatewayDataConnection : IDataConnection, IBrowsableDataConnection
{
private readonly IMxGatewayClientFactory _clientFactory;
private readonly ILogger<MxGatewayDataConnection> _logger;
private readonly ISecretResolver? _secretResolver;
private IMxGatewayClient? _client;
private ConnectionHealth _status = ConnectionHealth.Disconnected;
private CancellationTokenSource? _eventLoopCts;
@@ -51,10 +53,19 @@ public class MxGatewayDataConnection : IDataConnection, IBrowsableDataConnection
/// <summary>Initializes a new instance of <see cref="MxGatewayDataConnection"/>.</summary>
/// <param name="clientFactory">Factory used to create gateway client instances.</param>
/// <param name="logger">Logger instance.</param>
public MxGatewayDataConnection(IMxGatewayClientFactory clientFactory, ILogger<MxGatewayDataConnection> logger)
/// <param name="secretResolver">
/// Optional secret resolver used to resolve a <c>secret:&lt;name&gt;</c> ApiKey reference at
/// connect time. When null, a literal ApiKey still works, but a <c>secret:</c> reference
/// fails closed (a connection is never established with an unresolved key).
/// </param>
public MxGatewayDataConnection(
IMxGatewayClientFactory clientFactory,
ILogger<MxGatewayDataConnection> logger,
ISecretResolver? secretResolver = null)
{
_clientFactory = clientFactory;
_logger = logger;
_secretResolver = secretResolver;
}
/// <inheritdoc />
@@ -68,6 +79,25 @@ public class MxGatewayDataConnection : IDataConnection, IBrowsableDataConnection
{
var cfg = MxGatewayEndpointConfigSerializer.FromFlatDict(connectionDetails);
// Resolve a `secret:<name>` ApiKey reference BEFORE any teardown/client creation
// so a fail-closed throw here leaves adapter state untouched (no half-open client,
// previous connection — if any — still intact for a later retry). A literal key
// (no `secret:` prefix) passes through unchanged for back-compat.
var apiKey = cfg.ApiKey;
if (!string.IsNullOrEmpty(apiKey) &&
apiKey.StartsWith("secret:", StringComparison.OrdinalIgnoreCase))
{
if (_secretResolver is null)
{
throw new InvalidOperationException(
"MxGateway ApiKey uses a 'secret:' reference but no ISecretResolver is available to resolve it.");
}
var secretName = apiKey["secret:".Length..];
apiKey = await _secretResolver.GetAsync(new SecretName(secretName), cancellationToken)
?? throw new InvalidOperationException(
$"MxGateway ApiKey secret '{secretName}' could not be resolved (not found or tombstoned).");
}
// Reconnect reuses this adapter: cancel the previous event loop and dispose
// the previous client so a flapping gateway cannot accumulate orphaned
// streams/sockets, and the old loop's fault path cannot signal Disconnected
@@ -93,7 +123,7 @@ public class MxGatewayDataConnection : IDataConnection, IBrowsableDataConnection
await _client.ConnectAsync(new MxGatewayConnectionOptions(
cfg.Endpoint,
cfg.ApiKey,
apiKey,
string.IsNullOrWhiteSpace(cfg.ClientName) ? "scadabridge" : cfg.ClientName,
cfg.WriteUserId,
cfg.UseTls,
@@ -2,6 +2,7 @@ using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Protocol;
using ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Adapters;
using ZB.MOM.WW.Secrets.Abstractions;
namespace ZB.MOM.WW.ScadaBridge.DataConnectionLayer;
@@ -13,6 +14,7 @@ public class DataConnectionFactory : IDataConnectionFactory
{
private readonly Dictionary<string, Func<IDictionary<string, string>, IDataConnection>> _factories = new(StringComparer.OrdinalIgnoreCase);
private readonly ILoggerFactory _loggerFactory;
private readonly ISecretResolver? _secretResolver;
/// <summary>
/// Initializes a new <see cref="DataConnectionFactory"/> with default OPC UA global options.
@@ -26,9 +28,19 @@ public class DataConnectionFactory : IDataConnectionFactory
/// </summary>
/// <param name="loggerFactory">Logger factory used when creating protocol adapters.</param>
/// <param name="opcUaGlobalOptions">Global OPC UA options applied to all OPC UA connections created by this factory.</param>
public DataConnectionFactory(ILoggerFactory loggerFactory, IOptions<OpcUaGlobalOptions> opcUaGlobalOptions)
/// <param name="secretResolver">
/// Optional secret resolver threaded into the MxGateway adapter so a per-endpoint
/// <c>secret:&lt;name&gt;</c> ApiKey reference is resolved at connect time. DI supplies it on
/// the Site container (where <see cref="ISecretResolver"/> is registered); direct
/// construction without it keeps literal-key behaviour.
/// </param>
public DataConnectionFactory(
ILoggerFactory loggerFactory,
IOptions<OpcUaGlobalOptions> opcUaGlobalOptions,
ISecretResolver? secretResolver = null)
{
_loggerFactory = loggerFactory;
_secretResolver = secretResolver;
var globalOptions = opcUaGlobalOptions.Value;
// Register built-in protocols.
@@ -44,7 +56,8 @@ public class DataConnectionFactory : IDataConnectionFactory
// flat details dict (see MxGatewayEndpointConfigSerializer).
RegisterAdapter("MxGateway", details => new MxGatewayDataConnection(
new RealMxGatewayClientFactory(_loggerFactory),
_loggerFactory.CreateLogger<MxGatewayDataConnection>()));
_loggerFactory.CreateLogger<MxGatewayDataConnection>(),
_secretResolver));
}
/// <summary>
@@ -17,6 +17,7 @@
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" />
<PackageReference Include="OPCFoundation.NetStandard.Opc.Ua.Client" />
<PackageReference Include="ZB.MOM.WW.MxGateway.Client" />
<PackageReference Include="ZB.MOM.WW.Secrets.Abstractions" />
<PackageReference Include="ZB.MOM.WW.Configuration" />
</ItemGroup>
@@ -1,6 +1,6 @@
<CascadingAuthenticationState>
<Router AppAssembly="typeof(Routes).Assembly"
AdditionalAssemblies="new[] { typeof(ZB.MOM.WW.ScadaBridge.CentralUI.Components.Layout.MainLayout).Assembly }">
AdditionalAssemblies="new[] { typeof(ZB.MOM.WW.ScadaBridge.CentralUI.Components.Layout.MainLayout).Assembly, typeof(ZB.MOM.WW.Secrets.Ui.SecretsPage).Assembly }">
<Found Context="routeData">
<AuthorizeRouteView RouteData="routeData" DefaultLayout="typeof(ZB.MOM.WW.ScadaBridge.CentralUI.Components.Layout.MainLayout)">
<NotAuthorized>
+30
View File
@@ -1,3 +1,5 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.Auth.ApiKeys.DependencyInjection;
@@ -26,6 +28,11 @@ using ZB.MOM.WW.ScadaBridge.Security;
using ZB.MOM.WW.ScadaBridge.SiteCallAudit;
using ZB.MOM.WW.ScadaBridge.TemplateEngine;
using ZB.MOM.WW.ScadaBridge.Transport;
using ZB.MOM.WW.Secrets.Abstractions;
using ZB.MOM.WW.Secrets.Configuration;
using ZB.MOM.WW.Secrets.DependencyInjection;
using ZB.MOM.WW.Secrets.Sqlite;
using ZB.MOM.WW.Secrets.Ui;
using ZB.MOM.WW.Telemetry;
using Serilog;
@@ -42,6 +49,20 @@ var configuration = new ConfigurationBuilder()
.AddCommandLine(args)
.Build();
// Expand ${secret:...} config references before any validator/binder sees them (Layer A).
// Throwaway provider — disposed here, shares no singletons with the host container.
#pragma warning disable ASP0000 // deliberate throwaway container
await using (var secretsProvider = new ServiceCollection()
.AddZbSecrets(configuration, "Secrets")
.BuildServiceProvider())
#pragma warning restore ASP0000
{
await secretsProvider.GetRequiredService<SqliteSecretsStoreMigrator>().MigrateAsync(default);
var resolver = secretsProvider.GetRequiredService<ISecretResolver>();
await new SecretReferenceExpander(resolver)
.ExpandConfigurationAsync(configuration, default);
}
// Full startup validation — fail fast before any DI or actor system setup
StartupValidator.Validate(configuration);
@@ -158,6 +179,15 @@ try
.GetValue<bool>(nameof(ZB.MOM.WW.ScadaBridge.Security.Auth.AuthDisableLoginOptions.AllowOutsideDevelopment)));
builder.Services.AddSecurity(disableLogin);
builder.Services.AddCentralUI();
builder.Services.AddZbSecrets(builder.Configuration, "Secrets");
// Secrets UI authorization: adds the named policies secrets:manage + secrets:reveal
// (role-based) consumed by the /admin/secrets page. AddSecretsAuthorization only ADDS
// these two policies via Configure<AuthorizationOptions> — it composes additively with
// AddScadaBridgeAuthorization (invoked inside AddSecurity above) without clobbering.
// The library's AdminRole ("Administrator") satisfies both policies, and ScadaBridge
// builds identities with RoleClaimType = ZbClaimTypes.Role, so an Administrator is
// authorized for both manage + reveal. Done Host-side to keep Secrets.Ui out of Security.
builder.Services.Configure<AuthorizationOptions>(o => o.AddSecretsAuthorization());
builder.Services.AddInboundAPI();
// Inbound-API auth re-arch: the shared ZB.MOM.WW.Auth.ApiKeys verifier +
@@ -14,6 +14,7 @@ using ZB.MOM.WW.ScadaBridge.NotificationService;
using ZB.MOM.WW.ScadaBridge.SiteEventLogging;
using ZB.MOM.WW.ScadaBridge.SiteRuntime;
using ZB.MOM.WW.ScadaBridge.StoreAndForward;
using ZB.MOM.WW.Secrets.DependencyInjection;
using ZB.MOM.WW.Telemetry;
namespace ZB.MOM.WW.ScadaBridge.Host;
@@ -49,6 +50,7 @@ public static class SiteServiceRegistration
var siteDbPath = config["ScadaBridge:Database:SiteDbPath"] ?? "site.db";
services.AddSiteRuntime($"Data Source={siteDbPath}");
services.AddDataConnectionLayer();
services.AddZbSecrets(config, "Secrets");
// Adapter that surfaces the site id to
// StoreAndForwardService through DI WITHOUT introducing a
// StoreAndForward → HealthMonitoring project-reference cycle. Must be
@@ -37,6 +37,9 @@
<!-- Host/App.razor uses the kit's <ThemeHead/>/<ThemeScripts/> directly; declare the
dependency here rather than leaning on CentralUI re-exporting it transitively. -->
<PackageReference Include="ZB.MOM.WW.Theme" />
<PackageReference Include="ZB.MOM.WW.Secrets" />
<PackageReference Include="ZB.MOM.WW.Secrets.Abstractions" />
<PackageReference Include="ZB.MOM.WW.Secrets.Ui" />
</ItemGroup>
<ItemGroup>
@@ -1,5 +1,6 @@
{
"ScadaBridge": {
"_secretsClusterPosture": "Central pair KEK/store posture (production): see docs/operations/2026-07-16-secrets-clustered-master-key.md. Committed default is Source=Environment + relative SqlitePath (dev-safe); production uses a File KEK + shared store volume delivered out-of-band. Do NOT hardcode /shared paths here — the pre-host expander migrates the store at every Central boot and would break dev/test.",
"_nodeName": "Host-018: NodeName stamps SourceNode on AuditLog/Notifications/SiteCalls rows (CLAUDE.md 'Centralized Audit Log' decision) and backs IX_AuditLog_Node_Occurred. Convention: 'central-a'/'central-b' for central nodes, 'node-a'/'node-b' for site nodes. Override per-node in multi-node deployments (the docker per-node configs do this). When left at the default below, single-node dev rows are stamped with 'central-a'; an empty value normalises to a NULL SourceNode.",
"Node": {
"Role": "Central",
@@ -18,9 +19,9 @@
"FailureDetectionThreshold": "00:00:10",
"MinNrOfMembers": 1
},
"_secrets": "Host-003: Secrets are NOT committed in this file. Supply them via environment variables, which the Host's configuration builder (AddEnvironmentVariables) overlays over this file. Required: ScadaBridge__Database__ConfigurationDb, ScadaBridge__Security__Ldap__ServiceAccountPassword, ScadaBridge__Security__JwtSigningKey. The ${...} placeholders below are intentionally non-functional and must be overridden per environment. NOTE (Task 1.4): the LDAP settings moved into the nested Security:Ldap sub-section (bound to the shared ZB.MOM.WW.Auth LdapOptions) — the service-account-password env var is now ScadaBridge__Security__Ldap__ServiceAccountPassword (was ScadaBridge__Security__LdapServiceAccountPassword).",
"_secrets": "Host-003: Secrets are NOT committed in this file. The ${secret:...} references below are resolved at startup by the pre-host secrets expander (before StartupValidator runs) from the encrypted secrets store (SQLite, seeded via the ZB.MOM.WW.Secrets store/CLI/UI). The KEK is supplied out-of-band via the ZB_SECRETS_MASTER_KEY environment variable and never committed; an unseeded reference fails closed (SecretNotFoundException) before any SQL/LDAP/cluster wiring. ROLLBACK: the whole-key environment override still wins — set ScadaBridge__Database__ConfigurationDb / ScadaBridge__Security__Ldap__ServiceAccountPassword / ScadaBridge__Security__JwtSigningKey and .AddEnvironmentVariables() overlays the concrete value before expansion runs, so the ${secret:...} token is never evaluated. NOTE (Task 1.4): the LDAP settings moved into the nested Security:Ldap sub-section (bound to the shared ZB.MOM.WW.Auth LdapOptions) — the service-account-password env var is ScadaBridge__Security__Ldap__ServiceAccountPassword (was ScadaBridge__Security__LdapServiceAccountPassword).",
"Database": {
"ConfigurationDb": "${SCADABRIDGE_CONFIGURATIONDB_CONNECTION_STRING}"
"ConfigurationDb": "${secret:sql/scadabridge/configdb-connection}"
},
"Security": {
"Ldap": {
@@ -30,9 +31,9 @@
"AllowInsecure": true,
"SearchBase": "dc=zb,dc=local",
"ServiceAccountDn": "cn=admin,dc=zb,dc=local",
"ServiceAccountPassword": "${SCADABRIDGE_LDAP_SERVICE_ACCOUNT_PASSWORD}"
"ServiceAccountPassword": "${secret:ldap/scadabridge/service-account-password}"
},
"JwtSigningKey": "${SCADABRIDGE_JWT_SIGNING_KEY}",
"JwtSigningKey": "${secret:security/scadabridge/jwt-signing-key}",
"JwtExpiryMinutes": 15,
"IdleTimeoutMinutes": 30
},
@@ -9,6 +9,12 @@
}
}
},
"Secrets": {
"SqlitePath": "scadabridge-secrets.db",
"MasterKey": { "Source": "Environment", "EnvVarName": "ZB_SECRETS_MASTER_KEY" },
"RunMigrationsOnStartup": true,
"ResolveCacheTtl": "00:00:30"
},
"Serilog": {
"Using": [
"Serilog.Sinks.Console",
@@ -0,0 +1,140 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Protocol;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
using ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Adapters;
using ZB.MOM.WW.Secrets.Abstractions;
namespace ZB.MOM.WW.ScadaBridge.DataConnectionLayer.Tests.Adapters;
// G-3 / Task 9: the MxGateway per-endpoint ApiKey may hold a `secret:<name>` reference
// resolved via ISecretResolver at connect time. Literal keys pass through unchanged
// (back-compat); an unresolvable / missing secret, or a secret ref with no resolver
// available, fails closed (no connection established with an empty/null key).
[Collection("DataConnectionManagerActor")]
public class MxGatewayDataConnectionSecretsTests
{
private static Dictionary<string, string> Details(string apiKey) => new()
{
["Endpoint"] = "http://gw:5000",
["ApiKey"] = apiKey,
["ClientName"] = "client-a",
["WriteUserId"] = "0",
["ReadTimeoutMs"] = "2000",
};
private sealed class FakeSecretResolver : ISecretResolver
{
private readonly string? _value;
public FakeSecretResolver(string? value) => _value = value;
public List<string> Requested { get; } = new();
public Task<string?> GetAsync(SecretName name, CancellationToken ct)
{
Requested.Add(name.Value);
return Task.FromResult(_value);
}
}
[Fact]
public async Task ConnectAsync_resolves_secret_ref_apikey()
{
var fake = new FakeMxGatewayClient();
var resolver = new FakeSecretResolver("resolved-plaintext-key");
var adapter = new MxGatewayDataConnection(fake, NullLogger<MxGatewayDataConnection>.Instance, resolver);
await adapter.ConnectAsync(Details("secret:mxgateway/testconn/api-key"));
Assert.Equal(ConnectionHealth.Connected, adapter.Status);
Assert.NotNull(fake.ConnectedWith);
Assert.Equal("resolved-plaintext-key", fake.ConnectedWith!.ApiKey);
Assert.Contains("mxgateway/testconn/api-key", resolver.Requested);
}
[Fact]
public async Task ConnectAsync_passes_literal_apikey_unchanged_and_does_not_call_resolver()
{
var fake = new FakeMxGatewayClient();
var resolver = new FakeSecretResolver("SHOULD-NOT-BE-USED");
var adapter = new MxGatewayDataConnection(fake, NullLogger<MxGatewayDataConnection>.Instance, resolver);
await adapter.ConnectAsync(Details("literal-api-key"));
Assert.Equal("literal-api-key", fake.ConnectedWith!.ApiKey);
Assert.Empty(resolver.Requested);
}
[Fact]
public async Task ConnectAsync_fails_closed_when_secret_unresolvable()
{
var fake = new FakeMxGatewayClient();
var resolver = new FakeSecretResolver(null); // secret not found / tombstoned
var adapter = new MxGatewayDataConnection(fake, NullLogger<MxGatewayDataConnection>.Instance, resolver);
await Assert.ThrowsAsync<InvalidOperationException>(
() => adapter.ConnectAsync(Details("secret:mxgateway/testconn/missing")));
// Fail-closed: the underlying client was never connected and status is not Connected.
Assert.Null(fake.ConnectedWith);
Assert.NotEqual(ConnectionHealth.Connected, adapter.Status);
}
[Fact]
public async Task ConnectAsync_fails_closed_on_secret_ref_with_no_resolver()
{
var fake = new FakeMxGatewayClient();
var adapter = new MxGatewayDataConnection(fake, NullLogger<MxGatewayDataConnection>.Instance, secretResolver: null);
await Assert.ThrowsAsync<InvalidOperationException>(
() => adapter.ConnectAsync(Details("secret:mxgateway/testconn/api-key")));
Assert.Null(fake.ConnectedWith);
Assert.NotEqual(ConnectionHealth.Connected, adapter.Status);
}
// DI-threading seam (code-review follow-up): the four tests above construct the adapter
// directly with an explicit resolver, so they don't prove the factory→adapter DI wiring
// G-3 actually relies on. This test resolves IDataConnectionFactory from a real container
// (AddDataConnectionLayer + a registered fake ISecretResolver, no AddZbSecrets), creates a
// "MxGateway" adapter through it, and drives a secret:-ref ConnectAsync. The real client
// then fails to reach a non-existent gateway (expected, ignored) — but resolution happens
// BEFORE any connect attempt, so the fake resolver being invoked proves the greediest
// 3-arg DataConnectionFactory ctor picked up the DI-registered resolver and threaded it in.
// Had it been null, ConnectAsync would have thrown the "no ISecretResolver" fail-closed
// path instead and the resolver would never have been called.
[Fact]
public async Task Factory_from_DI_threads_registered_ISecretResolver_into_MxGateway_adapter()
{
var fake = new FakeSecretResolver("resolved-from-di");
var services = new ServiceCollection();
services.AddLogging();
services.AddSingleton<IConfiguration>(new ConfigurationBuilder().Build());
services.AddDataConnectionLayer();
services.AddSingleton<ISecretResolver>(fake);
using var provider = services.BuildServiceProvider();
var factory = provider.GetRequiredService<IDataConnectionFactory>();
// Point at a fast-refusing loopback port so the real client's connect fails quickly.
var details = Details("secret:mxgateway/testconn/api-key");
details["Endpoint"] = "http://127.0.0.1:1";
await using var adapter = factory.Create("MxGateway", details);
Assert.IsType<MxGatewayDataConnection>(adapter);
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
try
{
await adapter.ConnectAsync(details, cts.Token);
}
catch
{
// The real RealMxGatewayClient cannot reach 127.0.0.1:1 — irrelevant to this test.
}
// Resolution runs before the connect attempt: the resolver being invoked proves the
// factory threaded the DI-registered ISecretResolver into the adapter.
Assert.Contains("mxgateway/testconn/api-key", fake.Requested);
}
}
@@ -23,23 +23,19 @@ public class CentralActorPathTests : IAsyncLifetime
private WebApplicationFactory<Program>? _factory;
private ActorSystem? _actorSystem;
private string? _previousEnv;
private CentralDbTestEnvironment? _dbEnv;
public Task InitializeAsync()
{
_previousEnv = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT");
Environment.SetEnvironmentVariable("DOTNET_ENVIRONMENT", "Central");
// Supply the pepper so the Central-role StartupValidator preflight (1fcc4f5)
// passes before WebApplicationFactory gets a chance to overlay DI config.
// The pre-host config builder includes AddEnvironmentVariables(), so this
// env var is visible to StartupValidator.Validate() at Program.cs line 42.
Environment.SetEnvironmentVariable("ScadaBridge__InboundApi__ApiKeyPepper",
CentralDbTestEnvironment.TestPepper);
// Supply MachineDataDb so the reverted Host-008 Require (REQ-HOST-3/4, M2.9 #17)
// passes for Central-role StartupValidator. A non-empty placeholder satisfies
// the preflight; the DI override below replaces the real DbContext anyway.
Environment.SetEnvironmentVariable("ScadaBridge__Database__MachineDataDb",
"Server=localhost;Database=MachineData;");
// Supply the pepper, MachineDataDb and the G-4 secret-backed keys
// (ConfigurationDb / LDAP service-account password / JWT signing key) as
// whole-key env overrides so the pre-host config builder — which calls
// AddEnvironmentVariables() before the ${secret:...} expander runs — sees
// concrete values and the Central-role StartupValidator preflight passes.
_dbEnv = new CentralDbTestEnvironment();
_factory = new WebApplicationFactory<Program>()
.WithWebHostBuilder(builder =>
@@ -99,8 +95,7 @@ public class CentralActorPathTests : IAsyncLifetime
{
_factory?.Dispose();
Environment.SetEnvironmentVariable("DOTNET_ENVIRONMENT", _previousEnv);
Environment.SetEnvironmentVariable("ScadaBridge__InboundApi__ApiKeyPepper", null);
Environment.SetEnvironmentVariable("ScadaBridge__Database__MachineDataDb", null);
_dbEnv?.Dispose();
await Task.CompletedTask;
}
@@ -90,22 +90,19 @@ public class CentralAuditWiringTests : IDisposable
{
private readonly WebApplicationFactory<Program> _factory;
private readonly string? _previousEnv;
private readonly CentralDbTestEnvironment _dbEnv;
public CentralAuditWiringTests()
{
_previousEnv = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT");
Environment.SetEnvironmentVariable("DOTNET_ENVIRONMENT", "Central");
// Supply the pepper so the Central-role StartupValidator preflight (1fcc4f5)
// passes. The pre-host config builder uses AddEnvironmentVariables(), which
// runs before WithWebHostBuilder.ConfigureAppConfiguration applies DI config.
Environment.SetEnvironmentVariable("ScadaBridge__InboundApi__ApiKeyPepper",
CentralDbTestEnvironment.TestPepper);
// Supply MachineDataDb so the reverted Host-008 Require (REQ-HOST-3/4, M2.9 #17)
// passes for Central-role StartupValidator. A non-empty placeholder satisfies
// the preflight; the DI override below replaces the real DbContext anyway.
Environment.SetEnvironmentVariable("ScadaBridge__Database__MachineDataDb",
"Server=localhost;Database=MachineData;");
// Supply the pepper, MachineDataDb and the G-4 secret-backed keys
// (ConfigurationDb / LDAP service-account password / JWT signing key) as
// whole-key env overrides so the pre-host config builder — which calls
// AddEnvironmentVariables() before the ${secret:...} expander runs — sees
// concrete values and the Central-role StartupValidator preflight passes.
_dbEnv = new CentralDbTestEnvironment();
_factory = new WebApplicationFactory<Program>()
.WithWebHostBuilder(builder =>
@@ -161,8 +158,7 @@ public class CentralAuditWiringTests : IDisposable
{
_factory.Dispose();
Environment.SetEnvironmentVariable("DOTNET_ENVIRONMENT", _previousEnv);
Environment.SetEnvironmentVariable("ScadaBridge__InboundApi__ApiKeyPepper", null);
Environment.SetEnvironmentVariable("ScadaBridge__Database__MachineDataDb", null);
_dbEnv.Dispose();
}
[Fact]
@@ -15,7 +15,17 @@ namespace ZB.MOM.WW.ScadaBridge.Host.Tests;
/// Also supplies <c>ScadaBridge__Database__MachineDataDb</c> so the Central-role
/// StartupValidator preflight (reverts Host-008, REQ-HOST-3/4, M2.9 #17) does not
/// fail for tests that set <c>DOTNET_ENVIRONMENT=Central</c> without an explicit
/// MachineDataDb env var. All vars are restored on Dispose so tests stay isolated.
/// MachineDataDb env var.
///
/// G-4 (secrets adoption): <c>appsettings.Central.json</c> now carries
/// <c>${secret:...}</c> references for the ConfigurationDb connection string, the
/// LDAP service-account password and the JWT signing key. The pre-host secrets
/// expander (Program.cs) resolves those before StartupValidator runs and fails
/// closed on an unseeded reference. Supplying the concrete values as whole-key
/// environment overrides (the sanctioned rollback path) makes the expander skip
/// the tokens entirely — so tests that boot the real <c>Program</c> pipeline do
/// not need a seeded secrets store. All vars are restored on Dispose so tests
/// stay isolated.
/// </summary>
internal sealed class CentralDbTestEnvironment : IDisposable
{
@@ -37,9 +47,22 @@ internal sealed class CentralDbTestEnvironment : IDisposable
internal const string TestPepper = "test-pepper-01234567890";
private const string PepperKey = "ScadaBridge__InboundApi__ApiKeyPepper";
// G-4: whole-key overrides for the two remaining ${secret:...} config references
// in appsettings.Central.json (the LDAP service-account password and JWT signing
// key). Test-only placeholder values — non-empty, and the JWT key clears the
// ≥32-char StartupValidator length rule. Applied via env so the pre-host expander
// sees the concrete value and never evaluates the token.
private const string LdapServiceAccountPassword = "test-ldap-service-account-password";
private const string LdapPasswordKey = "ScadaBridge__Security__Ldap__ServiceAccountPassword";
private const string JwtSigningKey = "test-signing-key-must-be-at-least-32-chars-long!";
private const string JwtSigningKeyKey = "ScadaBridge__Security__JwtSigningKey";
private readonly string? _previousConfig;
private readonly string? _previousMachineData;
private readonly string? _previousPepper;
private readonly string? _previousLdapPassword;
private readonly string? _previousJwtSigningKey;
public CentralDbTestEnvironment()
{
@@ -51,6 +74,12 @@ internal sealed class CentralDbTestEnvironment : IDisposable
_previousPepper = Environment.GetEnvironmentVariable(PepperKey);
Environment.SetEnvironmentVariable(PepperKey, TestPepper);
_previousLdapPassword = Environment.GetEnvironmentVariable(LdapPasswordKey);
Environment.SetEnvironmentVariable(LdapPasswordKey, LdapServiceAccountPassword);
_previousJwtSigningKey = Environment.GetEnvironmentVariable(JwtSigningKeyKey);
Environment.SetEnvironmentVariable(JwtSigningKeyKey, JwtSigningKey);
}
public void Dispose()
@@ -58,5 +87,7 @@ internal sealed class CentralDbTestEnvironment : IDisposable
Environment.SetEnvironmentVariable(ConfigKey, _previousConfig);
Environment.SetEnvironmentVariable(MachineDataKey, _previousMachineData);
Environment.SetEnvironmentVariable(PepperKey, _previousPepper);
Environment.SetEnvironmentVariable(LdapPasswordKey, _previousLdapPassword);
Environment.SetEnvironmentVariable(JwtSigningKeyKey, _previousJwtSigningKey);
}
}
@@ -84,22 +84,19 @@ public class CentralCompositionRootTests : IDisposable
{
private readonly WebApplicationFactory<Program> _factory;
private readonly string? _previousEnv;
private readonly CentralDbTestEnvironment _dbEnv;
public CentralCompositionRootTests()
{
_previousEnv = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT");
Environment.SetEnvironmentVariable("DOTNET_ENVIRONMENT", "Central");
// Supply the pepper so the Central-role StartupValidator preflight (1fcc4f5)
// passes. The pre-host config builder uses AddEnvironmentVariables(), which
// runs before WithWebHostBuilder.ConfigureAppConfiguration applies DI config.
Environment.SetEnvironmentVariable("ScadaBridge__InboundApi__ApiKeyPepper",
CentralDbTestEnvironment.TestPepper);
// Supply MachineDataDb so the reverted Host-008 Require (REQ-HOST-3/4, M2.9 #17)
// passes for Central-role StartupValidator. A non-empty placeholder satisfies
// the preflight; the DI override below replaces the real DbContext anyway.
Environment.SetEnvironmentVariable("ScadaBridge__Database__MachineDataDb",
"Server=localhost;Database=MachineData;");
// Supply the pepper, MachineDataDb and the G-4 secret-backed keys
// (ConfigurationDb / LDAP service-account password / JWT signing key) as
// whole-key env overrides so the pre-host config builder — which calls
// AddEnvironmentVariables() before the ${secret:...} expander runs — sees
// concrete values and the Central-role StartupValidator preflight passes.
_dbEnv = new CentralDbTestEnvironment();
_factory = new WebApplicationFactory<Program>()
.WithWebHostBuilder(builder =>
@@ -164,8 +161,7 @@ public class CentralCompositionRootTests : IDisposable
{
_factory.Dispose();
Environment.SetEnvironmentVariable("DOTNET_ENVIRONMENT", _previousEnv);
Environment.SetEnvironmentVariable("ScadaBridge__InboundApi__ApiKeyPepper", null);
Environment.SetEnvironmentVariable("ScadaBridge__Database__MachineDataDb", null);
_dbEnv.Dispose();
}
// --- Singletons ---
@@ -0,0 +1,92 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.DependencyInjection;
using ZB.MOM.WW.ScadaBridge.Security;
using ZB.MOM.WW.Secrets.Ui;
namespace ZB.MOM.WW.ScadaBridge.Host.Tests;
/// <summary>
/// G-6 (Task 7) offline behavioral proof: composing the Secrets.Ui authorization
/// (<c>Configure&lt;AuthorizationOptions&gt;(o =&gt; o.AddSecretsAuthorization())</c>) on top of
/// ScadaBridge's own <see cref="AuthorizationPolicies.AddScadaBridgeAuthorization"/> yields the
/// two named policies <c>secrets:manage</c> + <c>secrets:reveal</c>, and — because ScadaBridge
/// builds identities with <c>RoleClaimType = ZbClaimTypes.Role</c> and the library's admin role is
/// literally <c>"Administrator"</c> — an <c>Administrator</c> principal is authorized for BOTH,
/// while a non-admin / anonymous principal is denied BOTH. This is the offline evidence for the
/// Task-6 "no app-specific policy remap needed" decision, exercised against the real
/// <see cref="IAuthorizationService"/> rather than mere registration.
/// </summary>
public class SecretsAuthorizationTests
{
private const string ManagePolicy = "secrets:manage";
private const string RevealPolicy = "secrets:reveal";
private static IServiceProvider BuildProvider()
{
var services = new ServiceCollection();
services.AddLogging();
// Mirror the Central composition: ScadaBridge's own authorization first
// (registers the core authorization services + ScadaBridge policies via
// AddAuthorization), then the additive Secrets.Ui policy configuration.
services.AddScadaBridgeAuthorization();
services.Configure<AuthorizationOptions>(o => o.AddSecretsAuthorization());
return services.BuildServiceProvider();
}
private static ClaimsPrincipal PrincipalWithRole(string role)
{
// Build the identity EXACTLY as ScadaBridge does: role claims under
// JwtTokenService.RoleClaimType (== ZbClaimTypes.Role == ClaimTypes.Role) and
// roleType set to the same, so IsInRole (used by the library's RequireRole) resolves.
var identity = new ClaimsIdentity(
new[] { new Claim(JwtTokenService.RoleClaimType, role) },
authenticationType: "Test",
nameType: JwtTokenService.UsernameClaimType,
roleType: JwtTokenService.RoleClaimType);
return new ClaimsPrincipal(identity);
}
[Fact]
public async Task BothSecretsPolicies_AreRegistered()
{
var provider = BuildProvider();
var policyProvider = provider.GetRequiredService<IAuthorizationPolicyProvider>();
Assert.NotNull(await policyProvider.GetPolicyAsync(ManagePolicy));
Assert.NotNull(await policyProvider.GetPolicyAsync(RevealPolicy));
}
[Fact]
public async Task Administrator_IsAuthorized_ForBothManageAndReveal()
{
var provider = BuildProvider();
var authService = provider.GetRequiredService<IAuthorizationService>();
var admin = PrincipalWithRole(Roles.Administrator);
Assert.True((await authService.AuthorizeAsync(admin, ManagePolicy)).Succeeded);
Assert.True((await authService.AuthorizeAsync(admin, RevealPolicy)).Succeeded);
}
[Fact]
public async Task NonAdministratorRole_IsDenied_ForBothManageAndReveal()
{
var provider = BuildProvider();
var authService = provider.GetRequiredService<IAuthorizationService>();
var viewer = PrincipalWithRole(Roles.Viewer);
Assert.False((await authService.AuthorizeAsync(viewer, ManagePolicy)).Succeeded);
Assert.False((await authService.AuthorizeAsync(viewer, RevealPolicy)).Succeeded);
}
[Fact]
public async Task AnonymousPrincipal_IsDenied_ForBothManageAndReveal()
{
var provider = BuildProvider();
var authService = provider.GetRequiredService<IAuthorizationService>();
var anonymous = new ClaimsPrincipal(new ClaimsIdentity());
Assert.False((await authService.AuthorizeAsync(anonymous, ManagePolicy)).Succeeded);
Assert.False((await authService.AuthorizeAsync(anonymous, RevealPolicy)).Succeeded);
}
}