using System.Buffers.Binary;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using XFEToolBox.Client.Core.Search;
namespace XFEToolBox.Test;
public static class NtfsVolumeScannerTests
{
[Test]
public static void NtfsScannerNativeLayoutsMatchWindowsDwordAlignment()
{
var information = typeof(NtfsVolumeScanner).GetNestedType("ByHandleFileInformation", BindingFlags.NonPublic)!;
var request = typeof(NtfsVolumeScanner).GetNestedType("MftEnumData", BindingFlags.NonPublic)!;
Ensure(Marshal.SizeOf(information) == 52 && Marshal.OffsetOf(information, "FileIndexHigh") == 44 &&
Marshal.OffsetOf(information, "FileIndexLow") == 48 && Marshal.SizeOf(request) == 24,
"Win32 FILETIME's DWORD alignment must not be replaced with C# long alignment.");
}
[Test]
public static void NtfsParserReadsV2AndV3WithoutTruncatingFileIds()
{
var id = new NtfsFileId(0x0007000000001234, 0xfedcba9876543210);
var parent = new NtfsFileId(0x0004000000005678, 0x1234567890abcdef);
var v2 = Record(2, id with { High = 0 }, parent with { High = 0 }, "文档-Report.txt", 0x20);
var v3 = Record(3, id, parent, "Projects", 0x10);
Ensure(NtfsVolumeScanner.TryReadRecord(v2, out var parsedV2) && parsedV2.Id == id with { High = 0 } &&
parsedV2.ParentId == parent with { High = 0 } && parsedV2.Name == "文档-Report.txt" && !parsedV2.IsDirectory,
"USN v2 must use FileNameOffset/Length and retain the complete 64-bit file reference.");
Ensure(NtfsVolumeScanner.TryReadRecord(v3, out var parsedV3) && parsedV3.Id == id &&
parsedV3.ParentId == parent && parsedV3.Name == "Projects" && parsedV3.IsDirectory,
"USN v3 must retain both halves of its 128-bit file and parent references.");
}
[Test]
public static void NtfsParserRejectsInvalidBoundsVersionsAndTraversal()
{
var valid = Record(2, new(70, 0), new(50, 0), "valid.txt", 0x20);
var length = valid.ToArray();
BinaryPrimitives.WriteUInt32LittleEndian(length, (uint)length.Length + 8);
Ensure(!NtfsVolumeScanner.TryReadRecord(length, out _), "An oversized record must fail closed.");
var oddName = valid.ToArray();
BinaryPrimitives.WriteUInt16LittleEndian(oddName.AsSpan(56), 3);
Ensure(!NtfsVolumeScanner.TryReadRecord(oddName, out _), "UTF-16 byte lengths must be even.");
var headerName = valid.ToArray();
BinaryPrimitives.WriteUInt16LittleEndian(headerName.AsSpan(58), 8);
Ensure(!NtfsVolumeScanner.TryReadRecord(headerName, out _), "A filename cannot point into the fixed header.");
var unknown = valid.ToArray();
BinaryPrimitives.WriteUInt16LittleEndian(unknown.AsSpan(4), 4);
Ensure(!NtfsVolumeScanner.TryReadRecord(unknown, out _), "Unsupported versions must trigger fallback, not silent data loss.");
foreach (var name in new[] { "..", ".", "escape\\file", "escape/file", "file:stream", "null\0name" })
Ensure(!NtfsVolumeScanner.TryReadRecord(Record(2, new(70, 0), new(50, 0), name, 0x20), out _),
"A raw record must not escape its validated parent directory.");
var rootId = new NtfsFileId(0x0005000000000005, 0);
Ensure(NtfsVolumeScanner.TryReadRecord(Record(2, rootId, rootId, ".", 0x10), out _),
"The self-parented NTFS root's '.' name must be accepted.");
}
[Test]
public static void NtfsParserFiltersDirectoryTopologyAndHonorsCancellation()
{
var file = Record(2, new(70, 0), new(50, 0), "file.txt", 0x20);
var directory = Record(3, new(50, 4), new(60, 3), "folder", 0x10);
var buffer = file.Concat(directory).ToArray();
var parsed = new List<NtfsUsnRecord>();
Ensure(NtfsVolumeScanner.ParseBuffer(buffer, true, parsed.Add) && parsed.Count == 1 && parsed[0].IsDirectory,
"The topology pass must only retain directory records.");
parsed.Clear();
Ensure(NtfsVolumeScanner.ParseBuffer(buffer, false, parsed.Add) && parsed.Count == 2,
"The publication pass must process all valid file and directory records.");
var truncated = buffer[..^1];
Ensure(!NtfsVolumeScanner.ParseBuffer(truncated, false, _ => { }), "Truncated buffers must require ordinary fallback.");
using var cancellation = new CancellationTokenSource();
cancellation.Cancel();
try
{
NtfsVolumeScanner.ParseBuffer(buffer, false, _ => { }, cancellation.Token);
throw new InvalidOperationException("USN parsing ignored cancellation.");
}
catch (OperationCanceledException) { }
}
[Test]
public static void NtfsResolverChecksEveryAncestorOnceAndRejectsDeniedSubtrees()
{
var root = new NtfsFileId(5, 0);
var accessible = new NtfsFileId(30, 0);
var denied = new NtfsFileId(40, 0);
var child = new NtfsFileId(50, 0);
var nodes = new Dictionary<NtfsFileId, NtfsDirectoryNode>
{
[accessible] = new(accessible, root, "Allowed", 0x10),
[denied] = new(denied, accessible, "Denied", 0x10),
[child] = new(child, denied, "Secret", 0x10)
};
var checks = new List<string>();
var resolver = new NtfsDirectoryResolver(@"C:\", root, nodes, (path, id) =>
{
checks.Add(path);
return id != denied;
});
Ensure(resolver.Resolve(child) is null && resolver.Resolve(child) is null,
"An inaccessible ancestor must hide all descendant MFT names.");
Ensure(checks.SequenceEqual(new[] { @"C:\Allowed", @"C:\Allowed\Denied" }),
"Ancestor ACL checks must be parent-first, cached, and stop at denial.");
Ensure(resolver.Resolve(accessible) == @"C:\Allowed" && checks.Count == 2,
"Validated directory paths should be reused without per-file disk operations.");
}
[Test]
public static void NtfsResolverRejectsReparseMissingParentsAndCycles()
{
var root = new NtfsFileId(5, 0);
var link = new NtfsFileId(30, 0);
var linkChild = new NtfsFileId(31, 0);
var orphan = new NtfsFileId(40, 0);
var cycleA = new NtfsFileId(50, 0);
var cycleB = new NtfsFileId(51, 0);
var nodes = new Dictionary<NtfsFileId, NtfsDirectoryNode>
{
[link] = new(link, root, "Junction", 0x410),
[linkChild] = new(linkChild, link, "Outside", 0x10),
[orphan] = new(orphan, new(41, 0), "Orphan", 0x10),
[cycleA] = new(cycleA, cycleB, "CycleA", 0x10),
[cycleB] = new(cycleB, cycleA, "CycleB", 0x10)
};
var checks = 0;
var resolver = new NtfsDirectoryResolver(@"C:\", root, nodes, (_, _) => { checks++; return true; });
Ensure(resolver.Resolve(linkChild) is null && resolver.Resolve(orphan) is null &&
resolver.Resolve(cycleA) is null && resolver.Resolve(cycleB) is null && checks == 0,
"Untrusted directory topology must fail closed without following links or cycling.");
}
[Test]
public static void NtfsResolverHandlesDeepTreesIteratively()
{
const int depth = 1024;
var root = new NtfsFileId(5, 0);
var nodes = new Dictionary<NtfsFileId, NtfsDirectoryNode>();
var parent = root;
for (var index = 0; index < depth; index++)
{
var id = new NtfsFileId((ulong)(index + 20), 0);
nodes[id] = new(id, parent, "d", 0x10);
parent = id;
}
var checks = 0;
var resolver = new NtfsDirectoryResolver(@"C:\", root, nodes, (_, _) => { checks++; return true; });
Ensure(resolver.Resolve(parent)?.Length == 3 + depth * 2 - 1 && checks == depth,
"A deep directory chain must resolve without recursive stack growth.");
Ensure(resolver.Resolve(parent) is not null && checks == depth, "Deep cached resolution should be constant-time.");
}
[Test]
public static void NtfsScannerDoesNotProbeNonVolumeScopesOrIgnoreCancellation()
{
foreach (var path in new[] { @"C:\Users", @"\\server\share", @"\\?\C:\", "/", "relative", "" })
Ensure(!NtfsVolumeScanner.TryScan(path, _ => throw new InvalidOperationException("No batches expected.")),
"Custom folders and remote paths must use ordinary directory enumeration.");
Ensure(NtfsVolumeScanner.TryNormalizeVolumeRoot("c:/", out var root) && root == @"C:\",
"An eligible DOS volume root should have a single canonical spelling.");
using var cancellation = new CancellationTokenSource();
cancellation.Cancel();
try
{
NtfsVolumeScanner.TryScan(@"C:\", _ => { }, cancellation.Token);
throw new InvalidOperationException("A cancelled scan must not open the volume.");
}
catch (OperationCanceledException) { }
Ensure(new NtfsUsnRecord(new(0x0012000000000000, 0), ParentId: default, Name: "$MFT", Attributes: 0).IsNtfsMetadata,
"NTFS reserved metadata records must not be published as ordinary user files.");
}
private static byte[] Record(ushort major, NtfsFileId id, NtfsFileId parent, string name, uint attributes)
{
var encoded = Encoding.Unicode.GetBytes(name);
var header = major == 3 ? 76 : 60;
var length = (header + 8 + encoded.Length + 7) & ~7;
var bytes = new byte[length];
BinaryPrimitives.WriteUInt32LittleEndian(bytes, (uint)length);
BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(4), major);
BinaryPrimitives.WriteUInt64LittleEndian(bytes.AsSpan(8), id.Low);
if (major == 3)
BinaryPrimitives.WriteUInt64LittleEndian(bytes.AsSpan(16), id.High);
var parentOffset = major == 3 ? 24 : 16;
BinaryPrimitives.WriteUInt64LittleEndian(bytes.AsSpan(parentOffset), parent.Low);
if (major == 3)
BinaryPrimitives.WriteUInt64LittleEndian(bytes.AsSpan(parentOffset + 8), parent.High);
var attributesOffset = major == 3 ? 68 : 52;
BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(attributesOffset), attributes);
BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(attributesOffset + 4), (ushort)encoded.Length);
BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(attributesOffset + 6), (ushort)(header + 8));
encoded.CopyTo(bytes.AsSpan(header + 8));
return bytes;
}
private static void Ensure(bool condition, string message)
{
if (!condition)
throw new InvalidOperationException(message);
}
}
using System.Buffers.Binary;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using XFEToolBox.Client.Core.Search;
namespace XFEToolBox.Test;
public static class NtfsVolumeScannerTests
{
[Test]
public static void NtfsScannerNativeLayoutsMatchWindowsDwordAlignment()
{
var information = typeof(NtfsVolumeScanner).GetNestedType("ByHandleFileInformation", BindingFlags.NonPublic)!;
var request = typeof(NtfsVolumeScanner).GetNestedType("MftEnumData", BindingFlags.NonPublic)!;
Ensure(Marshal.SizeOf(information) == 52 && Marshal.OffsetOf(information, "FileIndexHigh") == 44 &&
Marshal.OffsetOf(information, "FileIndexLow") == 48 && Marshal.SizeOf(request) == 24,
"Win32 FILETIME's DWORD alignment must not be replaced with C# long alignment.");
}
[Test]
public static void NtfsParserReadsV2AndV3WithoutTruncatingFileIds()
{
var id = new NtfsFileId(0x0007000000001234, 0xfedcba9876543210);
var parent = new NtfsFileId(0x0004000000005678, 0x1234567890abcdef);
var v2 = Record(2, id with { High = 0 }, parent with { High = 0 }, "文档-Report.txt", 0x20);
var v3 = Record(3, id, parent, "Projects", 0x10);
Ensure(NtfsVolumeScanner.TryReadRecord(v2, out var parsedV2) && parsedV2.Id == id with { High = 0 } &&
parsedV2.ParentId == parent with { High = 0 } && parsedV2.Name == "文档-Report.txt" && !parsedV2.IsDirectory,
"USN v2 must use FileNameOffset/Length and retain the complete 64-bit file reference.");
Ensure(NtfsVolumeScanner.TryReadRecord(v3, out var parsedV3) && parsedV3.Id == id &&
parsedV3.ParentId == parent && parsedV3.Name == "Projects" && parsedV3.IsDirectory,
"USN v3 must retain both halves of its 128-bit file and parent references.");
}
[Test]
public static void NtfsParserRejectsInvalidBoundsVersionsAndTraversal()
{
var valid = Record(2, new(70, 0), new(50, 0), "valid.txt", 0x20);
var length = valid.ToArray();
BinaryPrimitives.WriteUInt32LittleEndian(length, (uint)length.Length + 8);
Ensure(!NtfsVolumeScanner.TryReadRecord(length, out _), "An oversized record must fail closed.");
var oddName = valid.ToArray();
BinaryPrimitives.WriteUInt16LittleEndian(oddName.AsSpan(56), 3);
Ensure(!NtfsVolumeScanner.TryReadRecord(oddName, out _), "UTF-16 byte lengths must be even.");
var headerName = valid.ToArray();
BinaryPrimitives.WriteUInt16LittleEndian(headerName.AsSpan(58), 8);
Ensure(!NtfsVolumeScanner.TryReadRecord(headerName, out _), "A filename cannot point into the fixed header.");
var unknown = valid.ToArray();
BinaryPrimitives.WriteUInt16LittleEndian(unknown.AsSpan(4), 4);
Ensure(!NtfsVolumeScanner.TryReadRecord(unknown, out _), "Unsupported versions must trigger fallback, not silent data loss.");
foreach (var name in new[] { "..", ".", "escape\\file", "escape/file", "file:stream", "null\0name" })
Ensure(!NtfsVolumeScanner.TryReadRecord(Record(2, new(70, 0), new(50, 0), name, 0x20), out _),
"A raw record must not escape its validated parent directory.");
var rootId = new NtfsFileId(0x0005000000000005, 0);
Ensure(NtfsVolumeScanner.TryReadRecord(Record(2, rootId, rootId, ".", 0x10), out _),
"The self-parented NTFS root's '.' name must be accepted.");
}
[Test]
public static void NtfsParserFiltersDirectoryTopologyAndHonorsCancellation()
{
var file = Record(2, new(70, 0), new(50, 0), "file.txt", 0x20);
var directory = Record(3, new(50, 4), new(60, 3), "folder", 0x10);
var buffer = file.Concat(directory).ToArray();
var parsed = new List<NtfsUsnRecord>();
Ensure(NtfsVolumeScanner.ParseBuffer(buffer, true, parsed.Add) && parsed.Count == 1 && parsed[0].IsDirectory,
"The topology pass must only retain directory records.");
parsed.Clear();
Ensure(NtfsVolumeScanner.ParseBuffer(buffer, false, parsed.Add) && parsed.Count == 2,
"The publication pass must process all valid file and directory records.");
var truncated = buffer[..^1];
Ensure(!NtfsVolumeScanner.ParseBuffer(truncated, false, _ => { }), "Truncated buffers must require ordinary fallback.");
using var cancellation = new CancellationTokenSource();
cancellation.Cancel();
try
{
NtfsVolumeScanner.ParseBuffer(buffer, false, _ => { }, cancellation.Token);
throw new InvalidOperationException("USN parsing ignored cancellation.");
}
catch (OperationCanceledException) { }
}
[Test]
public static void NtfsResolverChecksEveryAncestorOnceAndRejectsDeniedSubtrees()
{
var root = new NtfsFileId(5, 0);
var accessible = new NtfsFileId(30, 0);
var denied = new NtfsFileId(40, 0);
var child = new NtfsFileId(50, 0);
var nodes = new Dictionary<NtfsFileId, NtfsDirectoryNode>
{
[accessible] = new(accessible, root, "Allowed", 0x10),
[denied] = new(denied, accessible, "Denied", 0x10),
[child] = new(child, denied, "Secret", 0x10)
};
var checks = new List<string>();
var resolver = new NtfsDirectoryResolver(@"C:\", root, nodes, (path, id) =>
{
checks.Add(path);
return id != denied;
});
Ensure(resolver.Resolve(child) is null && resolver.Resolve(child) is null,
"An inaccessible ancestor must hide all descendant MFT names.");
Ensure(checks.SequenceEqual(new[] { @"C:\Allowed", @"C:\Allowed\Denied" }),
"Ancestor ACL checks must be parent-first, cached, and stop at denial.");
Ensure(resolver.Resolve(accessible) == @"C:\Allowed" && checks.Count == 2,
"Validated directory paths should be reused without per-file disk operations.");
}
[Test]
public static void NtfsResolverRejectsReparseMissingParentsAndCycles()
{
var root = new NtfsFileId(5, 0);
var link = new NtfsFileId(30, 0);
var linkChild = new NtfsFileId(31, 0);
var orphan = new NtfsFileId(40, 0);
var cycleA = new NtfsFileId(50, 0);
var cycleB = new NtfsFileId(51, 0);
var nodes = new Dictionary<NtfsFileId, NtfsDirectoryNode>
{
[link] = new(link, root, "Junction", 0x410),
[linkChild] = new(linkChild, link, "Outside", 0x10),
[orphan] = new(orphan, new(41, 0), "Orphan", 0x10),
[cycleA] = new(cycleA, cycleB, "CycleA", 0x10),
[cycleB] = new(cycleB, cycleA, "CycleB", 0x10)
};
var checks = 0;
var resolver = new NtfsDirectoryResolver(@"C:\", root, nodes, (_, _) => { checks++; return true; });
Ensure(resolver.Resolve(linkChild) is null && resolver.Resolve(orphan) is null &&
resolver.Resolve(cycleA) is null && resolver.Resolve(cycleB) is null && checks == 0,
"Untrusted directory topology must fail closed without following links or cycling.");
}
[Test]
public static void NtfsResolverHandlesDeepTreesIteratively()
{
const int depth = 1024;
var root = new NtfsFileId(5, 0);
var nodes = new Dictionary<NtfsFileId, NtfsDirectoryNode>();
var parent = root;
for (var index = 0; index < depth; index++)
{
var id = new NtfsFileId((ulong)(index + 20), 0);
nodes[id] = new(id, parent, "d", 0x10);
parent = id;
}
var checks = 0;
var resolver = new NtfsDirectoryResolver(@"C:\", root, nodes, (_, _) => { checks++; return true; });
Ensure(resolver.Resolve(parent)?.Length == 3 + depth * 2 - 1 && checks == depth,
"A deep directory chain must resolve without recursive stack growth.");
Ensure(resolver.Resolve(parent) is not null && checks == depth, "Deep cached resolution should be constant-time.");
}
[Test]
public static void NtfsScannerDoesNotProbeNonVolumeScopesOrIgnoreCancellation()
{
foreach (var path in new[] { @"C:\Users", @"\\server\share", @"\\?\C:\", "/", "relative", "" })
Ensure(!NtfsVolumeScanner.TryScan(path, _ => throw new InvalidOperationException("No batches expected.")),
"Custom folders and remote paths must use ordinary directory enumeration.");
Ensure(NtfsVolumeScanner.TryNormalizeVolumeRoot("c:/", out var root) && root == @"C:\",
"An eligible DOS volume root should have a single canonical spelling.");
using var cancellation = new CancellationTokenSource();
cancellation.Cancel();
try
{
NtfsVolumeScanner.TryScan(@"C:\", _ => { }, cancellation.Token);
throw new InvalidOperationException("A cancelled scan must not open the volume.");
}
catch (OperationCanceledException) { }
Ensure(new NtfsUsnRecord(new(0x0012000000000000, 0), ParentId: default, Name: "$MFT", Attributes: 0).IsNtfsMetadata,
"NTFS reserved metadata records must not be published as ordinary user files.");
}
private static byte[] Record(ushort major, NtfsFileId id, NtfsFileId parent, string name, uint attributes)
{
var encoded = Encoding.Unicode.GetBytes(name);
var header = major == 3 ? 76 : 60;
var length = (header + 8 + encoded.Length + 7) & ~7;
var bytes = new byte[length];
BinaryPrimitives.WriteUInt32LittleEndian(bytes, (uint)length);
BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(4), major);
BinaryPrimitives.WriteUInt64LittleEndian(bytes.AsSpan(8), id.Low);
if (major == 3)
BinaryPrimitives.WriteUInt64LittleEndian(bytes.AsSpan(16), id.High);
var parentOffset = major == 3 ? 24 : 16;
BinaryPrimitives.WriteUInt64LittleEndian(bytes.AsSpan(parentOffset), parent.Low);
if (major == 3)
BinaryPrimitives.WriteUInt64LittleEndian(bytes.AsSpan(parentOffset + 8), parent.High);
var attributesOffset = major == 3 ? 68 : 52;
BinaryPrimitives.WriteUInt32LittleEndian(bytes.AsSpan(attributesOffset), attributes);
BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(attributesOffset + 4), (ushort)encoded.Length);
BinaryPrimitives.WriteUInt16LittleEndian(bytes.AsSpan(attributesOffset + 6), (ushort)(header + 8));
encoded.CopyTo(bytes.AsSpan(header + 8));
return bytes;
}
private static void Ensure(bool condition, string message)
{
if (!condition)
throw new InvalidOperationException(message);
}
}