F1 and "?" now open the wiki page of the screen inside the application (/aiuto, mockup 011) from a copy of the wiki shipped next to the program, so help works offline and always matches the installed version. Markdown is converted in-house and fully encoded; images of the repository are served from the copy. KHAEMHAT_HELP_URL sets the online wiki behind "Apri nel wiki"; "Segnala un problema" opens a new issue of that repo. A test checks that every page and menu entry has an existing wiki page. The bell opens a notifications panel (mockup 010) with all/unread filters and mark read. Broadcast notifications are now read per user through sys_notification_reads / notification_reads instead of one shared read_at. The global search asks ISearchProvider implementations through GlobalSearchService after a short pause; the first provider finds help pages and sections, # and @ say which modules will fill them. Escape also closes a side panel when the focus fell out of it. Decisions in ADR 0023. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
162 lines
8.3 KiB
C#
162 lines
8.3 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_HelpUrl_IsAnAbsoluteWebAddress()
|
|
{
|
|
var variables = Required();
|
|
variables["KHAEMHAT_HELP_URL"] = "https://git.example.com/acme/khaemhat/wiki/";
|
|
var options = new EnvironmentConfigurationReader(n => variables.GetValueOrDefault(n)).Read();
|
|
options.EnsureValid();
|
|
Assert.AreEqual("https://git.example.com/acme/khaemhat/wiki/", options.HelpUrl);
|
|
|
|
variables["KHAEMHAT_HELP_URL"] = "wiki/locale";
|
|
var error = Assert.ThrowsExactly<ConfigurationException>(() => new EnvironmentConfigurationReader(n => variables.GetValueOrDefault(n)).Read().EnsureValid());
|
|
Assert.IsTrue(error.Errors.Any(e => e.StartsWith("KHAEMHAT_HELP_URL", StringComparison.Ordinal)));
|
|
}
|
|
|
|
[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();
|
|
}
|
|
}
|