feat: data layer with SQLite and PostgreSQL providers, migrations and encrypted company registry (M1)
CI / Build and test (SQLite) (pull_request) Successful in 45s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / YAML check (pull_request) Successful in 3s
CI / Docker image (pull_request) Successful in 51s
CI / Build and test (SQLite) (pull_request) Successful in 45s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / YAML check (pull_request) Successful in 3s
CI / Docker image (pull_request) Successful in 51s
Every later milestone stores its data through this layer, so it has to behave the same on both engines and be safe by construction: - Khaemhat.Data: explicit entity maps, typed queries over a safe expression subset, SqlFragment where every interpolated value becomes a parameter, unit of work with transactions, repositories with audit columns and optimistic concurrency on row_version, retries on transient errors. - SQLite provider (STRICT tables, WAL, exact decimals as integers scaled by 10^6, Unicode case-insensitive LIKE, serialised writes) and PostgreSQL 16+ provider (numeric(19,6), timestamptz, jsonb, advisory locks, database creation and server info). Databases are configured from postgres:// and sqlite:// URLs whose password never appears in messages. - C# migrations with system and company catalogues, schema_version with checksums, one transaction per migration under a lock, refusal of unknown applied versions; first system tables sys_companies and sys_settings. - CompanyRegistry stores each company's database URL encrypted with the instance key (AES-256-GCM, HKDF-derived key, purpose as associated data), so a copied row cannot be read for another company. - tools/Khaemhat.DataModelTool, scripts/gen-datamodel.sh and scripts/new-migration.sh: the current schema section of docs/DATA-MODEL.md is generated from the migrations and a test fails when it is stale. - C# 14 binds array.Contains to MemoryExtensions over spans; the query translator unwraps the span conversion. - Tests run every data scenario on SQLite and PostgreSQL (PostgreSQL in CI); ADR 0018 records where the contracts differ from SPEC 5.1. Docs, wiki, changelog and status updated. Closes #7, #8, #9, #10, #11, #12, #13, #14 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
28e7a6e18a
commit
738c43ba0a
105 files changed
+8434
-73
No files matched your search
@@ -0,0 +1,189 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Khaemhat.Core.Security;
|
||||
|
||||
namespace Khaemhat.Infrastructure.Security;
|
||||
|
||||
/// <summary>
|
||||
/// The instance key from <c>KHAEMHAT_SECRET_KEY</c>: base64 of at least 32 random bytes (SPEC §6). The encryption key
|
||||
/// is derived with HKDF-SHA256, so the configured bytes are never used directly. The key is never printed.
|
||||
/// </summary>
|
||||
public sealed class SecretKey
|
||||
{
|
||||
/// <summary>The minimum length of the configured key, in bytes.</summary>
|
||||
public const int MinimumLength = 32;
|
||||
|
||||
private static readonly byte[] EncryptionInfo = "khaemhat/secrets/aes-256-gcm/v1"u8.ToArray();
|
||||
private static readonly byte[] IdentifierInfo = "khaemhat/secrets/key-id/v1"u8.ToArray();
|
||||
|
||||
private SecretKey(byte[] encryptionKey, string id)
|
||||
{
|
||||
EncryptionKey = encryptionKey;
|
||||
Id = id;
|
||||
}
|
||||
|
||||
/// <summary>A short public identifier of the key (8 hexadecimal digits), stored with each ciphertext.</summary>
|
||||
public string Id { get; }
|
||||
|
||||
internal byte[] EncryptionKey { get; }
|
||||
|
||||
/// <summary>Reads a key in base64.</summary>
|
||||
/// <param name="base64">The configured value.</param>
|
||||
/// <returns>The key.</returns>
|
||||
/// <exception cref="FormatException">Not base64, or shorter than 32 bytes (the message never repeats the value).</exception>
|
||||
public static SecretKey FromBase64(string base64)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(base64))
|
||||
{
|
||||
throw new FormatException("KHAEMHAT_SECRET_KEY is empty: set it to the base64 of at least 32 random bytes.");
|
||||
}
|
||||
|
||||
byte[] material;
|
||||
try
|
||||
{
|
||||
material = Convert.FromBase64String(base64.Trim());
|
||||
}
|
||||
catch (FormatException)
|
||||
{
|
||||
throw new FormatException("KHAEMHAT_SECRET_KEY is not valid base64.");
|
||||
}
|
||||
|
||||
if (material.Length < MinimumLength)
|
||||
{
|
||||
throw new FormatException($"KHAEMHAT_SECRET_KEY must be the base64 of at least {MinimumLength} bytes (for example: openssl rand -base64 32).");
|
||||
}
|
||||
|
||||
var encryption = HKDF.DeriveKey(HashAlgorithmName.SHA256, material, 32, salt: null, info: EncryptionInfo);
|
||||
var id = Convert.ToHexStringLower(HKDF.DeriveKey(HashAlgorithmName.SHA256, material, 4, salt: null, info: IdentifierInfo));
|
||||
CryptographicOperations.ZeroMemory(material);
|
||||
return new SecretKey(encryption, id);
|
||||
}
|
||||
|
||||
/// <summary>Creates a new random key in base64, for setup instructions and tests.</summary>
|
||||
/// <returns>The base64 text of 32 random bytes.</returns>
|
||||
public static string GenerateBase64() => Convert.ToBase64String(RandomNumberGenerator.GetBytes(MinimumLength));
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string ToString() => "SecretKey " + Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="ISecretProtector"/> with AES-256-GCM (SPEC §5.4). A protected value is
|
||||
/// <c>khs1.<key id>.<base64url(nonce | tag | ciphertext)></c>; the purpose is authenticated as associated
|
||||
/// data, so a value cannot be moved to another purpose, and a value of another key is recognized by its key id.
|
||||
/// </summary>
|
||||
/// <param name="key">The instance key.</param>
|
||||
public sealed class SecretProtector(SecretKey key) : ISecretProtector
|
||||
{
|
||||
private const string Prefix = "khs1";
|
||||
private const int NonceSize = 12;
|
||||
private const int TagSize = 16;
|
||||
|
||||
/// <summary>The key.</summary>
|
||||
public SecretKey Key { get; } = key ?? throw new ArgumentNullException(nameof(key));
|
||||
|
||||
/// <summary>The key id stored in a protected value, or <see langword="null"/> if it is not one.</summary>
|
||||
/// <param name="protectedValue">The value.</param>
|
||||
/// <returns>The key id.</returns>
|
||||
public static string? KeyIdOf(string? protectedValue)
|
||||
{
|
||||
var parts = protectedValue?.Split('.');
|
||||
return parts is [Prefix, var id, _] ? id : null;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Protect(string plaintext, string purpose)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(plaintext);
|
||||
ArgumentException.ThrowIfNullOrEmpty(purpose);
|
||||
var plain = Encoding.UTF8.GetBytes(plaintext);
|
||||
var buffer = new byte[NonceSize + TagSize + plain.Length];
|
||||
var nonce = buffer.AsSpan(0, NonceSize);
|
||||
RandomNumberGenerator.Fill(nonce);
|
||||
using (var aes = new AesGcm(Key.EncryptionKey, TagSize))
|
||||
{
|
||||
aes.Encrypt(nonce, plain, buffer.AsSpan(NonceSize + TagSize), buffer.AsSpan(NonceSize, TagSize), Encoding.UTF8.GetBytes(purpose));
|
||||
}
|
||||
|
||||
CryptographicOperations.ZeroMemory(plain);
|
||||
return Prefix + "." + Key.Id + "." + Base64Url(buffer);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Unprotect(string protectedValue, string purpose)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrEmpty(purpose);
|
||||
var parts = protectedValue?.Split('.');
|
||||
if (parts is not [Prefix, var id, var payload])
|
||||
{
|
||||
throw new SecretProtectionException("The value is not a protected secret.");
|
||||
}
|
||||
|
||||
if (!string.Equals(id, Key.Id, StringComparison.Ordinal))
|
||||
{
|
||||
throw new SecretProtectionException(
|
||||
$"The secret was protected with another instance key ({id}, current {Key.Id}): check KHAEMHAT_SECRET_KEY or run the key rotation.");
|
||||
}
|
||||
|
||||
byte[] buffer;
|
||||
try
|
||||
{
|
||||
buffer = FromBase64Url(payload);
|
||||
}
|
||||
catch (FormatException ex)
|
||||
{
|
||||
throw new SecretProtectionException("The protected secret is damaged.", ex);
|
||||
}
|
||||
|
||||
if (buffer.Length < NonceSize + TagSize)
|
||||
{
|
||||
throw new SecretProtectionException("The protected secret is damaged.");
|
||||
}
|
||||
|
||||
var plain = new byte[buffer.Length - NonceSize - TagSize];
|
||||
try
|
||||
{
|
||||
using var aes = new AesGcm(Key.EncryptionKey, TagSize);
|
||||
aes.Decrypt(
|
||||
buffer.AsSpan(0, NonceSize), buffer.AsSpan(NonceSize + TagSize), buffer.AsSpan(NonceSize, TagSize), plain, Encoding.UTF8.GetBytes(purpose));
|
||||
return Encoding.UTF8.GetString(plain);
|
||||
}
|
||||
catch (AuthenticationTagMismatchException ex)
|
||||
{
|
||||
throw new SecretProtectionException("The secret cannot be decrypted: damaged value or different purpose.", ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
CryptographicOperations.ZeroMemory(plain);
|
||||
}
|
||||
}
|
||||
|
||||
private static string Base64Url(byte[] bytes) => Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_');
|
||||
|
||||
private static byte[] FromBase64Url(string text)
|
||||
{
|
||||
var base64 = text.Replace('-', '+').Replace('_', '/');
|
||||
return Convert.FromBase64String(base64.PadRight(base64.Length + ((4 - (base64.Length % 4)) % 4), '='));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Re-encryption of secrets from the current key to <c>KHAEMHAT_SECRET_KEY_NEW</c> (SPEC §12.9). This is the building
|
||||
/// block; the procedure that walks every encrypted column of every database arrives in milestone M12.
|
||||
/// </summary>
|
||||
/// <param name="current">The protector with the current key.</param>
|
||||
/// <param name="next">The protector with the new key.</param>
|
||||
public sealed class SecretRotation(SecretProtector current, SecretProtector next)
|
||||
{
|
||||
/// <summary>Whether a value still needs to be re-encrypted with the new key.</summary>
|
||||
/// <param name="protectedValue">The protected value.</param>
|
||||
/// <returns><see langword="true"/> if it is not protected with the new key yet.</returns>
|
||||
public bool NeedsRotation(string protectedValue) => SecretProtector.KeyIdOf(protectedValue) != next.Key.Id;
|
||||
|
||||
/// <summary>Re-encrypts a value with the new key; values already rotated are returned unchanged.</summary>
|
||||
/// <param name="protectedValue">The protected value.</param>
|
||||
/// <param name="purpose">Its purpose.</param>
|
||||
/// <returns>The value protected with the new key.</returns>
|
||||
public string Rotate(string protectedValue, string purpose) =>
|
||||
NeedsRotation(protectedValue) ? next.Protect(current.Unprotect(protectedValue, purpose), purpose) : protectedValue;
|
||||
}
|
||||
Reference in new issue
Block a user