using System; using System.Diagnostics; using System.IO; using System.IO.Pipes; using System.Security.AccessControl; using System.Security.Cryptography; using System.Security.Principal; using System.Text; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using ClassNotify.Service.Ipc; using ClassNotify.Service.Services; using ClassNotify.Shared.Models; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace ClassNotify.EdgeSecurityTests; public class Program { private static int _passedTests = 0; private static int _failedTests = 0; public static async Task Main(string[] args) { Console.WriteLine("=========================================================="); Console.WriteLine(" ClassNotify P1 Batch 8: Edge Security Test Suite "); Console.WriteLine("=========================================================="); await RunTestAsync("Credential: Legacy Plaintext JSON Auto-Migration", Test_LegacyPlaintext_AutoMigration); await RunTestAsync("Credential: DPAPI LocalMachine Encryption Verification", Test_DPAPI_LocalMachine_Encryption); await RunTestAsync("Credential: Hardened NTFS File ACL Protection", Test_NTFS_FileAcl_Protection); await RunTestAsync("Credential: ACL Fail-Closed & Temp Cleanup Verification", Test_NTFS_Acl_FailClosed_And_Cleanup); await RunTestAsync("Credential: Strict ACL Allowlist Invariant Rejects Arbitrary SIDs", Test_NTFS_Acl_StrictAllowlist_RejectsArbitrarySid); await RunTestAsync("Setup: StartupManager Cleans Legacy Run & Scheduled Tasks", Test_Setup_StartupManager_CleansLegacyEntries); await RunTestAsync("NamedPipe: Rejects Legacy Protocol 1 Public Hello Without Token", Test_NamedPipe_Rejects_LegacyProtocol1_PublicHello); await RunTestAsync("NamedPipe: Rejects Handshake With Invalid Launch Token", Test_NamedPipe_Rejects_InvalidToken); await RunTestAsync("NamedPipe: Rejects Handshake With Mismatched Process Name", Test_NamedPipe_Rejects_MismatchedProcessName); await RunTestAsync("NamedPipe: Accepts Valid Protocol 2 Launch Token & PID", Test_NamedPipe_Accepts_ValidToken_And_MatchingPid); await RunTestAsync("NamedPipe: Token Rotation & Reconnection Verification", Test_NamedPipe_TokenRotation_OnCrash); await RunTestAsync("NamedPipe: SessionLauncher Fallback Fail-Closed Verification", Test_SessionLauncher_Fallback_FailClosed); await RunTestAsync("NamedPipe: Zero Secret Token Leakage In Audit Logs", Test_NamedPipe_HandshakeLog_ZeroTokenLeakage); Console.WriteLine("\n=========================================================="); Console.WriteLine($" Test Results: {_passedTests} Passed, {_failedTests} Failed"); Console.WriteLine("=========================================================="); return _failedTests == 0 ? 0 : 1; } private static async Task RunTestAsync(string testName, Func testAction) { try { await testAction(); Console.WriteLine($"[PASS] {testName}"); _passedTests++; } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"[FAIL] {testName}"); Console.WriteLine($" Exception: {ex.Message}"); Console.WriteLine($" StackTrace: {ex.StackTrace}"); Console.ResetColor(); _failedTests++; } } private static async Task Test_LegacyPlaintext_AutoMigration() { var tempFile = Path.Combine(Path.GetTempPath(), $"test_creds_{Guid.NewGuid():N}.json"); try { var rawSecretToken = "device_token_secret_1234567890abcdef"; var legacyJson = JsonSerializer.Serialize(new DeviceCredentials { DeviceId = "dev_legacy_01", DeviceToken = rawSecretToken, TenantId = "tenant_test", ClassId = "class_101", ClassDisplayName = "三年二班", ActivatedAt = DateTimeOffset.UtcNow }, new JsonSerializerOptions { WriteIndented = true }); await File.WriteAllTextAsync(tempFile, legacyJson); // Verify it was indeed written as plaintext var writtenBytes = await File.ReadAllBytesAsync(tempFile); var writtenText = Encoding.UTF8.GetString(writtenBytes); if (!writtenText.Contains(rawSecretToken)) { throw new Exception("Setup error: File does not contain raw secret token."); } // Load via DeviceCredentialProtector var loaded = DeviceCredentialProtector.LoadCredentials(tempFile); if (loaded == null) throw new Exception("LoadCredentials returned null."); if (loaded.DeviceId != "dev_legacy_01") throw new Exception($"Expected dev_legacy_01, got {loaded.DeviceId}"); if (loaded.DeviceToken != rawSecretToken) throw new Exception("DeviceToken mismatch."); // Verify file was migrated to encrypted ciphertext var migratedBytes = await File.ReadAllBytesAsync(tempFile); var migratedText = Encoding.UTF8.GetString(migratedBytes); if (migratedText.Contains(rawSecretToken)) { throw new Exception("Vulnerability: Raw secret token is still present in plaintext after migration!"); } if (migratedBytes[0] == (byte)'{') { throw new Exception("File still starts with JSON object delimiter '{' after migration!"); } // Verify second load correctly decrypts the migrated file var secondLoad = DeviceCredentialProtector.LoadCredentials(tempFile); if (secondLoad == null) throw new Exception("Second load failed to decrypt migrated file."); if (secondLoad.DeviceToken != rawSecretToken) throw new Exception("Second load returned mismatched token."); } finally { if (File.Exists(tempFile)) File.Delete(tempFile); } } private static async Task Test_DPAPI_LocalMachine_Encryption() { var tempFile = Path.Combine(Path.GetTempPath(), $"test_dpapi_{Guid.NewGuid():N}.json"); try { var originalCreds = new DeviceCredentials { DeviceId = "dev_dpapi_test", DeviceToken = "super_secure_token_xyz999", TenantId = "tenant_demo", ClassId = "class_demo", ClassDisplayName = "高一(1)班", ActivatedAt = DateTimeOffset.UtcNow }; DeviceCredentialProtector.SaveCredentials(tempFile, originalCreds); var encryptedBytes = await File.ReadAllBytesAsync(tempFile); if (encryptedBytes.Length == 0) throw new Exception("Encrypted file is empty."); // Verify raw byte decryption using DPAPI LocalMachine with entropy var entropy = Encoding.UTF8.GetBytes("ClassNotify_Device_Credential_V1"); var decryptedRaw = ProtectedData.Unprotect(encryptedBytes, entropy, DataProtectionScope.LocalMachine); var decryptedJson = Encoding.UTF8.GetString(decryptedRaw); if (!decryptedJson.Contains("super_secure_token_xyz999")) { throw new Exception("Decrypted JSON did not contain expected token."); } } finally { if (File.Exists(tempFile)) File.Delete(tempFile); } } private static async Task Test_NTFS_FileAcl_Protection() { await Task.Yield(); var tempFile = Path.Combine(Path.GetTempPath(), $"test_acl_{Guid.NewGuid():N}.json"); try { var creds = new DeviceCredentials { DeviceId = "dev_acl_test", DeviceToken = "token_acl_123" }; DeviceCredentialProtector.SaveCredentials(tempFile, creds); var fileInfo = new FileInfo(tempFile); var fileSecurity = fileInfo.GetAccessControl(); // Verify inheritance is disabled if (!fileSecurity.AreAccessRulesProtected) { throw new Exception("Access rules are not protected (inheritance should be disabled)."); } var rules = fileSecurity.GetAccessRules(true, false, typeof(SecurityIdentifier)); bool systemFull = false; bool adminFull = false; bool userAllowed = false; var systemSid = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null); var adminSid = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null); var usersSid = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null); var everyoneSid = new SecurityIdentifier(WellKnownSidType.WorldSid, null); foreach (FileSystemAccessRule rule in rules) { if (rule.IdentityReference.Equals(systemSid) && (rule.FileSystemRights & FileSystemRights.FullControl) == FileSystemRights.FullControl) { systemFull = true; } if (rule.IdentityReference.Equals(adminSid) && (rule.FileSystemRights & FileSystemRights.FullControl) == FileSystemRights.FullControl) { adminFull = true; } if (rule.IdentityReference.Equals(usersSid) || rule.IdentityReference.Equals(everyoneSid)) { if (rule.AccessControlType == AccessControlType.Allow) { userAllowed = true; } } } if (!systemFull) throw new Exception("SYSTEM was not granted FullControl."); if (!adminFull) throw new Exception("Administrators was not granted FullControl."); if (userAllowed) throw new Exception("Vulnerability: Ordinary Users / Everyone group was granted Access on credentials file."); } finally { if (File.Exists(tempFile)) File.Delete(tempFile); } } private static async Task Test_NamedPipe_Rejects_LegacyProtocol1_PublicHello() { string pipeName = $"CN_Test_Pipe_{Guid.NewGuid():N}"; var config = new ConfigurationBuilder() .AddInMemoryCollection(new[] { new KeyValuePair("ClassNotify:PipeName", pipeName) }) .Build(); using var loggerFactory = LoggerFactory.Create(b => b.AddConsole().SetMinimumLevel(LogLevel.Warning)); var logger = loggerFactory.CreateLogger(); var server = new NamedPipeServer(config, logger); using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); server.StartListening(cts.Token); await Task.Delay(500); // Give server time to create pipe // Connect client with Protocol 1 hello (no token) using var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous); await client.ConnectAsync(3000); using var writer = new StreamWriter(client, Encoding.UTF8) { AutoFlush = true }; var legacyHandshake = JsonSerializer.Serialize(new { type = "hello", client = "ClassNotify.Client", protocolVersion = 1 }); await writer.WriteLineAsync(legacyHandshake); await Task.Delay(500); if (server.IsClientConnected) { throw new Exception("Security Failure: NamedPipeServer authenticated a legacy Protocol 1 connection without token!"); } } private static async Task Test_NamedPipe_Rejects_InvalidToken() { string pipeName = $"CN_Test_Pipe_{Guid.NewGuid():N}"; var config = new ConfigurationBuilder() .AddInMemoryCollection(new[] { new KeyValuePair("ClassNotify:PipeName", pipeName) }) .Build(); using var loggerFactory = LoggerFactory.Create(b => b.AddConsole().SetMinimumLevel(LogLevel.Warning)); var logger = loggerFactory.CreateLogger(); var server = new NamedPipeServer(config, logger); server.ExpectedProcessName = Process.GetCurrentProcess().ProcessName; server.SetAuthorizedClient("valid_secret_token_111", Environment.ProcessId, (uint)Process.GetCurrentProcess().SessionId); using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); server.StartListening(cts.Token); await Task.Delay(500); using var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous); await client.ConnectAsync(3000); using var writer = new StreamWriter(client, Encoding.UTF8) { AutoFlush = true }; var invalidTokenHandshake = JsonSerializer.Serialize(new { type = "hello", client = "ClassNotify.Client", protocolVersion = 2, token = "wrong_counterfeit_token_999" }); await writer.WriteLineAsync(invalidTokenHandshake); await Task.Delay(500); if (server.IsClientConnected) { throw new Exception("Security Failure: NamedPipeServer authenticated a connection with an invalid token!"); } } private static async Task Test_NamedPipe_Rejects_MismatchedProcessName() { string pipeName = $"CN_Test_Pipe_{Guid.NewGuid():N}"; var config = new ConfigurationBuilder() .AddInMemoryCollection(new[] { new KeyValuePair("ClassNotify:PipeName", pipeName) }) .Build(); using var loggerFactory = LoggerFactory.Create(b => b.AddConsole().SetMinimumLevel(LogLevel.Warning)); var logger = loggerFactory.CreateLogger(); var server = new NamedPipeServer(config, logger); // By default ExpectedProcessName is "ClassNotify.Client". Since current process is not ClassNotify.Client, it must be rejected! server.SetAuthorizedClient("valid_token_333", Environment.ProcessId, (uint)Process.GetCurrentProcess().SessionId); using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); server.StartListening(cts.Token); await Task.Delay(500); using var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous); await client.ConnectAsync(3000); using var writer = new StreamWriter(client, Encoding.UTF8) { AutoFlush = true }; var handshake = JsonSerializer.Serialize(new { type = "hello", client = "ClassNotify.Client", protocolVersion = 2, token = "valid_token_333" }); await writer.WriteLineAsync(handshake); await Task.Delay(500); if (server.IsClientConnected) { throw new Exception("Security Failure: NamedPipeServer authenticated a process that does not match ExpectedProcessName!"); } } private static async Task Test_NamedPipe_Accepts_ValidToken_And_MatchingPid() { string pipeName = $"CN_Test_Pipe_{Guid.NewGuid():N}"; var config = new ConfigurationBuilder() .AddInMemoryCollection(new[] { new KeyValuePair("ClassNotify:PipeName", pipeName) }) .Build(); using var loggerFactory = LoggerFactory.Create(b => b.AddConsole().SetMinimumLevel(LogLevel.Warning)); var logger = loggerFactory.CreateLogger(); var server = new NamedPipeServer(config, logger); server.ExpectedProcessName = Process.GetCurrentProcess().ProcessName; string validToken = Guid.NewGuid().ToString("N"); server.SetAuthorizedClient(validToken, Environment.ProcessId, (uint)Process.GetCurrentProcess().SessionId); using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); server.StartListening(cts.Token); await Task.Delay(500); using var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous); await client.ConnectAsync(3000); using var writer = new StreamWriter(client, Encoding.UTF8) { AutoFlush = true }; var handshake = JsonSerializer.Serialize(new { type = "hello", client = "ClassNotify.Client", protocolVersion = 2, token = validToken }); await writer.WriteLineAsync(handshake); await Task.Delay(500); if (!server.IsClientConnected) { throw new Exception("NamedPipeServer failed to authenticate legitimate client with valid token and PID!"); } } private static async Task Test_NamedPipe_TokenRotation_OnCrash() { string pipeName = $"CN_Test_Pipe_{Guid.NewGuid():N}"; var config = new ConfigurationBuilder() .AddInMemoryCollection(new[] { new KeyValuePair("ClassNotify:PipeName", pipeName) }) .Build(); using var loggerFactory = LoggerFactory.Create(b => b.AddConsole().SetMinimumLevel(LogLevel.Warning)); var logger = loggerFactory.CreateLogger(); var server = new NamedPipeServer(config, logger); server.ExpectedProcessName = Process.GetCurrentProcess().ProcessName; string initialToken = Guid.NewGuid().ToString("N"); server.SetAuthorizedClient(initialToken, Environment.ProcessId, (uint)Process.GetCurrentProcess().SessionId); using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(15)); server.StartListening(cts.Token); await Task.Delay(500); // 1. Initial client connects using (var client1 = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous)) { await client1.ConnectAsync(3000); using var writer1 = new StreamWriter(client1, Encoding.UTF8) { AutoFlush = true }; await writer1.WriteLineAsync(JsonSerializer.Serialize(new { type = "hello", client = "ClassNotify.Client", protocolVersion = 2, token = initialToken })); await Task.Delay(500); if (!server.IsClientConnected) throw new Exception("Initial client connection failed."); } await Task.Delay(500); // 2. Simulate crash: invalidate authorization server.InvalidateAuthorization(); // 3. Attempt reconnect with OLD token -> must be rejected using (var clientOld = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous)) { await clientOld.ConnectAsync(3000); using var writerOld = new StreamWriter(clientOld, Encoding.UTF8) { AutoFlush = true }; await writerOld.WriteLineAsync(JsonSerializer.Serialize(new { type = "hello", client = "ClassNotify.Client", protocolVersion = 2, token = initialToken })); await Task.Delay(500); if (server.IsClientConnected) throw new Exception("Old token was accepted after invalidation!"); } await Task.Delay(500); // 4. Set NEW rotated token string rotatedToken = Guid.NewGuid().ToString("N"); server.SetAuthorizedClient(rotatedToken, Environment.ProcessId, (uint)Process.GetCurrentProcess().SessionId); // 5. Reconnect with NEW rotated token -> must succeed using (var clientNew = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous)) { await clientNew.ConnectAsync(3000); using var writerNew = new StreamWriter(clientNew, Encoding.UTF8) { AutoFlush = true }; await writerNew.WriteLineAsync(JsonSerializer.Serialize(new { type = "hello", client = "ClassNotify.Client", protocolVersion = 2, token = rotatedToken })); await Task.Delay(500); if (!server.IsClientConnected) throw new Exception("Rotated token was not accepted!"); } } private static async Task Test_NTFS_Acl_FailClosed_And_Cleanup() { // 1. Verify VerifyHardenedFileAcl throws if unauthorized identity is allowed var badFile = Path.Combine(Path.GetTempPath(), $"bad_acl_{Guid.NewGuid():N}.json"); try { await File.WriteAllTextAsync(badFile, "{}"); var fi = new FileInfo(badFile); var badSec = new FileSecurity(); badSec.SetAccessRuleProtection(true, false); // Add World (Everyone) rule badSec.AddAccessRule(new FileSystemAccessRule( new SecurityIdentifier(WellKnownSidType.WorldSid, null), FileSystemRights.Read, AccessControlType.Allow)); badSec.AddAccessRule(new FileSystemAccessRule( new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null), FileSystemRights.FullControl, AccessControlType.Allow)); badSec.AddAccessRule(new FileSystemAccessRule( new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null), FileSystemRights.FullControl, AccessControlType.Allow)); fi.SetAccessControl(badSec); bool caughtInsecure = false; try { DeviceCredentialProtector.VerifyHardenedFileAcl(badFile); } catch (InvalidOperationException) { caughtInsecure = true; } if (!caughtInsecure) throw new Exception("VerifyHardenedFileAcl did not reject insecure Everyone ACL!"); } finally { if (File.Exists(badFile)) File.Delete(badFile); } // 2. Verify SaveCredentials fail-closed & temp cleanup on error var invalidPath = Path.Combine("Z:\\NonExistentDrive_9999", "creds.json"); bool caughtSaveErr = false; try { DeviceCredentialProtector.SaveCredentials(invalidPath, new DeviceCredentials { DeviceId = "d1", DeviceToken = "t1" }); } catch { caughtSaveErr = true; } if (!caughtSaveErr) throw new Exception("SaveCredentials did not throw on invalid directory (fail-closed check)."); // 3. Verify no stray .tmp files left in temp dir var strayTmp = Directory.GetFiles(Path.GetTempPath(), "*bad_acl_*.tmp"); if (strayTmp.Length > 0) throw new Exception("Stray temp files detected after failure."); } private static async Task Test_SessionLauncher_Fallback_FailClosed() { // 1. Calling SessionLauncher with invalid exe or in non-interactive environment returns fail-closed var res = SessionLauncher.LaunchProcessInActiveUserSession(@"C:\nonexistent_path\fake_classnotify.exe"); if (res.Success) throw new Exception("SessionLauncher returned Success=true for non-existent executable!"); if (res.Pid > 0) throw new Exception($"SessionLauncher returned Pid={res.Pid} > 0 for failed launch!"); if (!string.IsNullOrEmpty(res.LaunchToken)) throw new Exception("SessionLauncher returned non-empty token for failed launch!"); // 2. NamedPipeServer must NOT authorize a client when Pid <= 0 or token is empty var pipeName = "ClassNotify_Test_FailClosed_" + Guid.NewGuid().ToString("N"); var config = new ConfigurationBuilder() .AddInMemoryCollection(new[] { new KeyValuePair("ClassNotify:PipeName", pipeName) }) .Build(); using var loggerFactory = LoggerFactory.Create(b => b.AddConsole().SetMinimumLevel(LogLevel.Warning)); var logger = loggerFactory.CreateLogger(); var server = new NamedPipeServer(config, logger); server.ExpectedProcessName = Process.GetCurrentProcess().ProcessName; // Verify that invalid parameters cannot establish an active authorized client server.InvalidateAuthorization(); using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); server.StartListening(cts.Token); await Task.Delay(500); // Attempting to connect without server authorization must be rejected using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous)) { await client.ConnectAsync(3000); using var writer = new StreamWriter(client, Encoding.UTF8) { AutoFlush = true }; await writer.WriteLineAsync(JsonSerializer.Serialize(new { type = "hello", client = "ClassNotify.Client", protocolVersion = 2, token = "unauthorized_token_777" })); await Task.Delay(500); if (server.IsClientConnected) throw new Exception("Server accepted connection without active registration!"); } } private static async Task Test_NamedPipe_HandshakeLog_ZeroTokenLeakage() { var pipeName = "ClassNotify_Test_LogLeak_" + Guid.NewGuid().ToString("N"); var config = new ConfigurationBuilder() .AddInMemoryCollection(new[] { new KeyValuePair("ClassNotify:PipeName", pipeName) }) .Build(); var capturedLogs = new System.Collections.Generic.List(); using var loggerFactory = LoggerFactory.Create(b => { b.AddProvider(new CustomLoggerProvider(msg => capturedLogs.Add(msg))); b.SetMinimumLevel(LogLevel.Trace); }); var logger = loggerFactory.CreateLogger(); var server = new NamedPipeServer(config, logger); server.ExpectedProcessName = Process.GetCurrentProcess().ProcessName; using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); server.StartListening(cts.Token); await Task.Delay(500); var secretCounterfeitToken = "SECRET_SUPER_CONFIDENTIAL_TOKEN_XYZ_123456"; using (var client = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous)) { await client.ConnectAsync(3000); using var writer = new StreamWriter(client, Encoding.UTF8) { AutoFlush = true }; await writer.WriteLineAsync(JsonSerializer.Serialize(new { type = "hello", client = "ClassNotify.Client", protocolVersion = 2, token = secretCounterfeitToken })); await Task.Delay(500); } // Verify that neither the secret token nor its prefix appears in logs var counterfeitPrefix = secretCounterfeitToken.Substring(0, 6); foreach (var log in capturedLogs) { if (log.Contains(secretCounterfeitToken) || log.Contains(counterfeitPrefix)) { throw new Exception($"SECURITY AUDIT FAILED: Secret token or prefix leaked in log: '{log}'"); } } // Also verify valid authorized client registration does not leak token or prefix var validSecret = "VALID_SECRET_TOKEN_XYZ_789012"; server.SetAuthorizedClient(validSecret, Environment.ProcessId, (uint)Process.GetCurrentProcess().SessionId); using (var clientValid = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous)) { await clientValid.ConnectAsync(3000); using var writerValid = new StreamWriter(clientValid, Encoding.UTF8) { AutoFlush = true }; await writerValid.WriteLineAsync(JsonSerializer.Serialize(new { type = "hello", client = "ClassNotify.Client", protocolVersion = 2, token = validSecret })); await Task.Delay(500); } var validPrefix = validSecret.Substring(0, 6); foreach (var log in capturedLogs) { if (log.Contains(validSecret) || log.Contains(validPrefix)) { throw new Exception($"SECURITY AUDIT FAILED: Valid secret token or prefix leaked in log: '{log}'"); } } } private static async Task Test_NTFS_Acl_StrictAllowlist_RejectsArbitrarySid() { await Task.Yield(); var testFile = Path.Combine(Path.GetTempPath(), $"allowlist_test_{Guid.NewGuid():N}.json"); try { await File.WriteAllTextAsync(testFile, "{}"); var fi = new FileInfo(testFile); var sec = new FileSecurity(); sec.SetAccessRuleProtection(isProtected: true, preserveInheritance: false); // Add SYSTEM and Admins FullControl sec.AddAccessRule(new FileSystemAccessRule( new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null), FileSystemRights.FullControl, AccessControlType.Allow)); sec.AddAccessRule(new FileSystemAccessRule( new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null), FileSystemRights.FullControl, AccessControlType.Allow)); // Add an arbitrary third-party SID (e.g. AuthenticatedUserSid) sec.AddAccessRule(new FileSystemAccessRule( new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null), FileSystemRights.Read, AccessControlType.Allow)); fi.SetAccessControl(sec); bool rejected = false; try { DeviceCredentialProtector.VerifyHardenedFileAcl(testFile); } catch (InvalidOperationException) { rejected = true; } if (!rejected) { throw new Exception("VerifyHardenedFileAcl failed to reject arbitrary third-party SID (AuthenticatedUserSid)!"); } } finally { if (File.Exists(testFile)) File.Delete(testFile); } } private static async Task Test_Setup_StartupManager_CleansLegacyEntries() { await Task.Yield(); var runKeyPath = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run"; using (var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(runKeyPath, writable: true)) { key?.SetValue("ClassNotifyClient", "\"C:\\ProgramData\\ClassNotify\\ClassNotify.Client.exe\""); } // Verify key exists using (var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(runKeyPath, writable: false)) { if (key?.GetValue("ClassNotifyClient") == null) { throw new Exception("Setup test error: Failed to set test Run key."); } } // Run CleanupLegacyStartupEntries ClassNotify.Setup.Services.StartupManager.CleanupLegacyStartupEntries(); // Verify key was removed using (var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(runKeyPath, writable: false)) { var val = key?.GetValue("ClassNotifyClient"); if (val != null) { throw new Exception("CleanupLegacyStartupEntries failed to delete legacy Run key!"); } } } } public class CustomLoggerProvider : ILoggerProvider { private readonly Action _logAction; public CustomLoggerProvider(Action logAction) => _logAction = logAction; public ILogger CreateLogger(string categoryName) => new CustomLogger(_logAction); public void Dispose() { } } public class CustomLogger : ILogger { private readonly Action _logAction; public CustomLogger(Action logAction) => _logAction = logAction; public IDisposable? BeginScope(TState state) where TState : notnull => null; public bool IsEnabled(LogLevel logLevel) => true; public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) { _logAction(formatter(state, exception)); } }