using System.Diagnostics; using System.Security.Cryptography; using System.Text.Json; using System.Net; using System.Text.RegularExpressions; using Microsoft.Data.SqlClient; using Microsoft.Extensions.Configuration; using PlotLine.Data; using PlotLine.Services; // Explicit operational test command, never registered in or deployed with the web application. // Uses normal user repositories and password verification; does not issue cookies or change authentication. internal static class DevBrowserIdentity { private sealed record Identity(int UserID, string Email, string Password, string Database); public static async Task RunAsync(string[] args) { if (!OperatingSystem.IsLinux()) throw new PlatformNotSupportedException("Development provisioning runs only on the Linux development host"); if (args.Length != 3 || args[1] is not ("create" or "cleanup") || !Path.GetFullPath(args[2]).StartsWith("/tmp/pd-dev-browser-", StringComparison.Ordinal)) throw new InvalidOperationException("Use --dev-browser-identity create|cleanup /tmp/pd-dev-browser-.json"); var start = new ProcessStartInfo("sudo") { RedirectStandardOutput = true, RedirectStandardError = true }; foreach (var part in new[] { "-n", "cat", "/etc/plotdirector/plotdirector.env" }) start.ArgumentList.Add(part); using var process = Process.Start(start)!; var environment = await process.StandardOutput.ReadToEndAsync(); await process.WaitForExitAsync(); if (process.ExitCode != 0) throw new InvalidOperationException("Development configuration unavailable"); var connectionString = environment.Split('\n').Single(line => line.StartsWith("ConnectionStrings__DefaultConnection=")).Split('=', 2)[1].Trim().Trim('"', '\''); if (new SqlConnectionStringBuilder(connectionString).InitialCatalog != "PlotDirector_Development") throw new InvalidOperationException("Only the development database is permitted"); using var connection = new SqlConnection(connectionString); await connection.OpenAsync(); using var verify = connection.CreateCommand(); verify.CommandText = "SELECT DB_NAME()"; if ((string?)await verify.ExecuteScalarAsync() != "PlotDirector_Development") throw new InvalidOperationException("Development database verification failed"); var config = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary { ["ConnectionStrings:DefaultConnection"] = connectionString }).Build(); var factory = new SqlConnectionFactory(config); var users = new UserRepository(factory); var path = Path.GetFullPath(args[2]); if (args[1] == "create") { if (File.Exists(path)) throw new InvalidOperationException("Refusing to overwrite an identity file"); // A uniquely named copy-only backup precedes all provisioning writes. var backup = $"/var/opt/mssql/backup/pwa-desktop-{DateTime.UtcNow:yyyyMMddTHHmmss}-{Guid.NewGuid():N}.bak"; using var command = connection.CreateCommand(); command.CommandTimeout = 300; command.CommandText = "BACKUP DATABASE [PlotDirector_Development] TO DISK = @path WITH COPY_ONLY, CHECKSUM;"; command.Parameters.AddWithValue("@path", backup); await command.ExecuteNonQueryAsync(); var checkBackup = new ProcessStartInfo("sudo") { RedirectStandardOutput = true, RedirectStandardError = true }; foreach (var part in new[] { "-n", "docker", "exec", "atlas-sql-server", "test", "-s", backup }) checkBackup.ArgumentList.Add(part); using var backupCheck = Process.Start(checkBackup)!; await backupCheck.WaitForExitAsync(); if (backupCheck.ExitCode != 0) throw new InvalidOperationException("Development backup file verification failed"); var email = $"pwa-browser-{Guid.NewGuid():N}@example.invalid"; var password = Convert.ToBase64String(RandomNumberGenerator.GetBytes(36)) + "aA1!"; var user = await users.CreateAsync(email, "Desktop Verification Author", new PasswordService().HashPassword(password), emailConfirmed: false); // Exercise the same verification token/confirmation repositories as the normal account flow. // The Dev-only mailbox belongs to this isolated test; no external email or token logging is needed. var token = Guid.NewGuid(); await new AuthenticationRepository(factory).CreateEmailVerificationTokenAsync(user.UserID, token, DateTime.UtcNow.AddMinutes(30)); if (!await users.ConfirmEmailAsync(user.UserID, token)) throw new InvalidOperationException("Test mailbox verification failed"); await using var stream = new FileStream(path, new FileStreamOptions { Mode = FileMode.CreateNew, Access = FileAccess.Write, UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite }); await JsonSerializer.SerializeAsync(stream, new Identity(user.UserID, email, password, "PlotDirector_Development")); Console.WriteLine("Dedicated development browser identity provisioned through normal account repositories; credentials stored privately. No production access."); } else { var identity = JsonSerializer.Deserialize(await File.ReadAllTextAsync(path))!; var user = await users.GetByEmailAsync(identity.Email); if (identity.Database != "PlotDirector_Development" || !identity.Email.StartsWith("pwa-browser-") || !identity.Email.EndsWith("@example.invalid") || user?.UserID != identity.UserID) throw new InvalidOperationException("Refusing cleanup: identity scope mismatch"); // Use the complete application workflow: it removes owned projects/files before the user. // The low-level user repository deliberately refuses accounts which still own projects. using var handler = new HttpClientHandler { CookieContainer = new CookieContainer(), AllowAutoRedirect = false }; using var client = new HttpClient(handler) { BaseAddress = new Uri("https://dev.plotdirector.com"), Timeout = TimeSpan.FromMinutes(2) }; static string Token(string html) { var match = Regex.Match(html, "]*\\bname=\"__RequestVerificationToken\")[^>]*\\bvalue=\"([^\"]+)\""); return match.Success ? WebUtility.HtmlDecode(match.Groups[1].Value) : throw new InvalidOperationException("Development antiforgery token unavailable"); } var login = await client.GetStringAsync("/Account/Login"); using var signedIn = await client.PostAsync("/Account/Login", new FormUrlEncodedContent(new Dictionary { ["Email"] = identity.Email, ["Password"] = identity.Password, ["__RequestVerificationToken"] = Token(login) })); if (signedIn.StatusCode != HttpStatusCode.Found || signedIn.Headers.Location?.OriginalString != "/Projects") throw new InvalidOperationException("Normal development login failed during cleanup"); var account = await client.GetStringAsync("/ManageAccount"); using var deleted = await client.PostAsync("/ManageAccount/HardDeleteAccount", new FormUrlEncodedContent(new Dictionary { ["confirmationEmail"] = identity.Email, ["__RequestVerificationToken"] = Token(account) })); if (deleted.StatusCode != HttpStatusCode.Found || await users.GetByEmailAsync(identity.Email) is not null) throw new InvalidOperationException("Normal development account cleanup failed"); File.Delete(path); Console.WriteLine("Dedicated development identity and its fixture data removed; private credential file deleted."); } } }