using ZB.MOM.WW.Auth.Abstractions.ApiKeys; namespace ZB.MOM.WW.Auth.ApiKeys.SqlServer; /// /// Keeps the SQL Server stores' key-id handling identical to the SQLite store they port (Auth-008): /// no silent truncation and exact key-id matching. /// /// /// /// Lengths. Every parameter carries an explicit size, and SqlClient truncates an over-length /// value to that size without an error. So an over-length key record is refused up front, and a /// lookup of an over-length key id answers "not found" without querying — such a key cannot exist, /// and the truncated parameter would otherwise match a different key that shares its first 64 /// characters. /// /// /// Case. The key_id column uses the database's collation, case-insensitive on a stock /// SQL Server, whereas SQLite compares key ids byte-for-byte. Changing the column's collation would /// need a schema migration of a primary key on a live shared store, so every key_id predicate /// instead adds : the collation-aware = still drives the primary-key /// seek, and the binary comparison then rejects a row that differs in case or trailing spaces. /// /// internal static class SqlServerColumnLimits { /// Width of api_keys.key_id (and api_key_audit.key_id). public const int KeyId = 64; /// Width of api_keys.key_prefix. public const int KeyPrefix = 16; /// Width of api_keys.display_name. public const int DisplayName = 256; /// /// Appended to every key_id = @key_id. NVARCHAR → VARBINARY yields the UTF-16 /// bytes, so the comparison is exact (case, accents and trailing spaces all significant). /// public const string ExactKeyIdMatch = "CAST(key_id AS VARBINARY(128)) = CAST(@key_id AS VARBINARY(128))"; /// Whether a key with this id could be stored at all. public static bool CanExist(string keyId) => keyId.Length <= KeyId; /// The first over-length field of , described, or when every field fits. public static string? OverLengthField(ApiKeyRecord record) => record.KeyId.Length > KeyId ? Describe(nameof(ApiKeyRecord.KeyId), record.KeyId.Length, KeyId) : record.KeyPrefix.Length > KeyPrefix ? Describe(nameof(ApiKeyRecord.KeyPrefix), record.KeyPrefix.Length, KeyPrefix) : record.DisplayName.Length > DisplayName ? Describe(nameof(ApiKeyRecord.DisplayName), record.DisplayName.Length, DisplayName) : null; /// Throws when a field of exceeds its column. public static void EnsureFits(ApiKeyRecord record) { if (OverLengthField(record) is { } problem) throw new ArgumentException($"API key record cannot be stored in SQL Server: {problem}.", nameof(record)); } private static string Describe(string field, int length, int max) => $"{field} is {length} characters, more than the column's {max}"; }