Files
Khaemhat/tests/Khaemhat.Web.Tests/Hosting/CompanyIsolationTests.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

87 lines
4.0 KiB
C#

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;
}
}