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>
143 lines
5.2 KiB
C#
143 lines
5.2 KiB
C#
using System.Net;
|
|
using System.Net.Http.Json;
|
|
using Khaemhat.Web.Hosting;
|
|
using Microsoft.AspNetCore.Builder;
|
|
|
|
namespace Khaemhat.Web.Tests.Hosting;
|
|
|
|
/// <summary>
|
|
/// Starts the real host on a free loopback port (no test-host package: SPEC §1.2) and calls it over HTTP.
|
|
/// </summary>
|
|
[TestClass]
|
|
public sealed class HostTests
|
|
{
|
|
private static WebApplication? _app;
|
|
private static Uri? _address;
|
|
private static string? _company;
|
|
|
|
[ClassInitialize]
|
|
public static async Task StartAsync(TestContext context)
|
|
{
|
|
(_app, _address, _company) = await TestInstance.StartAsync(context.CancellationToken);
|
|
}
|
|
|
|
[ClassCleanup]
|
|
public static async Task StopAsync()
|
|
{
|
|
if (_app is not null)
|
|
{
|
|
await _app.StopAsync();
|
|
await _app.DisposeAsync();
|
|
}
|
|
}
|
|
|
|
[TestMethod]
|
|
[DataRow("/health/live", "live")]
|
|
[DataRow("/health/ready", "ready")]
|
|
public async Task HealthProbes_AnswerOk(string path, string body)
|
|
{
|
|
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());
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task Health_ReportsStatusAndVersion()
|
|
{
|
|
using var client = Client();
|
|
var report = await client.GetFromJsonAsync<HealthEndpoints.HealthReport>(new Uri("/health", UriKind.Relative));
|
|
|
|
Assert.IsNotNull(report);
|
|
Assert.AreEqual("ok", report.Status);
|
|
Assert.IsTrue(report.Live);
|
|
Assert.IsTrue(report.Ready);
|
|
Assert.IsFalse(string.IsNullOrEmpty(report.Version));
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task HomePage_RedirectsAnonymousUsersToTheLogin()
|
|
{
|
|
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, "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 client = Client();
|
|
using var response = await client.GetAsync(new Uri("/does-not-exist", UriKind.Relative));
|
|
|
|
Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode);
|
|
}
|
|
|
|
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."),
|
|
};
|
|
}
|