Files
Khaemhat/tests/Khaemhat.Infrastructure.Tests/SecurityPrimitivesTests.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

92 lines
3.7 KiB
C#

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