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.
129 lines
7.4 KiB
C#
129 lines
7.4 KiB
C#
using Shouldly;
|
|
using Xunit;
|
|
using ZB.MOM.WW.OtOpcUa.Driver.Sql.Contracts;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Driver.Sql.Tests;
|
|
|
|
/// <summary>
|
|
/// lmxopcua#974 (review finding S-7): the named-query guard must read a literal / comment boundary exactly as the
|
|
/// provider does, or refuse. Each bypass string below was accepted by the single shared lexer as one harmless
|
|
/// <c>SELECT</c> while the named provider reads a second statement — <c>COMMIT</c> (ending the driver's
|
|
/// always-rolled-back transaction) followed by a write. The Postgres and MySQL strings were executed against the
|
|
/// live fixtures before the fix and committed their UPDATE (see <c>NamedQueryBypassLiveTests</c>).
|
|
/// </summary>
|
|
public sealed class SqlReadOnlyStatementDialectTests
|
|
{
|
|
/// <summary>(provider the string is a bypass on, the statement).</summary>
|
|
public static TheoryData<SqlProvider, string> Bypasses => new()
|
|
{
|
|
// MySQL: backslash escapes in '…' and "…", # comments, and -- that is NOT a comment without a space.
|
|
{ SqlProvider.MySql, "SELECT '\\'' ; COMMIT; DELETE FROM t; -- '" },
|
|
{ SqlProvider.MySql, "SELECT \"\\\"\" ; COMMIT; DELETE FROM t; -- \"" },
|
|
{ SqlProvider.MySql, "SELECT 1 #'\n; COMMIT; DELETE FROM t; -- '" },
|
|
{ SqlProvider.MySql, "SELECT 1--'\n' ; COMMIT; DELETE FROM t; -- '" },
|
|
{ SqlProvider.MySql, "SELECT 1 /*! ; COMMIT; DELETE FROM t */" },
|
|
// PostgreSQL: dollar quoting (anonymous and tagged), E'' backslash escapes, [ as a subscript, nested comments,
|
|
// and a line comment that a bare carriage return ends.
|
|
{ SqlProvider.Postgres, "SELECT $$'$$; COMMIT; DROP TABLE t; --'" },
|
|
{ SqlProvider.Postgres, "SELECT $q$'$q$; COMMIT; DROP TABLE t; --'" },
|
|
{ SqlProvider.Postgres, "SELECT E'\\''; COMMIT; DELETE FROM t; --'" },
|
|
{ SqlProvider.Postgres, "SELECT a[']'] ; COMMIT; DELETE FROM t; --'" },
|
|
{ SqlProvider.Postgres, "SELECT 1 /* /* */ ' */ ; COMMIT; DELETE FROM t; --'" },
|
|
{ SqlProvider.Postgres, "SELECT 1 --x\r; COMMIT; DELETE FROM t\n" },
|
|
// SQL Server: ]] is an escaped ] inside [ … ], and comments nest.
|
|
{ SqlProvider.SqlServer, "SELECT [a]]'] ; COMMIT; DELETE FROM t; --'" },
|
|
{ SqlProvider.SqlServer, "SELECT 1 /* /* */ ' */ ; COMMIT; DELETE FROM t; --'" },
|
|
// Oracle: q'[…]' ends at "]'", not at the next quote.
|
|
{ SqlProvider.Oracle, "SELECT q'[ ' ]' FROM dual; DELETE FROM t --'" },
|
|
};
|
|
|
|
[Theory]
|
|
[MemberData(nameof(Bypasses))]
|
|
public void Check_refusesTheBypass_asItsOwnProvider(SqlProvider provider, string sql)
|
|
=> SqlReadOnlyStatement.Check(sql, provider, out _).ShouldNotBeNull();
|
|
|
|
[Theory]
|
|
[MemberData(nameof(Bypasses))]
|
|
public void Check_refusesTheBypass_withoutAProvider_andForOdbc(SqlProvider provider, string sql)
|
|
{
|
|
_ = provider;
|
|
SqlReadOnlyStatement.Check(sql, out _).ShouldNotBeNull();
|
|
SqlReadOnlyStatement.Check(sql, SqlProvider.Odbc, out _).ShouldNotBeNull();
|
|
}
|
|
|
|
/// <summary>Positive controls: plain reads each dialect writes every day still pass — the guard did not just get stricter everywhere.</summary>
|
|
[Theory]
|
|
[InlineData(SqlProvider.SqlServer, "SELECT [it's], [a]]b], [update] FROM t WHERE x = @x")]
|
|
[InlineData(SqlProvider.SqlServer, "SELECT 'C:\\temp\\' AS path FROM t")] // no backslash escapes in T-SQL
|
|
[InlineData(SqlProvider.SqlServer, "SELECT a FROM #staging -- note\r\nWHERE 1 = 1")]
|
|
[InlineData(SqlProvider.Postgres, "SELECT a::text, arr[1], a$b FROM t WHERE x = @x AND y = $1")]
|
|
[InlineData(SqlProvider.Postgres, "SELECT 'it''s' AS v, \"Mixed Case\" FROM t /* note */")]
|
|
[InlineData(SqlProvider.MySql, "SELECT `delete`, `a``b` FROM t -- note\nWHERE x = @x # trailing")]
|
|
[InlineData(SqlProvider.MySql, "SELECT 'it''s', \"x\" FROM t;")]
|
|
[InlineData(SqlProvider.Oracle, "SELECT serial#, sid FROM v$session WHERE username = :p_user")]
|
|
[InlineData(SqlProvider.Oracle, "SELECT /*+ INDEX(t) */ 'C:\\temp' FROM t")]
|
|
public void Check_acceptsAnOrdinaryRead_inItsDialect(SqlProvider provider, string sql)
|
|
=> SqlReadOnlyStatement.Check(sql, provider, out _).ShouldBeNull();
|
|
|
|
[Theory]
|
|
[InlineData(SqlProvider.MySql, "SELECT 'C:\\temp' AS path")]
|
|
[InlineData(SqlProvider.Postgres, "SELECT 'C:\\temp' AS path")]
|
|
[InlineData(SqlProvider.Postgres, "SELECT $$text$$ AS v")]
|
|
[InlineData(SqlProvider.MySql, "SELECT 1 --comment")]
|
|
public void Check_refusesWhatItWillNotModel_withAReasonNamingTheConstruct(SqlProvider provider, string sql)
|
|
{
|
|
var problem = SqlReadOnlyStatement.Check(sql, provider, out _).ShouldNotBeNull();
|
|
problem.ShouldNotContain("more than one statement"); // the reason is the construct, not a downstream symptom
|
|
}
|
|
|
|
[Fact]
|
|
public void Check_withoutAProvider_requiresEveryDialectToAgree()
|
|
{
|
|
// A T-SQL bracket identifier is not a quote to PostgreSQL / MySQL / Oracle, which then read UPDATE as a keyword.
|
|
SqlReadOnlyStatement.Check("SELECT [update] FROM t", SqlProvider.SqlServer, out _).ShouldBeNull();
|
|
var problem = SqlReadOnlyStatement.Check("SELECT [update] FROM t", out _).ShouldNotBeNull();
|
|
problem.ShouldContain("every supported dialect");
|
|
SqlReadOnlyStatement.Check("SELECT a FROM t WHERE x = ?", SqlProvider.Odbc, out var normalised).ShouldBeNull();
|
|
normalised.ShouldBe("SELECT a FROM t WHERE x = ?");
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData(SqlProvider.Postgres, "SELECT a FROM t WHERE x = @line", "@line", true)]
|
|
[InlineData(SqlProvider.Postgres, "SELECT a FROM t WHERE x = $$@line$$", "@line", false)] // unlexable ⇒ not "used"
|
|
[InlineData(SqlProvider.MySql, "SELECT a FROM t # @line\nWHERE 1 = 1", "@line", false)] // inside a MySQL comment
|
|
[InlineData(SqlProvider.SqlServer, "SELECT a FROM t # @line\nWHERE 1 = 1", "@line", true)] // # is not a comment there
|
|
public void UsesMarker_lexesAsTheProvider(SqlProvider provider, string sql, string marker, bool expected)
|
|
=> SqlReadOnlyStatement.UsesMarker(sql, marker, provider).ShouldBe(expected);
|
|
|
|
[Fact]
|
|
public void ReplaceMarkers_rewritesOnlyRealTokens_andLeavesLiteralsAndCommentsAlone()
|
|
{
|
|
const string sql = "SELECT a, '@x' AS lit FROM t WHERE x = @x AND y = @xy AND z = @X -- @x\n AND w = @x";
|
|
|
|
var rewritten = SqlReadOnlyStatement.ReplaceMarkers(sql, SqlProvider.Postgres, ["@x", "@xy"], ["$1", "$2"]);
|
|
|
|
rewritten.ShouldBe("SELECT a, '@x' AS lit FROM t WHERE x = $1 AND y = $2 AND z = $1 -- @x\n AND w = $1");
|
|
}
|
|
|
|
[Fact]
|
|
public void ReplaceMarkers_refusesAStatementItCannotLex()
|
|
=> Should.Throw<InvalidOperationException>(() =>
|
|
SqlReadOnlyStatement.ReplaceMarkers("SELECT $$x$$ WHERE a = @a", SqlProvider.Postgres, ["@a"], ["$1"]));
|
|
|
|
[Fact]
|
|
public void CountPositionalMarkers_isMinusOne_whenDialectsDisagree()
|
|
{
|
|
SqlReadOnlyStatement.CountPositionalMarkers("SELECT a FROM t WHERE x = ? AND y = '?'").ShouldBe(1);
|
|
// MySQL reads "# ?" as a comment; SQL Server reads a marker.
|
|
SqlReadOnlyStatement.CountPositionalMarkers("SELECT a FROM t WHERE x = ? # ?\n").ShouldBe(-1);
|
|
}
|
|
|
|
[Fact]
|
|
public void Describe_usesTheProvidersLexicon()
|
|
{
|
|
var query = new SqlNamedQueryDto { Sql = "SELECT 'C:\\temp' AS p" };
|
|
SqlNamedQueryRules.Describe("q", query, SqlProvider.SqlServer).ShouldBeNull();
|
|
SqlNamedQueryRules.Describe("q", query, SqlProvider.MySql).ShouldNotBeNull().ShouldContain("backslash");
|
|
}
|
|
}
|