Files
lmxopcua/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/AuthorizationTests.cs
Joseph Doherty a25593a9c6 chore: organize solution into module folders (Core/Server/Drivers/Client/Tooling)
Group all 69 projects into category subfolders under src/ and tests/ so the
Rider Solution Explorer mirrors the module structure. Folders: Core, Server,
Drivers (with a nested Driver CLIs subfolder), Client, Tooling.

- Move every project folder on disk with git mv (history preserved as renames).
- Recompute relative paths in 57 .csproj files: cross-category ProjectReferences,
  the lib/ HintPath+None refs in Driver.Historian.Wonderware, and the external
  mxaccessgw refs in Driver.Galaxy and its test project.
- Rebuild ZB.MOM.WW.OtOpcUa.slnx with nested solution folders.
- Re-prefix project paths in functional scripts (e2e, compliance, smoke SQL,
  integration, install).

Build green (0 errors); unit tests pass. Docs left for a separate pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 01:55:28 -04:00

163 lines
5.6 KiB
C#

using Microsoft.Data.SqlClient;
using Shouldly;
using Xunit;
namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests;
/// <summary>
/// Creates two throwaway DB users — one in <c>OtOpcUaNode</c>, one in <c>OtOpcUaAdmin</c> —
/// and verifies the grants/denies from the <c>AuthorizationGrants</c> migration.
/// </summary>
[Trait("Category", "Authorization")]
[Collection(nameof(SchemaComplianceCollection))]
public sealed class AuthorizationTests
{
private readonly SchemaComplianceFixture _fixture;
public AuthorizationTests(SchemaComplianceFixture fixture) => _fixture = fixture;
[Fact]
public void Node_role_can_execute_GetCurrentGenerationForCluster_but_not_PublishGeneration()
{
var (user, password) = CreateUserInRole(_fixture, "Node");
try
{
using var conn = OpenAs(user, password);
Should.Throw<SqlException>(() =>
{
using var cmd = conn.CreateCommand();
cmd.CommandText = "EXEC dbo.sp_PublishGeneration @ClusterId='x', @DraftGenerationId=1";
cmd.ExecuteNonQuery();
}).Message.ShouldContain("permission", Case.Insensitive);
// Calling a granted proc authenticates; the proc itself will RAISERROR with Unauthorized
// because our test principal isn't bound to any node — that's expected.
var ex = Should.Throw<SqlException>(() =>
{
using var cmd = conn.CreateCommand();
cmd.CommandText = "EXEC dbo.sp_GetCurrentGenerationForCluster @NodeId='n', @ClusterId='c'";
cmd.ExecuteNonQuery();
});
ex.Message.ShouldContain("Unauthorized");
}
finally
{
DropUser(_fixture, user);
}
}
[Fact]
public void Node_role_cannot_SELECT_from_tables_directly()
{
var (user, password) = CreateUserInRole(_fixture, "Node");
try
{
using var conn = OpenAs(user, password);
var ex = Should.Throw<SqlException>(() =>
{
using var cmd = conn.CreateCommand();
cmd.CommandText = "SELECT COUNT(*) FROM dbo.ConfigGeneration";
cmd.ExecuteScalar();
});
ex.Message.ShouldContain("permission", Case.Insensitive);
}
finally
{
DropUser(_fixture, user);
}
}
[Fact]
public void Admin_role_can_execute_PublishGeneration()
{
var (user, password) = CreateUserInRole(_fixture, "Admin");
try
{
using var conn = OpenAs(user, password);
// Calling the proc is permitted; content-level errors (missing draft) are OK — they
// prove the grant succeeded (we got past the permission check into the proc body).
var ex = Should.Throw<SqlException>(() =>
{
using var cmd = conn.CreateCommand();
cmd.CommandText = "EXEC dbo.sp_PublishGeneration @ClusterId='no-such-cluster', @DraftGenerationId=9999";
cmd.ExecuteNonQuery();
});
ex.Message.ShouldNotContain("permission", Case.Insensitive);
}
finally
{
DropUser(_fixture, user);
}
}
/// <summary>Creates a SQL login + DB user in the given role and returns its credentials.</summary>
private static (string User, string Password) CreateUserInRole(SchemaComplianceFixture fx, string role)
{
var user = $"tst_{role.ToLower()}_{Guid.NewGuid():N}"[..24];
const string password = "TestUser_2026!";
var dbRole = role == "Node" ? "OtOpcUaNode" : "OtOpcUaAdmin";
// Create the login in master, the user in the test DB, and add it to the role.
using (var conn = new SqlConnection(
new SqlConnectionStringBuilder(fx.ConnectionString) { InitialCatalog = "master" }.ConnectionString))
{
conn.Open();
using var cmd = conn.CreateCommand();
cmd.CommandText = $"CREATE LOGIN [{user}] WITH PASSWORD = '{password}', CHECK_POLICY = OFF;";
cmd.ExecuteNonQuery();
}
using (var conn = fx.OpenConnection())
{
using var cmd = conn.CreateCommand();
cmd.CommandText = $@"
CREATE USER [{user}] FOR LOGIN [{user}];
ALTER ROLE {dbRole} ADD MEMBER [{user}];";
cmd.ExecuteNonQuery();
}
return (user, password);
}
private static void DropUser(SchemaComplianceFixture fx, string user)
{
try
{
using var dbConn = fx.OpenConnection();
using var cmd1 = dbConn.CreateCommand();
cmd1.CommandText = $"IF DATABASE_PRINCIPAL_ID('{user}') IS NOT NULL DROP USER [{user}];";
cmd1.ExecuteNonQuery();
}
catch { /* swallow — fixture disposes the DB anyway */ }
try
{
using var master = new SqlConnection(
new SqlConnectionStringBuilder(fx.ConnectionString) { InitialCatalog = "master" }.ConnectionString);
master.Open();
using var cmd = master.CreateCommand();
cmd.CommandText = $"IF SUSER_ID('{user}') IS NOT NULL DROP LOGIN [{user}];";
cmd.ExecuteNonQuery();
}
catch { /* ignore */ }
}
private SqlConnection OpenAs(string user, string password)
{
var cs = new SqlConnectionStringBuilder(_fixture.ConnectionString)
{
UserID = user,
Password = password,
IntegratedSecurity = false,
}.ConnectionString;
var conn = new SqlConnection(cs);
conn.Open();
return conn;
}
}