130 lines
8.6 KiB
C#
130 lines
8.6 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");
|
|
if(args.Contains("--restore-contract"))
|
|
{
|
|
// Actual application export/encoding, followed by the actual SQL restore,
|
|
// under the runtime role. The disposable clone's transaction always rolls back.
|
|
using var db=new SqlConnection(cs.ConnectionString);db.Open();
|
|
using var choose=db.CreateCommand();
|
|
choose.CommandText="SELECT IS_MEMBER('db_owner')+HAS_PERMS_BY_NAME(DB_NAME(),'DATABASE','ALTER')+HAS_PERMS_BY_NAME('dbo.Projects','OBJECT','ALTER')";
|
|
if(Convert.ToInt32(choose.ExecuteScalar())!=0)throw new InvalidOperationException("Unprivileged runtime principal required");
|
|
choose.CommandText="SELECT TOP(1) p.ProjectID FROM dbo.Projects p JOIN dbo.Books b ON b.ProjectID=p.ProjectID JOIN dbo.Chapters c ON c.BookID=b.BookID JOIN dbo.Scenes s ON s.ChapterID=c.ChapterID WHERE p.IsArchived=0 AND b.IsArchived=0 AND NOT EXISTS(SELECT 1 FROM dbo.NativeChapterReviews n JOIN dbo.Books k ON k.BookID=n.BookID WHERE k.ProjectID=p.ProjectID) AND NOT EXISTS(SELECT 1 FROM dbo.BookParagraphManuscripts m JOIN dbo.Books k ON k.BookID=m.BookID WHERE k.ProjectID=p.ProjectID) GROUP BY p.ProjectID ORDER BY COUNT_BIG(*),p.ProjectID";
|
|
var project=Convert.ToInt32(choose.ExecuteScalar());
|
|
if(project<=0)throw new InvalidOperationException("Eligible clone restore fixture unavailable");
|
|
var repository=new PlotLine.Data.ProjectBackupRepository(new QualificationConnections(cs.ConnectionString));
|
|
var exported=await repository.GetProjectBackupAsync(project)??throw new InvalidOperationException("Project export failed");
|
|
var payload=PlotLine.Data.BookRecoveryRepository.Encode(exported,null);
|
|
using var transaction=db.BeginTransaction();
|
|
try
|
|
{
|
|
using var restore=new SqlCommand("dbo.ProjectRestore_ApplyFromJson",db,transaction){CommandType=System.Data.CommandType.StoredProcedure,CommandTimeout=180};
|
|
restore.Parameters.AddWithValue("@ProjectID",project);
|
|
restore.Parameters.Add("@JsonData",System.Data.SqlDbType.NVarChar,-1).Value=payload;
|
|
await restore.ExecuteNonQueryAsync();
|
|
using var check=new SqlCommand("SELECT @@TRANCOUNT",db,transaction);
|
|
if(Convert.ToInt32(check.ExecuteScalar())!=1)throw new InvalidOperationException("Restore escaped its outer transaction");
|
|
transaction.Rollback();
|
|
Console.WriteLine("RUNTIME_RESTORE_CONTRACT passed; actual repository/export/restore; outer transaction rolled back.");
|
|
return;
|
|
}
|
|
catch {try{transaction.Rollback();}catch{}throw;}
|
|
}
|
|
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");
|
|
}
|
|
internal sealed class QualificationConnections(string value):PlotLine.Data.ISqlConnectionFactory
|
|
{
|
|
public System.Data.IDbConnection CreateConnection()=>new SqlConnection(value);
|
|
}
|
|
|
|
// 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)));
|
|
}
|
|
}
|