Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.Host.Tests/CentralDbTestEnvironment.cs
T
Joseph Doherty 513fa1aa16 docs(tests): fix CommentChecker findings across tests/ — 13,392 → 0 (repo-wide scan clean)
Comment/XML-doc changes only:
- add summaries to ~10k test methods, fixtures, fakes and helpers
  (+ <param> on theories, <returns> on async Task methods,
  <inheritdoc/> on interface implementations the checker can resolve)
- strip ~2.6k project-tracking references (WP*, P*-*, row-NN, Task N,
  #NN, Component-0NN) from comments, keeping the explanatory text;
  reword false positives in comments only
- real docs on fakes implementing BCL/library interfaces
  (IDisposable, ILogger, IOptionsMonitor, IAsyncLifetime)
- reword the last 5 src/ false positives (CWE-1236, failures-1,
  year-0001, M365)

Only non-comment edits: four one-line nested classes split across lines
so members can carry docs. Build 0 errors / 0 warnings.
2026-10-07 15:05:49 -04:00

123 lines
6.7 KiB
C#

namespace ZB.MOM.WW.ScadaBridge.Host.Tests;
/// <summary>
/// <c>appsettings.Central.json</c> no longer commits database connection
/// strings — they are externalised to environment variables. Tests that exercise the
/// full <c>Program</c> startup pipeline against the real SQL provider must therefore
/// supply the local dev connection string the way a deployment would: via an
/// environment variable (<c>Program</c>'s configuration builder calls
/// <c>AddEnvironmentVariables()</c>).
///
/// Also supplies <c>ScadaBridge__InboundApi__ApiKeyPepper</c> so the Central-role
/// StartupValidator preflight (added in 1fcc4f5) does not fail for tests that set
/// <c>DOTNET_ENVIRONMENT=Central</c> without an explicit pepper env var.
///
/// Also supplies <c>ScadaBridge__Database__MachineDataDb</c> so the Central-role
/// StartupValidator preflight (a missing MachineDataDb setting) does not
/// fail for tests that set <c>DOTNET_ENVIRONMENT=Central</c> without an explicit
/// 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.
///
/// Every var below is <b>process-wide</b>, and the reader — <c>Program</c>'s
/// <c>AddEnvironmentVariables()</c> — runs at an unpredictable point during host boot.
/// Two live instances therefore cannot be allowed to overlap: one's Dispose would
/// restore/clear a var while the other's boot is still reading it, and the fail-closed
/// secrets expander turns that into a <c>SecretNotFoundException</c>. Serialization via
/// <see cref="HostBootCollection"/> is what enforces the invariant; the overlap check in
/// the constructor makes a regression fail deterministically instead of intermittently.
/// </summary>
internal sealed class CentralDbTestEnvironment : IDisposable
{
// Local dev/test database — same credentials the infra docker-compose stack uses.
// This is a test fixture value, not a committed production secret.
private const string ConfigurationDb =
"Server=localhost,1433;Database=ScadaBridgeConfig;User Id=scadabridge_app;Password=ScadaBridge_Dev1#;TrustServerCertificate=true";
private const string ConfigKey = "ScadaBridge__Database__ConfigurationDb";
private const string MachineDataDb =
"Server=localhost,1433;Database=ScadaBridgeMachineData;User Id=scadabridge_app;Password=ScadaBridge_Dev1#;TrustServerCertificate=true";
private const string MachineDataKey = "ScadaBridge__Database__MachineDataDb";
// Test-only pepper — satisfies the ≥16-char StartupValidator requirement without
// committing a real secret. The env-var name uses the double-underscore delimiter
// so AddEnvironmentVariables() maps it to ScadaBridge:InboundApi:ApiKeyPepper.
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;
/// <summary>
/// Number of live instances. Only ever 0 or 1 while every consuming fixture is a
/// member of <see cref="HostBootCollection"/>; see the overlap check below.
/// </summary>
private static int _liveCount;
/// <summary>Initializes a new instance of <c>CentralDbTestEnvironment</c>.</summary>
public CentralDbTestEnvironment()
{
if (Interlocked.Increment(ref _liveCount) != 1)
{
Interlocked.Decrement(ref _liveCount);
throw new InvalidOperationException(
$"Two {nameof(CentralDbTestEnvironment)} instances are live at once, so one fixture's " +
"teardown can clear the process-wide environment variables another fixture's host boot " +
$"is reading. Add the offending test class to the \"{HostBootCollection.Name}\" collection " +
$"([Collection({nameof(HostBootCollection)}.Name)]) so xUnit runs it sequentially with the " +
"other host-boot fixtures.");
}
_previousConfig = Environment.GetEnvironmentVariable(ConfigKey);
Environment.SetEnvironmentVariable(ConfigKey, ConfigurationDb);
_previousMachineData = Environment.GetEnvironmentVariable(MachineDataKey);
Environment.SetEnvironmentVariable(MachineDataKey, MachineDataDb);
_previousPepper = Environment.GetEnvironmentVariable(PepperKey);
Environment.SetEnvironmentVariable(PepperKey, TestPepper);
_previousLdapPassword = Environment.GetEnvironmentVariable(LdapPasswordKey);
Environment.SetEnvironmentVariable(LdapPasswordKey, LdapServiceAccountPassword);
_previousJwtSigningKey = Environment.GetEnvironmentVariable(JwtSigningKeyKey);
Environment.SetEnvironmentVariable(JwtSigningKeyKey, JwtSigningKey);
}
/// <summary>Releases the resources held by the test fixture.</summary>
public void Dispose()
{
Environment.SetEnvironmentVariable(ConfigKey, _previousConfig);
Environment.SetEnvironmentVariable(MachineDataKey, _previousMachineData);
Environment.SetEnvironmentVariable(PepperKey, _previousPepper);
Environment.SetEnvironmentVariable(LdapPasswordKey, _previousLdapPassword);
Environment.SetEnvironmentVariable(JwtSigningKeyKey, _previousJwtSigningKey);
Interlocked.Decrement(ref _liveCount);
}
}