65c4330a68
#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.
134 lines
5.2 KiB
C#
134 lines
5.2 KiB
C#
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#987 (review finding S-10): a table write's "exactly one row" commit rule against a SQL Server table
|
|
/// whose AFTER INSERT/UPDATE trigger writes two audit rows per changed row and does not <c>SET NOCOUNT ON</c>.
|
|
/// SqlClient's <c>ExecuteNonQuery</c> returns the SUM of every DML statement the command caused (1 + 2 = 3), so a
|
|
/// driver trusting it rolled every such write back as "touched 3 rows". The dialect now reads the target
|
|
/// statement's own <c>@@ROWCOUNT</c>.
|
|
/// <para>Positive controls: the audit rows exist (the trigger really fired inside the committed write), and an
|
|
/// Update of an absent key is still <c>BadNoData</c> (the count is the target's, not a constant 1).</para>
|
|
/// </summary>
|
|
[Collection(SqlPollServerCollection.Name)]
|
|
public sealed class SqlServerTriggerWriteLiveTests(SqlPollServerFixture fixture)
|
|
{
|
|
[Theory]
|
|
[InlineData("Update")]
|
|
[InlineData("Upsert")]
|
|
public async Task Write_toATableWithARowWritingTrigger_commitsTheOneTargetRow(string mode)
|
|
{
|
|
SkipUnlessLive();
|
|
var key = mode == "Update" ? "Present" : NewKey();
|
|
var value = 100.0 + Random.Shared.Next(1, 1000);
|
|
await using var driver = await StartAsync(Target("Sp", key, mode));
|
|
|
|
(await WriteAsync(driver, "Sp", value)).ShouldBe(SqlStatusCodes.Good);
|
|
|
|
Convert.ToDouble(await ScalarAsync(
|
|
$"SELECT sp_value FROM [{SqlPollServerFixture.Schema}].[{SqlPollServerFixture.AuditedTable}] WHERE tag_name = N'{key}'"),
|
|
CultureInfo.InvariantCulture).ShouldBe(value);
|
|
Convert.ToInt32(await ScalarAsync(
|
|
$"SELECT COUNT(*) FROM [{SqlPollServerFixture.Schema}].[{SqlPollServerFixture.AuditLogTable}] " +
|
|
$"WHERE tag_name = N'{key}' AND sp_value = {value.ToString(CultureInfo.InvariantCulture)}"),
|
|
CultureInfo.InvariantCulture).ShouldBe(2);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Insert_intoATableWithARowWritingTrigger_commitsTheOneNewRow()
|
|
{
|
|
SkipUnlessLive();
|
|
var key = NewKey();
|
|
await using var driver = await StartAsync(Target("Sp", key, "Insert"));
|
|
|
|
(await WriteAsync(driver, "Sp", 4.5)).ShouldBe(SqlStatusCodes.Good);
|
|
|
|
Convert.ToInt32(await ScalarAsync(
|
|
$"SELECT COUNT(*) FROM [{SqlPollServerFixture.Schema}].[{SqlPollServerFixture.AuditedTable}] WHERE tag_name = N'{key}'"),
|
|
CultureInfo.InvariantCulture).ShouldBe(1);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Update_ofAnAbsentKey_onATriggeredTable_isStillBadNoData()
|
|
{
|
|
SkipUnlessLive();
|
|
await using var driver = await StartAsync(Target("Sp", NewKey(), "Update"));
|
|
|
|
(await WriteAsync(driver, "Sp", 1.0)).ShouldBe(SqlStatusCodes.BadNoData);
|
|
}
|
|
|
|
private void SkipUnlessLive()
|
|
{
|
|
if (fixture.SkipReason is { } reason) Assert.Skip(reason);
|
|
}
|
|
|
|
private static string NewKey() => "T-" + Guid.NewGuid().ToString("N")[..12];
|
|
|
|
private static RawTagEntry Target(string rawPath, string key, string mode)
|
|
{
|
|
var config = new JsonObject
|
|
{
|
|
["driver"] = "Sql",
|
|
["model"] = "KeyValue",
|
|
["table"] = SqlPollServerFixture.Schema + "." + SqlPollServerFixture.AuditedTable,
|
|
["keyColumn"] = "tag_name",
|
|
["keyValue"] = key,
|
|
["valueColumn"] = "sp_value",
|
|
["type"] = "Float64",
|
|
["writable"] = true,
|
|
["write"] = new JsonObject { ["mode"] = mode },
|
|
};
|
|
return new RawTagEntry(rawPath, config.ToJsonString(), WriteIdempotent: false);
|
|
}
|
|
|
|
private async Task<SqlDriver> StartAsync(params RawTagEntry[] tags)
|
|
{
|
|
var driver = new SqlDriver(
|
|
new SqlDriverOptions
|
|
{
|
|
RawTags = tags,
|
|
CommandTimeout = TimeSpan.FromSeconds(30),
|
|
OperationTimeout = TimeSpan.FromSeconds(45),
|
|
AllowWrites = true,
|
|
},
|
|
driverInstanceId: "sql-trigger-writes",
|
|
dialect: new SqlServerDialect(),
|
|
connectionString: fixture.ConnectionString);
|
|
try
|
|
{
|
|
await driver.InitializeAsync("{}", TestContext.Current.CancellationToken);
|
|
}
|
|
catch
|
|
{
|
|
await driver.DisposeAsync();
|
|
throw;
|
|
}
|
|
|
|
return driver;
|
|
}
|
|
|
|
private static async Task<uint> WriteAsync(SqlDriver driver, string reference, object? value)
|
|
=> (await ((IWritable)driver).WriteAsync([new WriteRequest(reference, value)], TestContext.Current.CancellationToken))
|
|
.ShouldHaveSingleItem().StatusCode;
|
|
|
|
private async Task<object?> ScalarAsync(string sql)
|
|
{
|
|
var connection = await fixture.OpenInspectionConnectionAsync();
|
|
await using (connection)
|
|
{
|
|
var command = connection.CreateCommand();
|
|
await using (command)
|
|
{
|
|
command.CommandText = sql;
|
|
return await command.ExecuteScalarAsync(TestContext.Current.CancellationToken);
|
|
}
|
|
}
|
|
}
|
|
}
|