using System.Diagnostics; using System.Security.Claims; using System.Text.Encodings.Web; using Dapper; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Builder; using Microsoft.Data.SqlClient; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using PlotLine.Data; // Explicit local clone-only HTTP qualification host. No production authentication bypass is installed. internal static class SqlLaunchBenchmarkHost { public static async Task Run() { var info = new ProcessStartInfo("sudo") { RedirectStandardOutput = true }; foreach (var value in new[] { "-n", "cat", "/etc/plotdirector/plotdirector.env" }) info.ArgumentList.Add(value); using var process = Process.Start(info)!; var env = await process.StandardOutput.ReadToEndAsync(); await process.WaitForExitAsync(); if (process.ExitCode != 0) throw new Exception("Development configuration unavailable"); var raw = env.Split('\n').Single(l => l.StartsWith("ConnectionStrings__DefaultConnection=")).Split('=', 2)[1].Trim().Trim('"', '\''); var sql = new SqlConnectionStringBuilder(raw); if (sql.InitialCatalog != "PlotDirector_Development") throw new Exception("Unexpected configured target"); sql.InitialCatalog = "PlotDirector_SQLLaunch_20261119"; using var db = new SqlConnection(sql.ConnectionString); await db.OpenAsync(); if (await db.ExecuteScalarAsync("SELECT DB_NAME()") != sql.InitialCatalog) throw new Exception("Clone required"); var users = (await db.QueryAsync("SELECT DISTINCT UserID FROM dbo.ProjectUserAccess WHERE AccessRole=N'Owner' AND IsActive=1")).ToHashSet(); var app = PlotLine.Program.BuildApplication(["--applicationName=PlotLine", "--environment=Development", "--contentRoot=" + Path.GetFullPath("PlotLine"), "--urls=http://127.0.0.1:5240", "--DataProtection:KeysPath=/home/nick/sql-launch-20261119/keys"], builder => { builder.Configuration.AddInMemoryCollection(new Dictionary { ["ConnectionStrings:DefaultConnection"] = sql.ConnectionString, ["SqlDiagnostics:Enabled"] = "true" }); foreach (var descriptor in builder.Services.Where(d => d.ServiceType == typeof(IHostedService)).ToArray()) builder.Services.Remove(descriptor); builder.Services.AddHostedService(s => s.GetRequiredService()); builder.Services.AddSingleton(users); builder.Services.AddAuthentication(options => { options.DefaultAuthenticateScheme = "CloneBenchmark"; options.DefaultChallengeScheme = "CloneBenchmark"; }) .AddScheme("CloneBenchmark", _ => { }); }); app.MapGet("/clone-instrumentation-error", (Microsoft.AspNetCore.Http.HttpContext context) => Task.FromException(new InvalidOperationException("Synthetic instrumentation failure"))); await app.RunAsync(); } sealed class CloneAuthentication(IOptionsMonitor options, ILoggerFactory logger, UrlEncoder encoder, HashSet users) : AuthenticationHandler(options, logger, encoder) { protected override Task HandleAuthenticateAsync() { if (!int.TryParse(Request.Headers["X-Clone-Author"], out var user) || !users.Contains(user)) return Task.FromResult(AuthenticateResult.Fail("Clone author required")); var identity = new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier, user.ToString()), new Claim(ClaimTypes.Name, "Clone benchmark")], Scheme.Name); return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity), Scheme.Name))); } } }