fix(auth): SQL Server key store refuses truncation and matches key ids exactly (Auth-008)

- Over-length key records (key_id > 64, prefix > 16, display name > 256) are
  refused with ArgumentException before connecting; an over-64 key-id lookup
  or mutation answers not-found without querying (SqlClient silently
  truncated the sized parameter, so a different id sharing the first 64
  characters matched).
- Every key_id predicate adds an exact VARBINARY comparison, so lookups are
  case- and trailing-space-exact like SQLite; the PK seek is unchanged and
  there is no schema change.
- SqliteApiKeyStoreImporter reports case-only key-id collisions and
  over-length rows in new init lists (KeyIdCollisions, KeysRejected) instead
  of counting them as skips or importing them truncated.
- Audit text truncation kept deliberately and documented.

Offline refused-port tests and live SQL Server 2022 tests fail pre-fix;
SqlServer suite 101/101 live. Auth findings now 0 open; CLAUDE.md records
the #46/#50 work; code-reviews/README.md regenerated.

(scadaproj#46)

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
This commit is contained in:
Joseph Doherty
2026-11-09 15:26:03 -05:00
parent c4366539ca
commit b33f0f93c9
11 changed files with 417 additions and 30 deletions
@@ -23,11 +23,17 @@ public sealed class SqlServerApiKeyAdminStore(AuthSqlServerConnectionFactory con
/// <remarks>
/// A plain INSERT: a duplicate <c>key_id</c> surfaces as a primary-key
/// <see cref="SqlException"/> rather than silently overwriting an existing key (the SQLite store
/// raises its own <c>SqliteException</c> in the same situation).
/// raises its own <c>SqliteException</c> in the same situation). Unlike SQLite, the primary key
/// follows the database collation, so on a case-insensitive database <c>Line1</c> cannot be
/// created beside <c>line1</c> either. A key id over 64, prefix over 16 or display name over 256
/// characters throws <see cref="ArgumentException"/> before anything is sent (since 0.4.4; it
/// was silently truncated before).
/// </remarks>
/// <exception cref="ArgumentException">A field is longer than its column.</exception>
public async Task CreateAsync(ApiKeyRecord record, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(record);
SqlServerColumnLimits.EnsureFits(record);
string schema = connectionFactory.Schema;
@@ -65,6 +71,8 @@ public sealed class SqlServerApiKeyAdminStore(AuthSqlServerConnectionFactory con
public async Task<bool> RevokeAsync(string keyId, DateTimeOffset whenUtc, CancellationToken ct)
{
ArgumentException.ThrowIfNullOrWhiteSpace(keyId);
if (!SqlServerColumnLimits.CanExist(keyId))
return false;
string schema = connectionFactory.Schema;
@@ -74,7 +82,7 @@ public sealed class SqlServerApiKeyAdminStore(AuthSqlServerConnectionFactory con
await using SqlCommand command = connectionFactory.CreateCommand(connection, $"""
UPDATE [{schema}].[{SqlServerAuthSchema.ApiKeysTable}]
SET revoked_utc = @revoked_utc
WHERE key_id = @key_id AND revoked_utc IS NULL;
WHERE key_id = @key_id AND {SqlServerColumnLimits.ExactKeyIdMatch} AND revoked_utc IS NULL;
""");
command.Parameters.Add("@key_id", SqlDbType.NVarChar, 64).Value = keyId;
command.Parameters.Add("@revoked_utc", SqlDbType.DateTimeOffset).Value = whenUtc;
@@ -93,6 +101,8 @@ public sealed class SqlServerApiKeyAdminStore(AuthSqlServerConnectionFactory con
public async Task<bool> RotateAsync(string keyId, byte[] newSecretHash, CancellationToken ct)
{
ArgumentException.ThrowIfNullOrWhiteSpace(keyId);
if (!SqlServerColumnLimits.CanExist(keyId))
return false;
ArgumentNullException.ThrowIfNull(newSecretHash);
string schema = connectionFactory.Schema;
@@ -105,7 +115,7 @@ public sealed class SqlServerApiKeyAdminStore(AuthSqlServerConnectionFactory con
SET secret_hash = @secret_hash,
last_used_utc = NULL,
revoked_utc = NULL
WHERE key_id = @key_id;
WHERE key_id = @key_id AND {SqlServerColumnLimits.ExactKeyIdMatch};
""");
command.Parameters.Add("@key_id", SqlDbType.NVarChar, 64).Value = keyId;
command.Parameters.Add("@secret_hash", SqlDbType.VarBinary, 64).Value = newSecretHash;
@@ -119,6 +129,8 @@ public sealed class SqlServerApiKeyAdminStore(AuthSqlServerConnectionFactory con
public async Task<bool> SetScopesAsync(string keyId, IReadOnlySet<string> scopes, CancellationToken ct)
{
ArgumentException.ThrowIfNullOrWhiteSpace(keyId);
if (!SqlServerColumnLimits.CanExist(keyId))
return false;
ArgumentNullException.ThrowIfNull(scopes);
string schema = connectionFactory.Schema;
@@ -129,7 +141,7 @@ public sealed class SqlServerApiKeyAdminStore(AuthSqlServerConnectionFactory con
await using SqlCommand command = connectionFactory.CreateCommand(connection, $"""
UPDATE [{schema}].[{SqlServerAuthSchema.ApiKeysTable}]
SET scopes = @scopes
WHERE key_id = @key_id;
WHERE key_id = @key_id AND {SqlServerColumnLimits.ExactKeyIdMatch};
""");
command.Parameters.Add("@key_id", SqlDbType.NVarChar, 64).Value = keyId;
command.Parameters.Add("@scopes", SqlDbType.NVarChar, -1).Value = ScopeSerializer.Serialize(scopes);
@@ -143,6 +155,8 @@ public sealed class SqlServerApiKeyAdminStore(AuthSqlServerConnectionFactory con
public async Task<bool> SetEnabledAsync(string keyId, bool enabled, DateTimeOffset whenUtc, CancellationToken ct)
{
ArgumentException.ThrowIfNullOrWhiteSpace(keyId);
if (!SqlServerColumnLimits.CanExist(keyId))
return false;
string schema = connectionFactory.Schema;
@@ -159,7 +173,7 @@ public sealed class SqlServerApiKeyAdminStore(AuthSqlServerConnectionFactory con
command = connectionFactory.CreateCommand(connection, $"""
UPDATE [{schema}].[{SqlServerAuthSchema.ApiKeysTable}]
SET revoked_utc = NULL
WHERE key_id = @key_id;
WHERE key_id = @key_id AND {SqlServerColumnLimits.ExactKeyIdMatch};
""");
command.Parameters.Add("@key_id", SqlDbType.NVarChar, 64).Value = keyId;
}
@@ -168,7 +182,7 @@ public sealed class SqlServerApiKeyAdminStore(AuthSqlServerConnectionFactory con
command = connectionFactory.CreateCommand(connection, $"""
UPDATE [{schema}].[{SqlServerAuthSchema.ApiKeysTable}]
SET revoked_utc = @revoked_utc
WHERE key_id = @key_id;
WHERE key_id = @key_id AND {SqlServerColumnLimits.ExactKeyIdMatch};
""");
command.Parameters.Add("@key_id", SqlDbType.NVarChar, 64).Value = keyId;
command.Parameters.Add("@revoked_utc", SqlDbType.DateTimeOffset).Value = whenUtc;
@@ -190,6 +204,8 @@ public sealed class SqlServerApiKeyAdminStore(AuthSqlServerConnectionFactory con
public async Task<bool> DeleteAsync(string keyId, CancellationToken ct)
{
ArgumentException.ThrowIfNullOrWhiteSpace(keyId);
if (!SqlServerColumnLimits.CanExist(keyId))
return false;
string schema = connectionFactory.Schema;
@@ -198,7 +214,7 @@ public sealed class SqlServerApiKeyAdminStore(AuthSqlServerConnectionFactory con
await using SqlCommand command = connectionFactory.CreateCommand(connection, $"""
DELETE FROM [{schema}].[{SqlServerAuthSchema.ApiKeysTable}]
WHERE key_id = @key_id AND revoked_utc IS NOT NULL;
WHERE key_id = @key_id AND {SqlServerColumnLimits.ExactKeyIdMatch} AND revoked_utc IS NOT NULL;
""");
command.Parameters.Add("@key_id", SqlDbType.NVarChar, 64).Value = keyId;
@@ -13,6 +13,14 @@ namespace ZB.MOM.WW.Auth.ApiKeys.SqlServer;
public sealed class SqlServerApiKeyAuditStore(AuthSqlServerConnectionFactory connectionFactory) : IApiKeyAuditStore
{
/// <inheritdoc />
/// <remarks>
/// <b>Over-length text is truncated, deliberately.</b> <c>key_id</c>, <c>event_type</c> and
/// <c>remote_address</c> are 64-character columns; a longer value is stored as its first 64
/// characters (the SQLite store keeps it whole). Unlike a key record (refused when over-length,
/// see <see cref="SqlServerApiKeyAdminStore.CreateAsync"/>), an audit append is not refused: it
/// runs after the action it records, and failing it would lose the record of a change that has
/// already happened. <c>details</c> is unbounded.
/// </remarks>
public async Task AppendAsync(ApiKeyAuditEntry entry, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(entry);
@@ -42,6 +42,8 @@ public sealed class SqlServerApiKeyStore(AuthSqlServerConnectionFactory connecti
public async Task MarkUsedAsync(string keyId, DateTimeOffset whenUtc, CancellationToken ct)
{
ArgumentException.ThrowIfNullOrWhiteSpace(keyId);
if (!SqlServerColumnLimits.CanExist(keyId))
return;
string schema = connectionFactory.Schema;
@@ -51,7 +53,7 @@ public sealed class SqlServerApiKeyStore(AuthSqlServerConnectionFactory connecti
await using SqlCommand command = connectionFactory.CreateCommand(connection, $"""
UPDATE [{schema}].[{SqlServerAuthSchema.ApiKeysTable}]
SET last_used_utc = @last_used_utc
WHERE key_id = @key_id AND revoked_utc IS NULL;
WHERE key_id = @key_id AND {SqlServerColumnLimits.ExactKeyIdMatch} AND revoked_utc IS NULL;
""");
command.Parameters.Add("@key_id", SqlDbType.NVarChar, 64).Value = keyId;
command.Parameters.Add("@last_used_utc", SqlDbType.DateTimeOffset).Value = whenUtc;
@@ -61,6 +63,11 @@ public sealed class SqlServerApiKeyStore(AuthSqlServerConnectionFactory connecti
private async Task<ApiKeyRecord?> FindAsync(string keyId, bool requireActive, CancellationToken ct)
{
// An id longer than the column cannot be stored; querying would truncate it and could match
// another key sharing its first 64 characters (Auth-008).
if (!SqlServerColumnLimits.CanExist(keyId))
return null;
string schema = connectionFactory.Schema;
string table = $"[{schema}].[{SqlServerAuthSchema.ApiKeysTable}]";
@@ -72,8 +79,8 @@ public sealed class SqlServerApiKeyStore(AuthSqlServerConnectionFactory connecti
await using SqlCommand command = connectionFactory.CreateCommand(
connection,
requireActive
? $"SELECT {SelectColumns} FROM {table} WHERE key_id = @key_id AND revoked_utc IS NULL;"
: $"SELECT {SelectColumns} FROM {table} WHERE key_id = @key_id;");
? $"SELECT {SelectColumns} FROM {table} WHERE key_id = @key_id AND {SqlServerColumnLimits.ExactKeyIdMatch} AND revoked_utc IS NULL;"
: $"SELECT {SelectColumns} FROM {table} WHERE key_id = @key_id AND {SqlServerColumnLimits.ExactKeyIdMatch};");
command.Parameters.Add("@key_id", SqlDbType.NVarChar, 64).Value = keyId;
await using SqlDataReader reader = await command.ExecuteReaderAsync(ct).ConfigureAwait(false);
@@ -0,0 +1,61 @@
using ZB.MOM.WW.Auth.Abstractions.ApiKeys;
namespace ZB.MOM.WW.Auth.ApiKeys.SqlServer;
/// <summary>
/// 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.
/// </summary>
/// <remarks>
/// <para>
/// <b>Lengths.</b> 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.
/// </para>
/// <para>
/// <b>Case.</b> The <c>key_id</c> 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 <c>key_id</c> predicate
/// instead adds <see cref="ExactKeyIdMatch"/>: the collation-aware <c>=</c> still drives the primary-key
/// seek, and the binary comparison then rejects a row that differs in case or trailing spaces.
/// </para>
/// </remarks>
internal static class SqlServerColumnLimits
{
/// <summary>Width of <c>api_keys.key_id</c> (and <c>api_key_audit.key_id</c>).</summary>
public const int KeyId = 64;
/// <summary>Width of <c>api_keys.key_prefix</c>.</summary>
public const int KeyPrefix = 16;
/// <summary>Width of <c>api_keys.display_name</c>.</summary>
public const int DisplayName = 256;
/// <summary>
/// Appended to every <c>key_id = @key_id</c>. <c>NVARCHAR</c> → <c>VARBINARY</c> yields the UTF-16
/// bytes, so the comparison is exact (case, accents and trailing spaces all significant).
/// </summary>
public const string ExactKeyIdMatch = "CAST(key_id AS VARBINARY(128)) = CAST(@key_id AS VARBINARY(128))";
/// <summary>Whether a key with this id could be stored at all.</summary>
public static bool CanExist(string keyId) => keyId.Length <= KeyId;
/// <summary>The first over-length field of <paramref name="record"/>, described, or <see langword="null"/> when every field fits.</summary>
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;
/// <summary>Throws <see cref="ArgumentException"/> when a field of <paramref name="record"/> exceeds its column.</summary>
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}";
}
@@ -13,7 +13,26 @@ namespace ZB.MOM.WW.Auth.ApiKeys.SqlServer;
/// <param name="AuditSkipped">Audit rows that already existed in SQL Server.</param>
/// <param name="SourceFound">Whether the SQLite file existed at all.</param>
public sealed record ApiKeyImportResult(
int KeysInserted, int KeysSkipped, int AuditInserted, int AuditSkipped, bool SourceFound);
int KeysInserted, int KeysSkipped, int AuditInserted, int AuditSkipped, bool SourceFound)
{
/// <summary>
/// Source key ids that were NOT imported because SQL Server already holds a key whose id differs
/// only in case (since 0.4.4, Auth-008). SQLite compares key ids exactly, so <c>Line1</c> and
/// <c>line1</c> can both exist there; the SQL Server <c>key_id</c> primary key uses the database's
/// collation (case-insensitive by default) and cannot hold both. Such a key's token will not
/// verify against the shared store — re-mint it under a distinct id. Not counted in
/// <see cref="KeysSkipped"/>, which counts only exact duplicates.
/// </summary>
public IReadOnlyList<string> KeyIdCollisions { get; init; } = [];
/// <summary>
/// Source key ids that were NOT imported because a value exceeds its SQL Server column
/// (<c>key_id</c> 64, <c>key_prefix</c> 16, <c>display_name</c> 256 characters) (since 0.4.4,
/// Auth-008). Up to 0.4.3 such a row was imported silently truncated. Not counted in
/// <see cref="KeysSkipped"/>.
/// </summary>
public IReadOnlyList<string> KeysRejected { get; init; } = [];
}
/// <summary>
/// Copies every key and audit row from a per-node SQLite store into the shared SQL Server store,
@@ -208,13 +227,32 @@ public sealed class SqliteApiKeyStoreImporter(AuthSqlServerConnectionFactory sql
(SqlTransaction)await connection.BeginTransactionAsync(ct).ConfigureAwait(false);
int keysInserted = 0;
int keysSkipped = 0;
int auditInserted = 0;
List<string> collisions = [];
List<string> rejected = [];
foreach (ApiKeyRecord key in keys)
{
if (await InsertKeyIfAbsentAsync(connection, transaction, schema, key, ct).ConfigureAwait(false))
// Refused rather than written truncated: a truncated key_id would verify only through an
// equally truncated lookup and authenticate as an id nobody assigned (Auth-008).
if (SqlServerColumnLimits.OverLengthField(key) is not null)
{
keysInserted++;
rejected.Add(key.KeyId);
continue;
}
switch (await InsertKeyIfAbsentAsync(connection, transaction, schema, key, ct).ConfigureAwait(false))
{
case KeyInsertOutcome.Inserted:
keysInserted++;
break;
case KeyInsertOutcome.AlreadyPresent:
keysSkipped++;
break;
default:
collisions.Add(key.KeyId);
break;
}
}
@@ -230,15 +268,28 @@ public sealed class SqliteApiKeyStoreImporter(AuthSqlServerConnectionFactory sql
return new ApiKeyImportResult(
KeysInserted: keysInserted,
KeysSkipped: keys.Count - keysInserted,
KeysSkipped: keysSkipped,
AuditInserted: auditInserted,
AuditSkipped: auditEntries.Count - auditInserted,
SourceFound: true);
SourceFound: true)
{
KeyIdCollisions = collisions,
KeysRejected = rejected,
};
}
// Returns true when this call inserted the row. The guard is inside the statement rather than a
// separate SELECT so the check and the insert cannot straddle a concurrent writer.
private async Task<bool> InsertKeyIfAbsentAsync(
private enum KeyInsertOutcome
{
Inserted = 1,
AlreadyPresent = 0,
CaseVariantPresent = 2,
}
// The guard is inside the statement rather than a separate SELECT so the check and the insert
// cannot straddle a concurrent writer. The collation-aware `key_id = @key_id` finds a row whose
// id differs only in case — the primary key would refuse to hold both — and the exact match tells
// that collision apart from a genuine duplicate.
private async Task<KeyInsertOutcome> InsertKeyIfAbsentAsync(
SqlConnection connection,
SqlTransaction transaction,
string schema,
@@ -246,14 +297,23 @@ public sealed class SqliteApiKeyStoreImporter(AuthSqlServerConnectionFactory sql
CancellationToken ct)
{
await using SqlCommand command = sql.CreateCommand(connection, $"""
IF NOT EXISTS (
IF EXISTS (
SELECT 1 FROM [{schema}].[{SqlServerAuthSchema.ApiKeysTable}]
WHERE key_id = @key_id AND {SqlServerColumnLimits.ExactKeyIdMatch})
SELECT 0;
ELSE IF EXISTS (
SELECT 1 FROM [{schema}].[{SqlServerAuthSchema.ApiKeysTable}] WHERE key_id = @key_id)
SELECT 2;
ELSE
BEGIN
INSERT INTO [{schema}].[{SqlServerAuthSchema.ApiKeysTable}] (
key_id, key_prefix, secret_hash, display_name, scopes,
constraints, created_utc, last_used_utc, revoked_utc, expires_utc)
VALUES (
@key_id, @key_prefix, @secret_hash, @display_name, @scopes,
@constraints, @created_utc, @last_used_utc, @revoked_utc, @expires_utc);
SELECT 1;
END
""", transaction);
command.Parameters.Add("@key_id", SqlDbType.NVarChar, 64).Value = key.KeyId;
command.Parameters.Add("@key_prefix", SqlDbType.NVarChar, 16).Value = key.KeyPrefix;
@@ -266,7 +326,8 @@ public sealed class SqliteApiKeyStoreImporter(AuthSqlServerConnectionFactory sql
command.Parameters.Add("@revoked_utc", SqlDbType.DateTimeOffset).Value = (object?)key.RevokedUtc ?? DBNull.Value;
command.Parameters.Add("@expires_utc", SqlDbType.DateTimeOffset).Value = (object?)key.ExpiresUtc ?? DBNull.Value;
return await command.ExecuteNonQueryAsync(ct).ConfigureAwait(false) > 0;
object? outcome = await command.ExecuteScalarAsync(ct).ConfigureAwait(false);
return (KeyInsertOutcome)Convert.ToInt32(outcome, System.Globalization.CultureInfo.InvariantCulture);
}
// Audit rows carry no natural key (audit_id is per-file IDENTITY), so identity is the triple