PlotDirector/PlotLine.Tests/DevBrowserIdentity.cs

169 lines
14 KiB
C#

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);
private static async Task VerifiedBackupAsync()
{
// 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";
// Operator-only setup reuses the installed Development backup worker. Runtime
// SQL permissions deliberately do not include BACKUP DATABASE; never grant it.
const string backupCode = """
import sys, os, grp, fcntl, tempfile, uuid
from pathlib import Path
sys.path.insert(0, '/usr/local/lib/plotdirector-dev-deployment')
from development import Development, DevelopmentWorker
from release import load, require, safe_name, verify_bundle
cfg = Development().configuration()
backup = sys.argv[1]
require(backup.startswith(cfg['database_backup_directory']+'/pwa-desktop-') and backup.endswith('.bak') and '..' not in backup, 'Invalid fixture backup')
with open(Path(cfg['root'])/'deployment.lock', 'r+') as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
active = load(Path(cfg['root'])/'active-deployment.json')
source = Path(cfg['inbox'])/safe_name(active['release'])
group = grp.getgrnam(cfg['migration_account']).gr_gid
with tempfile.TemporaryDirectory(prefix='.browser-backup-', dir=cfg['root']) as temporary:
os.chown(temporary, 0, group); os.chmod(temporary, 0o750)
manifest, authorization, payload = verify_bundle(source, temporary, cfg['public_key'])
require(authorization['package_sha256'] == active['package_sha256'], 'Active package mismatch')
for entry in [payload, *payload.rglob('*')]:
os.chown(entry, 0, group); entry.chmod(0o750 if entry.is_dir() else 0o640)
worker = DevelopmentWorker(cfg)
try:
worker.call('begin', package_root=str(payload), deployment_id='browser-backup-'+uuid.uuid4().hex, package_sha256=authorization['package_sha256'])
require(worker.call('backup', path=backup)['verified'], 'Backup not verified')
finally:
worker.close()
""";
var backupStart = new ProcessStartInfo("sudo") { RedirectStandardOutput = true, RedirectStandardError = true };
foreach (var part in new[] { "-n", "/usr/bin/python3", "-I", "-c", backupCode, backup }) backupStart.ArgumentList.Add(part);
using var backupProcess = Process.Start(backupStart)!;
var backupOutput = backupProcess.StandardOutput.ReadToEndAsync();
var backupErrors = backupProcess.StandardError.ReadToEndAsync();
await backupProcess.WaitForExitAsync();
await Task.WhenAll(backupOutput, backupErrors); // Never log protected operational output.
if (backupProcess.ExitCode != 0) throw new InvalidOperationException("Existing Development backup worker refused provisioning; no identity created");
}
public static async Task RunAsync(string[] args)
{
if (!OperatingSystem.IsLinux() || !string.Equals(Dns.GetHostName(), "atlas", StringComparison.OrdinalIgnoreCase)) throw new PlatformNotSupportedException("Development provisioning runs only on the Linux development host");
if (args.Length != 3 || args[1] is not ("create" or "cleanup" or "configure-worker") || (args[1] == "configure-worker" ? Path.GetFullPath(args[2]) != Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".config/cyj/credentials/application-browser.json") : !Path.GetFullPath(args[2]).StartsWith("/tmp/pd-dev-browser-", StringComparison.Ordinal)))
throw new InvalidOperationException("Use --dev-browser-identity create|cleanup /tmp/pd-dev-browser-<unique>.json, or configure-worker with the private application-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('"', '\'');
var target = new SqlConnectionStringBuilder(connectionString);
if (target.InitialCatalog != "PlotDirector_Development" || target.DataSource is not ("192.168.10.10,1433" or "tcp:192.168.10.10,1433")) 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<string, string?> { ["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");
await VerifiedBackupAsync();
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 if (args[1] == "configure-worker")
{
var identity = JsonSerializer.Deserialize<Identity>(await File.ReadAllTextAsync(path))!;
var user = await users.GetByEmailAsync(identity.Email);
if (identity.Database != "PlotDirector_Development" || !Regex.IsMatch(identity.Email, @"^pwa-browser-[a-f0-9]{32}@example\.invalid$") || user is null || user.UserID != identity.UserID || !new PasswordService().VerifyPassword(identity.Password, user.PasswordHash))
throw new InvalidOperationException("Dedicated worker identity scope mismatch");
var read = new ProcessStartInfo("sudo") { RedirectStandardOutput = true, RedirectStandardError = true };
foreach (var part in new[] { "-n", "cat", "/opt/plotdirector-dev/current/appsettings.json" }) read.ArgumentList.Add(part);
using var settingsProcess = Process.Start(read)!;
var settings = await settingsProcess.StandardOutput.ReadToEndAsync();
await settingsProcess.WaitForExitAsync();
if (settingsProcess.ExitCode != 0) throw new InvalidOperationException("Development administrator policy unavailable");
using var settingsStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(settings));
var overrides = environment.Split('\n').Where(line => line.StartsWith("Admin__AllowedEmails__", StringComparison.Ordinal))
.Select(line => line.Split('=', 2)).ToDictionary(parts => parts[0].Replace("__", ":"), parts => (string?)parts[1].Trim().Trim('"', '\''));
var administratorConfig = new ConfigurationBuilder().AddJsonStream(settingsStream).AddInMemoryCollection(overrides).Build();
var administrators = administratorConfig.GetSection("Admin:AllowedEmails").Get<string[]>() ?? [];
if (administrators.Length != 1 || administrators.Any(email => email.Equals(identity.Email, StringComparison.OrdinalIgnoreCase)))
throw new InvalidOperationException("A single configured human administrator is required for the provisioning audit; never grant the fixture administrator access");
var administrator = await users.GetByEmailAsync(administrators[0]);
if (administrator is null || !administrator.EmailConfirmed || administrator.UserID == identity.UserID)
throw new InvalidOperationException("Configured provisioning sponsor is unavailable");
var subscriptions = new SubscriptionRepository(factory);
var current = await subscriptions.GetCurrentSubscriptionAsync(identity.UserID)
?? throw new InvalidOperationException("Dedicated account has no normal writer subscription");
var existingOverride = await subscriptions.GetActiveOverrideAsync(identity.UserID, DateTime.UtcNow);
if (existingOverride is not null && existingOverride.ExpiryDateUTC is null && existingOverride.SubscriptionLevelID == current.SubscriptionLevelID)
{
Console.WriteLine("Dedicated Development writer entitlement already configured; no changes made.");
return;
}
await VerifiedBackupAsync();
await subscriptions.SaveOverrideAsync(identity.UserID, current.SubscriptionLevelID, DateTime.UtcNow, null,
"Owner-authorised permanent Development-only CYJ browser acceptance fixture; same ordinary writer plan, no billing-provider change.", administrator.UserID);
var active = await subscriptions.GetActiveOverrideAsync(identity.UserID, DateTime.UtcNow);
var future = await subscriptions.GetActiveOverrideAsync(identity.UserID, DateTime.UtcNow.AddYears(1));
if (active is null || active.ExpiryDateUTC is not null || active.SubscriptionLevelID != current.SubscriptionLevelID || future?.SubscriptionLevelID != current.SubscriptionLevelID)
throw new InvalidOperationException("Dedicated writer entitlement verification failed");
Console.WriteLine("Non-expiring Development writer entitlement provisioned using the existing audited administrative override; no administrator role or billing change.");
}
else
{
var identity = JsonSerializer.Deserialize<Identity>(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, "<input\\b(?=[^>]*\\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<string, string> {
["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<string, string> {
["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.");
}
}
}