using Omika.Diagnostics.Security; namespace Omika.Diagnostics.Tests; /// Tests de la génération/hachage de la clé d'accès serveur client (T19, §27-§32). public class DiagnosticApiKeyGeneratorTests { [Fact] public void GenerateKey_HasPrefix_AndDecodesTo32Bytes() { string key = DiagnosticApiKeyGenerator.GenerateKey(); Assert.StartsWith(DiagnosticApiKeyGenerator.KeyPrefix, key); string base64Url = key[DiagnosticApiKeyGenerator.KeyPrefix.Length..]; byte[] bytes = DecodeBase64Url(base64Url); Assert.Equal(DiagnosticApiKeyGenerator.KeyBytes, bytes.Length); } [Fact] public void GenerateKey_ProducesUniqueKeys() { HashSet keys = Enumerable.Range(0, 100).Select(_ => DiagnosticApiKeyGenerator.GenerateKey()).ToHashSet(); Assert.Equal(100, keys.Count); } [Fact] public void Hash_IsDeterministic_And64HexChars() { string hash1 = DiagnosticApiKeyGenerator.Hash("omkdiag_test"); string hash2 = DiagnosticApiKeyGenerator.Hash("omkdiag_test"); Assert.Equal(hash1, hash2); Assert.Equal(64, hash1.Length); Assert.Matches("^[0-9A-F]{64}$", hash1); } [Fact] public void Verify_ReturnsTrue_ForMatchingKey() { string key = DiagnosticApiKeyGenerator.GenerateKey(); string hash = DiagnosticApiKeyGenerator.Hash(key); Assert.True(DiagnosticApiKeyGenerator.Verify(key, hash)); } [Fact] public void Verify_ReturnsFalse_ForWrongKey() { string hash = DiagnosticApiKeyGenerator.Hash("omkdiag_real_key"); Assert.False(DiagnosticApiKeyGenerator.Verify("omkdiag_other_key", hash)); } [Fact] public void Verify_ReturnsFalse_ForMalformedHash() { Assert.False(DiagnosticApiKeyGenerator.Verify("omkdiag_x", "not-a-hex-hash")); } [Fact] public void Verify_ReturnsFalse_ForEmptyInputs() { Assert.False(DiagnosticApiKeyGenerator.Verify("", "0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF")); Assert.False(DiagnosticApiKeyGenerator.Verify("omkdiag_x", "")); } [Fact] public void DisplayPrefix_ReturnsFirst8Chars() { string prefix = DiagnosticApiKeyGenerator.DisplayPrefix("omkdiag_abcdefgh", 8); Assert.Equal("omkdiag_", prefix); Assert.Equal(8, prefix.Length); } private static byte[] DecodeBase64Url(string value) { string base64 = value.Replace('-', '+').Replace('_', '/'); switch (base64.Length % 4) { case 2: base64 += "=="; break; case 3: base64 += "="; break; } return Convert.FromBase64String(base64); } }