Files
lmxopcua/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.IntegrationTests/NamedQueryBypassLiveTests.cs
T
Joseph Doherty 65c4330a68 fix(sql): #974 #987 named queries are lexed per dialect and run read-only + single-statement; key rows attribute by server semantics; SQL Server writes count only the target statement
#974 (S-7) — the named-query guard had one lexer for five dialects and took live SQL for literal text
where a provider ends a literal earlier (MySQL backslash escapes, PostgreSQL dollar quotes, T-SQL ]],
nested comments, MySQL # / "--x", bare-CR line comments, Oracle q'..'). All 13 bypass strings were
accepted; the MySQL and PostgreSQL ones were executed against the live fixtures and the smuggled
UPDATE committed past the always-rolled-back transaction.
- SqlReadOnlyStatement (own file) lexes per provider and REFUSES constructs dialects disagree on;
  Odbc / no provider = every dialect must agree. Factory and AdminUI form pass the provider; the form
  re-validates queries on a provider change.
- ISqlDialect.BeginNamedQueryAsync / SealNamedQueryCommand / EndNamedQueryAsync: PostgreSQL and Oracle
  SET TRANSACTION READ ONLY; MySQL read-only session + transaction (restored after); PostgreSQL rewrites
  @name markers to positional $n (a parameterless query gets one unused typed $1) so Npgsql sends the
  text unsplit and the server refuses a second statement.

#987 (S-6) — key-value rows are attributed by SqlKeyMatcher (exact, then typed / padding-insensitive,
then case/accent-insensitive — only for rows the server matched); a named query's rowKey uses the
exact + representational stages only.
#987 (S-10) — SQL Server table writes read the target statement's own @@ROWCOUNT through an OUTPUT
parameter; SqlClient's ExecuteNonQuery sums trigger DML (reproduced: 1 + 2 audit rows = 3, every write
rolled back BadConfigurationError).

Tests: per-dialect bypass theory + positive controls, matcher + SQLite collation/affinity attribution,
Postgres seal, dialect-hook wiring, SQL Server write-plan capture; live NamedQueryBypassLiveTests
(PG/MySQL/Oracle), SqlServerTriggerWriteLiveTests, MySQL writing-function now refused.
2026-12-03 10:33:45 -05:00

323 lines
15 KiB
C#

using System.Data.Common;
using System.Globalization;
using System.Text.Json.Nodes;
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 (review finding S-7), against real servers: a write smuggled past the named-query guard must not
/// land. Each smuggled statement is one the pre-fix guard ACCEPTED as a single SELECT, and each test proves three
/// things:
/// <list type="number">
/// <item><b>It is a working bypass on this server</b> (positive control) — run the old way, inside an ordinary
/// transaction that is rolled back afterwards, the embedded <c>COMMIT</c> ends that transaction and the UPDATE
/// after it commits. (The control then restores the row.)</item>
/// <item><b>The guard now refuses it</b> as this provider lexes it.</item>
/// <item><b>The execution layer stops it even with the guard bypassed</b> — the statement is handed to the driver
/// as an already-"validated" named query, and the row is unchanged afterwards: PostgreSQL refuses a second
/// statement at the protocol level (positional parameters), MySQL runs the query in a read-only session.</item>
/// </list>
/// A legitimate named query (with and without parameters) still reads Good through the same harness — the
/// sealed / read-only path is not simply failing every query.
/// <para>Each leg writes a target row its login may UPDATE (<c>write_targets.Present</c> /
/// <c>setpoints.Line1.SpeedSp</c>) to a random value, so a pass cannot be a stale coincidence.</para>
/// </summary>
public abstract class NamedQueryBypassLiveSuite
{
protected abstract string? SkipReason { get; }
protected abstract string ConnectionString { get; }
protected abstract ISqlDialect Dialect { get; }
/// <summary>The qualified table + key of the row the smuggled UPDATE targets.</summary>
protected abstract (string Table, string Key) Target { get; }
/// <summary>The smuggled statement; <c>{0}</c> is the value its UPDATE writes.</summary>
protected abstract string SmuggledFormat { get; }
/// <summary>A legitimate parameterised read: (sql, param name, param value, column, expected value).</summary>
protected abstract (string Sql, string Param, object Value, string Column, double Expected) LegitimateRead { get; }
[Fact]
public async Task SmuggledWrite_isAWorkingBypassOnThisServer_theOldWay()
{
SkipUnlessLive();
var original = await ReadTargetAsync();
var smuggled = Random.Shared.Next(1000, 900_000);
try
{
await RunTheOldWayAsync(Smuggled(smuggled));
(await ReadTargetAsync()).ShouldBe(smuggled); // the bypass is real: the UPDATE committed past the rollback
}
finally
{
await WriteTargetAsync(original);
}
}
[Fact]
public void SmuggledWrite_isRefusedByTheGuard()
=> SqlReadOnlyStatement.Check(Smuggled(1), Dialect.Provider, out _).ShouldNotBeNull();
[Fact]
public async Task SmuggledWrite_pastTheGuard_doesNotLand()
{
SkipUnlessLive();
var original = await ReadTargetAsync();
var smuggled = Random.Shared.Next(1000, 900_000);
try
{
await using var driver = await StartAsync(
new SqlNamedQuery("evil", Smuggled(smuggled), [], [], SqlNamedQueryRules.DefaultMaxRows),
Tag("Q/Evil", "evil", "v"));
await driver.ReadAsync(["Q/Evil"], TestContext.Current.CancellationToken);
(await ReadTargetAsync()).ShouldBe(original);
}
finally
{
await WriteTargetAsync(original);
}
}
[Fact]
public async Task LegitimateNamedQueries_stillRead_withAndWithoutParameters()
{
SkipUnlessLive();
var read = LegitimateRead;
await using var driver = await StartAsync(
new SqlNamedQuery("withParam", read.Sql, [read.Param], [read.Value], SqlNamedQueryRules.DefaultMaxRows),
Tag("Q/WithParam", "withParam", read.Column),
new SqlNamedQuery("noParam", $"SELECT COUNT(*) AS n FROM {Target.Table}", [], [], SqlNamedQueryRules.DefaultMaxRows),
Tag("Q/NoParam", "noParam", "n"));
var snapshots = await driver.ReadAsync(["Q/WithParam", "Q/NoParam"], TestContext.Current.CancellationToken);
snapshots[0].StatusCode.ShouldBe(SqlStatusCodes.Good);
Convert.ToDouble(snapshots[0].Value, CultureInfo.InvariantCulture).ShouldBe(read.Expected);
snapshots[1].StatusCode.ShouldBe(SqlStatusCodes.Good);
Convert.ToInt64(snapshots[1].Value, CultureInfo.InvariantCulture).ShouldBeGreaterThan(0);
}
// ---- helpers ----
protected void SkipUnlessLive()
{
if (SkipReason is { } reason) Assert.Skip(reason);
}
private string Smuggled(int value) => string.Format(CultureInfo.InvariantCulture, SmuggledFormat, value);
/// <summary>A driver whose named queries are taken as given — the guard deliberately not consulted.</summary>
protected async Task<SqlDriver> StartAsync(params object[] queriesAndTags)
=> await StartAsync(ConnectionString, queriesAndTags);
protected async Task<SqlDriver> StartAsync(string connectionString, object[] queriesAndTags, bool allowWrites = false)
{
var driver = new SqlDriver(
new SqlDriverOptions
{
RawTags = queriesAndTags.OfType<RawTagEntry>().ToList(),
Queries = queriesAndTags.OfType<SqlNamedQuery>().ToDictionary(q => q.Name, StringComparer.Ordinal),
CommandTimeout = TimeSpan.FromSeconds(30),
OperationTimeout = TimeSpan.FromSeconds(45),
AllowWrites = allowWrites,
},
driverInstanceId: "sql-bypass-" + Dialect.Provider,
dialect: Dialect,
connectionString: connectionString);
try
{
await driver.InitializeAsync("{}", TestContext.Current.CancellationToken);
}
catch
{
await driver.DisposeAsync();
throw;
}
return driver;
}
protected static RawTagEntry Tag(string rawPath, string query, string column)
=> new(rawPath, new JsonObject
{
["driver"] = "Sql", ["model"] = "Query", ["query"] = query, ["column"] = column,
}.ToJsonString(), WriteIdempotent: false);
/// <summary>What the driver did before #974: a plain transaction, the statement, a rollback.</summary>
private async Task RunTheOldWayAsync(string sql)
{
await using var connection = await OpenAsync();
await using var transaction = await connection.BeginTransactionAsync(TestContext.Current.CancellationToken);
await using (var command = connection.CreateCommand())
{
command.Transaction = transaction;
command.CommandText = sql;
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)
{
// "This transaction has completed" — the smuggled COMMIT already ended it, which is the point.
}
}
protected async Task<double> ReadTargetAsync()
=> Convert.ToDouble(await ScalarAsync($"SELECT sp_value FROM {Target.Table} WHERE tag_name = '{Target.Key}'"),
CultureInfo.InvariantCulture);
private async Task WriteTargetAsync(double value)
=> await ScalarAsync(string.Create(CultureInfo.InvariantCulture,
$"UPDATE {Target.Table} SET sp_value = {value} WHERE tag_name = '{Target.Key}'"));
private async Task<object?> ScalarAsync(string sql)
{
await using var connection = await OpenAsync();
await using var command = connection.CreateCommand();
command.CommandText = sql;
return await command.ExecuteScalarAsync(TestContext.Current.CancellationToken);
}
private async Task<DbConnection> OpenAsync()
{
var connection = Dialect.Factory.CreateConnection()!;
connection.ConnectionString = ConnectionString;
await connection.OpenAsync(TestContext.Current.CancellationToken);
return connection;
}
}
/// <summary>PostgreSQL: the dollar-quote bypass, sealed by positional parameters (the server refuses a second command).</summary>
[Collection(PostgresCollection.Name)]
public sealed class PostgresNamedQueryBypassTests(PostgresFixture fixture) : NamedQueryBypassLiveSuite
{
protected override string? SkipReason => fixture.SkipReason;
protected override string ConnectionString => fixture.ConnectionString;
protected override ISqlDialect Dialect { get; } = new PostgresDialect();
protected override (string Table, string Key) Target => (PostgresFixture.Qualified("write_targets"), "Present");
protected override string SmuggledFormat =>
"SELECT $$'$$ AS v; COMMIT; UPDATE sqlpoll.write_targets SET sp_value = {0} WHERE tag_name = 'Present'; --'";
// tag_id is INTEGER and the bound value text: the positional rewrite must keep Npgsql's untyped bind working.
protected override (string Sql, string Param, object Value, string Column, double Expected) LegitimateRead =>
("SELECT num_value FROM sqlpoll.int_tag_values WHERE tag_id = @id", "id", "101", "num_value", 77.5);
/// <summary>
/// The read-only transaction, separately from the seal: a single-statement data-modifying CTE (which the guard
/// would refuse, so it is handed over unguarded) is one statement, so only <c>SET TRANSACTION READ ONLY</c> can
/// stop it — and the read FAILS rather than returning a Good value whose effect was merely rolled back.
/// </summary>
[Fact]
public async Task DataModifyingCte_pastTheGuard_isRefusedByTheReadOnlyTransaction()
{
SkipUnlessLive();
var original = await ReadTargetAsync();
await using var driver = await StartAsync(
new SqlNamedQuery("cte",
"WITH u AS (UPDATE sqlpoll.write_targets SET sp_value = sp_value + 1 WHERE tag_name = 'Present' RETURNING sp_value) SELECT sp_value AS v FROM u",
[], [], SqlNamedQueryRules.DefaultMaxRows),
Tag("Q/Cte", "cte", "v"));
var snapshot = (await driver.ReadAsync(["Q/Cte"], TestContext.Current.CancellationToken))[0];
SqlStatusCodes.IsBad(snapshot.StatusCode).ShouldBeTrue();
(await ReadTargetAsync()).ShouldBe(original);
}
}
/// <summary>MySQL: the backslash-escape bypass, stopped by the read-only session.</summary>
[Collection(MySqlCollection.Name)]
public sealed class MySqlNamedQueryBypassTests(MySqlFixture fixture) : NamedQueryBypassLiveSuite
{
protected override string? SkipReason => fixture.SkipReason;
protected override string ConnectionString => fixture.ConnectionString;
protected override ISqlDialect Dialect { get; } = new MySqlDialect();
protected override (string Table, string Key) Target => (MySqlFixture.Qualified("setpoints"), "Line1.SpeedSp");
protected override string SmuggledFormat =>
"SELECT '\\'' AS v; COMMIT; UPDATE sqlpoll.setpoints SET sp_value = {0} WHERE tag_name = 'Line1.SpeedSp'; -- '";
protected override (string Sql, string Param, object Value, string Column, double Expected) LegitimateRead =>
("SELECT num_value FROM sqlpoll.int_tag_values WHERE tag_id = @id", "id", "101", "num_value", 77.5);
/// <summary>
/// The read-only session is restored after the named query, so a pooled connection is not handed to a write
/// still read-only. Pinned on ONE physical connection with the pool's own reset turned off — otherwise the
/// pool's reset would mask a missing restore. A write after a named query on that connection must commit.
/// </summary>
[Fact]
public async Task ReadOnlySession_isRestored_beforeTheConnectionServesAWrite()
{
SkipUnlessLive();
var pinned = ConnectionString + ";Connection Reset=false;Maximum Pool Size=1;Application Name=OtOpcUa.Sql.ITs.pin";
var value = Random.Shared.Next(1000, 900_000);
await using var driver = await StartAsync(pinned,
[
new SqlNamedQuery("count", "SELECT COUNT(*) AS n FROM sqlpoll.setpoints", [], [], SqlNamedQueryRules.DefaultMaxRows),
Tag("Q/Count", "count", "n"),
new RawTagEntry("Sp", new JsonObject
{
["driver"] = "Sql", ["model"] = "KeyValue", ["table"] = "sqlpoll.write_targets", ["keyColumn"] = "tag_name",
["keyValue"] = "Present", ["valueColumn"] = "sp_value", ["type"] = "Float64", ["writable"] = true,
}.ToJsonString(), WriteIdempotent: false),
], allowWrites: true);
(await driver.ReadAsync(["Q/Count"], TestContext.Current.CancellationToken))[0].StatusCode.ShouldBe(SqlStatusCodes.Good);
var written = await ((IWritable)driver).WriteAsync([new WriteRequest("Sp", (double)value)], TestContext.Current.CancellationToken);
written.ShouldHaveSingleItem().StatusCode.ShouldBe(SqlStatusCodes.Good);
}
}
/// <summary>Oracle: ODP.NET already refuses a second statement; the read-only transaction must not break an ordinary read.</summary>
[Collection(OracleCollection.Name)]
public sealed class OracleNamedQueryReadOnlyTests(OracleFixture fixture)
{
[Fact]
public async Task LegitimateNamedQuery_readsInsideTheReadOnlyTransaction_onRepeatedPolls()
{
if (fixture.SkipReason is { } reason) Assert.Skip(reason);
var driver = new SqlDriver(
new SqlDriverOptions
{
RawTags = [new RawTagEntry("Q/One", """{"driver":"Sql","model":"Query","query":"one","column":"V"}""", WriteIdempotent: false)],
Queries = new Dictionary<string, SqlNamedQuery>(StringComparer.Ordinal)
{
["one"] = new("one", "SELECT 41 + :p_x AS v FROM dual", ["x"], [1L], SqlNamedQueryRules.DefaultMaxRows),
},
CommandTimeout = TimeSpan.FromSeconds(60),
OperationTimeout = TimeSpan.FromSeconds(90),
},
driverInstanceId: "sql-oracle-readonly",
dialect: new OracleDialect(),
connectionString: fixture.ConnectionString);
await using (driver)
{
await driver.InitializeAsync("{}", TestContext.Current.CancellationToken);
for (var poll = 0; poll < 3; poll++)
{
var snapshot = (await driver.ReadAsync(["Q/One"], TestContext.Current.CancellationToken))[0];
snapshot.StatusCode.ShouldBe(SqlStatusCodes.Good);
Convert.ToInt64(snapshot.Value, CultureInfo.InvariantCulture).ShouldBe(42L);
}
}
}
}