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,147 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
using Khaemhat.Core.Logging;
|
||||
using Khaemhat.Core.Scheduling;
|
||||
|
||||
namespace Khaemhat.Core.Tests.Common;
|
||||
|
||||
/// <summary>The five-field cron of the scheduled tasks (SPEC §9.6) and the log sections (SPEC §9.5).</summary>
|
||||
[TestClass]
|
||||
public sealed class CronExpressionTests
|
||||
{
|
||||
private static readonly TimeZoneInfo Rome = TimeZoneInfo.FindSystemTimeZoneById("Europe/Rome");
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("15 * * * *", "2026-11-11T10:20:00Z", "2026-11-11T11:15:00Z")]
|
||||
[DataRow("*/10 * * * *", "2026-11-11T10:20:00Z", "2026-11-11T10:30:00Z")]
|
||||
[DataRow("0 9-17/4 * * *", "2026-11-11T10:00:00Z", "2026-11-11T13:00:00Z")]
|
||||
[DataRow("30 3 1,15 * *", "2026-11-11T00:00:00Z", "2026-11-15T03:30:00Z")]
|
||||
[DataRow("0 0 * * 7", "2026-11-11T00:00:00Z", "2026-11-15T00:00:00Z")]
|
||||
[DataRow("0 0 29 2 *", "2026-03-01T00:00:00Z", "2028-02-29T00:00:00Z")]
|
||||
public void NextAfter_InUtc(string cron, string after, string expected)
|
||||
{
|
||||
var next = CronExpression.Parse(cron).NextAfter(DateTime.Parse(after, null, System.Globalization.DateTimeStyles.AdjustToUniversal), TimeZoneInfo.Utc);
|
||||
|
||||
Assert.AreEqual(DateTime.Parse(expected, null, System.Globalization.DateTimeStyles.AdjustToUniversal), next);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void DayOfMonthAndDayOfWeek_MatchEither()
|
||||
{
|
||||
// The 13th or any Friday: after Wednesday 11 November 2026 comes Friday the 13th, then Friday the 20th.
|
||||
var cron = CronExpression.Parse("0 12 13 * 5");
|
||||
var first = cron.NextAfter(new DateTime(2026, 11, 11, 0, 0, 0, DateTimeKind.Utc), TimeZoneInfo.Utc);
|
||||
var second = cron.NextAfter(first!.Value, TimeZoneInfo.Utc);
|
||||
|
||||
Assert.AreEqual(new DateTime(2026, 11, 13, 12, 0, 0, DateTimeKind.Utc), first);
|
||||
Assert.AreEqual(new DateTime(2026, 11, 20, 12, 0, 0, DateTimeKind.Utc), second);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void LocalTimes_FollowTheTimeZone_AndSkipTheMissingHour()
|
||||
{
|
||||
var cron = CronExpression.Parse("30 2 * * *");
|
||||
|
||||
// 29 March 2026: in Rome clocks jump from 02:00 to 03:00, so 02:30 does not exist that night.
|
||||
var spring = cron.NextAfter(new DateTime(2026, 3, 28, 12, 0, 0, DateTimeKind.Utc), Rome);
|
||||
Assert.AreEqual(new DateTime(2026, 3, 30, 0, 30, 0, DateTimeKind.Utc), spring);
|
||||
|
||||
// In winter Rome is UTC+1.
|
||||
var winter = cron.NextAfter(new DateTime(2026, 11, 11, 12, 0, 0, DateTimeKind.Utc), Rome);
|
||||
Assert.AreEqual(new DateTime(2026, 11, 12, 1, 30, 0, DateTimeKind.Utc), winter);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("")]
|
||||
[DataRow("* * * *")]
|
||||
[DataRow("60 * * * *")]
|
||||
[DataRow("* 24 * * *")]
|
||||
[DataRow("* * 0 * *")]
|
||||
[DataRow("* * * 13 *")]
|
||||
[DataRow("* * * * 8")]
|
||||
[DataRow("*/0 * * * *")]
|
||||
[DataRow("a * * * *")]
|
||||
public void InvalidExpressions_AreRefused(string text)
|
||||
{
|
||||
Assert.IsFalse(CronExpression.TryParse(text, out _, out var error));
|
||||
Assert.IsFalse(string.IsNullOrEmpty(error));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void LogSections_ComeFromTheCategory()
|
||||
{
|
||||
Assert.AreEqual(LogSection.Migrations, LogSections.FromCategory("Khaemhat.Data.Migrations.MigrationRunner"));
|
||||
Assert.AreEqual("Sistema", LogSections.Label(LogSection.System));
|
||||
Assert.AreEqual(LogSection.Authentication, LogSections.FromCategory("Khaemhat.Application.Security.SignInService"));
|
||||
Assert.AreEqual(LogSection.ScheduledJobs, LogSections.FromCategory("Khaemhat.Application.Jobs.JobScheduler"));
|
||||
Assert.AreEqual("Performance", LogSections.Scope(LogSection.Performance).Single().Value);
|
||||
}
|
||||
}
|
||||
@@ -63,11 +63,17 @@ public sealed class MappingTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Registry_FindsTheSystemMaps()
|
||||
public void Registry_FindsTheMapsOfBothDatabases()
|
||||
{
|
||||
var registry = new MapRegistry().AddFromAssembly(typeof(CompanyMap).Assembly);
|
||||
|
||||
CollectionAssert.AreEquivalent(new[] { "sys_companies", "sys_settings" }, registry.Maps.Select(m => m.Table).ToArray());
|
||||
string[] expected =
|
||||
[
|
||||
"sys_companies", "sys_data_protection_keys", "sys_job_locks", "sys_job_runs", "sys_license_activations", "sys_licenses", "sys_log",
|
||||
"sys_notifications", "sys_roles_templates", "sys_scheduled_tasks", "sys_security_audit", "sys_sessions", "sys_settings", "sys_users",
|
||||
"audit_log", "notifications", "role_permissions", "roles", "user_permission_overrides", "user_roles", "user_sessions", "users",
|
||||
];
|
||||
CollectionAssert.AreEquivalent(expected, registry.Maps.Select(m => m.Table).ToArray());
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
|
||||
@@ -87,14 +87,17 @@ public sealed class MigrationTests
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void SystemMaps_AgreeWithTheMigratedSchema()
|
||||
public void Maps_AgreeWithTheMigratedSchema()
|
||||
{
|
||||
var model = MigrationCatalog.ForSystem().BuildModel();
|
||||
var systemModel = MigrationCatalog.ForSystem().BuildModel();
|
||||
var companyModel = MigrationCatalog.ForCompany().BuildModel();
|
||||
var maps = new MapRegistry().AddFromAssembly(typeof(CompanyMap).Assembly);
|
||||
var problems = new List<string>();
|
||||
|
||||
foreach (var map in maps.Maps)
|
||||
{
|
||||
// System tables carry the sys_ prefix (SPEC 5.4); every other table lives in the company databases.
|
||||
var model = map.Table.StartsWith("sys_", StringComparison.Ordinal) ? systemModel : companyModel;
|
||||
var table = model.Table(map.Table);
|
||||
if (table is null)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using Khaemhat.Core.Caching;
|
||||
using Khaemhat.Infrastructure.Caching;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
|
||||
namespace Khaemhat.Infrastructure.Tests;
|
||||
|
||||
/// <summary>The in-house Redis client (SPEC §9.3): protocol vectors, URL parsing and the fall back to memory.</summary>
|
||||
[TestClass]
|
||||
public sealed class RespTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void Command_IsAnArrayOfBulkStrings()
|
||||
{
|
||||
var bytes = Resp.Command("SET", "kh:_:a", "\u00e8", "PX", 1500L);
|
||||
|
||||
Assert.AreEqual("*5\r\n$3\r\nSET\r\n$6\r\nkh:_:a\r\n$2\r\n\u00e8\r\n$2\r\nPX\r\n$4\r\n1500\r\n", Encoding.UTF8.GetString(bytes));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task Replies_OfEveryKind_AreRead()
|
||||
{
|
||||
var reader = Reader("+OK\r\n-ERR wrong\r\n:42\r\n$5\r\nhello\r\n$-1\r\n*2\r\n$1\r\na\r\n:7\r\n*-1\r\n$0\r\n\r\n");
|
||||
|
||||
Assert.AreEqual("OK", (await Resp.ReadAsync(reader)).Text);
|
||||
var error = await Resp.ReadAsync(reader);
|
||||
Assert.AreEqual(RespKind.Error, error.Kind);
|
||||
Assert.AreEqual("ERR wrong", error.Text);
|
||||
Assert.AreEqual(42, (await Resp.ReadAsync(reader)).Number);
|
||||
Assert.AreEqual("hello", (await Resp.ReadAsync(reader)).Text);
|
||||
Assert.AreEqual(RespKind.Null, (await Resp.ReadAsync(reader)).Kind);
|
||||
var array = await Resp.ReadAsync(reader);
|
||||
Assert.AreEqual(2, array.Items!.Count);
|
||||
Assert.AreEqual("a", array.Items[0].Text);
|
||||
Assert.AreEqual(7, array.Items[1].Number);
|
||||
Assert.AreEqual(RespKind.Null, (await Resp.ReadAsync(reader)).Kind);
|
||||
Assert.AreEqual(string.Empty, (await Resp.ReadAsync(reader)).Text);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task BulkStrings_MayContainLineBreaks_AndArriveInPieces()
|
||||
{
|
||||
var reader = new BufferedReader(new TrickleStream(Encoding.UTF8.GetBytes("$4\r\na\r\nb\r\n+OK\r\n")));
|
||||
|
||||
Assert.AreEqual("a\r\nb", (await Resp.ReadAsync(reader)).Text);
|
||||
Assert.AreEqual("OK", (await Resp.ReadAsync(reader)).Text);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public async Task AClosedConnection_IsAnIoError()
|
||||
{
|
||||
await Assert.ThrowsExactlyAsync<IOException>(() => Resp.ReadAsync(Reader("$10\r\nabc")));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Endpoint_ReadsTheUrl_AndHidesThePassword()
|
||||
{
|
||||
var endpoint = RedisEndpoint.Parse("rediss://cache:s%40cret@redis.local:6380/2");
|
||||
|
||||
Assert.AreEqual("redis.local", endpoint.Host);
|
||||
Assert.AreEqual(6380, endpoint.Port);
|
||||
Assert.IsTrue(endpoint.UseTls);
|
||||
Assert.AreEqual("cache", endpoint.User);
|
||||
Assert.AreEqual("s@cret", endpoint.Password);
|
||||
Assert.AreEqual(2, endpoint.Database);
|
||||
Assert.AreEqual("rediss://***@redis.local:6380/2", endpoint.ToString());
|
||||
|
||||
var plain = RedisEndpoint.Parse("redis://:pw@localhost");
|
||||
Assert.IsNull(plain.User);
|
||||
Assert.AreEqual("pw", plain.Password);
|
||||
Assert.AreEqual(6379, plain.Port);
|
||||
Assert.AreEqual(0, plain.Database);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("http://localhost")]
|
||||
[DataRow("redis://localhost/abc")]
|
||||
[DataRow("not a url")]
|
||||
public void Endpoint_RefusesOtherUrls(string url) => Assert.ThrowsExactly<FormatException>(() => RedisEndpoint.Parse(url));
|
||||
|
||||
[TestMethod]
|
||||
public void Pattern_EscapesGlobCharacters() =>
|
||||
Assert.AreEqual(@"kh:A\*B:\[x\]:", RedisCacheProvider.EscapePattern("kh:A*B:[x]:"));
|
||||
|
||||
[TestMethod]
|
||||
public async Task UnreachableRedis_FallsBackToMemory()
|
||||
{
|
||||
// A port nobody listens on: bind a listener, take its port, close it.
|
||||
var listener = new TcpListener(IPAddress.Loopback, 0);
|
||||
listener.Start();
|
||||
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
|
||||
listener.Stop();
|
||||
await using var cache = new RedisCacheProvider(
|
||||
new RedisClient(RedisEndpoint.Parse("redis://127.0.0.1:" + port)) { Timeout = TimeSpan.FromSeconds(1) },
|
||||
TimeProvider.System, NullLogger<RedisCacheProvider>.Instance);
|
||||
var key = CacheKeys.For("A", "test", "x");
|
||||
|
||||
await cache.SetAsync(key, 41, TimeSpan.FromMinutes(1));
|
||||
var value = await cache.GetOrCreateAsync(key, _ => ValueTask.FromResult(0), TimeSpan.FromMinutes(1));
|
||||
|
||||
Assert.AreEqual(41, value);
|
||||
Assert.IsFalse(cache.IsDistributed);
|
||||
await cache.RemoveByPrefixAsync(CacheKeys.Prefix("A", "test"));
|
||||
Assert.AreEqual(0, await cache.GetAsync<int>(key));
|
||||
}
|
||||
|
||||
private static BufferedReader Reader(string text) => new(new MemoryStream(Encoding.UTF8.GetBytes(text)));
|
||||
|
||||
/// <summary>Returns one byte per read, as a slow network would.</summary>
|
||||
private sealed class TrickleStream(byte[] data) : MemoryStream(data)
|
||||
{
|
||||
public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default) =>
|
||||
base.ReadAsync(buffer[..Math.Min(1, buffer.Length)], cancellationToken);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Khaemhat.Infrastructure.Licensing;
|
||||
using Khaemhat.Infrastructure.Security;
|
||||
|
||||
namespace Khaemhat.Infrastructure.Tests;
|
||||
|
||||
/// <summary>TOTP (RFC 6238), password hashes and signed licences (SPEC §7, §8).</summary>
|
||||
[TestClass]
|
||||
public sealed class SecurityPrimitivesTests
|
||||
{
|
||||
private static readonly byte[] RfcSecret = Encoding.ASCII.GetBytes("12345678901234567890");
|
||||
|
||||
[TestMethod]
|
||||
[DataRow(59L, "287082")]
|
||||
[DataRow(1111111109L, "081804")]
|
||||
[DataRow(1234567890L, "005924")]
|
||||
[DataRow(2000000000L, "279037")]
|
||||
public void Totp_MatchesTheRfc6238Vectors(long unixSeconds, string expected) =>
|
||||
Assert.AreEqual(expected, TotpGenerator.Compute(RfcSecret, TotpGenerator.StepOf(DateTimeOffset.FromUnixTimeSeconds(unixSeconds))));
|
||||
|
||||
[TestMethod]
|
||||
public void Totp_AcceptsOneStepOfDrift_AndNeverTheSameCodeTwice()
|
||||
{
|
||||
var secret = Base32.Encode(RfcSecret);
|
||||
var now = DateTimeOffset.FromUnixTimeSeconds(1111111109);
|
||||
var previous = TotpGenerator.Compute(RfcSecret, TotpGenerator.StepOf(now) - 1);
|
||||
|
||||
var step = TotpGenerator.Verify(secret, previous, now, lastUsedStep: null);
|
||||
|
||||
Assert.AreEqual(TotpGenerator.StepOf(now) - 1, step);
|
||||
Assert.IsNull(TotpGenerator.Verify(secret, previous, now, lastUsedStep: step));
|
||||
Assert.IsNull(TotpGenerator.Verify(secret, "12345", now, null));
|
||||
Assert.IsNull(TotpGenerator.Verify(secret, "abcdef", now, null));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Base32_RoundTrips()
|
||||
{
|
||||
var data = RandomNumberGenerator.GetBytes(20);
|
||||
|
||||
CollectionAssert.AreEqual(data, Base32.Decode(Base32.Encode(data)));
|
||||
Assert.AreEqual("GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ", Base32.Encode(RfcSecret));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void Licence_SignedWithTheKey_IsValid_AndAnyChangeBreaksIt()
|
||||
{
|
||||
var (privatePem, publicKey) = LicenseSigner.CreateKeyPair();
|
||||
using var key = ECDsa.Create();
|
||||
key.ImportFromPem(privatePem);
|
||||
var document = new LicenseDocument
|
||||
{
|
||||
Id = "L-1",
|
||||
Licensee = "Prova S.r.l.",
|
||||
IssuedAt = new DateTime(2026, 11, 1, 0, 0, 0, DateTimeKind.Utc),
|
||||
MaxConcurrentUsers = 5,
|
||||
MaxCompanies = 1,
|
||||
Modules = ["CORE", "ACCT"],
|
||||
};
|
||||
var text = LicenseSigner.Sign(document, key);
|
||||
var verifier = new LicenseVerifier(publicKey);
|
||||
|
||||
var valid = verifier.Verify(text);
|
||||
Assert.IsNull(valid.Error);
|
||||
Assert.AreEqual("Prova S.r.l.", valid.Document!.Licensee);
|
||||
|
||||
var tampered = text.Replace("Prova S.r.l.", "Altra S.r.l.", StringComparison.Ordinal);
|
||||
Assert.AreNotEqual(text, tampered, "The test must change the licence.");
|
||||
Assert.AreEqual(LicenseErrors.SignatureInvalid, verifier.Verify(tampered).Error);
|
||||
Assert.AreEqual(LicenseErrors.SignatureInvalid, LicenseVerifier.Product.Verify(text).Error);
|
||||
Assert.AreEqual(LicenseErrors.FormatInvalid, verifier.Verify("{not json").Error);
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ActivationCode_SignedWithTheKey_IsValid_AndForgeriesAreNot()
|
||||
{
|
||||
var (privatePem, publicKey) = LicenseSigner.CreateKeyPair();
|
||||
using var key = ECDsa.Create();
|
||||
key.ImportFromPem(privatePem);
|
||||
var code = LicenseSigner.SignActivationCode("CRM", new DateOnly(2027, 12, 1), null, key);
|
||||
var verifier = new LicenseVerifier(publicKey);
|
||||
|
||||
var (parsed, error) = verifier.VerifyActivationCode(code);
|
||||
|
||||
Assert.IsNull(error);
|
||||
Assert.AreEqual("CRM", parsed!.Module);
|
||||
Assert.IsNotNull(LicenseVerifier.Product.VerifyActivationCode(code).Error);
|
||||
Assert.IsNotNull(verifier.VerifyActivationCode(code.Replace("CRM", "ACCT", StringComparison.Ordinal)).Error);
|
||||
}
|
||||
}
|
||||
@@ -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