Files
Khaemhat/tests/Khaemhat.Web.Tests/Hosting/TestInstance.cs
T
Alby96andClaude Opus 5.5 032c602b49
CI / Build and test (SQLite) (pull_request) Successful in 55s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / YAML check (pull_request) Successful in 5s
CI / Docker image (pull_request) Failing after 2m4s
feat: system and security - start-up, accounts, sign-in, licences, log, jobs, companies (M2)
The instance now starts on its own from KHAEMHAT_* variables: it migrates the system
and company databases, creates the super user and the first company, and only then
reports ready. Users sign in with password and TOTP through revocable database
sessions, and licences decide which modules and how many companies are available.

- Configuration: every wrong variable reported at once (exit code 2), _FILE variants
- Accounts, password policy and lockout, TOTP with recovery codes, session states
  with token rotation, security audit with a hash chain
- Sign-in pages (mockups 001-003), authorization attributes, security headers and a
  CSP without inline scripts, login rate limit
- Signed licences, activation codes, test mode, licence tool
- DataProtection keys in the system database, encrypted with the instance key
- Memory or Redis cache (in-house RESP client) that falls back to memory
- Database log by section with trace id; cron scheduler with locks and system jobs;
  record history (audit_log)
- Company creation, states, company context and X-Company, 503 in maintenance
- In-memory SQLite databases stay alive for the process (tests, demo)
- Tests for all of the above, ADR 0019, wiki, SECURITY, CHANGELOG, STATUS, DATA-MODEL

Refs #15 #16 #17 #18 #19 #20 #21 #22 #23 #24

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 15:29:24 +01:00

83 lines
3.6 KiB
C#

using System.Net;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using Khaemhat.Web.Hosting;
using Microsoft.AspNetCore.Builder;
namespace Khaemhat.Web.Tests.Hosting;
/// <summary>
/// The variables of a test instance: in-memory SQLite databases with unique names (tests run in one process), a fresh
/// secret key, a super user, one company and licences in test mode.
/// </summary>
internal static partial class TestInstance
{
/// <summary>The super user of the test instances.</summary>
public const string SuperUser = "root";
/// <summary>Its first password (test value, valid for the password policy).</summary>
public const string SuperUserPassword = "Test-Password-2026";
/// <summary>The arguments that start an instance, plus <paramref name="extra"/>.</summary>
/// <param name="companyCode">The company created at the first start.</param>
/// <param name="extra">More arguments (they win over the defaults).</param>
/// <returns>The command line.</returns>
public static string[] Arguments(out string companyCode, params string[] extra)
{
var id = Convert.ToHexString(RandomNumberGenerator.GetBytes(4));
companyCode = "T" + id;
string[] defaults =
[
"--urls", "http://127.0.0.1:0",
"--environment", "Production",
"--KHAEMHAT_SYSTEM_DB=sqlite://memory/system_" + id,
"--KHAEMHAT_SECRET_KEY=" + Convert.ToBase64String(RandomNumberGenerator.GetBytes(32)),
"--KHAEMHAT_DATA_DIR=" + Path.Combine(Path.GetTempPath(), "khaemhat-tests", id),
"--KHAEMHAT_SUPERUSER=" + SuperUser,
"--KHAEMHAT_SUPERUSER_PASSWORD=" + SuperUserPassword,
"--KHAEMHAT_COMPANY_CODE=" + companyCode,
"--KHAEMHAT_LICENSE_MODE=test",
];
return [.. defaults, .. extra];
}
/// <summary>Builds and starts an instance and waits until the start sequence is over.</summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The running instance, its address and the company code.</returns>
public static async Task<(WebApplication App, Uri Address, string Company)> StartAsync(CancellationToken cancellationToken)
{
var app = KhaemhatApp.Build(Arguments(out var company));
await app.StartAsync(cancellationToken);
var address = new Uri(app.Urls.First());
using var client = new HttpClient { BaseAddress = address };
var deadline = DateTime.UtcNow.AddSeconds(60);
while (true)
{
using var response = await client.GetAsync(new Uri("/health/ready", UriKind.Relative), cancellationToken);
if (response.StatusCode == HttpStatusCode.OK)
{
return (app, address, company);
}
if (DateTime.UtcNow > deadline || await response.Content.ReadAsStringAsync(cancellationToken) == "failed")
{
throw new InvalidOperationException("The test instance did not become ready.");
}
await Task.Delay(100, cancellationToken);
}
}
/// <summary>The antiforgery token of a page with a form.</summary>
/// <param name="html">The page.</param>
/// <returns>The token.</returns>
public static string AntiforgeryToken(string html)
{
var match = TokenPattern().Match(html);
return match.Success ? WebUtility.HtmlDecode(match.Groups[1].Value) : throw new InvalidOperationException("No antiforgery token in the page.");
}
[GeneratedRegex("name=\"__RequestVerificationToken\"[^>]*value=\"([^\"]+)\"")]
private static partial Regex TokenPattern();
}