feat(sql): implement the design §8.1 catalog identifier-validation gate (#496)
Until now ISqlDialect.QuoteIdentifier was the SOLE defence for authored
table/column names: an identifier went from the TagConfig blob straight into a
command text, bracket-quoted. The residual risk was bounded — a hostile name is
quoted into one nonexistent object, the query fails after the connection opens,
and the tag Bad-codes — but "bounded" is not "filtered", and the design promised
a filter. Both ISqlDialect and SqlServerDialect carried a doc paragraph saying so.
SqlCatalogGate + SqlCatalogLoader now resolve every authored identifier against
the live catalog at Initialize, and REPLACE it with the catalog's own spelling.
The identifier text in an emitted poll query is therefore a string this driver
read back out of ListSchemas/ListTables/ListColumns — not operator input. Quoting
becomes the backstop it was documented to be.
Decisions worth knowing before touching this:
- Substitution, not just validation. Matching is exact-ordinal first, then a
UNIQUE case-insensitive hit: SQL Server's default collation is CI so case
variants have always worked, and rejecting them would break valid deployments.
An ambiguous CI match under a case-sensitive collation is refused rather than
guessed — picking one would publish another column's data under the operator's
node, which is worse than rejecting the tag.
- Charset check BEFORE catalog lookup. Each identifier goes through
QuoteIdentifier for its rejection rules first, so a name carrying a control or
Unicode format character is rejected WITHOUT its value being echoed into a log
line (Trojan-Source). A name that passes is safe to render, which is why
catalog-miss messages do name it — an operator hunting a typo has to see what
they wrote. Both halves are pinned by tests.
- A rejected tag keeps its node. It is dropped from the POLLED table but stays in
the AUTHORED table, so it still materializes and reads BadNodeIdUnknown —
§8.1's specified outcome. My first wiring dropped it from both, which deleted
the node instead; an existing test (ReinitializeAsync_recoversFromFaulted)
caught it. A status code can only be published by a node that exists, and a
missing address-space entry is far harder to diagnose than a Bad quality.
- An unreadable catalog FAULTS Initialize; it does not reject every tag. That is
the absence of evidence about the tags, not evidence against them — rejecting
all of them would serve a confidently-empty address space and send the operator
hunting typos that do not exist. Zero visible schemas is treated the same way,
because that is exactly what a missing GRANT looks like. Faulting lands
DriverInstanceActor in Reconnecting with its retry timer running.
- Bounded load: one schema list, one default-schema scalar, then one ListTables
per distinct authored schema and one ListColumns per distinct authored relation
— never a full catalog enumeration, and nothing after Initialize. Every
authored name reaches the catalog queries as a bound @schema/@table parameter,
so building the allow-list cannot itself be an injection vector.
- ISqlDialect gains DefaultSchemaSql ("SELECT SCHEMA_NAME()"). An unqualified
`TagValues` must resolve in whatever schema the SERVER reports; hardcoding dbo
would be a silent lie on any estate that maps service accounts to their own
default schema. It is a query, not a constant, because the answer is
per-connection.
- Accepted v1 limitation: a 3-part db.schema.table (or linked-server name)
addresses a catalog this connection cannot enumerate, so it cannot be
allow-listed and is rejected with a message pointing at the fix — expose the
data through a view in the connected database.
VerifyLivenessAsync's wall-clock pattern is extracted to RunBoundedAsync and
reused, so the new I/O gets the same R2-01 / STAB-14 protection rather than a
second hand-rolled copy. (It also fixes a latent bug in the extracted code: the
OperationCanceledException arm detached the wrong task.)
Tests: 24 pure gate tests + 9 end-to-end driver tests against the real SQLite
catalog + 3 new live tests against the real SQL Server on 10.100.0.35 (21 in that
suite now pass, exercising the real SELECT SCHEMA_NAME() + INFORMATION_SCHEMA
path). Verified falsifiable: bypassing the gate turns exactly the three rejection
assertions red and leaves the rest green.
SqlInjectionRegressionTests is deliberately NOT rewritten to expect
BadNodeIdUnknown. It drives SqlPollReader directly, below the gate, and pins the
quoting backstop on its own — defence in depth is only worth the name if each
layer holds independently. Rewriting those assertions would delete the backstop's
only coverage and leave the gate a single point of failure. Its scope note, which
said the gate does not exist, is updated to say why it stays where it is.
This commit is contained in:
@@ -74,7 +74,23 @@ public sealed class SqlDriver
|
||||
private IReadOnlyDictionary<string, SqlTagDefinition> _tagsByRawPath =
|
||||
new Dictionary<string, SqlTagDefinition>(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>Resolves a read/subscribe RawPath to its authored definition — a single table hit, or a miss.</summary>
|
||||
/// <summary>
|
||||
/// The subset of <see cref="_tagsByRawPath"/> that survived the design §8.1 catalog gate, with every
|
||||
/// identifier rewritten to the catalog's own spelling. <b>This — not the authored table — is what a
|
||||
/// read or a poll resolves against</b>, so an identifier that never appeared in the catalog can never
|
||||
/// reach a query.
|
||||
/// <para><b>Why the two tables are separate.</b> A tag the gate rejected must still <em>exist</em> as a
|
||||
/// node: §8.1's specified outcome is that it publishes
|
||||
/// <see cref="SqlStatusCodes.BadNodeIdUnknown"/>, and a status code can only be published by a node
|
||||
/// that is there. Dropping rejected tags from the authored table too would delete the node instead,
|
||||
/// turning a diagnosable Bad quality into a silently missing address-space entry — a strictly worse
|
||||
/// failure for the operator trying to find their typo.</para>
|
||||
/// <para>Swapped atomically, for the same reason the authored table is.</para>
|
||||
/// </summary>
|
||||
private IReadOnlyDictionary<string, SqlTagDefinition> _polledByRawPath =
|
||||
new Dictionary<string, SqlTagDefinition>(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>Resolves a read/subscribe RawPath to its <b>catalog-validated</b> definition, or a miss.</summary>
|
||||
private readonly EquipmentTagRefResolver<SqlTagDefinition> _resolver;
|
||||
|
||||
/// <summary>
|
||||
@@ -182,8 +198,18 @@ public sealed class SqlDriver
|
||||
/// <summary>The current authored-tag snapshot. Read through a barrier — <see cref="BuildTagTable"/> swaps it.</summary>
|
||||
private IReadOnlyDictionary<string, SqlTagDefinition> Tags => Volatile.Read(ref _tagsByRawPath);
|
||||
|
||||
/// <summary>The resolver's lookup: RawPath → authored definition, or null on a miss.</summary>
|
||||
private SqlTagDefinition? Lookup(string rawPath) => Tags.GetValueOrDefault(rawPath);
|
||||
/// <summary>
|
||||
/// The catalog-validated snapshot. Read through a barrier — <see cref="ApplyCatalogGateAsync"/> swaps it.
|
||||
/// </summary>
|
||||
private IReadOnlyDictionary<string, SqlTagDefinition> PolledTags => Volatile.Read(ref _polledByRawPath);
|
||||
|
||||
/// <summary>
|
||||
/// The resolver's lookup: RawPath → <b>catalog-validated</b> definition, or null on a miss.
|
||||
/// <para>Deliberately reads <see cref="PolledTags"/> rather than <see cref="Tags"/>: a tag the gate
|
||||
/// rejected must miss here so the reader publishes
|
||||
/// <see cref="SqlStatusCodes.BadNodeIdUnknown"/>, exactly as design §8.1 specifies.</para>
|
||||
/// </summary>
|
||||
private SqlTagDefinition? Lookup(string rawPath) => PolledTags.GetValueOrDefault(rawPath);
|
||||
|
||||
// ---- IDriver lifecycle ----
|
||||
|
||||
@@ -196,11 +222,16 @@ public sealed class SqlDriver
|
||||
/// I/O, and on failure this method records <see cref="DriverState.Faulted"/> <b>and rethrows</b> —
|
||||
/// <c>DriverInstanceActor</c> reads a throw as InitializeFailed and lands in Reconnecting with its
|
||||
/// retry timer running, which is exactly the recovery a database that is merely down needs.</para>
|
||||
/// <para>The liveness check is then followed by the design §8.1 <b>catalog gate</b>
|
||||
/// (<see cref="ApplyCatalogGateAsync"/>), which is the second and last piece of I/O. It runs after
|
||||
/// liveness because it needs a working connection, and before the driver reports Healthy because the
|
||||
/// tag table it publishes must be the validated one — a poll must never see an unvalidated
|
||||
/// identifier.</para>
|
||||
/// </summary>
|
||||
/// <param name="driverConfigJson">The driver configuration JSON (unused; see remarks).</param>
|
||||
/// <param name="cancellationToken">Cancellation token for the operation.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
/// <exception cref="InvalidOperationException">The database could not be reached.</exception>
|
||||
/// <exception cref="InvalidOperationException">The database could not be reached, or its catalog could not be read.</exception>
|
||||
public async Task InitializeAsync(string driverConfigJson, CancellationToken cancellationToken)
|
||||
{
|
||||
WriteHealth(new DriverHealth(DriverState.Initializing, null, null));
|
||||
@@ -234,6 +265,36 @@ public sealed class SqlDriver
|
||||
throw new InvalidOperationException(message, ex);
|
||||
}
|
||||
|
||||
// Separate try from liveness so the operator surface names the stage that actually failed: "could
|
||||
// not reach the database" and "reached it but could not read its catalog" send an operator to
|
||||
// different places, and the second is usually a GRANT rather than an outage.
|
||||
try
|
||||
{
|
||||
await ApplyCatalogGateAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
WriteHealth(new DriverHealth(DriverState.Unknown, null, null));
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Same discipline as above: exception TYPE only on the operator surface, full exception to the
|
||||
// log sink. A catalog read that fails is NOT evidence the tags are wrong — it is the absence of
|
||||
// evidence — so this faults the driver (and retries) rather than rejecting every tag and serving
|
||||
// a confidently-empty address space.
|
||||
var message =
|
||||
$"Sql driver '{_driverInstanceId}' reached {Endpoint} but could not read its catalog to " +
|
||||
$"validate authored tables/columns: {ex.GetType().Name}. Check that the connecting principal " +
|
||||
"can read the catalog views.";
|
||||
_logger.LogError(ex,
|
||||
"Sql driver {DriverInstanceId} catalog validation against {Endpoint} failed.",
|
||||
_driverInstanceId, Endpoint);
|
||||
WriteHealth(new DriverHealth(DriverState.Faulted, null, message));
|
||||
TransitionHostTo(HostState.Stopped);
|
||||
throw new InvalidOperationException(message, ex);
|
||||
}
|
||||
|
||||
WriteHealth(new DriverHealth(DriverState.Healthy, DateTime.UtcNow, null));
|
||||
TransitionHostTo(HostState.Running);
|
||||
_logger.LogInformation(
|
||||
@@ -594,6 +655,94 @@ public sealed class SqlDriver
|
||||
}
|
||||
|
||||
Volatile.Write(ref _tagsByRawPath, table);
|
||||
|
||||
// Nothing is pollable until the catalog gate has validated it. Clearing here (rather than leaving a
|
||||
// previous generation's validated table in place) means a Reinitialize whose gate then fails cannot
|
||||
// keep polling the OLD identifiers against a database whose schema may be exactly what changed.
|
||||
Volatile.Write(ref _polledByRawPath, new Dictionary<string, SqlTagDefinition>(StringComparer.Ordinal));
|
||||
}
|
||||
|
||||
// ---- catalog gate (design §8.1) ----
|
||||
|
||||
/// <summary>
|
||||
/// Validates every authored identifier against the live catalog and republishes the tag table with
|
||||
/// catalog spellings, dropping the tags that do not resolve (design §8.1).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para><b>Why this must run before the driver reports Healthy.</b> The table this swaps in is what
|
||||
/// every poll resolves against. Running it later — or in the background — would leave a window in
|
||||
/// which an unvalidated identifier could be quoted into a query, which is the entire hole the gate
|
||||
/// exists to close.</para>
|
||||
/// <para><b>A dropped tag is not a driver fault.</b> It disappears from the table, so its RawPath
|
||||
/// resolves to nothing and it publishes <see cref="SqlStatusCodes.BadNodeIdUnknown"/> — one operator
|
||||
/// typo must not stop the other tags on that database, the same rule
|
||||
/// <see cref="BuildTagTable"/> follows for a malformed blob. Each drop is logged at Warning with the
|
||||
/// tag, the field and the reason, because a node that silently goes Bad with nothing in the log is
|
||||
/// unsupportable.</para>
|
||||
/// <para><b>No tags ⇒ no I/O.</b> A driver with nothing authored has nothing to validate, and issuing
|
||||
/// catalog queries to prove that would be a round-trip that can only fail.</para>
|
||||
/// <para>Bounded by the same wall-clock discipline as the liveness check (R2-01 / STAB-14): the work
|
||||
/// runs on the thread pool so a provider implementing the async path synchronously blocks a pool
|
||||
/// thread rather than wedging Initialize forever with no retry.</para>
|
||||
/// </remarks>
|
||||
/// <param name="cancellationToken">The caller's token.</param>
|
||||
/// <returns>A task that completes when the tag table has been validated and republished.</returns>
|
||||
private async Task ApplyCatalogGateAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var authored = Tags;
|
||||
if (authored.Count == 0) return;
|
||||
|
||||
var tables = authored.Values
|
||||
.Select(definition => definition.Table)
|
||||
.Where(table => !string.IsNullOrWhiteSpace(table))
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.ToArray();
|
||||
|
||||
var catalog = await RunBoundedAsync(
|
||||
token => LoadCatalogAsync(tables, token),
|
||||
_options.OperationTimeout,
|
||||
"the catalog queries did not return",
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var result = SqlCatalogGate.Apply(authored.Values, catalog, _dialect);
|
||||
|
||||
foreach (var rejection in result.Rejected)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"Sql tag '{Tag}' rejected by the catalog gate: {Field} — {Reason}. It will publish "
|
||||
+ "BadNodeIdUnknown until the tag or the database is corrected. Driver={DriverInstanceId}",
|
||||
rejection.RawPath, rejection.Field, rejection.Reason, _driverInstanceId);
|
||||
}
|
||||
|
||||
var validated = new Dictionary<string, SqlTagDefinition>(result.Accepted.Count, StringComparer.Ordinal);
|
||||
foreach (var definition in result.Accepted) validated[definition.Name] = definition;
|
||||
|
||||
// Only the POLLED table is replaced. The authored table is left intact so every authored tag keeps
|
||||
// its node and a rejected one publishes BadNodeIdUnknown rather than vanishing (see _polledByRawPath).
|
||||
Volatile.Write(ref _polledByRawPath, validated);
|
||||
|
||||
_logger.LogInformation(
|
||||
"Sql driver {DriverInstanceId} catalog gate accepted {Accepted} of {Total} authored tag(s) "
|
||||
+ "across {Tables} table(s) on {Endpoint}.",
|
||||
_driverInstanceId, result.Accepted.Count, authored.Count, tables.Length, Endpoint);
|
||||
}
|
||||
|
||||
/// <summary>Opens one connection and reads the catalog slice the authored tables need.</summary>
|
||||
private async Task<SqlCatalog> LoadCatalogAsync(
|
||||
IReadOnlyCollection<string> authoredTables, CancellationToken cancellationToken)
|
||||
{
|
||||
var connection = _factory.CreateConnection()
|
||||
?? throw new InvalidOperationException(
|
||||
$"the {_dialect.Provider} provider factory returned no connection.");
|
||||
|
||||
await using (connection.ConfigureAwait(false))
|
||||
{
|
||||
connection.ConnectionString = _connectionString;
|
||||
await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
|
||||
return await SqlCatalogLoader
|
||||
.LoadAsync(connection, _dialect, authoredTables, _options.CommandTimeout, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- liveness ----
|
||||
@@ -611,18 +760,50 @@ public sealed class SqlDriver
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken">The caller's token.</param>
|
||||
/// <returns>A task that completes when the database has answered.</returns>
|
||||
private async Task VerifyLivenessAsync(CancellationToken cancellationToken)
|
||||
private Task VerifyLivenessAsync(CancellationToken cancellationToken) =>
|
||||
RunBoundedAsync(
|
||||
async token => { await PingAsync(token).ConfigureAwait(false); return true; },
|
||||
_options.CommandTimeout,
|
||||
"the liveness statement did not return",
|
||||
cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Runs <paramref name="work"/> under a hard wall-clock <paramref name="budget"/>, on the thread pool,
|
||||
/// converting a breach into a <see cref="TimeoutException"/> worded from <paramref name="what"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>The R2-01 / STAB-14 shape, shared by the two pieces of I/O Initialize performs. It exists
|
||||
/// because a token is not a deadline: some ADO.NET providers implement the async path synchronously,
|
||||
/// and a wedged socket can hang <em>inside</em> the provider's own cancellation handshake. Without an
|
||||
/// independent wall clock, <c>DriverInstanceActor</c>'s init task would never complete and the driver
|
||||
/// would sit in Connecting forever with no retry — the exact frozen-peer wedge the S7 driver shipped.</para>
|
||||
/// <para>Both the linked CTS deadline and an outer <see cref="TaskExtensions"/> wait are used, because
|
||||
/// each covers a case the other does not: the CTS handles a provider that <em>does</em> honour
|
||||
/// cancellation, and the outer wait handles one that does not. An abandoned attempt keeps ownership of
|
||||
/// its own connection and disposes it; <see cref="Detach"/> observes its eventual fault.</para>
|
||||
/// </remarks>
|
||||
/// <typeparam name="T">The work's result type.</typeparam>
|
||||
/// <param name="work">The operation to bound. Receives the deadline-linked token.</param>
|
||||
/// <param name="budget">The wall-clock allowance.</param>
|
||||
/// <param name="what">Sentence fragment naming the operation, e.g. "the catalog queries did not return".</param>
|
||||
/// <param name="cancellationToken">The caller's token.</param>
|
||||
/// <returns>The work's result.</returns>
|
||||
/// <exception cref="TimeoutException">The budget elapsed first.</exception>
|
||||
private static async Task<T> RunBoundedAsync<T>(
|
||||
Func<CancellationToken, Task<T>> work,
|
||||
TimeSpan budget,
|
||||
string what,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var budget = _options.CommandTimeout;
|
||||
var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
Task work;
|
||||
Task<T> running;
|
||||
try
|
||||
{
|
||||
deadline.CancelAfter(budget);
|
||||
work = Task.Run(
|
||||
running = Task.Run(
|
||||
async () =>
|
||||
{
|
||||
try { await PingAsync(deadline.Token).ConfigureAwait(false); }
|
||||
try { return await work(deadline.Token).ConfigureAwait(false); }
|
||||
finally { deadline.Dispose(); }
|
||||
},
|
||||
CancellationToken.None);
|
||||
@@ -636,20 +817,18 @@ public sealed class SqlDriver
|
||||
|
||||
try
|
||||
{
|
||||
await work.WaitAsync(budget, cancellationToken).ConfigureAwait(false);
|
||||
return await running.WaitAsync(budget, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (TimeoutException)
|
||||
{
|
||||
Detach(work);
|
||||
throw new TimeoutException(
|
||||
$"the liveness statement did not return within {(int)budget.TotalMilliseconds} ms.");
|
||||
Detach(running);
|
||||
throw new TimeoutException($"{what} within {(int)budget.TotalMilliseconds} ms.");
|
||||
}
|
||||
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
// Our deadline fired and the provider DID honour the linked token.
|
||||
Detach(work);
|
||||
throw new TimeoutException(
|
||||
$"the liveness statement did not return within {(int)budget.TotalMilliseconds} ms.");
|
||||
Detach(running);
|
||||
throw new TimeoutException($"{what} within {(int)budget.TotalMilliseconds} ms.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -752,6 +931,7 @@ public sealed class SqlDriver
|
||||
{
|
||||
await _poll.DisposeAsync().ConfigureAwait(false);
|
||||
Volatile.Write(ref _tagsByRawPath, new Dictionary<string, SqlTagDefinition>(StringComparer.Ordinal));
|
||||
Volatile.Write(ref _polledByRawPath, new Dictionary<string, SqlTagDefinition>(StringComparer.Ordinal));
|
||||
_resolver.Clear(); // no-op in v3 (the resolver reads the live table by closure); kept for symmetry
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user