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>
148 lines
7.6 KiB
C#
148 lines
7.6 KiB
C#
using System.Security.Cryptography;
|
|
using Khaemhat.Application.Audit;
|
|
using Khaemhat.Application.Configuration;
|
|
using Khaemhat.Application.Instance;
|
|
using Khaemhat.Application.Security;
|
|
using Khaemhat.Core.Instance;
|
|
using Khaemhat.Core.Security;
|
|
using Khaemhat.Data;
|
|
using Khaemhat.Data.Companies;
|
|
|
|
namespace Khaemhat.Application.Tests;
|
|
|
|
/// <summary>Configuration, password policy, company context and record history (SPEC §5, §6, §7).</summary>
|
|
[TestClass]
|
|
public sealed class SystemRulesTests
|
|
{
|
|
private static readonly string Key = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32));
|
|
|
|
[TestMethod]
|
|
public void Configuration_ReadsSecretsFromFiles()
|
|
{
|
|
var variables = Required();
|
|
variables.Remove("KHAEMHAT_SECRET_KEY");
|
|
variables["KHAEMHAT_SECRET_KEY_FILE"] = "/run/secrets/key";
|
|
var reader = new EnvironmentConfigurationReader(n => variables.GetValueOrDefault(n), path => path == "/run/secrets/key" ? Key + "\n" : throw new IOException());
|
|
|
|
var options = reader.Read();
|
|
options.EnsureValid();
|
|
|
|
Assert.AreEqual(Key, options.SecretKey);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void Configuration_RefusesAValueAndItsFileTogether_AndUnreadableFiles()
|
|
{
|
|
var variables = Required();
|
|
variables["KHAEMHAT_SECRET_KEY_FILE"] = "/run/secrets/key";
|
|
variables["KHAEMHAT_SUPERUSER_PASSWORD_FILE"] = "/missing";
|
|
var reader = new EnvironmentConfigurationReader(n => variables.GetValueOrDefault(n), path => path == "/run/secrets/key" ? Key : throw new FileNotFoundException());
|
|
|
|
var error = Assert.ThrowsExactly<ConfigurationException>(() => reader.Read().EnsureValid());
|
|
|
|
Assert.IsTrue(error.Errors.Any(e => e.Contains("KHAEMHAT_SECRET_KEY and KHAEMHAT_SECRET_KEY_FILE", StringComparison.Ordinal)));
|
|
Assert.IsTrue(error.Errors.Any(e => e.Contains("KHAEMHAT_SUPERUSER_PASSWORD_FILE", StringComparison.Ordinal)));
|
|
Assert.IsFalse(error.Errors.Any(e => e.Contains(Key, StringComparison.Ordinal)), "Errors never repeat a secret.");
|
|
}
|
|
|
|
[TestMethod]
|
|
public void Configuration_ReportsEveryMissingVariableAtOnce()
|
|
{
|
|
var error = Assert.ThrowsExactly<ConfigurationException>(() => new EnvironmentConfigurationReader(_ => null).Read().EnsureValid());
|
|
|
|
Assert.IsTrue(error.Errors.Count >= 2);
|
|
Assert.IsTrue(error.Errors.Any(e => e.StartsWith("KHAEMHAT_SYSTEM_DB", StringComparison.Ordinal)));
|
|
Assert.IsTrue(error.Errors.Any(e => e.StartsWith("KHAEMHAT_SECRET_KEY", StringComparison.Ordinal)));
|
|
}
|
|
|
|
[TestMethod]
|
|
[DataRow("Corta-1", "password_too_short")]
|
|
[DataRow("sololettereminuscole", "password_too_simple")]
|
|
[DataRow("Mario.Rossi-2026", "password_contains_user_name")]
|
|
public void PasswordPolicy_RefusesWeakPasswords(string password, string error) =>
|
|
CollectionAssert.Contains(new PasswordPolicy(new SecurityPolicyOptions()).Check(password, "mario.rossi").ToList(), error);
|
|
|
|
[TestMethod]
|
|
public void PasswordPolicy_AcceptsAGoodPassword() =>
|
|
Assert.AreEqual(0, new PasswordPolicy(new SecurityPolicyOptions()).Check("Granaio-di-Tebe-57", "mario.rossi").Count);
|
|
|
|
[TestMethod]
|
|
public async Task CompanyContext_CompanyAccountsStayInTheirCompany()
|
|
{
|
|
var resolver = new CompanyContextResolver(new FakeRegistry(("A", CompanyStatus.Active), ("B", CompanyStatus.Active)));
|
|
var user = new Actor("mario", UserLevel.Standard, null, 7, "A");
|
|
|
|
Assert.AreEqual("A", (await resolver.ResolveAsync(user, null)).Code);
|
|
Assert.AreEqual("A", (await resolver.ResolveAsync(user, "a")).Code);
|
|
Assert.AreEqual(CompanyAccess.Forbidden, (await resolver.ResolveAsync(user, "B")).Access);
|
|
Assert.AreEqual(CompanyAccess.None, (await resolver.ResolveAsync(null, "A")).Access);
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task CompanyContext_InstanceAccountsChooseTheCompany()
|
|
{
|
|
var resolver = new CompanyContextResolver(new FakeRegistry(("A", CompanyStatus.Active), ("B", CompanyStatus.Maintenance), ("C", CompanyStatus.Disabled)));
|
|
var admin = new Actor("root", UserLevel.SuperUser, 1, null, "A");
|
|
|
|
Assert.AreEqual("A", (await resolver.ResolveAsync(admin, null)).Code);
|
|
Assert.AreEqual("B", (await resolver.ResolveAsync(admin, "B")).Code);
|
|
Assert.AreEqual(CompanyAccess.Disabled, (await resolver.ResolveAsync(admin, "C")).Access);
|
|
Assert.AreEqual(CompanyAccess.NotFound, (await resolver.ResolveAsync(admin, "Z")).Access);
|
|
Assert.AreEqual(CompanyAccess.None, (await resolver.ResolveAsync(admin with { CompanyCode = null }, null)).Access);
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task CompanyContext_MaintenanceIsClosedToCompanyAccounts_ReadOnlyIsFlagged()
|
|
{
|
|
var resolver = new CompanyContextResolver(new FakeRegistry(("B", CompanyStatus.Maintenance), ("R", CompanyStatus.ReadOnly)));
|
|
|
|
var maintenance = await resolver.ResolveAsync(new Actor("mario", UserLevel.Standard, null, 7, "B"), null);
|
|
var readOnly = await resolver.ResolveAsync(new Actor("anna", UserLevel.Standard, null, 8, "R"), null);
|
|
|
|
Assert.IsTrue(maintenance.IsUnavailable);
|
|
Assert.ThrowsExactly<InvalidOperationException>(() => maintenance.Scope());
|
|
Assert.AreEqual(CompanyAccess.Granted, readOnly.Access);
|
|
Assert.IsTrue(readOnly.IsReadOnly);
|
|
Assert.AreEqual(DatabaseScope.Company("R"), readOnly.Scope());
|
|
}
|
|
|
|
[TestMethod]
|
|
public void AuditDiff_ListsOnlyChangedFields_AndNeverSecrets()
|
|
{
|
|
var before = new Role { Code = "VEND", Name = "Vendite", Description = null, CreatedBy = "a" };
|
|
var after = new Role { Code = "VEND", Name = "Vendite Italia", Description = "Rete", CreatedBy = "b" };
|
|
|
|
var diff = AuditTrail.Diff(before, after);
|
|
|
|
CollectionAssert.AreEquivalent(new[] { "Description", "Name" }, diff.Keys.ToArray());
|
|
CollectionAssert.AreEqual(new object?[] { "Vendite", "Vendite Italia" }, diff["Name"]);
|
|
Assert.IsFalse(AuditTrail.Diff(new CompanyUser { PasswordHash = "x" }, new CompanyUser { PasswordHash = "y" }).ContainsKey("PasswordHash"));
|
|
Assert.IsTrue(AuditTrail.Diff<Role>(null, after).ContainsKey("Code"));
|
|
}
|
|
|
|
private static Dictionary<string, string> Required() => new(StringComparer.Ordinal)
|
|
{
|
|
["KHAEMHAT_SYSTEM_DB"] = "sqlite://memory/config",
|
|
["KHAEMHAT_SECRET_KEY"] = Key,
|
|
["KHAEMHAT_DATA_DIR"] = Path.GetFullPath(Path.GetTempPath()),
|
|
["KHAEMHAT_SUPERUSER"] = "root",
|
|
["KHAEMHAT_SUPERUSER_PASSWORD"] = "Test-Password-2026",
|
|
};
|
|
|
|
private sealed class FakeRegistry(params (string Code, CompanyStatus Status)[] companies) : ICompanyRegistry
|
|
{
|
|
private readonly List<Company> _companies = [.. companies.Select((c, i) => new Company { Id = i + 1, Code = c.Code, Name = c.Code, Status = c.Status })];
|
|
|
|
public Task<IReadOnlyList<Company>> ListAsync(CancellationToken cancellationToken = default) => Task.FromResult<IReadOnlyList<Company>>(_companies);
|
|
|
|
public Task<Company?> FindAsync(string code, CancellationToken cancellationToken = default) =>
|
|
Task.FromResult(_companies.FirstOrDefault(c => string.Equals(c.Code, code, StringComparison.OrdinalIgnoreCase)));
|
|
|
|
public Task<Company> RegisterAsync(CompanyRegistration registration, CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
|
|
|
public Task<DatabaseTarget> ResolveAsync(string code, CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
|
|
|
public Task SetStatusAsync(string code, CompanyStatus status, CancellationToken cancellationToken = default) => throw new NotSupportedException();
|
|
}
|
|
}
|