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;
///
/// lmxopcua#974 (security review 2026-12-02), against the real SQL Server: T-SQL needs no ; between
/// statements, so SELECT 1 AS v COMMIT UPDATE … is three statements to the server and was one
/// SELECT 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
/// SELECT-only login.
///
/// Positive control: run the old way (an ordinary transaction, rolled back afterwards) the
/// smuggled COMMIT ends the transaction and the UPDATE commits. The row is restored.
/// The guard refuses it, for SqlServer and Odbc alike.
/// A real read with a CTE, a window function, subqueries and a parameter is accepted by the guard and
/// reads Good through the driver.
///
///
[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(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 ReadTargetAsync()
=> Convert.ToDouble(await ScalarAsync($"SELECT sp_value FROM {Target} WHERE tag_name = 'Present'"), CultureInfo.InvariantCulture);
private async Task