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
@@ -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