rename: prefix gateway projects/namespaces with ZB.MOM.WW + sln→slnx

Apply the ZB.MOM.WW. prefix to all gateway-side projects, folders,
.csproj/.sln contents, C# namespaces, using directives, generated proto
C# (csharp_namespace + checked-in generated files), InternalsVisibleTo
attributes, project-name string literals (LoadProject, .sln lookups,
worker exe paths, staticwebassets manifest), and the install/script/doc
references that point at any of the above. Migrate the solution from
.sln to .slnx via `dotnet sln migrate` and delete the old file.

External-runtime identifiers are intentionally NOT prefixed so external
configuration keeps working:
- GatewayMetrics.cs MeterName ("MxGateway.Server")
- DashboardAuthenticationDefaults Scheme/Policy ("MxGateway.Dashboard")
- GatewayRequestLoggingMiddleware logger category ("MxGateway.Request")
- StaRuntime thread name ("MxGateway.Worker.STA")
- appsettings.json root section "MxGateway" + env-var prefix
  MxGateway__... and secret-name MxGateway:ApiKeyPepper
- C:\ProgramData\MxGateway\ data dir paths

Also fixes two tests that were not rename-related but became visible
while validating the rename:

- WorkerLiveMxAccessSmokeTests.ShutDownAsync: cancellation that the
  gateway service correctly maps to RpcException(Cancelled) per gRPC
  convention was being misclassified as a stream fault. Added a sibling
  catch on RpcException with StatusCode.Cancelled.

- IntegrationTestEnvironment.ResolveRepositoryRoot: extracted IsRepositoryRoot
  and made it accept either a .git marker OR a .sln/.slnx next to src/
  so the worker-exe walker works in non-git working copies.

clients/proto/proto-inputs.json's protoRoot updated to point at
src/ZB.MOM.WW.MxGateway.Contracts/Protos.

Verified by `dotnet build` and a full `dotnet test` of the .slnx with
MXGATEWAY_RUN_LIVE_{MXACCESS,LDAP,GALAXY}_TESTS=1:
  Tests: 472/472 pass
  Worker.Tests: 280/280 pass (4 dev-rig [Fact(Skip=...)] skipped)
  IntegrationTests: 18/18 pass

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Joseph Doherty
2026-05-23 16:22:23 -04:00
parent 867bf18116
commit dc9c0c950c
491 changed files with 32854 additions and 8414 deletions
@@ -0,0 +1,112 @@
using System.Security.Claims;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.MxGateway.Server.Configuration;
using ZB.MOM.WW.MxGateway.Server.Dashboard;
namespace ZB.MOM.WW.MxGateway.IntegrationTests;
[Collection(LiveResourcesCollection.Name)]
[Trait("Category", "LiveLdap")]
public sealed class DashboardLdapLiveTests
{
[LiveLdapFact]
public async Task AuthenticateAsync_AdminInGwAdminGroup_Succeeds()
{
DashboardAuthenticator authenticator = CreateAuthenticator();
DashboardAuthenticationResult result = await authenticator.AuthenticateAsync(
"admin",
"admin123",
CancellationToken.None);
Assert.True(result.Succeeded);
Assert.NotNull(result.Principal);
Assert.Equal("admin", result.Principal.FindFirst(ClaimTypes.NameIdentifier)?.Value);
Assert.Contains(result.Principal.Claims, claim =>
claim.Type == DashboardAuthenticationDefaults.LdapGroupClaimType
&& claim.Value.Contains("GwAdmin", StringComparison.OrdinalIgnoreCase));
}
[LiveLdapFact]
public async Task AuthenticateAsync_ReadOnlyUserMissingGwAdminGroup_Fails()
{
DashboardAuthenticator authenticator = CreateAuthenticator();
DashboardAuthenticationResult result = await authenticator.AuthenticateAsync(
"readonly",
"readonly123",
CancellationToken.None);
Assert.False(result.Succeeded);
Assert.Null(result.Principal);
Assert.DoesNotContain("readonly123", result.FailureMessage, StringComparison.Ordinal);
}
[LiveLdapFact]
public async Task AuthenticateAsync_AdminWithWrongPassword_FailsWithoutLeakingPassword()
{
// Exercises the LdapException branch: the user exists and the service
// account search succeeds, but the candidate bind is rejected.
const string wrongPassword = "definitely-not-the-admin-password";
DashboardAuthenticator authenticator = CreateAuthenticator();
DashboardAuthenticationResult result = await authenticator.AuthenticateAsync(
"admin",
wrongPassword,
CancellationToken.None);
Assert.False(result.Succeeded);
Assert.Null(result.Principal);
Assert.DoesNotContain(wrongPassword, result.FailureMessage, StringComparison.Ordinal);
}
[LiveLdapFact]
public async Task AuthenticateAsync_UnknownUsername_Fails()
{
// Exercises the `candidate is null` branch: the service-account search
// returns no entry, so no candidate bind is attempted.
DashboardAuthenticator authenticator = CreateAuthenticator();
DashboardAuthenticationResult result = await authenticator.AuthenticateAsync(
"no-such-user-9f3c1",
"irrelevant-password",
CancellationToken.None);
Assert.False(result.Succeeded);
Assert.Null(result.Principal);
}
[LiveLdapFact]
public async Task AuthenticateAsync_ServerUnreachable_FailsWithoutThrowing()
{
// Exercises the connect-failure path: a closed loopback port produces a
// connection error that DashboardAuthenticator must absorb into a Fail
// result rather than propagating an exception to the dashboard.
DashboardAuthenticator authenticator = new(
Options.Create(new GatewayOptions
{
Ldap = new LdapOptions
{
// 1 is a reserved port number that no LDAP server listens on.
Port = 1,
},
}),
NullLogger<DashboardAuthenticator>.Instance);
DashboardAuthenticationResult result = await authenticator.AuthenticateAsync(
"admin",
"admin123",
CancellationToken.None);
Assert.False(result.Succeeded);
Assert.Null(result.Principal);
}
private static DashboardAuthenticator CreateAuthenticator()
{
return new DashboardAuthenticator(
Options.Create(new GatewayOptions()),
NullLogger<DashboardAuthenticator>.Instance);
}
}
@@ -0,0 +1,70 @@
using ZB.MOM.WW.MxGateway.Server.Galaxy;
namespace ZB.MOM.WW.MxGateway.IntegrationTests.Galaxy;
[Collection(LiveResourcesCollection.Name)]
[Trait("Category", "LiveGalaxy")]
public sealed class GalaxyRepositoryLiveTests
{
/// <summary>Verifies that the Galaxy Repository can establish a live connection to the ZB database.</summary>
[LiveGalaxyRepositoryFact]
public async Task TestConnection_AgainstZb_Succeeds()
{
GalaxyRepository repository = CreateRepository();
bool ok = await repository.TestConnectionAsync(CancellationToken.None);
Assert.True(ok, "TestConnectionAsync should return true against the ZB database.");
}
/// <summary>Verifies that the last deploy time can be retrieved from the ZB database.</summary>
[LiveGalaxyRepositoryFact]
public async Task GetLastDeployTime_AgainstZb_ReturnsTimestamp()
{
GalaxyRepository repository = CreateRepository();
DateTime? lastDeploy = await repository.GetLastDeployTimeAsync(CancellationToken.None);
Assert.NotNull(lastDeploy);
}
/// <summary>Verifies that the hierarchy can be retrieved from the ZB database.</summary>
[LiveGalaxyRepositoryFact]
public async Task GetHierarchy_AgainstZb_ReturnsObjects()
{
GalaxyRepository repository = CreateRepository();
List<GalaxyHierarchyRow> rows = await repository.GetHierarchyAsync(CancellationToken.None);
Assert.NotEmpty(rows);
Assert.All(rows, row =>
{
Assert.True(row.GobjectId > 0);
Assert.False(string.IsNullOrEmpty(row.TagName));
Assert.False(string.IsNullOrEmpty(row.BrowseName));
});
}
/// <summary>Verifies that object attributes can be retrieved from the ZB database.</summary>
[LiveGalaxyRepositoryFact]
public async Task GetAttributes_AgainstZb_ReturnsAtLeastOneAttribute()
{
GalaxyRepository repository = CreateRepository();
List<GalaxyAttributeRow> rows = await repository.GetAttributesAsync(CancellationToken.None);
Assert.NotEmpty(rows);
Assert.All(rows, row =>
{
Assert.True(row.GobjectId > 0);
Assert.False(string.IsNullOrEmpty(row.AttributeName));
Assert.False(string.IsNullOrEmpty(row.FullTagReference));
});
}
private static GalaxyRepository CreateRepository() => new(new GalaxyRepositoryOptions
{
ConnectionString = LiveGalaxyRepositoryFactAttribute.ConnectionString,
CommandTimeoutSeconds = 30,
});
}
@@ -0,0 +1,33 @@
using ZB.MOM.WW.MxGateway.Server.Galaxy;
namespace ZB.MOM.WW.MxGateway.IntegrationTests.Galaxy;
/// <summary>Fact attribute that skips tests unless live Galaxy Repository tests are explicitly enabled.</summary>
public sealed class LiveGalaxyRepositoryFactAttribute : FactAttribute
{
/// <summary>Environment variable name to enable live Galaxy Repository tests.</summary>
public const string EnableVariableName = "MXGATEWAY_RUN_LIVE_GALAXY_TESTS";
/// <summary>Environment variable name for the Galaxy Repository connection string.</summary>
public const string ConnectionStringVariableName = "MXGATEWAY_LIVE_GALAXY_CONN";
/// <summary>Initializes a new instance of the LiveGalaxyRepositoryFactAttribute class.</summary>
public LiveGalaxyRepositoryFactAttribute()
{
if (!Enabled)
{
Skip = $"Set {EnableVariableName}=1 to run live Galaxy Repository tests.";
}
}
/// <summary>Gets a value indicating whether live Galaxy Repository tests are enabled.</summary>
public static bool Enabled => IntegrationTestEnvironment.IsEnabled(EnableVariableName);
/// <summary>
/// Gets the Galaxy Repository connection string from environment or the production
/// default. The default is sourced from <see cref="GalaxyRepositoryOptions.DefaultConnectionString"/>
/// so the live-test fallback cannot drift away from the production default.
/// </summary>
public static string ConnectionString =>
Environment.GetEnvironmentVariable(ConnectionStringVariableName)
?? GalaxyRepositoryOptions.DefaultConnectionString;
}
@@ -0,0 +1,139 @@
using ZB.MOM.WW.MxGateway.Contracts;
namespace ZB.MOM.WW.MxGateway.IntegrationTests;
public static class IntegrationTestEnvironment
{
/// <summary>
/// Sourced from <see cref="GatewayContractInfo.LiveMxAccessOptInVariableName"/>
/// so the env-var literal is shared with
/// <c>ZB.MOM.WW.MxGateway.Worker.Tests.TestSupport.LiveMxAccessFactAttribute</c>
/// (Worker.Tests-025).
/// </summary>
public const string LiveMxAccessVariableName = GatewayContractInfo.LiveMxAccessOptInVariableName;
public const string LiveMxAccessWorkerExecutableVariableName = "MXGATEWAY_LIVE_MXACCESS_WORKER_EXE";
public const string LiveMxAccessItemVariableName = "MXGATEWAY_LIVE_MXACCESS_ITEM";
public const string LiveMxAccessClientNameVariableName = "MXGATEWAY_LIVE_MXACCESS_CLIENT_NAME";
public const string LiveMxAccessEventTimeoutSecondsVariableName = "MXGATEWAY_LIVE_MXACCESS_EVENT_TIMEOUT_SECONDS";
/// <summary>Gets whether live MXAccess tests are enabled.</summary>
public static bool LiveMxAccessTestsEnabled => IsEnabled(LiveMxAccessVariableName);
/// <summary>
/// Gets whether an opt-in live-test suite is enabled, by comparing the named
/// environment variable to <c>1</c>. Shared by every <c>Live*FactAttribute</c>
/// so the opt-in check has a single implementation.
/// </summary>
/// <param name="variableName">The environment variable that gates the suite.</param>
/// <returns><see langword="true"/> when the variable is exactly <c>1</c>.</returns>
public static bool IsEnabled(string variableName) =>
string.Equals(
Environment.GetEnvironmentVariable(variableName),
"1",
StringComparison.Ordinal);
/// <summary>Gets the MXAccess item name for live tests.</summary>
public static string LiveMxAccessItem =>
GetOptionalEnvironmentVariable(
LiveMxAccessItemVariableName,
"TestChildObject.TestInt");
/// <summary>Gets the client name for live tests.</summary>
public static string LiveMxAccessClientName =>
GetOptionalEnvironmentVariable(
LiveMxAccessClientNameVariableName,
"ZB.MOM.WW.MxGateway.IntegrationTests");
/// <summary>Gets the timeout for waiting on events in live tests.</summary>
public static TimeSpan LiveMxAccessEventTimeout =>
TimeSpan.FromSeconds(GetPositiveIntegerEnvironmentVariable(
LiveMxAccessEventTimeoutSecondsVariableName,
defaultValue: 15));
/// <summary>Resolves the path to the worker executable for live tests.</summary>
/// <returns>Path to ZB.MOM.WW.MxGateway.Worker.exe.</returns>
public static string ResolveLiveMxAccessWorkerExecutablePath()
{
string? configuredPath = Environment.GetEnvironmentVariable(LiveMxAccessWorkerExecutableVariableName);
if (!string.IsNullOrWhiteSpace(configuredPath))
{
return Path.GetFullPath(configuredPath);
}
string repositoryRoot = ResolveRepositoryRoot(AppContext.BaseDirectory);
string[] candidatePaths =
[
Path.Combine(repositoryRoot, "src", "ZB.MOM.WW.MxGateway.Worker", "bin", "x86", "Debug", "net48", "ZB.MOM.WW.MxGateway.Worker.exe"),
Path.Combine(repositoryRoot, "src", "ZB.MOM.WW.MxGateway.Worker", "bin", "Debug", "net48", "ZB.MOM.WW.MxGateway.Worker.exe"),
Path.Combine(repositoryRoot, "src", "ZB.MOM.WW.MxGateway.Worker", "bin", "x86", "Release", "net48", "ZB.MOM.WW.MxGateway.Worker.exe"),
Path.Combine(repositoryRoot, "src", "ZB.MOM.WW.MxGateway.Worker", "bin", "Release", "net48", "ZB.MOM.WW.MxGateway.Worker.exe"),
Path.Combine(repositoryRoot, "src", "ZB.MOM.WW.MxGateway.Worker", "bin", "x86", "Release", "ZB.MOM.WW.MxGateway.Worker.exe"),
];
return candidatePaths.FirstOrDefault(File.Exists)
?? candidatePaths[0];
}
private static string GetOptionalEnvironmentVariable(
string name,
string defaultValue)
{
string? value = Environment.GetEnvironmentVariable(name);
return string.IsNullOrWhiteSpace(value)
? defaultValue
: value;
}
private static int GetPositiveIntegerEnvironmentVariable(
string name,
int defaultValue)
{
string? value = Environment.GetEnvironmentVariable(name);
if (int.TryParse(value, out int parsed) && parsed > 0)
{
return parsed;
}
return defaultValue;
}
/// <summary>Resolves the root directory of the repository by walking parents for a src/ directory next to either a .git marker or a .sln/.slnx file.</summary>
/// <param name="startDirectory">Starting directory to search from.</param>
/// <returns>The repository root path, or the start directory if not found.</returns>
internal static string ResolveRepositoryRoot(string startDirectory)
{
DirectoryInfo? directory = new(startDirectory);
while (directory is not null)
{
if (IsRepositoryRoot(directory))
{
return directory.FullName;
}
directory = directory.Parent;
}
return Directory.GetCurrentDirectory();
}
private static bool IsRepositoryRoot(DirectoryInfo directory)
{
string srcPath = Path.Combine(directory.FullName, "src");
if (!Directory.Exists(srcPath))
{
return false;
}
// Accept a checked-out git repo OR an unpacked working tree that ships a
// .sln/.slnx alongside src/. The .sln/.slnx fallback lets the integration
// tests run in copies that have no .git folder (e.g. an extracted zip).
if (Directory.Exists(Path.Combine(directory.FullName, ".git"))
|| File.Exists(Path.Combine(directory.FullName, ".git")))
{
return true;
}
return Directory.EnumerateFiles(srcPath, "*.slnx").Any()
|| Directory.EnumerateFiles(srcPath, "*.sln").Any();
}
}
@@ -0,0 +1,48 @@
namespace ZB.MOM.WW.MxGateway.IntegrationTests;
public sealed class IntegrationTestEnvironmentTests
{
/// <summary>Verifies that live MXAccess tests use correct environment variable name.</summary>
[Fact]
public void LiveMxAccessTests_AreOptInByEnvironmentVariable()
{
Assert.Equal(
"MXGATEWAY_RUN_LIVE_MXACCESS_TESTS",
IntegrationTestEnvironment.LiveMxAccessVariableName);
}
/// <summary>Verifies that worker executable uses correct environment variable name.</summary>
[Fact]
public void LiveMxAccessWorkerExecutable_UsesDocumentedEnvironmentVariable()
{
Assert.Equal(
"MXGATEWAY_LIVE_MXACCESS_WORKER_EXE",
IntegrationTestEnvironment.LiveMxAccessWorkerExecutableVariableName);
}
/// <summary>Verifies that repository root resolution accepts git worktree files.</summary>
[Fact]
public void ResolveRepositoryRoot_AcceptsGitWorktreeFile()
{
string temporaryRoot = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
string nestedDirectory = Path.Combine(temporaryRoot, "tests", "bin");
try
{
Directory.CreateDirectory(nestedDirectory);
Directory.CreateDirectory(Path.Combine(temporaryRoot, "src"));
File.WriteAllText(Path.Combine(temporaryRoot, ".git"), "gitdir: ../.git/worktrees/test");
string repositoryRoot = IntegrationTestEnvironment.ResolveRepositoryRoot(nestedDirectory);
Assert.Equal(temporaryRoot, repositoryRoot);
}
finally
{
if (Directory.Exists(temporaryRoot))
{
Directory.Delete(temporaryRoot, recursive: true);
}
}
}
}
@@ -0,0 +1,16 @@
namespace ZB.MOM.WW.MxGateway.IntegrationTests;
public sealed class LiveLdapFactAttribute : FactAttribute
{
public const string EnableVariableName = "MXGATEWAY_RUN_LIVE_LDAP_TESTS";
public LiveLdapFactAttribute()
{
if (!Enabled)
{
Skip = $"Set {EnableVariableName}=1 to run live LDAP tests.";
}
}
public static bool Enabled => IntegrationTestEnvironment.IsEnabled(EnableVariableName);
}
@@ -0,0 +1,14 @@
namespace ZB.MOM.WW.MxGateway.IntegrationTests;
/// <summary>Marks an xUnit test as requiring installed MXAccess COM and live provider state.</summary>
public sealed class LiveMxAccessFactAttribute : FactAttribute
{
/// <summary>Initializes the attribute, skipping the test unless the integration test environment variable is set.</summary>
public LiveMxAccessFactAttribute()
{
if (!IntegrationTestEnvironment.LiveMxAccessTestsEnabled)
{
Skip = $"Set {IntegrationTestEnvironment.LiveMxAccessVariableName}=1 to run live MXAccess tests.";
}
}
}
@@ -0,0 +1,16 @@
namespace ZB.MOM.WW.MxGateway.IntegrationTests;
/// <summary>
/// xUnit collection that serializes every live integration-test class. The live
/// suites contend for genuinely shared singletons — one MXAccess COM provider,
/// one <c>ZB</c> SQL database, and one GLAuth instance with a per-IP failure
/// lockout — so they must not run in parallel with one another. Placing each
/// live class in this collection disables xUnit's default cross-class
/// parallelism for them while leaving non-live tests free to parallelize.
/// </summary>
[CollectionDefinition(Name, DisableParallelization = true)]
public sealed class LiveResourcesCollection
{
/// <summary>The collection name applied via <c>[Collection]</c> on live test classes.</summary>
public const string Name = "Live external resources";
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.4" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ZB.MOM.WW.MxGateway.Contracts\ZB.MOM.WW.MxGateway.Contracts.csproj" />
<ProjectReference Include="..\ZB.MOM.WW.MxGateway.Server\ZB.MOM.WW.MxGateway.Server.csproj" />
</ItemGroup>
</Project>