97 lines
5.9 KiB
C#

using System.Security.Cryptography;
using System.Text.Json;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.DataProtection.Infrastructure;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Authentication;
using System.Security.Claims;
using System.Text.Encodings.Web;
// Test-only host. Same PlotLine assembly/controllers/Razor; no email, payment,
// OpenAI credentials or application background services. Never installed on web1.
var configPath = Environment.GetEnvironmentVariable("PD_QUALIFICATION_CONFIG")
?? throw new InvalidOperationException("Private qualification configuration required");
using var configDoc=JsonDocument.Parse(File.ReadAllText(configPath));
var c=configDoc.RootElement;
var cs=new SqlConnectionStringBuilder(c.GetProperty("connection").GetString());
if(cs.DataSource!="192.168.10.10,1433" || !cs.InitialCatalog.StartsWith("PlotDirector_Qualification_",StringComparison.Ordinal)
|| !cs.UserID.StartsWith("PDQualification_",StringComparison.Ordinal))
throw new InvalidOperationException("Not an isolated qualification identity");
var owners=c.GetProperty("owner_ids").EnumerateArray().Select(x=>x.GetInt32()).ToHashSet();
var requestToken=c.GetProperty("request_token").GetString()!;
if(requestToken.Length<40)throw new InvalidOperationException("Private request token required");
using(var connection=new SqlConnection(cs.ConnectionString))
{
connection.Open();
using var command=new SqlCommand("SELECT DB_NAME()",connection);
if((string?)command.ExecuteScalar()!=cs.InitialCatalog)throw new InvalidOperationException("Database identity mismatch");
}
var contentRoot=c.GetProperty("content_root").GetString()!;
var dll=Path.Combine(contentRoot,"PlotLine.dll");
var expected=c.GetProperty("dll_sha256").GetString();
if(Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(dll)))!=expected
|| Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(typeof(PlotLine.Program).Assembly.Location)))!=expected)
throw new InvalidOperationException("Application assembly differs from qualified payload");
var keys=c.GetProperty("keys_path").GetString()!;
var url=c.GetProperty("url").GetString()!;
if(!url.StartsWith("http://127.0.0.1:",StringComparison.Ordinal))throw new InvalidOperationException("Loopback binding required");
var values=new Dictionary<string,string?> {
["ConnectionStrings:DefaultConnection"]=cs.ConnectionString,
["Storage:UploadsRoot"]=c.GetProperty("uploads_path").GetString(),
["DataProtection:KeysPath"]=keys,
["Site:PublicBaseUrl"]=url,
["EmailSettings:SmtpServer"]="127.0.0.1",["EmailSettings:Port"]="1",
["EmailSettings:Username"]="",["EmailSettings:Password"]="",
["EmailSettings:FromAddress"]="qualification@example.invalid",
["Stripe:PublishableKey"]="",["Stripe:SecretKey"]="",["Stripe:WebhookSecret"]="",
["OpenAI:ApiKey"]="",["Geography:Enabled"]="false",
["StoryIntelligence:WorkersEnabled"]="false",["Illustrations:GenerationWorkerEnabled"]="false",
["WritingSolver:EnableIndexing"]="false",
["Features:ParagraphManuscripts"]="true"
};
var app=PlotLine.Program.BuildApplication(["--applicationName=PlotLine","--environment=Qualification",
"--contentRoot="+contentRoot,"--urls="+url,"--DataProtection:KeysPath="+keys],builder=>{
builder.Configuration.Sources.Clear();
builder.Configuration.AddInMemoryCollection(values);
// Removes retention, email, geocoding, native expiry, AI, presence and notification
// workers. The web host is registered when Build() completes.
builder.Services.RemoveAll<IHostedService>();
builder.Services.ConfigureHttpClientDefaults(http=>http.ConfigurePrimaryHttpMessageHandler(()=>new NoExternalRequests()));
builder.Services.AddSingleton(owners);
builder.Services.AddSingleton(new QualificationToken(requestToken));
builder.Services.AddAuthentication(options=>{
options.DefaultAuthenticateScheme="Qualification"; options.DefaultChallengeScheme="Qualification";
}).AddScheme<AuthenticationSchemeOptions,QualificationAuthentication>("Qualification",_=>{});
});
app.Urls.Clear();app.Urls.Add(url);
app.MapGet("/qualification/transport",(HttpContext context)=>Results.Json(new {scheme=context.Request.Scheme}));
Console.WriteLine("QUALIFICATION_HOST isolated database identity and binary checksum verified; all application workers disabled.");
await app.RunAsync();
internal sealed class NoExternalRequests:HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,CancellationToken cancellationToken)
=> throw new InvalidOperationException("Outbound HTTP disabled in qualification");
}
// Explicit clone-only test authentication, absent from PlotLine/production binaries.
// Loopback binding and SQL identity guards above are mandatory before registration.
internal sealed record QualificationToken(string Value);
internal sealed class QualificationAuthentication(IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,UrlEncoder encoder,HashSet<int> owners,QualificationToken token)
:AuthenticationHandler<AuthenticationSchemeOptions>(options,logger,encoder)
{
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
var supplied=System.Text.Encoding.UTF8.GetBytes(Request.Headers["X-Qualification-Token"].ToString());
if(!CryptographicOperations.FixedTimeEquals(supplied,System.Text.Encoding.UTF8.GetBytes(token.Value))
|| !int.TryParse(Request.Headers["X-Qualification-Author"],out var owner)||!owners.Contains(owner))
return Task.FromResult(AuthenticateResult.NoResult());
var identity=new ClaimsIdentity([new Claim(ClaimTypes.NameIdentifier,owner.ToString()),
new Claim(ClaimTypes.Name,"Isolated qualification")],Scheme.Name);
return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity),Scheme.Name)));
}
}