Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests/MediumPersistenceRegressionTests.cs
T
Joseph Doherty 513fa1aa16 docs(tests): fix CommentChecker findings across tests/ — 13,392 → 0 (repo-wide scan clean)
Comment/XML-doc changes only:
- add summaries to ~10k test methods, fixtures, fakes and helpers
  (+ <param> on theories, <returns> on async Task methods,
  <inheritdoc/> on interface implementations the checker can resolve)
- strip ~2.6k project-tracking references (WP*, P*-*, row-NN, Task N,
  #NN, Component-0NN) from comments, keeping the explanatory text;
  reword false positives in comments only
- real docs on fakes implementing BCL/library interfaces
  (IDisposable, ILogger, IOptionsMonitor, IAsyncLifetime)
- reword the last 5 src/ false positives (CWE-1236, failures-1,
  year-0001, M365)

Only non-comment edits: four one-line nested classes split across lines
so members can carry docs. Build 0 errors / 0 warnings.
2026-10-07 15:05:49 -04:00

111 lines
6.1 KiB
C#

using Microsoft.AspNetCore.DataProtection;
using Microsoft.EntityFrameworkCore;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites;
namespace ZB.MOM.WW.ScadaBridge.ConfigurationDatabase.Tests;
public class MediumPersistenceRegressionTests
{
private static ScadaBridgeDbContext Create(bool protectedWrites = true)
{
var options = new DbContextOptionsBuilder<ScadaBridgeDbContext>()
.UseSqlite("Data Source=:memory:;Foreign Keys=False").Options;
var db = protectedWrites ? new ScadaBridgeDbContext(options, new EphemeralDataProtectionProvider())
: new ScadaBridgeDbContext(options);
db.Database.OpenConnection();
db.Database.EnsureCreated();
return db;
}
/// <summary>Verifies that an instance unique name cannot exist at two different sites.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task DL1_UniqueNameCannotExistAtTwoSites()
{
await using var db = Create();
db.Instances.Add(new Instance("shared-pump") { SiteId = 1, TemplateId = 1 });
await db.SaveChangesAsync();
db.Instances.Add(new Instance("shared-pump") { SiteId = 2, TemplateId = 1 });
await Assert.ThrowsAsync<InstanceNameConflictException>(() => db.SaveChangesAsync());
}
/// <summary>Verifies that a context with a different data protection key cannot read protected connection configuration.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task DL2_ConvertersDoNotShareKeysAcrossProviders()
{
await using var connection = new Microsoft.Data.Sqlite.SqliteConnection("Data Source=:memory:;Foreign Keys=False");
await connection.OpenAsync();
var options = new DbContextOptionsBuilder<ScadaBridgeDbContext>().UseSqlite(connection).Options;
await using (var first = new ScadaBridgeDbContext(options, new EphemeralDataProtectionProvider()))
{
await first.Database.EnsureCreatedAsync();
first.DataConnections.Add(new DataConnection("key-isolation", "OpcUa", 1) { PrimaryConfiguration = "{}" });
await first.SaveChangesAsync();
}
await using var wrongKey = new ScadaBridgeDbContext(options, new EphemeralDataProtectionProvider());
await Assert.ThrowsAsync<System.Security.Cryptography.CryptographicException>(() =>
wrongKey.DataConnections.SingleAsync(c => c.Name == "key-isolation"));
}
/// <summary>Verifies that the legacy upgrade protects both configuration columns and is safe to run twice.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task DL2_LegacyUpgradeProtectsBothColumnsAndIsIdempotent()
{
await using var db = Create();
await db.Database.ExecuteSqlRawAsync("INSERT INTO DataConnections (SiteId, Name, Protocol, PrimaryConfiguration, BackupConfiguration, FailoverRetryCount) VALUES (1, 'legacy', 'OpcUa', {0}, {1}, 3)",
"""{"Password":"primary-secret"}""", """{"Password":"backup-secret"}""");
await DataConnectionSecretUpgrade.UpgradeAsync(db);
await using var command = db.Database.GetDbConnection().CreateCommand();
command.CommandText = "SELECT PrimaryConfiguration FROM DataConnections WHERE Name = 'legacy'";
var first = (string)(await command.ExecuteScalarAsync())!;
Assert.DoesNotContain("primary-secret", first);
await DataConnectionSecretUpgrade.UpgradeAsync(db);
Assert.Equal(first, (string)(await command.ExecuteScalarAsync())!);
var row = await db.DataConnections.SingleAsync(c => c.Name == "legacy");
Assert.Contains("primary-secret", row.PrimaryConfiguration);
Assert.Contains("backup-secret", row.BackupConfiguration);
}
/// <summary>Verifies that data connection configuration is stored encrypted and reads back unchanged.</summary>
/// <param name="backup">True to exercise the backup configuration column, false for the primary.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task DL2_DataConnectionConfigurationIsEncryptedAndRoundTrips(bool backup)
{
await using var db = Create();
const string secret = "{\"Password\":\"medium-secret-never-plaintext\"}";
var connection = new DataConnection("test", "OpcUa", 1);
if (backup) connection.BackupConfiguration = secret; else connection.PrimaryConfiguration = secret;
db.DataConnections.Add(connection);
await db.SaveChangesAsync();
db.ChangeTracker.Clear();
await using var cmd = db.Database.GetDbConnection().CreateCommand();
cmd.CommandText = $"SELECT {(backup ? "BackupConfiguration" : "PrimaryConfiguration")} FROM DataConnections WHERE Id = {connection.Id}";
var raw = Assert.IsType<string>(await cmd.ExecuteScalarAsync());
Assert.DoesNotContain("medium-secret", raw);
var loaded = await db.DataConnections.SingleAsync(c => c.Id == connection.Id);
Assert.Equal(secret, backup ? loaded.BackupConfiguration : loaded.PrimaryConfiguration);
}
/// <summary>Verifies that a context without a data protection provider refuses to write connection configuration.</summary>
/// <param name="backup">True to exercise the backup configuration column, false for the primary.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task DL2_SchemaOnlyContextCannotWriteProtocolCredentials(bool backup)
{
await using var db = Create(false);
var connection = new DataConnection("test", "OpcUa", 1);
if (backup) connection.BackupConfiguration = "{}"; else connection.PrimaryConfiguration = "{}";
db.DataConnections.Add(connection);
var error = await Assert.ThrowsAsync<InvalidOperationException>(() => db.SaveChangesAsync());
Assert.Contains("Data Protection", error.Message);
}
}