feat: system and security - start-up, accounts, sign-in, licences, log, jobs, companies (M2)
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
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
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>
This commit is contained in:
1 parent
4582837b70
commit
032c602b49
107 files changed
+12202
-116
No files matched your search
@@ -0,0 +1,86 @@
|
||||
using Khaemhat.Application.Instance;
|
||||
using Khaemhat.Application.Jobs;
|
||||
using Khaemhat.Application.Licensing;
|
||||
using Khaemhat.Application.Security;
|
||||
using Khaemhat.Core.Instance;
|
||||
using Khaemhat.Core.Security;
|
||||
using Khaemhat.Data;
|
||||
using Khaemhat.Data.Companies;
|
||||
using Khaemhat.Data.Querying;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Khaemhat.Web.Tests.Hosting;
|
||||
|
||||
/// <summary>Two companies on one instance (SPEC §1.4, issue #23): each has its own database and no data crosses over.</summary>
|
||||
[TestClass]
|
||||
public sealed class CompanyIsolationTests
|
||||
{
|
||||
[TestMethod]
|
||||
public async Task ASecondCompany_HasItsOwnDatabase_AndSeesNothingOfTheFirst()
|
||||
{
|
||||
var (app, _, first) = await TestInstance.StartAsync(CancellationToken.None);
|
||||
await using (app)
|
||||
{
|
||||
var services = app.Services;
|
||||
var second = "S" + first[1..];
|
||||
|
||||
// One company is free; more need the MULTI module (here the test code, accepted only in test mode).
|
||||
var root = new Actor(TestInstance.SuperUser, UserLevel.SuperUser, 1, null, null);
|
||||
var activation = await services.GetRequiredService<ILicenseActivationService>().ActivateAsync(root, TestLicenseCatalog.All);
|
||||
Assert.IsTrue(activation.Succeeded, activation.Outcome);
|
||||
var created = await services.GetRequiredService<CompanyService>().CreateAsync(Actor.System, new NewCompany(second, "Seconda S.r.l."));
|
||||
Assert.AreEqual(CompanyStatus.Active, created.Status);
|
||||
|
||||
var factory = services.GetRequiredService<IUnitOfWorkFactory>();
|
||||
await using (var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(first)))
|
||||
{
|
||||
await unitOfWork.BeginAsync();
|
||||
await unitOfWork.Repository<Role, long>().InsertAsync(new Role { Code = "SOLO_PRIMA", Name = "Solo nella prima" });
|
||||
await unitOfWork.CommitAsync();
|
||||
}
|
||||
|
||||
Assert.AreEqual(1, await CountAsync(factory, first, "SOLO_PRIMA"));
|
||||
Assert.AreEqual(0, await CountAsync(factory, second, "SOLO_PRIMA"));
|
||||
|
||||
// Both companies got the predefined roles from their own seeding.
|
||||
Assert.IsTrue(await CountAsync(factory, second, null) > 0);
|
||||
var registry = services.GetRequiredService<ICompanyRegistry>();
|
||||
Assert.AreNotEqual((await registry.ResolveAsync(first)).DatabaseName, (await registry.ResolveAsync(second)).DatabaseName);
|
||||
await app.StopAsync();
|
||||
}
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task TheStartSequence_RunTwice_ChangesNothing_AndSystemJobsRun()
|
||||
{
|
||||
var (app, _, company) = await TestInstance.StartAsync(CancellationToken.None);
|
||||
await using (app)
|
||||
{
|
||||
var services = app.Services;
|
||||
var registry = services.GetRequiredService<ICompanyRegistry>();
|
||||
var roles = await CountAsync(services.GetRequiredService<IUnitOfWorkFactory>(), company, null);
|
||||
|
||||
await services.GetRequiredService<StartupOrchestrator>().RunAsync();
|
||||
|
||||
Assert.AreEqual(1, (await registry.ListAsync()).Count);
|
||||
Assert.AreEqual(roles, await CountAsync(services.GetRequiredService<IUnitOfWorkFactory>(), company, null));
|
||||
Assert.IsTrue(services.GetRequiredService<BootstrapState>().IsReady);
|
||||
|
||||
var scheduler = services.GetRequiredService<JobScheduler>();
|
||||
await scheduler.EnsureSystemTasksAsync();
|
||||
foreach (var task in JobScheduler.SystemTasks)
|
||||
{
|
||||
Assert.AreEqual(JobOutcome.Succeeded, await scheduler.RunAsync(task.Code), task.Code);
|
||||
}
|
||||
|
||||
await app.StopAsync();
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<int> CountAsync(IUnitOfWorkFactory factory, string company, string? code)
|
||||
{
|
||||
await using var unitOfWork = await factory.CreateAsync(DatabaseScope.Company(company));
|
||||
var query = code is null ? Query.For<Role>() : Query.For<Role>().Where(r => r.Code == code);
|
||||
return (await unitOfWork.Repository<Role, long>().ListAsync(query)).Items.Count;
|
||||
}
|
||||
}
|
||||
@@ -12,20 +12,18 @@ namespace Khaemhat.Web.Tests.Hosting;
|
||||
public sealed class HostTests
|
||||
{
|
||||
private static WebApplication? _app;
|
||||
private static HttpClient? _client;
|
||||
private static Uri? _address;
|
||||
private static string? _company;
|
||||
|
||||
[ClassInitialize]
|
||||
public static async Task StartAsync(TestContext context)
|
||||
{
|
||||
_app = KhaemhatApp.Build(["--urls", "http://127.0.0.1:0", "--environment", "Production"]);
|
||||
await _app.StartAsync(context.CancellationToken);
|
||||
_client = new HttpClient { BaseAddress = new Uri(_app.Urls.First()) };
|
||||
(_app, _address, _company) = await TestInstance.StartAsync(context.CancellationToken);
|
||||
}
|
||||
|
||||
[ClassCleanup]
|
||||
public static async Task StopAsync()
|
||||
{
|
||||
_client?.Dispose();
|
||||
if (_app is not null)
|
||||
{
|
||||
await _app.StopAsync();
|
||||
@@ -38,7 +36,8 @@ public sealed class HostTests
|
||||
[DataRow("/health/ready", "ready")]
|
||||
public async Task HealthProbes_AnswerOk(string path, string body)
|
||||
{
|
||||
using var response = await Client.GetAsync(new Uri(path, UriKind.Relative));
|
||||
using var client = Client();
|
||||
using var response = await client.GetAsync(new Uri(path, UriKind.Relative));
|
||||
|
||||
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.AreEqual(body, await response.Content.ReadAsStringAsync());
|
||||
@@ -47,7 +46,8 @@ public sealed class HostTests
|
||||
[TestMethod]
|
||||
public async Task Health_ReportsStatusAndVersion()
|
||||
{
|
||||
var report = await Client.GetFromJsonAsync<HealthEndpoints.HealthReport>(new Uri("/health", UriKind.Relative));
|
||||
using var client = Client();
|
||||
var report = await client.GetFromJsonAsync<HealthEndpoints.HealthReport>(new Uri("/health", UriKind.Relative));
|
||||
|
||||
Assert.IsNotNull(report);
|
||||
Assert.AreEqual("ok", report.Status);
|
||||
@@ -57,22 +57,86 @@ public sealed class HostTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task HomePage_ShowsTheUnderConstructionPage()
|
||||
public async Task HomePage_RedirectsAnonymousUsersToTheLogin()
|
||||
{
|
||||
var html = await Client.GetStringAsync(new Uri("/", UriKind.Relative));
|
||||
using var client = Client();
|
||||
using var response = await client.GetAsync(new Uri("/", UriKind.Relative));
|
||||
|
||||
Assert.AreEqual(HttpStatusCode.Redirect, response.StatusCode);
|
||||
StringAssert.StartsWith(response.Headers.Location?.OriginalString, "/login");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task LoginPage_IsItalianAndListsTheCompany()
|
||||
{
|
||||
using var client = Client();
|
||||
var html = await client.GetStringAsync(new Uri("/login", UriKind.Relative));
|
||||
|
||||
StringAssert.Contains(html, "Khaemhat");
|
||||
StringAssert.Contains(html, "in costruzione");
|
||||
StringAssert.Contains(html, "lang=\"it\"");
|
||||
StringAssert.Contains(html, "Accedi");
|
||||
StringAssert.Contains(html, _company!);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Responses_CarryTheSecurityHeaders()
|
||||
{
|
||||
using var client = Client();
|
||||
using var response = await client.GetAsync(new Uri("/login", UriKind.Relative));
|
||||
|
||||
StringAssert.Contains(string.Join(';', response.Headers.GetValues("Content-Security-Policy")), "script-src 'self'");
|
||||
Assert.AreEqual("DENY", response.Headers.GetValues("X-Frame-Options").Single());
|
||||
Assert.IsTrue(response.Headers.Contains("X-Trace-Id"));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Login_WithAWrongPassword_StaysOnThePage()
|
||||
{
|
||||
using var client = Client();
|
||||
using var response = await PostLoginAsync(client, TestInstance.SuperUser, "not-the-password");
|
||||
|
||||
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
|
||||
Assert.IsFalse(response.Headers.TryGetValues("Set-Cookie", out var cookies) && cookies.Any(c => c.StartsWith("khaemhat_session=", StringComparison.Ordinal)));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Login_OfTheSuperUser_AsksForANewPasswordFirst()
|
||||
{
|
||||
using var client = Client();
|
||||
using var response = await PostLoginAsync(client, TestInstance.SuperUser, TestInstance.SuperUserPassword);
|
||||
|
||||
Assert.AreEqual(HttpStatusCode.Redirect, response.StatusCode);
|
||||
StringAssert.Contains(response.Headers.Location?.OriginalString, "/login/cambio-password");
|
||||
var cookie = response.Headers.GetValues("Set-Cookie").Single(c => c.StartsWith("khaemhat_session=", StringComparison.Ordinal));
|
||||
StringAssert.Contains(cookie, "httponly");
|
||||
StringAssert.Contains(cookie, "samesite=lax");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task UnknownPage_AnswersNotFound()
|
||||
{
|
||||
using var response = await Client.GetAsync(new Uri("/does-not-exist", UriKind.Relative));
|
||||
using var client = Client();
|
||||
using var response = await client.GetAsync(new Uri("/does-not-exist", UriKind.Relative));
|
||||
|
||||
Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode);
|
||||
}
|
||||
|
||||
private static HttpClient Client => _client ?? throw new InvalidOperationException("Host not started.");
|
||||
private static async Task<HttpResponseMessage> PostLoginAsync(HttpClient client, string user, string password)
|
||||
{
|
||||
var page = await client.GetStringAsync(new Uri("/login", UriKind.Relative));
|
||||
using var form = new FormUrlEncodedContent(new Dictionary<string, string>
|
||||
{
|
||||
["_handler"] = "login",
|
||||
["__RequestVerificationToken"] = TestInstance.AntiforgeryToken(page),
|
||||
["Input.CompanyCode"] = string.Empty,
|
||||
["Input.UserName"] = user,
|
||||
["Input.Password"] = password,
|
||||
});
|
||||
return await client.PostAsync(new Uri("/login", UriKind.Relative), form);
|
||||
}
|
||||
|
||||
private static HttpClient Client() =>
|
||||
new(new HttpClientHandler { AllowAutoRedirect = false, UseCookies = true, CookieContainer = new CookieContainer() })
|
||||
{
|
||||
BaseAddress = _address ?? throw new InvalidOperationException("Host not started."),
|
||||
};
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using Khaemhat.Application.Configuration;
|
||||
using Khaemhat.Web.Hosting;
|
||||
|
||||
namespace Khaemhat.Web.Tests.Hosting;
|
||||
@@ -12,7 +13,7 @@ public sealed class InstanceVariablesTests
|
||||
[TestMethod]
|
||||
public async Task LogLevel_SetsTheDefaultLevel()
|
||||
{
|
||||
await using var app = KhaemhatApp.Build(["--urls", "http://127.0.0.1:0", "--KHAEMHAT_LOG_LEVEL=warning"]);
|
||||
await using var app = KhaemhatApp.Build(TestInstance.Arguments(out _, "--KHAEMHAT_LOG_LEVEL=warning"));
|
||||
|
||||
Assert.AreEqual("Warning", app.Configuration["Logging:LogLevel:Default"]);
|
||||
}
|
||||
@@ -20,16 +21,26 @@ public sealed class InstanceVariablesTests
|
||||
[TestMethod]
|
||||
public void LogLevel_RejectsAnUnknownValue()
|
||||
{
|
||||
var error = Assert.ThrowsExactly<InvalidOperationException>(
|
||||
() => KhaemhatApp.Build(["--urls", "http://127.0.0.1:0", "--KHAEMHAT_LOG_LEVEL=loud"]));
|
||||
var error = Assert.ThrowsExactly<ConfigurationException>(
|
||||
() => KhaemhatApp.Build(TestInstance.Arguments(out _, "--KHAEMHAT_LOG_LEVEL=loud")));
|
||||
|
||||
StringAssert.Contains(error.Message, "KHAEMHAT_LOG_LEVEL");
|
||||
Assert.IsTrue(error.Errors.Any(e => e.Contains("KHAEMHAT_LOG_LEVEL", StringComparison.Ordinal)));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void MissingRequiredVariables_AreAllReported()
|
||||
{
|
||||
var error = Assert.ThrowsExactly<ConfigurationException>(() => KhaemhatApp.Build(["--urls", "http://127.0.0.1:0"]));
|
||||
|
||||
Assert.IsTrue(error.Errors.Any(e => e.Contains("KHAEMHAT_SYSTEM_DB", StringComparison.Ordinal)));
|
||||
Assert.IsTrue(error.Errors.Any(e => e.Contains("KHAEMHAT_SECRET_KEY", StringComparison.Ordinal)));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Urls_AreTakenFromTheVariable()
|
||||
{
|
||||
await using var app = KhaemhatApp.Build(["--KHAEMHAT_URLS=http://127.0.0.1:0"]);
|
||||
var arguments = TestInstance.Arguments(out _).Where(a => a is not ("--urls" or "http://127.0.0.1:0")).Append("--KHAEMHAT_URLS=http://127.0.0.1:0");
|
||||
await using var app = KhaemhatApp.Build([.. arguments]);
|
||||
|
||||
Assert.AreEqual("http://127.0.0.1:0", app.Configuration["urls"]);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
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();
|
||||
}
|
||||
Reference in new issue
Block a user