280 lines
13 KiB
C#
280 lines
13 KiB
C#
using System.Globalization;
|
|
using Microsoft.Data.SqlClient;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Xunit;
|
|
using ZB.MOM.WW.OtOpcUa.Configuration;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests;
|
|
|
|
/// <summary>
|
|
/// Spins up a dedicated test database, applies the EF migrations against it, and exposes a
|
|
/// <see cref="SqlConnection"/> factory. Disposed at collection teardown (drops the DB).
|
|
/// Gated by the <c>OTOPCUA_CONFIG_TEST_SERVER</c> env var so CI runs can opt in explicitly;
|
|
/// local runs default to the shared Docker host's SQL Server on <c>10.100.0.35:14330</c>.
|
|
/// </summary>
|
|
public sealed class SchemaComplianceFixture : IDisposable
|
|
{
|
|
/// <summary>The name prefix every Configuration test database carries; also the reaper's LIKE anchor.</summary>
|
|
internal const string TestDatabasePrefix = "OtOpcUaConfig_Test_";
|
|
|
|
private const string DefaultServer = "10.100.0.35,14330";
|
|
private const string DefaultSaPassword = "OtOpcUaDev_2026!";
|
|
|
|
/// <summary>How long a test database must have existed before the reaper considers it certainly orphaned.</summary>
|
|
private static readonly TimeSpan OrphanAge = TimeSpan.FromHours(24);
|
|
|
|
private static readonly Lazy<int> Reaper = new(RunReaper, LazyThreadSafetyMode.ExecutionAndPublication);
|
|
|
|
/// <summary>Gets the name of the test database.</summary>
|
|
public string DatabaseName { get; }
|
|
/// <summary>Gets the connection string for the test database.</summary>
|
|
public string ConnectionString { get; }
|
|
|
|
/// <summary>Initializes a new instance of the SchemaComplianceFixture class.</summary>
|
|
public SchemaComplianceFixture()
|
|
{
|
|
var server = Environment.GetEnvironmentVariable("OTOPCUA_CONFIG_TEST_SERVER") ?? DefaultServer;
|
|
var saPassword = Environment.GetEnvironmentVariable("OTOPCUA_CONFIG_TEST_SA_PASSWORD") ?? DefaultSaPassword;
|
|
|
|
// A killed test process never reaches Dispose, so its database outlives the run. Reap the ones old
|
|
// enough to be certainly nobody's, once per process. This fixture has no reachability probe, so an
|
|
// unreachable server must leave behaviour exactly as it was: the reaper silently does nothing and
|
|
// Migrate() below throws as it always has.
|
|
_ = Reaper.Value;
|
|
|
|
DatabaseName = $"{TestDatabasePrefix}{DateTime.UtcNow:yyyyMMddHHmmss}_{Guid.NewGuid():N}";
|
|
ConnectionString =
|
|
$"Server={server};Database={DatabaseName};User Id=sa;Password={saPassword};TrustServerCertificate=True;Encrypt=False;";
|
|
|
|
var options = new DbContextOptionsBuilder<OtOpcUaConfigDbContext>()
|
|
.UseSqlServer(ConnectionString)
|
|
.Options;
|
|
|
|
using var ctx = new OtOpcUaConfigDbContext(options);
|
|
ctx.Database.Migrate();
|
|
}
|
|
|
|
/// <summary>Opens a new SQL connection to the test database.</summary>
|
|
/// <returns>An open SQL connection.</returns>
|
|
public SqlConnection OpenConnection()
|
|
{
|
|
var conn = new SqlConnection(ConnectionString);
|
|
conn.Open();
|
|
return conn;
|
|
}
|
|
|
|
private static int RunReaper()
|
|
{
|
|
var server = Environment.GetEnvironmentVariable("OTOPCUA_CONFIG_TEST_SERVER") ?? DefaultServer;
|
|
var saPassword = Environment.GetEnvironmentVariable("OTOPCUA_CONFIG_TEST_SA_PASSWORD") ?? DefaultSaPassword;
|
|
var master =
|
|
$"Server={server};Database=master;User Id=sa;Password={saPassword};TrustServerCertificate=True;Encrypt=False;";
|
|
|
|
return SqlTestDatabaseReaper.ReapOrphans(master, TestDatabasePrefix, DateTime.UtcNow - OrphanAge).Count;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Disposes the fixture and drops the test database — via the same parameterized
|
|
/// <see cref="SqlTestDatabaseReaper.TryDropDatabase"/> the reaper uses, so this file carries
|
|
/// exactly one drop-DDL shape. Best-effort like the AdminUI fixture's teardown: the name is
|
|
/// self-minted so a swallowed failure only leaks a database the startup reaper reclaims
|
|
/// within 24 h.
|
|
/// </summary>
|
|
public void Dispose()
|
|
{
|
|
var masterConnection =
|
|
new SqlConnectionStringBuilder(ConnectionString) { InitialCatalog = "master" }.ConnectionString;
|
|
|
|
SqlTestDatabaseReaper.TryDropDatabase(masterConnection, DatabaseName);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Drops test databases that a killed test process left behind on the <b>shared</b> SQL Server.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// <para>
|
|
/// <see cref="SchemaComplianceFixture"/> names its database
|
|
/// <c>{prefix}{yyyyMMddHHmmss-UTC}_{guid:N}</c> and drops it in <c>Dispose</c> — which a
|
|
/// <c>Ctrl-C</c>, a crashed runner or a killed container never reaches, so the database survives
|
|
/// forever on an instance nobody gardens.
|
|
/// </para>
|
|
/// <para>
|
|
/// This is <c>DROP DATABASE</c> against a server other people share, so the rules are deliberately
|
|
/// narrow and every one of them is load-bearing:
|
|
/// </para>
|
|
/// <list type="bullet">
|
|
/// <item>
|
|
/// the <c>LIKE</c> is an <b>exact prefix</b> with <c>_</c> escaped (an unescaped <c>_</c> is a
|
|
/// single-character wildcard in T-SQL) — never widen it;
|
|
/// </item>
|
|
/// <item>
|
|
/// a matching name is dropped only when its <b>whole</b> shape is one this code could have
|
|
/// minted — prefix, a parseable 14-digit UTC timestamp, <c>_</c>, then 32 hex digits. That is
|
|
/// belt <i>and</i> braces against second-order injection: the name is also passed as a
|
|
/// <b>parameter</b> through <c>QUOTENAME</c> rather than interpolated into DDL, but the shape
|
|
/// check independently guarantees a candidate cannot contain <c>]</c> or <c>'</c>;
|
|
/// </item>
|
|
/// <item>
|
|
/// only names <b>strictly older than the cutoff</b> are dropped. At 24 hours that is far beyond
|
|
/// any run, so the reaper can never race a live sibling run on the same server; and
|
|
/// </item>
|
|
/// <item>
|
|
/// nothing here ever throws. Unlike this project's <c>Dispose</c>, which deliberately lets a
|
|
/// teardown failure surface, opportunistic housekeeping must never fail a green run.
|
|
/// </item>
|
|
/// </list>
|
|
/// <para>
|
|
/// Deliberately duplicated from the AdminUI.Tests copy rather than shared: the two suites have no
|
|
/// common test-support assembly, and a new one purely for ~100 lines of best-effort housekeeping
|
|
/// costs more than the duplication.
|
|
/// </para>
|
|
/// </remarks>
|
|
internal static class SqlTestDatabaseReaper
|
|
{
|
|
private const string TimestampFormat = "yyyyMMddHHmmss";
|
|
private const int ConnectTimeoutSeconds = 3;
|
|
|
|
/// <summary>
|
|
/// Drops every database matching <paramref name="prefix"/> whose embedded creation timestamp is
|
|
/// strictly older than <paramref name="cutoffUtc"/>.
|
|
/// </summary>
|
|
/// <param name="masterConnectionString">A connection string pointed at <c>master</c>.</param>
|
|
/// <param name="prefix">The exact test-database name prefix, e.g. <c>OtOpcUaConfig_Test_</c>.</param>
|
|
/// <param name="cutoffUtc">Databases created strictly before this UTC instant are dropped.</param>
|
|
/// <returns>The names actually dropped; empty when there was nothing to reap or anything went wrong.</returns>
|
|
internal static IReadOnlyList<string> ReapOrphans(string masterConnectionString, string prefix, DateTime cutoffUtc)
|
|
{
|
|
var reaped = new List<string>();
|
|
|
|
try
|
|
{
|
|
foreach (var name in ListCandidates(masterConnectionString, prefix))
|
|
{
|
|
if (!TryParseCreatedUtc(name, prefix, out var createdUtc)) continue;
|
|
if (createdUtc >= cutoffUtc) continue;
|
|
|
|
try
|
|
{
|
|
if (TryDropDatabase(masterConnectionString, name)) reaped.Add(name);
|
|
}
|
|
catch (Exception)
|
|
{
|
|
// One stubborn database must not stop the sweep, nor fail the run that triggered it.
|
|
}
|
|
}
|
|
}
|
|
catch (Exception)
|
|
{
|
|
// Enumeration failed (server down, no permission). Reaping is opportunistic housekeeping.
|
|
}
|
|
|
|
if (reaped.Count > 0)
|
|
{
|
|
Console.WriteLine(
|
|
$"[sql-test-reaper] dropped {reaped.Count} orphaned test database(s) older than " +
|
|
$"{cutoffUtc:yyyy-MM-dd HH:mm:ss}Z: {string.Join(", ", reaped)}");
|
|
}
|
|
|
|
return reaped;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Drops the named database, swallowing every failure — this is called unwrapped from
|
|
/// <c>finally</c> blocks, so it must be genuinely best-effort.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// The database name is an <b>identifier</b>, which cannot be parameterised directly, so it rides
|
|
/// in as a parameter and <c>QUOTENAME</c> escapes it server-side. Interpolating it into the DDL
|
|
/// instead would make any attacker-chosen database name on this shared server a second-order
|
|
/// injection executed as <c>sa</c>.
|
|
/// </remarks>
|
|
/// <param name="masterConnectionString">A connection string pointed at <c>master</c>.</param>
|
|
/// <param name="databaseName">The database to drop.</param>
|
|
/// <returns><see langword="true"/> when the statement ran without error.</returns>
|
|
internal static bool TryDropDatabase(string masterConnectionString, string databaseName)
|
|
{
|
|
try
|
|
{
|
|
using var conn = new SqlConnection(masterConnectionString);
|
|
conn.Open();
|
|
|
|
using var cmd = conn.CreateCommand();
|
|
|
|
// The QUOTENAME result must be assembled into a variable first: EXEC(<string>) accepts only a
|
|
// concatenation of literals and variables, so the tempting one-liner
|
|
// EXEC('ALTER DATABASE ' + QUOTENAME(@name) + …) is a syntax error, not a subtle bug.
|
|
cmd.CommandText = @"
|
|
DECLARE @sql nvarchar(max);
|
|
IF DB_ID(@name) IS NOT NULL
|
|
BEGIN
|
|
SET @sql = N'ALTER DATABASE ' + QUOTENAME(@name) + N' SET SINGLE_USER WITH ROLLBACK IMMEDIATE; ' +
|
|
N'DROP DATABASE ' + QUOTENAME(@name) + N';';
|
|
EXEC sp_executesql @sql;
|
|
END";
|
|
cmd.Parameters.Add(new SqlParameter("@name", databaseName));
|
|
|
|
cmd.ExecuteNonQuery();
|
|
return true;
|
|
}
|
|
catch (Exception)
|
|
{
|
|
// Teardown is best-effort: a dropped connection here must not fail an otherwise-green run.
|
|
// The database name carries a timestamp, so a leaked one is reaped by the next run instead.
|
|
return false;
|
|
}
|
|
}
|
|
|
|
private static List<string> ListCandidates(string masterConnectionString, string prefix)
|
|
{
|
|
var names = new List<string>();
|
|
|
|
// A short connect timeout, because this runs BEFORE whatever the fixture does next: on an
|
|
// unreachable server the default ~15 s would simply be added to the latency the caller already pays
|
|
// — here, on top of the connect timeout Migrate() is about to spend proving the same thing.
|
|
var probe = new SqlConnectionStringBuilder(masterConnectionString)
|
|
{
|
|
ConnectTimeout = ConnectTimeoutSeconds,
|
|
}.ConnectionString;
|
|
|
|
using var conn = new SqlConnection(probe);
|
|
conn.Open();
|
|
|
|
using var cmd = conn.CreateCommand();
|
|
cmd.CommandText = @"SELECT name FROM sys.databases WHERE name LIKE @pattern ESCAPE '\'";
|
|
cmd.Parameters.Add(new SqlParameter("@pattern", prefix.Replace("_", @"\_", StringComparison.Ordinal) + "%"));
|
|
|
|
using var reader = cmd.ExecuteReader();
|
|
while (reader.Read()) names.Add(reader.GetString(0));
|
|
|
|
return names;
|
|
}
|
|
|
|
private static bool TryParseCreatedUtc(string databaseName, string prefix, out DateTime createdUtc)
|
|
{
|
|
createdUtc = default;
|
|
|
|
if (!databaseName.StartsWith(prefix, StringComparison.Ordinal)) return false;
|
|
|
|
var rest = databaseName.AsSpan(prefix.Length);
|
|
|
|
// Expect exactly "<14-digit timestamp>_<32 hex digits>" — anything else is not a name this code
|
|
// minted. Validating the GUID tail is what bounds the character set of every candidate name: a
|
|
// "N"-format GUID is hex only, so no candidate can carry a ']' or a quote into the drop statement.
|
|
if (rest.Length < TimestampFormat.Length + 1 || rest[TimestampFormat.Length] != '_') return false;
|
|
if (!Guid.TryParseExact(rest[(TimestampFormat.Length + 1)..], "N", out _)) return false;
|
|
|
|
return DateTime.TryParseExact(
|
|
rest[..TimestampFormat.Length],
|
|
TimestampFormat,
|
|
CultureInfo.InvariantCulture,
|
|
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal,
|
|
out createdUtc);
|
|
}
|
|
}
|
|
|
|
[CollectionDefinition(nameof(SchemaComplianceCollection))]
|
|
public sealed class SchemaComplianceCollection : ICollectionFixture<SchemaComplianceFixture>
|
|
{
|
|
}
|