diff --git a/src/ZB.MOM.WW.MxGateway.Server/Configuration/GatewayConfigPathRules.cs b/src/ZB.MOM.WW.MxGateway.Server/Configuration/GatewayConfigPathRules.cs
index 43d17fb2..e057a143 100644
--- a/src/ZB.MOM.WW.MxGateway.Server/Configuration/GatewayConfigPathRules.cs
+++ b/src/ZB.MOM.WW.MxGateway.Server/Configuration/GatewayConfigPathRules.cs
@@ -1,3 +1,4 @@
+using System.Runtime.InteropServices;
using ZB.MOM.WW.Configuration;
namespace ZB.MOM.WW.MxGateway.Server.Configuration;
@@ -16,7 +17,7 @@ internal static class GatewayConfigPathRules
/// host running the validator. Security-sensitive paths (the auth DB, the self-signed
/// private key, the Galaxy snapshot) must be absolute: a non-rooted value silently resolves
/// against the launch working directory, so the store moves with the CWD and can leak into the
- /// source tree. Rooting is checked with — the current
+ /// source tree. Rooting is checked with — the current
/// OS — so a Windows drive/UNC literal on a Unix host fails fast at startup rather than being
/// blessed and then written as a junk-named relative file. Reject
/// rather than auto-root; silent relocation of a credential store is worse than a boot error.
@@ -32,7 +33,9 @@ internal static class GatewayConfigPathRules
return;
}
- if (!Path.IsPathRooted(value))
+ // Fully qualified, not merely rooted: Windows' drive-relative "C:secrets.db" and root-relative
+ // "\secrets.db" are rooted yet still resolve against a current directory (Secrets-005).
+ if (!Path.IsPathFullyQualified(value))
{
builder.Add(message);
}
@@ -101,28 +104,233 @@ internal static class GatewayConfigPathRules
return;
}
+ // Two readings, and the value is inside if EITHER says so (mirrors ZB.MOM.WW.Secrets
+ // SecretsStorePathRules, Secrets-005; mxgw pins Secrets 0.6.2 so the rules are copied, not called):
+ // - as SPELLED (full path, device prefix / loopback share normalised): a store configured
+ // through the content root moves with it on a rename even when a link inside carries it
+ // elsewhere today;
+ // - as LOCATED (symlinks, junctions and 8.3 names resolved): a store spelled through an
+ // alias of the content root sits in the directory the deploy replaces.
// A malformed path is AddIfInvalidPath's message to report; staying silent here keeps one
// bad value from producing two failures that say different things about the same mistake.
- if (!TryGetFullPath(value, out string fullValue) || !TryGetFullPath(contentRoot, out string fullRoot))
+ string spelledValue, spelledRoot, locatedValue, locatedRoot;
+ try
+ {
+ spelledValue = Spelled(value);
+ spelledRoot = Spelled(contentRoot);
+ locatedValue = Canonicalize(value);
+ locatedRoot = Canonicalize(contentRoot);
+ }
+ catch (Exception ex) when (ex is ArgumentException or NotSupportedException
+ or PathTooLongException or IOException
+ or UnauthorizedAccessException)
{
return;
}
- fullRoot = fullRoot.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
-
- StringComparison comparison = OperatingSystem.IsWindows()
- ? StringComparison.OrdinalIgnoreCase
- : StringComparison.Ordinal;
-
- // The separator is load-bearing: a bare prefix test would also match a sibling directory
- // whose name merely starts with the root's ("/srv/app" against "/srv/app-data").
- if (string.Equals(fullValue, fullRoot, comparison)
- || fullValue.StartsWith(fullRoot + Path.DirectorySeparatorChar, comparison))
+ if (IsUnder(spelledValue, spelledRoot) || IsUnder(locatedValue, locatedRoot))
{
builder.Add(message);
}
}
+ private static bool IsUnder(string fullValue, string fullRoot)
+ {
+ // The separator is load-bearing, not cosmetic. Without it a bare prefix test treats
+ // "/srv/app-data" as inside "/srv/app" and refuses a legitimate sibling directory — and
+ // because this rule is fail-closed at startup, that false positive is an application that
+ // will not boot.
+ string rootWithSeparator = fullRoot.TrimEnd(
+ Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + Path.DirectorySeparatorChar;
+
+ // Path case sensitivity follows the OS, not a convention. Comparing case-insensitively
+ // everywhere would reject "/srv/App/store.db" as living under "/srv/app" on Linux, where
+ // those are genuinely different directories.
+ StringComparison comparison = OperatingSystem.IsWindows()
+ ? StringComparison.OrdinalIgnoreCase
+ : StringComparison.Ordinal;
+
+ // Equal to the root counts as inside (the gateway's original rule).
+ return string.Equals(fullValue, fullRoot.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar), comparison)
+ || fullValue.StartsWith(rootWithSeparator, comparison);
+ }
+
+ private static string Spelled(string path) => OperatingSystem.IsWindows()
+ ? NormalizeWindowsSpelling(Path.GetFullPath(NormalizeWindowsSpelling(path)))
+ : Path.GetFullPath(path);
+
+ private const int MaxLinkDepth = 40;
+
+ ///
+ /// Returns the location names, independent of how it is spelled: full
+ /// path, Windows device prefix stripped and loopback admin share mapped to its drive, and every
+ /// existing component resolved through symbolic links / junctions (and, on Windows, 8.3 short
+ /// names expanded). Components that do not exist yet are appended as written.
+ ///
+ /// The path to canonicalise.
+ /// The canonical full path.
+ internal static string Canonicalize(string path) => Canonicalize(path, depth: 0);
+
+ private static string Canonicalize(string path, int depth)
+ {
+ if (depth > MaxLinkDepth)
+ {
+ throw new IOException("Too many levels of symbolic links.");
+ }
+
+ string full = Spelled(path);
+
+ string root = Path.GetPathRoot(full) ?? string.Empty;
+ string[] parts = full[root.Length..].Split(
+ new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar },
+ StringSplitOptions.RemoveEmptyEntries);
+
+ string current = root;
+ for (int i = 0; i < parts.Length; i++)
+ {
+ string next = Path.Combine(current, parts[i]);
+ FileSystemInfo? info = Directory.Exists(next) ? new DirectoryInfo(next)
+ : File.Exists(next) ? new FileInfo(next)
+ : null;
+
+ if (info is null)
+ {
+ // Not created yet (the store usually is not, at validation time): nothing on disk
+ // can redirect the rest, so append it as written.
+ return Path.Combine(new[] { current }.Concat(parts[i..]).ToArray());
+ }
+
+ if (info.LinkTarget is not null)
+ {
+ FileSystemInfo? target = info.ResolveLinkTarget(returnFinalTarget: true);
+ if (target is not null)
+ {
+ // The target's own parent directories may be links too: canonicalise it whole.
+ next = Canonicalize(target.FullName, depth + 1);
+ }
+ }
+ else if (OperatingSystem.IsWindows())
+ {
+ next = ExpandShortName(next);
+ }
+
+ current = next;
+ }
+
+ return current;
+ }
+
+ ///
+ /// Strips the Win32 device prefixes (\\?\C:\…, \\.\C:\…, \\?\UNC\…) and maps
+ /// a loopback administrative share (\\localhost\C$\…) back to its drive.
+ ///
+ private static string NormalizeWindowsSpelling(string path)
+ {
+ string p = path.Replace('/', '\\');
+ if (p.StartsWith(@"\\?\UNC\", StringComparison.OrdinalIgnoreCase))
+ {
+ p = @"\\" + p[8..];
+ }
+ else if (p.StartsWith(@"\\?\", StringComparison.Ordinal) || p.StartsWith(@"\\.\", StringComparison.Ordinal))
+ {
+ p = p[4..];
+ }
+
+ if (p.StartsWith(@"\\", StringComparison.Ordinal))
+ {
+ string[] segments = p[2..].Split('\\');
+ if (segments.Length >= 2
+ && IsLoopbackHost(segments[0])
+ && segments[1].Length == 2
+ && char.IsAsciiLetter(segments[1][0])
+ && segments[1][1] == '$')
+ {
+ p = segments[1][0] + @":\" + string.Join('\\', segments[2..]);
+ }
+ else if (segments.Length >= 2 && IsLoopbackHost(segments[0]) && TryGetLocalSharePath(segments[1]) is { } sharePath)
+ {
+ // An ordinary (non-administrative) share on THIS machine: map it to the directory it
+ // publishes so a store reached through a share that points back at the content root
+ // is compared by location.
+ p = sharePath.TrimEnd('\\') + (segments.Length > 2 ? @"\" + string.Join('\\', segments[2..]) : string.Empty);
+ }
+ }
+
+ return p;
+ }
+
+ ///
+ /// Returns the local directory published by share on this machine, or
+ /// when it cannot be determined (no such share, or the caller lacks the
+ /// rights NetShareGetInfo level 2 demands — Administrators / Server Operators). A share on
+ /// ANOTHER machine is never resolved: what it points at is that server's configuration.
+ ///
+ private static string? TryGetLocalSharePath(string shareName)
+ {
+ try
+ {
+ if (NetShareGetInfo(null, shareName, 2, out IntPtr buffer) != 0)
+ {
+ return null;
+ }
+
+ try
+ {
+ SHARE_INFO_2 info = Marshal.PtrToStructure(buffer);
+ return string.IsNullOrWhiteSpace(info.shi2_path) ? null : info.shi2_path;
+ }
+ finally
+ {
+ _ = NetApiBufferFree(buffer);
+ }
+ }
+ catch (Exception ex) when (ex is DllNotFoundException or EntryPointNotFoundException or SEHException)
+ {
+ return null;
+ }
+ }
+
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
+ private struct SHARE_INFO_2
+ {
+ public string shi2_netname;
+ public uint shi2_type;
+ public string shi2_remark;
+ public uint shi2_permissions;
+ public uint shi2_max_uses;
+ public uint shi2_current_uses;
+ public string shi2_path;
+ public string shi2_passwd;
+ }
+
+ [DllImport("netapi32.dll", CharSet = CharSet.Unicode)]
+ private static extern uint NetShareGetInfo(string? serverName, string netName, uint level, out IntPtr bufptr);
+
+ [DllImport("netapi32.dll")]
+ private static extern uint NetApiBufferFree(IntPtr buffer);
+
+ private static bool IsLoopbackHost(string host) =>
+ host.Equals("localhost", StringComparison.OrdinalIgnoreCase)
+ || host.Equals("127.0.0.1", StringComparison.Ordinal)
+ || host.Equals("::1", StringComparison.Ordinal)
+ || host.Equals("[::1]", StringComparison.Ordinal)
+ || host.Equals(Environment.MachineName, StringComparison.OrdinalIgnoreCase);
+
+ private static string ExpandShortName(string existingPath)
+ {
+ if (!existingPath.Contains('~'))
+ {
+ return existingPath;
+ }
+
+ char[] buffer = new char[1024];
+ uint length = GetLongPathNameW(existingPath, buffer, (uint)buffer.Length);
+ return length > 0 && length < buffer.Length ? new string(buffer, 0, (int)length) : existingPath;
+ }
+
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
+ private static extern uint GetLongPathNameW(string shortPath, [Out] char[] longPath, uint bufferLength);
+
private static bool TryGetFullPath(string value, out string fullPath)
{
try
diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Configuration/GatewayConfigPathSpellingTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Configuration/GatewayConfigPathSpellingTests.cs
new file mode 100644
index 00000000..41e5f03f
--- /dev/null
+++ b/src/ZB.MOM.WW.MxGateway.Tests/Configuration/GatewayConfigPathSpellingTests.cs
@@ -0,0 +1,223 @@
+using System.Runtime.InteropServices;
+using ZB.MOM.WW.Configuration;
+using ZB.MOM.WW.MxGateway.Server.Configuration;
+
+namespace ZB.MOM.WW.MxGateway.Tests.Configuration;
+
+/// A fact that is skipped (visibly) on anything but Windows.
+[AttributeUsage(AttributeTargets.Method)]
+internal sealed class WindowsOnlyFactAttribute : FactAttribute
+{
+ public WindowsOnlyFactAttribute()
+ {
+ if (!OperatingSystem.IsWindows())
+ {
+ Skip = "Windows path semantics; run on a Windows host.";
+ }
+ }
+}
+
+///
+/// Mirrors the ZB.MOM.WW.Secrets Secrets-005 tests (scadaproj#45 / #52): the store-path rules compare
+/// locations, not spellings. Symlink cases run wherever links can be created; Windows-only spellings
+/// (drive-relative, device prefix, loopback admin share, local share, 8.3) are skipped elsewhere.
+///
+public sealed class GatewayConfigPathSpellingTests : IDisposable
+{
+ private readonly string _base;
+
+ public GatewayConfigPathSpellingTests()
+ {
+ _base = Path.Combine(Path.GetTempPath(), $"mxgw-spelling-{Guid.NewGuid():N}");
+ Directory.CreateDirectory(Path.Combine(_base, "app", "data"));
+ Directory.CreateDirectory(Path.Combine(_base, "outside"));
+ }
+
+ public void Dispose()
+ {
+ try
+ {
+ Directory.Delete(_base, recursive: true);
+ }
+ catch (IOException)
+ {
+ // best-effort temp cleanup
+ }
+ }
+
+ private static bool Inside(string value, string root)
+ {
+ ValidationBuilder builder = new();
+ GatewayConfigPathRules.AddIfUnderContentRoot(value, root, "inside", builder);
+ return !builder.IsValid;
+ }
+
+ private static bool NotRooted(string value)
+ {
+ ValidationBuilder builder = new();
+ GatewayConfigPathRules.AddIfNotRooted(value, "relative", builder);
+ return !builder.IsValid;
+ }
+
+ private static bool TryLink(string link, string target)
+ {
+ try
+ {
+ Directory.CreateSymbolicLink(link, target);
+ return true;
+ }
+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
+ {
+ return false; // Windows without the symlink privilege
+ }
+ }
+
+ /// Verifies a store reached through a symlink to the content root is inside it.
+ [Fact]
+ public void StoreThroughSymlinkIntoContentRoot_IsInside()
+ {
+ string root = Path.Combine(_base, "app");
+ string link = Path.Combine(_base, "alias");
+ if (!TryLink(link, root))
+ {
+ return;
+ }
+
+ Assert.True(Inside(Path.Combine(root, "data", "secrets.db"), root)); // positive control
+ Assert.True(Inside(Path.Combine(link, "data", "secrets.db"), root));
+ }
+
+ /// Verifies a content root reached through a "current" link still contains its store.
+ [Fact]
+ public void ContentRootThroughCurrentSymlink_StillContainsStore()
+ {
+ string real = Path.Combine(_base, "app");
+ string current = Path.Combine(_base, "current");
+ if (!TryLink(current, real))
+ {
+ return;
+ }
+
+ Assert.True(Inside(Path.Combine(real, "data", "secrets.db"), current));
+ Assert.True(Inside(Path.Combine(current, "data", "secrets.db"), real));
+ }
+
+ /// Verifies a store spelled through the content root stays refused even if a link leads out.
+ [Fact]
+ public void StoreSpelledThroughContentRoot_StaysRefused_EvenIfLinkLeadsOut()
+ {
+ string root = Path.Combine(_base, "app");
+ string link = Path.Combine(root, "durable");
+ if (!TryLink(link, Path.Combine(_base, "outside")))
+ {
+ return;
+ }
+
+ Assert.True(Inside(Path.Combine(link, "secrets.db"), root));
+ Assert.False(Inside(Path.Combine(_base, "outside", "secrets.db"), root)); // control
+ }
+
+ /// Verifies a not-yet-created store is compared as written.
+ [Fact]
+ public void NotYetCreatedStore_IsComparedAsWritten()
+ {
+ string root = Path.Combine(_base, "app");
+ Assert.True(Inside(Path.Combine(root, "new", "deeper", "secrets.db"), root));
+ Assert.False(Inside(Path.Combine(_base, "outside", "new", "secrets.db"), root));
+ }
+
+ /// Verifies drive-relative and root-relative paths are not fully qualified on Windows.
+ [WindowsOnlyFact]
+ public void DriveAndRootRelativePaths_AreNotAbsoluteOnWindows()
+ {
+ Assert.True(NotRooted(@"C:secrets.db"));
+ Assert.True(NotRooted(@"\secrets.db"));
+ Assert.False(NotRooted(@"C:\data\secrets.db"));
+ Assert.False(NotRooted(@"\\server\share\secrets.db"));
+ }
+
+ /// Verifies device-prefixed and loopback admin share spellings are inside on Windows.
+ [WindowsOnlyFact]
+ public void DevicePrefixedAndLoopbackShareSpellings_AreInsideOnWindows()
+ {
+ string root = Path.Combine(_base, "app");
+ string full = Path.GetFullPath(Path.Combine(root, "data", "secrets.db"));
+ string drive = full[..1];
+ string rest = full[3..];
+
+ Assert.True(Inside(@"\\?\" + full, root));
+ Assert.True(Inside(@"\\.\" + full, root));
+ Assert.True(Inside($@"\\localhost\{drive}$\{rest}", root));
+ Assert.True(Inside($@"\\127.0.0.1\{drive}$\{rest}", root));
+ Assert.True(Inside($@"\\?\UNC\localhost\{drive}$\{rest}", root));
+ }
+
+ /// Verifies an 8.3 short-name spelling is inside on Windows (skips quietly if 8.3 is disabled).
+ [WindowsOnlyFact]
+ public void ShortNameSpelling_IsInsideOnWindows()
+ {
+ string longDir = Path.Combine(_base, "Application Directory");
+ Directory.CreateDirectory(longDir);
+ string? shortDir = ShortName(longDir);
+ if (shortDir is null || !shortDir.Contains('~'))
+ {
+ return; // 8.3 names disabled on this volume
+ }
+
+ Assert.True(Inside(Path.Combine(shortDir, "secrets.db"), longDir));
+ Assert.True(Inside(Path.Combine(longDir, "secrets.db"), shortDir));
+ }
+
+ /// Verifies an ordinary local share that points at the content root is inside on Windows.
+ [WindowsOnlyFact]
+ public void OrdinaryLocalShareToContentRoot_IsInsideOnWindows()
+ {
+ string root = Path.Combine(_base, "app");
+ string share = "mxgwtest" + Guid.NewGuid().ToString("N")[..8];
+ ShareInfo2 info = new() { shi2_netname = share, shi2_max_uses = uint.MaxValue, shi2_path = root };
+ if (NetShareAdd(null, 2, ref info, out _) != 0)
+ {
+ return; // needs Administrators
+ }
+
+ try
+ {
+ Assert.True(Inside($@"\\localhost\{share}\data\secrets.db", root));
+ Assert.True(Inside($@"\\{Environment.MachineName}\{share}\secrets.db", root));
+ Assert.False(Inside($@"\\localhost\{share}\secrets.db", Path.Combine(_base, "outside")));
+ }
+ finally
+ {
+ _ = NetShareDel(null, share, 0);
+ }
+ }
+
+ private static string? ShortName(string path)
+ {
+ char[] buffer = new char[1024];
+ uint n = GetShortPathNameW(path, buffer, (uint)buffer.Length);
+ return n == 0 ? null : new string(buffer, 0, (int)n);
+ }
+
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
+ private struct ShareInfo2
+ {
+ public string shi2_netname;
+ public uint shi2_type;
+ public string? shi2_remark;
+ public uint shi2_permissions;
+ public uint shi2_max_uses;
+ public uint shi2_current_uses;
+ public string shi2_path;
+ public string? shi2_passwd;
+ }
+
+ [DllImport("netapi32.dll", CharSet = CharSet.Unicode)]
+ private static extern uint NetShareAdd(string? server, uint level, ref ShareInfo2 buf, out uint parmErr);
+
+ [DllImport("netapi32.dll", CharSet = CharSet.Unicode)]
+ private static extern uint NetShareDel(string? server, string netName, uint reserved);
+
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
+ private static extern uint GetShortPathNameW(string longPath, [Out] char[] shortPath, uint size);
+}