Files
lmxopcua/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.IntegrationTests/SqlServerNamedQueryBatchLiveTests.cs
T
Joseph Doherty 35d14936ac fix(sql): #974 review — parse SqlServer/Odbc named queries as T-SQL; ';' is not a statement boundary
The named-query guard's only statement boundary was ';', but T-SQL runs
';'-less batches: 'SELECT 1 COMMIT KILL 55', '... COMMIT DISABLE TRIGGER ALL ON
DATABASE', '... COMMIT SHUTDOWN WITH NOWAIT' and a TEXTPTR/WRITETEXT write were
all accepted for SqlServer AND Odbc — a COMMIT ending the rolled-back
transaction, then anything not on the keyword list.

For SqlServer, and for Odbc / no provider (backend unknown: strictest reading),
SqlReadOnlyStatement now also parses the statement with
Microsoft.SqlServer.TransactSql.ScriptDom 180.154.0 (central package pin; both
QUOTED_IDENTIFIER settings) and requires exactly one batch holding exactly one
SelectStatement, no INTO, and no OPENQUERY/OPENROWSET/OPENDATASOURCE. Odbc '?'
markers are read as variables for the parse. The lexical guard stays as a
second layer.

Tests: SqlReadOnlyStatementTransactSqlTests (11 batch strings x SqlServer/Odbc/
none, pass-through rowsets — all failed first; CTE/subquery/window/param/UNION/
FOR XML/OPTION and ODBC '?' positive controls). SqlNamedQueryTests' SQLite-backed
Odbc stand-in used the T-SQL reserved word 'top' as an alias (renamed).
Live (SQL Server 10.100.0.35,14330): SqlServerNamedQueryBatchLiveTests proves
'SELECT 1 AS v COMMIT UPDATE ...' commits the old way, the guard refuses it,
and a CTE+window+subquery+@param query reads Good; SqlServerReadTests /
write-mode / trigger suites unchanged (30/30). Class comment and
docs/drivers/Sql.md corrected.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-03 12:21:23 -05:00

130 lines
6.1 KiB
C#

using System.Globalization;
using System.Text.Json.Nodes;
using Microsoft.Data.SqlClient;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.Sql.Contracts;
namespace ZB.MOM.WW.OtOpcUa.Driver.Sql.IntegrationTests;
/// <summary>
/// lmxopcua#974 (security review 2026-12-02), against the real SQL Server: T-SQL needs no <c>;</c> between
/// statements, so <c>SELECT 1 AS v COMMIT UPDATE …</c> is three statements to the server and was one
/// <c>SELECT</c> to the lexical guard. SQL Server has no execution-layer seal (it runs batches, and the driver's
/// transaction is merely rolled back), so the guard's T-SQL parse is the line in front of the
/// <c>SELECT</c>-only login.
/// <list type="number">
/// <item><b>Positive control</b>: run the old way (an ordinary transaction, rolled back afterwards) the
/// smuggled <c>COMMIT</c> ends the transaction and the UPDATE commits. The row is restored.</item>
/// <item>The guard refuses it, for SqlServer and Odbc alike.</item>
/// <item>A real read with a CTE, a window function, subqueries and a parameter is accepted by the guard and
/// reads Good through the driver.</item>
/// </list>
/// </summary>
[Collection(SqlPollServerCollection.Name)]
public sealed class SqlServerNamedQueryBatchLiveTests(SqlPollServerFixture fixture)
{
private static readonly string Target = SqlPollServerFixture.Qualified("write_targets");
private static string Smuggled(int value)
=> string.Create(CultureInfo.InvariantCulture,
$"SELECT 1 AS v COMMIT UPDATE {Target} SET sp_value = {value} WHERE tag_name = 'Present'");
[Fact]
public async Task SemicolonLessBatch_isAWorkingBypassOnThisServer_theOldWay()
{
SkipUnlessLive();
var original = await ReadTargetAsync();
var smuggled = Random.Shared.Next(1000, 900_000);
try
{
await using var connection = await OpenAsync();
await using var transaction = (SqlTransaction)await connection.BeginTransactionAsync(TestContext.Current.CancellationToken);
await using (var command = new SqlCommand(Smuggled(smuggled), connection, transaction))
{
await using var reader = await command.ExecuteReaderAsync(TestContext.Current.CancellationToken);
do { while (await reader.ReadAsync(TestContext.Current.CancellationToken)) { } }
while (await reader.NextResultAsync(TestContext.Current.CancellationToken));
}
try { await transaction.RollbackAsync(TestContext.Current.CancellationToken); }
catch (InvalidOperationException) { /* the smuggled COMMIT already ended it — the point */ }
(await ReadTargetAsync()).ShouldBe(smuggled);
}
finally
{
await ScalarAsync(string.Create(CultureInfo.InvariantCulture,
$"UPDATE {Target} SET sp_value = {original} WHERE tag_name = 'Present'"));
}
}
[Fact]
public void SemicolonLessBatch_isRefusedByTheGuard_forSqlServerAndOdbc()
{
SqlReadOnlyStatement.Check(Smuggled(1), SqlProvider.SqlServer, out _).ShouldNotBeNull();
SqlReadOnlyStatement.Check(Smuggled(1), SqlProvider.Odbc, out _).ShouldNotBeNull();
}
[Fact]
public async Task LegitimateRead_withCteWindowSubqueryAndParameter_passesTheGuard_andReadsGood()
{
SkipUnlessLive();
var kv = SqlPollServerFixture.Qualified(SqlPollServerFixture.KeyValueTable);
var sql =
$"WITH ranked AS (SELECT tag_name, num_value, ROW_NUMBER() OVER (PARTITION BY tag_name ORDER BY sample_ts DESC) AS rn " +
$"FROM {kv} WHERE num_value IS NOT NULL) " +
$"SELECT r.num_value AS v, (SELECT COUNT(*) FROM {kv}) AS n FROM ranked AS r " +
$"WHERE r.rn = 1 AND r.tag_name = @key AND r.num_value >= (SELECT MIN(num_value) FROM {kv})";
SqlReadOnlyStatement.Check(sql, SqlProvider.SqlServer, out var normalised).ShouldBeNull();
var driver = new SqlDriver(
new SqlDriverOptions
{
RawTags =
[
new RawTagEntry("Q/V", new JsonObject { ["driver"] = "Sql", ["model"] = "Query", ["query"] = "q", ["column"] = "v" }.ToJsonString(), WriteIdempotent: false),
],
Queries = new Dictionary<string, SqlNamedQuery>(StringComparer.Ordinal)
{
["q"] = new("q", normalised, ["key"], [SqlPollServerFixture.PresentKey], SqlNamedQueryRules.DefaultMaxRows),
},
CommandTimeout = TimeSpan.FromSeconds(30),
OperationTimeout = TimeSpan.FromSeconds(45),
},
driverInstanceId: "sql-batch-guard-live",
dialect: new SqlServerDialect(),
connectionString: fixture.ConnectionString);
await using (driver)
{
await driver.InitializeAsync("{}", TestContext.Current.CancellationToken);
var snapshot = (await driver.ReadAsync(["Q/V"], TestContext.Current.CancellationToken))[0];
snapshot.StatusCode.ShouldBe(SqlStatusCodes.Good);
Convert.ToDouble(snapshot.Value, CultureInfo.InvariantCulture).ShouldBe(SqlPollServerFixture.PresentValue);
}
}
private void SkipUnlessLive()
{
if (fixture.SkipReason is { } reason) Assert.Skip(reason);
}
private async Task<double> ReadTargetAsync()
=> Convert.ToDouble(await ScalarAsync($"SELECT sp_value FROM {Target} WHERE tag_name = 'Present'"), CultureInfo.InvariantCulture);
private async Task<object?> ScalarAsync(string sql)
{
await using var connection = await OpenAsync();
await using var command = new SqlCommand(sql, connection);
return await command.ExecuteScalarAsync(TestContext.Current.CancellationToken);
}
private async Task<SqlConnection> OpenAsync()
{
var connection = new SqlConnection(fixture.ConnectionString);
await connection.OpenAsync(TestContext.Current.CancellationToken);
return connection;
}
}