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>
118 lines
4.8 KiB
C#
118 lines
4.8 KiB
C#
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);
|
|
}
|
|
}
|