fix(security): per-instance credential references (#835) and confined OpcUaClient user-certificate path (#836)
#835: inside one driver namespace, a secret:<ns>/<X>/... reference whose first segment names ANOTHER existing same-type driver instance (id or name, case-insensitive; another-instance match beats an own-name match, so renaming one's driver after a victim's unlocks nothing) is refused at save (DriverConfigSaveGate.ValidateAsync), deploy (CredentialReferenceOtherInstance, Heidenhain included), Test Connect (TestDriverConnect.DriverInstanceId, ConfigDb read off the mailbox) and live browse (BrowserSessionService, fail-closed without a ConfigDb). One rule: DriverCredentialPolicy.DescribeOtherInstanceProblems + DriverInstanceIdentities. Shared names and the driver's own id stay valid; env: is not instance-scoped. Running drivers are unchanged (warn-only window: the deploy gate and the upgrade preflight / /raw banner list them). #836: OpcUaClient UserCertificatePath is a relative path inside Drivers:OpcUaClient:UserCertificateDirectory (default <LocalAppData>/OtOpcUa/pki/user-certificates). Syntactic rule (CredentialFilePaths, a DriverCredentialPolicy path field) at every #815 seam; at load time ResolveSecretRefsAsync joins, canonicalises and requires lexical AND link-resolved containment before the PFX password is resolved, and LoadCertificate refuses an unresolved path. A running driver's pre-#836 absolute path keeps loading with a rate-limited warning (LegacyCredentialReferenceTracker.ReportPath). Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
+91
@@ -0,0 +1,91 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// The deploy gate for lmxopcua#835 (a credential reference naming ANOTHER driver instance's secret) and #836 (the
|
||||
/// OpcUaClient user-certificate path confined to the node's certificate directory).
|
||||
/// </summary>
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class DraftValidatorCredentialInstanceAndPathTests
|
||||
{
|
||||
private static IReadOnlyList<ValidationError> Validate(params DriverInstance[] drivers) =>
|
||||
Validate(drivers, []);
|
||||
|
||||
private static IReadOnlyList<ValidationError> Validate(DriverInstance[] drivers, Device[] devices) =>
|
||||
DraftValidator.Validate(new DraftSnapshot
|
||||
{
|
||||
GenerationId = 1,
|
||||
ClusterId = "c",
|
||||
DriverInstances = drivers,
|
||||
Devices = devices,
|
||||
Tags = [],
|
||||
}).Where(e => e.Code is CredentialReferenceDeployChecks.Code or CredentialReferenceDeployChecks.OtherInstanceCode).ToList();
|
||||
|
||||
private static DriverInstance Drv(string id, string name, string type, string config) =>
|
||||
new() { DriverInstanceId = id, ClusterId = "c", Name = name, DriverType = type, DriverConfig = config };
|
||||
|
||||
[Fact]
|
||||
public void A_galaxy_driver_naming_another_instances_key_is_refused()
|
||||
{
|
||||
var e = Validate(
|
||||
Drv("DRV-victim", "Victim", "GalaxyMxGateway", """{"Gateway":{"ApiKeySecretRef":"secret:galaxy/DRV-victim/apikey"}}"""),
|
||||
Drv("DRV-evil", "Evil", "GalaxyMxGateway", """{"Gateway":{"Endpoint":"http://evil:5001","ApiKeySecretRef":"secret:galaxy/DRV-victim/apikey"}}"""))
|
||||
.ShouldHaveSingleItem();
|
||||
e.Code.ShouldBe(CredentialReferenceDeployChecks.OtherInstanceCode);
|
||||
e.Context.ShouldBe("DRV-evil");
|
||||
e.Message.ShouldContain("lmxopcua#835");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_device_config_naming_another_instance_by_name_is_refused() =>
|
||||
Validate(
|
||||
[
|
||||
Drv("DRV-a", "Victim", "OpcUaClient", "{}"),
|
||||
Drv("DRV-b", "Evil", "OpcUaClient", "{}"),
|
||||
],
|
||||
[new Device { DeviceId = "dev-b", DriverInstanceId = "DRV-b", Name = "d", DeviceConfig = """{"Password":"secret:opcuaclient/victim/pw"}""" }])
|
||||
.ShouldHaveSingleItem().Context.ShouldBe("dev-b");
|
||||
|
||||
[Fact]
|
||||
public void Shared_and_own_keys_pass() =>
|
||||
Validate(
|
||||
Drv("DRV-a", "A", "GalaxyMxGateway", """{"Gateway":{"ApiKeySecretRef":"secret:galaxy/DRV-a/apikey"}}"""),
|
||||
Drv("DRV-b", "B", "GalaxyMxGateway", """{"Gateway":{"ApiKeySecretRef":"secret:galaxy/gw/apikey"}}"""),
|
||||
Drv("DRV-c", "C", "GalaxyMxGateway", """{"Gateway":{"ApiKeySecretRef":"secret:galaxy/gw/apikey"}}"""))
|
||||
.ShouldBeEmpty();
|
||||
|
||||
[Fact]
|
||||
public void Heidenhain_cross_instance_is_reported_by_this_gate() =>
|
||||
DraftValidator.Validate(new DraftSnapshot
|
||||
{
|
||||
GenerationId = 1, ClusterId = "c",
|
||||
DriverInstances =
|
||||
[
|
||||
Drv("H1", "line1", "Heidenhain", """{"Access":{"InspectPassword":"secret:heidenhain/line1/inspect"}}"""),
|
||||
Drv("H2", "line2", "Heidenhain", """{"Access":{"InspectPassword":"secret:heidenhain/line1/inspect"}}"""),
|
||||
],
|
||||
Devices = [], Tags = [],
|
||||
})
|
||||
.Where(e => e.Code == CredentialReferenceDeployChecks.OtherInstanceCode)
|
||||
.ShouldHaveSingleItem().Context.ShouldBe("H2");
|
||||
|
||||
[Theory]
|
||||
[InlineData("""{"AuthType":"Certificate","UserCertificatePath":"C:\\Windows\\System32\\config\\systemprofile\\host.pfx"}""")]
|
||||
[InlineData("""{"UserCertificatePath":"/etc/ssl/private/host.pfx"}""")]
|
||||
[InlineData("""{"UserCertificatePath":"plant1/../../host.pfx"}""")]
|
||||
public void An_opcuaclient_user_certificate_path_outside_the_directory_is_refused(string config)
|
||||
{
|
||||
var e = Validate(Drv("DRV-o", "o", "OpcUaClient", config)).ShouldHaveSingleItem();
|
||||
e.Code.ShouldBe(CredentialReferenceDeployChecks.Code);
|
||||
e.Message.ShouldContain("lmxopcua#836");
|
||||
e.Message.ShouldNotContain("host.pfx");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A_relative_user_certificate_path_passes() =>
|
||||
Validate(Drv("DRV-o", "o", "OpcUaClient", """{"AuthType":"Certificate","UserCertificatePath":"plant1/user.pfx"}""")).ShouldBeEmpty();
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#836: a key-material file field (OpcUaClient <c>UserCertificatePath</c>) is a relative path confined to a
|
||||
/// node directory — syntactically at the admin seams, lexically + through links at load time.
|
||||
/// </summary>
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class CredentialFilePathsTests
|
||||
{
|
||||
[Theory]
|
||||
[InlineData("user.pfx")]
|
||||
[InlineData("plant1/user.pfx")]
|
||||
[InlineData("plant1\\user.pfx")]
|
||||
[InlineData("a/b-c_d.e/f.pfx")]
|
||||
public void Plain_relative_paths_are_acceptable(string path) => CredentialFilePaths.IsAcceptableRelative(path).ShouldBeTrue();
|
||||
|
||||
[Theory]
|
||||
[InlineData("/etc/ssl/private/host.pfx")]
|
||||
[InlineData("\\\\server\\share\\x.pfx")]
|
||||
[InlineData("\\x.pfx")]
|
||||
[InlineData("C:\\certs\\user.pfx")]
|
||||
[InlineData("C:user.pfx")]
|
||||
[InlineData("../user.pfx")]
|
||||
[InlineData("plant1/../../user.pfx")]
|
||||
[InlineData("./user.pfx")]
|
||||
[InlineData("plant1//user.pfx")]
|
||||
[InlineData("plant1/")]
|
||||
[InlineData("~/user.pfx")]
|
||||
[InlineData("user pfx")]
|
||||
[InlineData("secret:opcuaclient/x")]
|
||||
public void Absolute_traversal_and_odd_paths_are_refused(string path)
|
||||
{
|
||||
CredentialFilePaths.IsAcceptableRelative(path).ShouldBeFalse();
|
||||
CredentialFilePaths.IsAcceptable(path).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Blank_is_acceptable_but_not_a_relative_path()
|
||||
{
|
||||
CredentialFilePaths.IsAcceptable(null).ShouldBeTrue();
|
||||
CredentialFilePaths.IsAcceptable("").ShouldBeTrue();
|
||||
CredentialFilePaths.IsAcceptableRelative("").ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("""{"UserCertificatePath":"/etc/ssl/private/host.pfx"}""", 1)]
|
||||
[InlineData("""{"userCertificatePath":"..\\..\\Windows\\x.pfx"}""", 1)]
|
||||
[InlineData("""{"Devices":[{"UserCertificatePath":"C:\\x.pfx"}]}""", 1)]
|
||||
[InlineData("""{"UserCertificatePath":42}""", 1)]
|
||||
[InlineData("""{"UserCertificatePath":"plant1/user.pfx"}""", 0)]
|
||||
[InlineData("""{"UserCertificatePath":null}""", 0)]
|
||||
public void The_driver_policy_scans_the_OpcUaClient_path_field(string config, int expected)
|
||||
{
|
||||
var problems = DriverCredentialPolicy.DescribeProblems(DriverTypeNames.OpcUaClient, config);
|
||||
problems.Count.ShouldBe(expected);
|
||||
if (expected > 0)
|
||||
{
|
||||
problems[0].ShouldContain("lmxopcua#836");
|
||||
problems[0].ShouldContain(DriverCredentialPolicy.OpcUaClientUserCertificateDirectoryKey);
|
||||
problems[0].ShouldNotContain("host.pfx");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Other_drivers_do_not_scan_the_path_field() =>
|
||||
DriverCredentialPolicy.DescribeProblems(DriverTypeNames.Galaxy, """{"UserCertificatePath":"/etc/x.pfx"}""").ShouldBeEmpty();
|
||||
|
||||
[Fact]
|
||||
public void ResolveWithin_returns_the_path_inside_the_directory()
|
||||
{
|
||||
using var dir = new TempDir();
|
||||
var resolved = CredentialFilePaths.ResolveWithin("plant1/user.pfx", dir.Path, "F", "D");
|
||||
resolved.ShouldBe(Path.Combine(Path.GetFullPath(dir.Path), "plant1", "user.pfx"));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("../escape.pfx")]
|
||||
[InlineData("/etc/passwd")]
|
||||
public void ResolveWithin_refuses_a_bad_value_fail_closed(string value)
|
||||
{
|
||||
using var dir = new TempDir();
|
||||
Should.Throw<CredentialReferenceException>(() => CredentialFilePaths.ResolveWithin(value, dir.Path, "F", "D"))
|
||||
.Message.ShouldContain("fail-closed");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ResolveWithin_refuses_a_file_symlink_that_escapes_the_directory()
|
||||
{
|
||||
using var dir = new TempDir();
|
||||
using var outside = new TempDir();
|
||||
var target = Path.Combine(outside.Path, "victim.pfx");
|
||||
File.WriteAllText(target, "x");
|
||||
var link = Path.Combine(dir.Path, "user.pfx");
|
||||
if (!TryCreateLink(() => File.CreateSymbolicLink(link, target))) return;
|
||||
|
||||
Should.Throw<CredentialReferenceException>(() => CredentialFilePaths.ResolveWithin("user.pfx", dir.Path, "F", "D"))
|
||||
.Message.ShouldContain("symbolic link");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ResolveWithin_refuses_a_directory_symlink_that_escapes_the_directory()
|
||||
{
|
||||
using var dir = new TempDir();
|
||||
using var outside = new TempDir();
|
||||
File.WriteAllText(Path.Combine(outside.Path, "victim.pfx"), "x");
|
||||
if (!TryCreateLink(() => Directory.CreateSymbolicLink(Path.Combine(dir.Path, "plant1"), outside.Path))) return;
|
||||
|
||||
Should.Throw<CredentialReferenceException>(() => CredentialFilePaths.ResolveWithin("plant1/victim.pfx", dir.Path, "F", "D"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ResolveWithin_accepts_a_symlink_that_stays_inside_the_directory()
|
||||
{
|
||||
using var dir = new TempDir();
|
||||
Directory.CreateDirectory(Path.Combine(dir.Path, "real"));
|
||||
File.WriteAllText(Path.Combine(dir.Path, "real", "user.pfx"), "x");
|
||||
if (!TryCreateLink(() => File.CreateSymbolicLink(Path.Combine(dir.Path, "alias.pfx"), Path.Combine(dir.Path, "real", "user.pfx")))) return;
|
||||
|
||||
CredentialFilePaths.ResolveWithin("alias.pfx", dir.Path, "F", "D").ShouldEndWith("alias.pfx");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ResolveWithin_accepts_a_directory_that_is_itself_reached_through_a_link()
|
||||
{
|
||||
// e.g. macOS /var -> /private/var: the configured directory's own parents may be links.
|
||||
using var outside = new TempDir();
|
||||
using var holder = new TempDir();
|
||||
var linkedDir = Path.Combine(holder.Path, "certs");
|
||||
if (!TryCreateLink(() => Directory.CreateSymbolicLink(linkedDir, outside.Path))) return;
|
||||
File.WriteAllText(Path.Combine(outside.Path, "user.pfx"), "x");
|
||||
|
||||
CredentialFilePaths.ResolveWithin("user.pfx", linkedDir, "F", "D").ShouldEndWith("user.pfx");
|
||||
}
|
||||
|
||||
private static bool TryCreateLink(Action create)
|
||||
{
|
||||
try
|
||||
{
|
||||
create();
|
||||
return true;
|
||||
}
|
||||
catch (Exception e) when (e is UnauthorizedAccessException or IOException)
|
||||
{
|
||||
return false; // Windows without the symlink privilege: the lexical tests still cover the rule.
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class TempDir : IDisposable
|
||||
{
|
||||
public TempDir()
|
||||
{
|
||||
Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "otopcua-836-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(Path);
|
||||
}
|
||||
|
||||
public string Path { get; }
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
try { Directory.Delete(Path, recursive: true); } catch (IOException) { } catch (UnauthorizedAccessException) { }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#835: inside one namespace, a credential reference whose instance segment
|
||||
/// (<c>secret:galaxy/<X>/…</c>) names ANOTHER existing instance of the same driver type is refused.
|
||||
/// </summary>
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class CredentialInstanceScopeTests
|
||||
{
|
||||
private static readonly DriverInstanceIdentity[] Instances =
|
||||
[
|
||||
new("DRV-aaa", "PlantA", DriverTypeNames.Galaxy),
|
||||
new("DRV-bbb", "PlantB", DriverTypeNames.Galaxy),
|
||||
new("DRV-ccc", "UpstreamC", DriverTypeNames.OpcUaClient),
|
||||
new("DRV-ddd", "UpstreamD", DriverTypeNames.OpcUaClient),
|
||||
];
|
||||
|
||||
private static string Galaxy(string apiKeyRef) =>
|
||||
"{\"Gateway\":{\"Endpoint\":\"http://evil:5001\",\"ApiKeySecretRef\":" + System.Text.Json.JsonSerializer.Serialize(apiKeyRef) + "}}";
|
||||
|
||||
[Theory]
|
||||
[InlineData("secret:galaxy/DRV-bbb/apikey")]
|
||||
[InlineData("secret:galaxy/PlantB/apikey")]
|
||||
[InlineData("secret:galaxy/plantb/apikey")] // case-insensitive
|
||||
[InlineData("secret:otopcua/galaxy/PlantB/apikey")] // the second namespace
|
||||
[InlineData("${secret:galaxy/PlantB/apikey}")] // the token spelling
|
||||
[InlineData("secret:galaxy/PlantB")] // the segment alone
|
||||
public void A_reference_naming_another_instance_is_refused(string reference)
|
||||
{
|
||||
var problem = DriverCredentialPolicy
|
||||
.DescribeOtherInstanceProblems(DriverTypeNames.Galaxy, Galaxy(reference), "DRV-aaa", Instances)
|
||||
.ShouldHaveSingleItem();
|
||||
problem.ShouldContain("Gateway.ApiKeySecretRef");
|
||||
problem.ShouldContain("lmxopcua#835");
|
||||
problem.ShouldContain("DRV-bbb");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("secret:galaxy/DRV-aaa/apikey")] // its own id
|
||||
[InlineData("secret:galaxy/PlantA/apikey")] // its own name
|
||||
[InlineData("secret:galaxy/gw/apikey")] // a shared name no instance uses
|
||||
[InlineData("secret:galaxy/apikey")]
|
||||
[InlineData("secret:galaxy/UpstreamC/apikey")] // another TYPE's instance — not this namespace's owner
|
||||
[InlineData("env:OTOPCUA_GALAXY_PLANTB_KEY")] // env carries no instance convention
|
||||
[InlineData("dev:k")]
|
||||
[InlineData("")]
|
||||
public void Own_shared_and_non_secret_references_pass(string reference) =>
|
||||
DriverCredentialPolicy.DescribeOtherInstanceProblems(DriverTypeNames.Galaxy, Galaxy(reference), "DRV-aaa", Instances)
|
||||
.ShouldBeEmpty();
|
||||
|
||||
[Fact]
|
||||
public void A_driver_being_created_may_name_no_existing_instance() =>
|
||||
DriverCredentialPolicy.DescribeOtherInstanceProblems(DriverTypeNames.Galaxy, Galaxy("secret:galaxy/PlantA/apikey"), null, Instances)
|
||||
.ShouldHaveSingleItem();
|
||||
|
||||
[Fact]
|
||||
public void Renaming_ones_own_driver_after_the_victim_does_not_unlock_the_victims_secret()
|
||||
{
|
||||
// Attacker DRV-zzz renamed itself "PlantB" (names are unique per folder, not fleet-wide).
|
||||
var withTwin = Instances.Append(new DriverInstanceIdentity("DRV-zzz", "PlantB", DriverTypeNames.Galaxy));
|
||||
DriverCredentialPolicy.DescribeOtherInstanceProblems(DriverTypeNames.Galaxy, Galaxy("secret:galaxy/PlantB/apikey"), "DRV-zzz", withTwin)
|
||||
.ShouldHaveSingleItem();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_ack_password_and_device_level_fields_are_checked_too()
|
||||
{
|
||||
DriverCredentialPolicy.DescribeOtherInstanceProblems(
|
||||
DriverTypeNames.Galaxy, """{"AlarmAck":{"FallbackPasswordSecretRef":"secret:otopcua/galaxy/DRV-bbb/ack"}}""", "DRV-aaa", Instances)
|
||||
.ShouldHaveSingleItem().ShouldContain("AlarmAck.FallbackPasswordSecretRef");
|
||||
DriverCredentialPolicy.DescribeOtherInstanceProblems(
|
||||
DriverTypeNames.Galaxy, """{"Devices":[{"Gateway":{"ApiKeySecretRef":"secret:galaxy/PlantB/k"}}]}""", "DRV-aaa", Instances)
|
||||
.ShouldHaveSingleItem().ShouldContain("Devices[0].Gateway.ApiKeySecretRef");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("""{"Password":"secret:opcuaclient/UpstreamD/pw"}""", 1)]
|
||||
[InlineData("""{"UserCertificatePassword":"secret:opcuaclient/DRV-ddd/pfx"}""", 1)]
|
||||
[InlineData("""{"Password":"secret:opcuaclient/UpstreamC/pw"}""", 0)]
|
||||
[InlineData("""{"Password":"secret:opcuaclient/shared/pw"}""", 0)]
|
||||
public void OpcUaClient_has_the_same_rule(string config, int expected) =>
|
||||
DriverCredentialPolicy.DescribeOtherInstanceProblems(DriverTypeNames.OpcUaClient, config, "DRV-ccc", Instances)
|
||||
.Count.ShouldBe(expected);
|
||||
|
||||
[Fact]
|
||||
public void Heidenhain_has_the_same_rule()
|
||||
{
|
||||
IEnumerable<DriverInstanceIdentity> hh = [new("H1", "line1", DriverTypeNames.Heidenhain), new("H2", "line2", DriverTypeNames.Heidenhain)];
|
||||
DriverCredentialPolicy.DescribeOtherInstanceProblems(
|
||||
DriverTypeNames.Heidenhain, """{"Access":{"InspectPassword":"secret:heidenhain/line2/inspect"}}""", "H1", hh)
|
||||
.ShouldHaveSingleItem();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HasInstanceSegments_gates_the_ConfigDb_read()
|
||||
{
|
||||
DriverCredentialPolicy.HasInstanceSegments(DriverTypeNames.Galaxy, Galaxy("secret:galaxy/x/apikey")).ShouldBeTrue();
|
||||
DriverCredentialPolicy.HasInstanceSegments(DriverTypeNames.Galaxy, Galaxy("env:OTOPCUA_GALAXY_X")).ShouldBeFalse();
|
||||
DriverCredentialPolicy.HasInstanceSegments(DriverTypeNames.Galaxy, Galaxy("env:ConnectionStrings__ConfigDb")).ShouldBeFalse();
|
||||
DriverCredentialPolicy.HasInstanceSegments(DriverTypeNames.Modbus, """{"Password":"secret:galaxy/x"}""").ShouldBeFalse();
|
||||
DriverCredentialPolicy.HasInstanceSegments(DriverTypeNames.Galaxy, "not json").ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_combined_overload_reports_both_rules()
|
||||
{
|
||||
var config = """{"Gateway":{"ApiKeySecretRef":"secret:galaxy/PlantB/k"},"AlarmAck":{"FallbackPasswordSecretRef":"env:ConnectionStrings__ConfigDb"}}""";
|
||||
var problems = DriverCredentialPolicy.DescribeProblems(DriverTypeNames.Galaxy, config, "DRV-aaa", Instances);
|
||||
problems.Count.ShouldBe(2);
|
||||
problems.ShouldContain(p => p.Contains("lmxopcua#815"));
|
||||
problems.ShouldContain(p => p.Contains("lmxopcua#835"));
|
||||
}
|
||||
}
|
||||
+35
-3
@@ -45,7 +45,10 @@ public sealed class OpcUaClientBrowserCertificateAuthTests
|
||||
ex.Message.ShouldNotContain("does not support");
|
||||
}
|
||||
|
||||
/// <summary>A valid PFX whose password is a <c>secret:</c> ref resolves through the injected store.</summary>
|
||||
/// <summary>
|
||||
/// A valid PFX (a relative path inside the user-certificate directory — lmxopcua#836) whose password is a
|
||||
/// <c>secret:</c> ref resolves through the injected store.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task A_certificate_identity_is_built_with_its_secret_password_resolved()
|
||||
{
|
||||
@@ -55,12 +58,13 @@ public sealed class OpcUaClientBrowserCertificateAuthTests
|
||||
var opts = new OpcUaClientDriverOptions
|
||||
{
|
||||
AuthType = OpcUaAuthType.Certificate,
|
||||
UserCertificatePath = path,
|
||||
UserCertificatePath = Path.GetFileName(path),
|
||||
UserCertificatePassword = "secret:opcuaclient/browse-cert",
|
||||
};
|
||||
|
||||
var identity = await OpcUaClientDriverBrowser.BuildBrowseUserIdentityAsync(
|
||||
opts, new OneSecret("opcuaclient/browse-cert", "s3cret-pw"), TestContext.Current.CancellationToken);
|
||||
opts, new OneSecret("opcuaclient/browse-cert", "s3cret-pw"), TestContext.Current.CancellationToken,
|
||||
userCertificateDirectory: Path.GetDirectoryName(path));
|
||||
|
||||
identity.TokenType.ShouldBe(UserTokenType.Certificate);
|
||||
}
|
||||
@@ -70,6 +74,34 @@ public sealed class OpcUaClientBrowserCertificateAuthTests
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#836: the browse is a hard-fail path — an absolute <c>UserCertificatePath</c> (any PFX the service account
|
||||
/// can read) is refused before it is loaded or its password resolved, even when the file exists.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task The_browse_refuses_an_absolute_user_certificate_path()
|
||||
{
|
||||
var path = WritePfx("s3cret-pw");
|
||||
try
|
||||
{
|
||||
var opts = new OpcUaClientDriverOptions
|
||||
{
|
||||
AuthType = OpcUaAuthType.Certificate,
|
||||
UserCertificatePath = path,
|
||||
UserCertificatePassword = "s3cret-pw",
|
||||
};
|
||||
|
||||
var ex = await Should.ThrowAsync<ZB.MOM.WW.OtOpcUa.Core.Abstractions.CredentialReferenceException>(() =>
|
||||
OpcUaClientDriverBrowser.BuildBrowseUserIdentityAsync(
|
||||
opts, null, TestContext.Current.CancellationToken, userCertificateDirectory: Path.GetDirectoryName(path)));
|
||||
ex.Message.ShouldContain("lmxopcua#836");
|
||||
}
|
||||
finally
|
||||
{
|
||||
try { File.Delete(path); } catch { /* best-effort */ }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>With no secret store, a <c>secret:</c> ref fails closed instead of being sent as the literal.</summary>
|
||||
[Fact]
|
||||
public async Task A_secret_ref_with_no_secret_store_fails_closed()
|
||||
|
||||
+150
@@ -0,0 +1,150 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#836: the user-certificate identity loads only a PFX inside the node's user-certificate directory — the
|
||||
/// authored <c>UserCertificatePath</c> is relative, resolved (and link-checked) by <c>ResolveSecretRefsAsync</c>, which
|
||||
/// both the running driver and the AdminUI browser call before building the identity.
|
||||
/// </summary>
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class OpcUaClientUserCertificatePathTests : IDisposable
|
||||
{
|
||||
private readonly string _dir = Path.Combine(Path.GetTempPath(), "otopcua-836-ucert-" + Guid.NewGuid().ToString("N"));
|
||||
private readonly string _outside = Path.Combine(Path.GetTempPath(), "otopcua-836-outside-" + Guid.NewGuid().ToString("N"));
|
||||
|
||||
public OpcUaClientUserCertificatePathTests()
|
||||
{
|
||||
Directory.CreateDirectory(Path.Combine(_dir, "plant1"));
|
||||
Directory.CreateDirectory(_outside);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
foreach (var d in new[] { _dir, _outside })
|
||||
try { Directory.Delete(d, recursive: true); } catch (IOException) { } catch (UnauthorizedAccessException) { }
|
||||
}
|
||||
|
||||
private static void WritePfx(string path)
|
||||
{
|
||||
using var rsa = RSA.Create(2048);
|
||||
var req = new CertificateRequest("CN=Issue836", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
|
||||
using var cert = req.CreateSelfSigned(DateTimeOffset.UtcNow.AddMinutes(-5), DateTimeOffset.UtcNow.AddHours(1));
|
||||
File.WriteAllBytes(path, cert.Export(X509ContentType.Pfx, "pw"));
|
||||
}
|
||||
|
||||
private static OpcUaClientDriverOptions Cert(string path) =>
|
||||
new() { AuthType = OpcUaAuthType.Certificate, UserCertificatePath = path, UserCertificatePassword = "pw" };
|
||||
|
||||
[Fact]
|
||||
public async Task A_relative_path_inside_the_directory_resolves_and_loads()
|
||||
{
|
||||
WritePfx(Path.Combine(_dir, "plant1", "user.pfx"));
|
||||
|
||||
var resolved = await OpcUaUserIdentityFactory.ResolveSecretRefsAsync(
|
||||
Cert("plant1/user.pfx"), null, TestContext.Current.CancellationToken, userCertificateDirectory: _dir);
|
||||
|
||||
resolved.UserCertificatePath.ShouldBe(Path.Combine(Path.GetFullPath(_dir), "plant1", "user.pfx"));
|
||||
OpcUaUserIdentityFactory.Build(resolved).TokenType.ShouldBe(Opc.Ua.UserTokenType.Certificate);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("../outside.pfx")]
|
||||
[InlineData("plant1/../../outside.pfx")]
|
||||
public async Task Traversal_is_refused_before_any_load(string path) =>
|
||||
await Should.ThrowAsync<CredentialReferenceException>(() => OpcUaUserIdentityFactory.ResolveSecretRefsAsync(
|
||||
Cert(path), null, TestContext.Current.CancellationToken, userCertificateDirectory: _dir));
|
||||
|
||||
[Fact]
|
||||
public async Task An_absolute_path_is_refused_on_the_hard_fail_path_even_inside_the_directory()
|
||||
{
|
||||
var abs = Path.Combine(_dir, "plant1", "user.pfx");
|
||||
WritePfx(abs);
|
||||
var ex = await Should.ThrowAsync<CredentialReferenceException>(() => OpcUaUserIdentityFactory.ResolveSecretRefsAsync(
|
||||
Cert(abs), null, TestContext.Current.CancellationToken, userCertificateDirectory: _dir));
|
||||
ex.Message.ShouldContain("lmxopcua#836");
|
||||
ex.Message.ShouldNotContain(abs);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_symlink_escaping_the_directory_is_refused()
|
||||
{
|
||||
var victim = Path.Combine(_outside, "victim.pfx");
|
||||
WritePfx(victim);
|
||||
try
|
||||
{
|
||||
File.CreateSymbolicLink(Path.Combine(_dir, "user.pfx"), victim);
|
||||
}
|
||||
catch (Exception e) when (e is UnauthorizedAccessException or IOException)
|
||||
{
|
||||
return; // no symlink privilege (Windows): covered lexically above
|
||||
}
|
||||
|
||||
await Should.ThrowAsync<CredentialReferenceException>(() => OpcUaUserIdentityFactory.ResolveSecretRefsAsync(
|
||||
Cert("user.pfx"), null, TestContext.Current.CancellationToken, userCertificateDirectory: _dir));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_running_driver_keeps_loading_a_legacy_absolute_path_and_warns()
|
||||
{
|
||||
var abs = Path.Combine(_outside, "legacy.pfx");
|
||||
WritePfx(abs);
|
||||
var warnings = new List<string>();
|
||||
var tracker = new LegacyCredentialReferenceTracker(DriverCredentialPolicy.OpcUaClientScope, "ouc", warnings.Add);
|
||||
|
||||
var resolved = await OpcUaUserIdentityFactory.ResolveSecretRefsAsync(
|
||||
Cert(abs), null, TestContext.Current.CancellationToken, legacy: tracker, userCertificateDirectory: _dir);
|
||||
|
||||
resolved.UserCertificatePath.ShouldBe(abs);
|
||||
OpcUaUserIdentityFactory.Build(resolved).TokenType.ShouldBe(Opc.Ua.UserTokenType.Certificate);
|
||||
warnings.ShouldHaveSingleItem().ShouldContain("lmxopcua#836");
|
||||
warnings[0].ShouldNotContain(abs);
|
||||
tracker.Diagnostics.ShouldContainKey(LegacyCredentialReferenceTracker.DiagnosticsKeyPrefix + "UserCertificatePath");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_legacy_tracker_does_not_relax_a_relative_path_that_escapes()
|
||||
{
|
||||
var tracker = new LegacyCredentialReferenceTracker(DriverCredentialPolicy.OpcUaClientScope, "ouc", _ => { });
|
||||
await Should.ThrowAsync<CredentialReferenceException>(() => OpcUaUserIdentityFactory.ResolveSecretRefsAsync(
|
||||
Cert("../x.pfx"), null, TestContext.Current.CancellationToken, legacy: tracker, userCertificateDirectory: _dir));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_non_certificate_auth_type_leaves_the_path_alone()
|
||||
{
|
||||
var options = new OpcUaClientDriverOptions { AuthType = OpcUaAuthType.Anonymous, UserCertificatePath = "/etc/stale.pfx" };
|
||||
(await OpcUaUserIdentityFactory.ResolveSecretRefsAsync(options, null, TestContext.Current.CancellationToken, userCertificateDirectory: _dir))
|
||||
.ShouldBeSameAs(options);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadCertificate_refuses_an_unresolved_relative_path()
|
||||
{
|
||||
Should.Throw<InvalidOperationException>(() => OpcUaUserIdentityFactory.LoadCertificate(Cert("plant1/user.pfx")))
|
||||
.Message.ShouldContain("not been resolved");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_path_is_checked_before_any_secret_is_read()
|
||||
{
|
||||
var reads = 0;
|
||||
var options = Cert("/etc/x.pfx") with { UserCertificatePassword = "secret:opcuaclient/pfx-pw" };
|
||||
await Should.ThrowAsync<CredentialReferenceException>(() => OpcUaUserIdentityFactory.ResolveSecretRefsAsync(
|
||||
options, new CountingResolver(() => reads++), TestContext.Current.CancellationToken, userCertificateDirectory: _dir));
|
||||
reads.ShouldBe(0);
|
||||
}
|
||||
|
||||
private sealed class CountingResolver(Action onRead) : ZB.MOM.WW.Secrets.Abstractions.ISecretResolver
|
||||
{
|
||||
public Task<string?> GetAsync(ZB.MOM.WW.Secrets.Abstractions.SecretName name, CancellationToken ct)
|
||||
{
|
||||
onRead();
|
||||
return Task.FromResult<string?>("pw");
|
||||
}
|
||||
}
|
||||
}
|
||||
+90
-1
@@ -42,7 +42,8 @@ public sealed class BrowserSessionCredentialScopeTests
|
||||
{
|
||||
var bespoke = new RecordingBrowser(DriverTypeNames.Galaxy);
|
||||
var svc = new BrowserSessionService(
|
||||
[bespoke], new BrowseSessionRegistry(), NullLogger<BrowserSessionService>.Instance, new RecordingUniversal(), null!, null!);
|
||||
[bespoke], new BrowseSessionRegistry(), NullLogger<BrowserSessionService>.Instance, new RecordingUniversal(), null!, null!,
|
||||
SeededFactory());
|
||||
|
||||
await svc.OpenAsync(DriverTypeNames.Galaxy, """{"Gateway":{"ApiKeySecretRef":"secret:galaxy/main/apikey"}}""",
|
||||
TestContext.Current.CancellationToken);
|
||||
@@ -50,6 +51,94 @@ public sealed class BrowserSessionCredentialScopeTests
|
||||
bespoke.Opens.ShouldBe(1);
|
||||
}
|
||||
|
||||
/// <summary>lmxopcua#835: a reference naming ANOTHER instance's secret never opens a browser.</summary>
|
||||
[Theory]
|
||||
[InlineData("DRV-evil")]
|
||||
[InlineData(null)]
|
||||
public async Task A_reference_naming_another_instance_never_opens_a_browser(string? ownerId)
|
||||
{
|
||||
var bespoke = new RecordingBrowser(DriverTypeNames.Galaxy);
|
||||
var universal = new RecordingUniversal();
|
||||
var svc = new BrowserSessionService(
|
||||
[bespoke], new BrowseSessionRegistry(), NullLogger<BrowserSessionService>.Instance, universal, null!, null!, SeededFactory());
|
||||
|
||||
var result = await svc.OpenAsync(DriverTypeNames.Galaxy,
|
||||
"""{"Gateway":{"Endpoint":"http://evil:5001","ApiKeySecretRef":"secret:galaxy/DRV-victim/apikey"}}""", ownerId,
|
||||
TestContext.Current.CancellationToken);
|
||||
|
||||
result.Ok.ShouldBeFalse();
|
||||
result.Message.ShouldNotBeNull().ShouldContain("lmxopcua#835");
|
||||
bespoke.Opens.ShouldBe(0);
|
||||
universal.Opens.ShouldBe(0);
|
||||
}
|
||||
|
||||
/// <summary>Positive control: the owning driver's own id-scoped secret reaches the browser.</summary>
|
||||
[Fact]
|
||||
public async Task The_owners_own_secret_reaches_the_browser()
|
||||
{
|
||||
var bespoke = new RecordingBrowser(DriverTypeNames.Galaxy);
|
||||
var svc = new BrowserSessionService(
|
||||
[bespoke], new BrowseSessionRegistry(), NullLogger<BrowserSessionService>.Instance, new RecordingUniversal(), null!, null!,
|
||||
SeededFactory());
|
||||
|
||||
await svc.OpenAsync(DriverTypeNames.Galaxy, """{"Gateway":{"ApiKeySecretRef":"secret:galaxy/Victim/apikey"}}""", "DRV-victim",
|
||||
TestContext.Current.CancellationToken);
|
||||
|
||||
bespoke.Opens.ShouldBe(1);
|
||||
}
|
||||
|
||||
/// <summary>Without the instance list the cross-instance rule cannot be checked, so the browse fails closed.</summary>
|
||||
[Fact]
|
||||
public async Task Without_a_config_db_an_in_scope_secret_reference_fails_closed()
|
||||
{
|
||||
var bespoke = new RecordingBrowser(DriverTypeNames.Galaxy);
|
||||
var svc = new BrowserSessionService(
|
||||
[bespoke], new BrowseSessionRegistry(), NullLogger<BrowserSessionService>.Instance, new RecordingUniversal(), null!, null!);
|
||||
|
||||
var result = await svc.OpenAsync(DriverTypeNames.Galaxy, """{"Gateway":{"ApiKeySecretRef":"secret:galaxy/main/apikey"}}""",
|
||||
TestContext.Current.CancellationToken);
|
||||
|
||||
result.Ok.ShouldBeFalse();
|
||||
result.Message.ShouldNotBeNull().ShouldContain("fail-closed");
|
||||
bespoke.Opens.ShouldBe(0);
|
||||
}
|
||||
|
||||
/// <summary>lmxopcua#836: an absolute OpcUaClient user-certificate path never opens a browser.</summary>
|
||||
[Fact]
|
||||
public async Task An_absolute_user_certificate_path_never_opens_a_browser()
|
||||
{
|
||||
var bespoke = new RecordingBrowser(DriverTypeNames.OpcUaClient);
|
||||
var svc = new BrowserSessionService(
|
||||
[bespoke], new BrowseSessionRegistry(), NullLogger<BrowserSessionService>.Instance, new RecordingUniversal(), null!, null!);
|
||||
|
||||
var result = await svc.OpenAsync(DriverTypeNames.OpcUaClient,
|
||||
"""{"EndpointUrl":"opc.tcp://evil:4840","AuthType":"Certificate","UserCertificatePath":"C:\\ProgramData\\x\\host.pfx"}""",
|
||||
TestContext.Current.CancellationToken);
|
||||
|
||||
result.Ok.ShouldBeFalse();
|
||||
result.Message.ShouldNotBeNull().ShouldContain("lmxopcua#836");
|
||||
bespoke.Opens.ShouldBe(0);
|
||||
}
|
||||
|
||||
private static Microsoft.EntityFrameworkCore.IDbContextFactory<ZB.MOM.WW.OtOpcUa.Configuration.OtOpcUaConfigDbContext> SeededFactory()
|
||||
{
|
||||
var name = $"browse-835-{Guid.NewGuid():N}";
|
||||
using (var db = Uns.RawTreeTestDb.CreateNamed(name))
|
||||
{
|
||||
db.DriverInstances.Add(new ZB.MOM.WW.OtOpcUa.Configuration.Entities.DriverInstance
|
||||
{
|
||||
DriverInstanceId = "DRV-victim", ClusterId = "c", Name = "Victim", DriverType = DriverTypeNames.Galaxy, DriverConfig = "{}",
|
||||
});
|
||||
db.DriverInstances.Add(new ZB.MOM.WW.OtOpcUa.Configuration.Entities.DriverInstance
|
||||
{
|
||||
DriverInstanceId = "DRV-evil", ClusterId = "c", Name = "Evil", DriverType = DriverTypeNames.Galaxy, DriverConfig = "{}",
|
||||
});
|
||||
db.SaveChanges();
|
||||
}
|
||||
|
||||
return Uns.RawTreeTestDb.Factory(name);
|
||||
}
|
||||
|
||||
private sealed class RecordingBrowser(string driverType) : IDriverBrowser
|
||||
{
|
||||
public int Opens { get; private set; }
|
||||
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.AdminUI.Deployments;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Deployments;
|
||||
|
||||
/// <summary>
|
||||
/// The upgrade preflight / <c>/raw</c> banner lists the configs the deploy gate will now refuse for lmxopcua#835
|
||||
/// (another instance's secret) and #836 (absolute user-certificate path) — Draft and Deployed alike.
|
||||
/// </summary>
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class CredentialReferencePreflightInstanceAndPathTests
|
||||
{
|
||||
private static DriverInstance Drv(string id, string name, string type, string config) =>
|
||||
new() { DriverInstanceId = id, ClusterId = "c", Name = name, DriverType = type, DriverConfig = config };
|
||||
|
||||
[Fact]
|
||||
public void Draft_and_deployed_cross_instance_references_are_listed()
|
||||
{
|
||||
var drivers = new[]
|
||||
{
|
||||
Drv("DRV-a", "A", DriverTypeNames.Galaxy, """{"Gateway":{"ApiKeySecretRef":"secret:galaxy/DRV-a/apikey"}}"""),
|
||||
Drv("DRV-b", "B", DriverTypeNames.Galaxy, """{"Gateway":{"ApiKeySecretRef":"secret:galaxy/DRV-a/apikey"}}"""),
|
||||
};
|
||||
var devices = new[] { new Device { DeviceId = "dev-b", DriverInstanceId = "DRV-b", Name = "gw", DeviceConfig = """{"AlarmAck":{"FallbackPasswordSecretRef":"secret:otopcua/galaxy/A/ack"}}""" } };
|
||||
var deployed = new[]
|
||||
{
|
||||
new DriverInstanceSpec(Guid.NewGuid(), "DRV-a", "A", DriverTypeNames.Galaxy, true, "{}"),
|
||||
new DriverInstanceSpec(Guid.NewGuid(), "DRV-b", "B", DriverTypeNames.Galaxy, true, """{"Gateway":{"ApiKeySecretRef":"secret:galaxy/A/apikey"}}"""),
|
||||
};
|
||||
|
||||
var findings = CredentialReferencePreflight.Scan(drivers, devices, deployed);
|
||||
|
||||
findings.Count.ShouldBe(3);
|
||||
findings.ShouldAllBe(f => f.DriverInstanceId == "DRV-b" && f.Problem.Contains("lmxopcua#835"));
|
||||
findings.Count(f => f.Source == CredentialFindingSource.Draft).ShouldBe(2);
|
||||
findings.Single(f => f.Source == CredentialFindingSource.Deployed).DriverName.ShouldBe("B");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void An_absolute_user_certificate_path_is_listed_without_the_path()
|
||||
{
|
||||
var findings = CredentialReferencePreflight.Scan(
|
||||
[Drv("o", "Upstream", DriverTypeNames.OpcUaClient, """{"AuthType":"Certificate","UserCertificatePath":"C:\\certs\\plant.pfx"}""")],
|
||||
[],
|
||||
[]);
|
||||
|
||||
var f = findings.ShouldHaveSingleItem();
|
||||
f.Problem.ShouldContain("lmxopcua#836");
|
||||
f.Problem.ShouldNotContain("plant.pfx");
|
||||
}
|
||||
}
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.AdminUI.Uns;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Uns;
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#835 (a credential reference naming ANOTHER driver instance's secret) and #836 (the OpcUaClient
|
||||
/// user-certificate path confined to a node directory) at the SAVE path (RawTreeService): nothing reaches the
|
||||
/// config DB, through driver and device create + update.
|
||||
/// </summary>
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class CredentialInstanceAndPathSavePathTests
|
||||
{
|
||||
private static CancellationToken Ct => TestContext.Current.CancellationToken;
|
||||
|
||||
private static string Galaxy(string reference) =>
|
||||
"""{"Gateway":{"Endpoint":"http://evil:5001","ApiKeySecretRef":"REF"}}""".Replace("REF", reference);
|
||||
|
||||
private static async Task<(RawTreeService Svc, string Db, string VictimId)> WithVictimAsync()
|
||||
{
|
||||
var name = RawTreeTestDb.SeedFresh();
|
||||
var svc = new RawTreeService(RawTreeTestDb.Factory(name));
|
||||
var victim = await svc.CreateDriverAsync(RawTreeTestDb.ClusterId, null, "Victim", DriverTypeNames.Galaxy,
|
||||
Galaxy("secret:galaxy/victim-own/apikey"), Ct);
|
||||
victim.Ok.ShouldBeTrue(victim.Error);
|
||||
return (svc, name, victim.CreatedId!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateDriver_refuses_a_reference_naming_another_instance()
|
||||
{
|
||||
var (svc, name, victimId) = await WithVictimAsync();
|
||||
|
||||
var byName = await svc.CreateDriverAsync(RawTreeTestDb.ClusterId, null, "evil1", DriverTypeNames.Galaxy,
|
||||
Galaxy("secret:galaxy/Victim/apikey"), Ct);
|
||||
var byId = await svc.CreateDriverAsync(RawTreeTestDb.ClusterId, null, "evil2", DriverTypeNames.Galaxy,
|
||||
Galaxy($"secret:galaxy/{victimId}/apikey"), Ct);
|
||||
|
||||
byName.Ok.ShouldBeFalse();
|
||||
byName.Error!.ShouldContain("lmxopcua#835");
|
||||
byId.Ok.ShouldBeFalse();
|
||||
using var db = RawTreeTestDb.CreateNamed(name);
|
||||
db.DriverInstances.ShouldNotContain(d => d.Name == "evil1" || d.Name == "evil2");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Update_and_device_paths_refuse_and_keep_the_stored_config()
|
||||
{
|
||||
var (svc, name, victimId) = await WithVictimAsync();
|
||||
var evil = await svc.CreateDriverAsync(RawTreeTestDb.ClusterId, null, "evil", DriverTypeNames.Galaxy,
|
||||
Galaxy("secret:galaxy/shared/apikey"), Ct);
|
||||
evil.Ok.ShouldBeTrue(evil.Error);
|
||||
|
||||
byte[] rv;
|
||||
string deviceId;
|
||||
byte[] deviceRv;
|
||||
using (var db = RawTreeTestDb.CreateNamed(name))
|
||||
{
|
||||
rv = db.DriverInstances.Single(d => d.DriverInstanceId == evil.CreatedId).RowVersion;
|
||||
var device = db.Devices.Single(d => d.DriverInstanceId == evil.CreatedId);
|
||||
deviceId = device.DeviceId;
|
||||
deviceRv = device.RowVersion;
|
||||
}
|
||||
|
||||
var stolen = Galaxy($"secret:galaxy/{victimId}/apikey");
|
||||
(await svc.UpdateDriverAsync(evil.CreatedId!, "evil", stolen, null, rv, Ct)).Error.ShouldNotBeNull().ShouldContain("lmxopcua#835");
|
||||
(await svc.UpdateDeviceAsync(deviceId, "dev", stolen, true, deviceRv, Ct)).Ok.ShouldBeFalse();
|
||||
(await svc.CreateDeviceAsync(evil.CreatedId!, "dev2", stolen, Ct)).Ok.ShouldBeFalse();
|
||||
|
||||
using var check = RawTreeTestDb.CreateNamed(name);
|
||||
check.DriverInstances.Single(d => d.DriverInstanceId == evil.CreatedId).DriverConfig.ShouldContain("secret:galaxy/shared/apikey");
|
||||
check.Devices.Where(d => d.DriverInstanceId == evil.CreatedId).ShouldAllBe(d => !d.DeviceConfig.Contains(victimId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_driver_may_save_its_own_id_scoped_secret_on_update_and_on_its_devices()
|
||||
{
|
||||
var (svc, name, victimId) = await WithVictimAsync();
|
||||
byte[] rv;
|
||||
string deviceId;
|
||||
byte[] deviceRv;
|
||||
using (var db = RawTreeTestDb.CreateNamed(name))
|
||||
{
|
||||
rv = db.DriverInstances.Single(d => d.DriverInstanceId == victimId).RowVersion;
|
||||
var device = db.Devices.Single(d => d.DriverInstanceId == victimId);
|
||||
deviceId = device.DeviceId;
|
||||
deviceRv = device.RowVersion;
|
||||
}
|
||||
|
||||
var own = Galaxy($"secret:galaxy/{victimId}/apikey");
|
||||
(await svc.UpdateDriverAsync(victimId, "Victim", own, null, rv, Ct)).Ok.ShouldBeTrue();
|
||||
(await svc.UpdateDeviceAsync(deviceId, "dev", Galaxy("secret:galaxy/Victim/apikey"), true, deviceRv, Ct)).Ok.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("""{"AuthType":"Certificate","UserCertificatePath":"C:\\Windows\\System32\\config\\systemprofile\\host.pfx"}""")]
|
||||
[InlineData("""{"AuthType":"Certificate","UserCertificatePath":"/etc/ssl/private/host.pfx"}""")]
|
||||
[InlineData("""{"AuthType":"Certificate","UserCertificatePath":"../host.pfx"}""")]
|
||||
public async Task An_opcuaclient_user_certificate_path_outside_the_directory_is_never_stored(string config)
|
||||
{
|
||||
var name = RawTreeTestDb.SeedFresh();
|
||||
var svc = new RawTreeService(RawTreeTestDb.Factory(name));
|
||||
var result = await svc.CreateDriverAsync(RawTreeTestDb.ClusterId, null, "ouc836", DriverTypeNames.OpcUaClient, config, Ct);
|
||||
result.Ok.ShouldBeFalse();
|
||||
result.Error!.ShouldContain("lmxopcua#836");
|
||||
DriverConfigSaveGate.Validate(DriverTypeNames.OpcUaClient, config).ShouldNotBeNull(); // the modals' live check too
|
||||
using var db = RawTreeTestDb.CreateNamed(name);
|
||||
db.DriverInstances.ShouldNotContain(d => d.Name == "ouc836");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_relative_user_certificate_path_saves()
|
||||
{
|
||||
var name = RawTreeTestDb.SeedFresh();
|
||||
var svc = new RawTreeService(RawTreeTestDb.Factory(name));
|
||||
(await svc.CreateDriverAsync(RawTreeTestDb.ClusterId, null, "ouc-ok", DriverTypeNames.OpcUaClient,
|
||||
"""{"AuthType":"Certificate","UserCertificatePath":"plant1/user.pfx"}""", Ct)).Ok.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LoadDeviceDriverInstanceId_names_the_owning_driver()
|
||||
{
|
||||
var name = RawTreeTestDb.SeedFresh();
|
||||
var svc = new RawTreeService(RawTreeTestDb.Factory(name));
|
||||
(await svc.LoadDeviceDriverInstanceIdAsync(RawTreeTestDb.FolderedDeviceId, Ct)).ShouldBe(RawTreeTestDb.FolderedDriverId);
|
||||
(await svc.LoadDeviceDriverInstanceIdAsync("DEV-nope", Ct)).ShouldBeNull();
|
||||
}
|
||||
}
|
||||
+77
@@ -50,6 +50,83 @@ public sealed class AdminOperationsActorCredentialScopeTests : ControlPlaneActor
|
||||
probe.Calls.ShouldBe(1);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#835: a reference naming ANOTHER instance's secret never reaches the probe, whether the caller names
|
||||
/// its own driver or not (a null owner — a not-yet-created driver — is the stricter case).
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData("DRV-evil")]
|
||||
[InlineData(null)]
|
||||
public void A_reference_naming_another_instances_secret_never_reaches_the_probe(string? ownerId)
|
||||
{
|
||||
var dbName = Guid.NewGuid().ToString("N");
|
||||
var factory = NewInMemoryDbFactory(dbName);
|
||||
SeedGalaxyDrivers(factory);
|
||||
var probe = new RecordingProbe(DriverTypeNames.Galaxy);
|
||||
var actor = Sys.ActorOf(AdminOperationsActor.Props(factory, CreateTestProbe("coord").Ref, new IDriverProbe[] { probe }));
|
||||
|
||||
actor.Tell(new TestDriverConnect(
|
||||
DriverTypeNames.Galaxy, """{"Gateway":{"Endpoint":"http://attacker:5001","ApiKeySecretRef":"secret:galaxy/Victim/apikey"}}""",
|
||||
5, Guid.NewGuid(), ownerId));
|
||||
|
||||
var reply = ExpectMsg<TestDriverConnectResult>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
reply.Ok.ShouldBeFalse();
|
||||
reply.Message.ShouldNotBeNull().ShouldContain("Test Connect refused");
|
||||
reply.Message.ShouldContain("lmxopcua#835");
|
||||
probe.Calls.ShouldBe(0);
|
||||
}
|
||||
|
||||
/// <summary>Positive control: the owner's own secret (and a shared one) does reach the probe.</summary>
|
||||
[Theory]
|
||||
[InlineData("secret:galaxy/DRV-victim/apikey")]
|
||||
[InlineData("secret:galaxy/shared-gw/apikey")]
|
||||
public void The_owners_own_or_a_shared_secret_reaches_the_probe(string reference)
|
||||
{
|
||||
var factory = NewInMemoryDbFactory();
|
||||
SeedGalaxyDrivers(factory);
|
||||
var probe = new RecordingProbe(DriverTypeNames.Galaxy);
|
||||
var actor = Sys.ActorOf(AdminOperationsActor.Props(factory, CreateTestProbe("coord").Ref, new IDriverProbe[] { probe }));
|
||||
|
||||
actor.Tell(new TestDriverConnect(
|
||||
DriverTypeNames.Galaxy, """{"Gateway":{"Endpoint":"http://gw:5001","ApiKeySecretRef":"REF"}}""".Replace("REF", reference),
|
||||
5, Guid.NewGuid(), "DRV-victim"));
|
||||
|
||||
ExpectMsg<TestDriverConnectResult>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken).Ok.ShouldBeTrue();
|
||||
probe.Calls.ShouldBe(1);
|
||||
}
|
||||
|
||||
/// <summary>lmxopcua#836: an absolute OpcUaClient user-certificate path never reaches the probe.</summary>
|
||||
[Fact]
|
||||
public void An_absolute_user_certificate_path_never_reaches_the_probe()
|
||||
{
|
||||
var probe = new RecordingProbe(DriverTypeNames.OpcUaClient);
|
||||
var actor = Sys.ActorOf(AdminOperationsActor.Props(NewInMemoryDbFactory(), CreateTestProbe("coord").Ref, new IDriverProbe[] { probe }));
|
||||
|
||||
actor.Tell(new TestDriverConnect(
|
||||
DriverTypeNames.OpcUaClient,
|
||||
"""{"EndpointUrl":"opc.tcp://attacker:4840","AuthType":"Certificate","UserCertificatePath":"/etc/ssl/private/host.pfx"}""",
|
||||
5, Guid.NewGuid()));
|
||||
|
||||
var reply = ExpectMsg<TestDriverConnectResult>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
|
||||
reply.Ok.ShouldBeFalse();
|
||||
reply.Message.ShouldNotBeNull().ShouldContain("lmxopcua#836");
|
||||
probe.Calls.ShouldBe(0);
|
||||
}
|
||||
|
||||
private static void SeedGalaxyDrivers(Microsoft.EntityFrameworkCore.IDbContextFactory<ZB.MOM.WW.OtOpcUa.Configuration.OtOpcUaConfigDbContext> factory)
|
||||
{
|
||||
using var db = factory.CreateDbContext();
|
||||
db.DriverInstances.Add(new ZB.MOM.WW.OtOpcUa.Configuration.Entities.DriverInstance
|
||||
{
|
||||
DriverInstanceId = "DRV-victim", ClusterId = "c", Name = "Victim", DriverType = DriverTypeNames.Galaxy, DriverConfig = "{}",
|
||||
});
|
||||
db.DriverInstances.Add(new ZB.MOM.WW.OtOpcUa.Configuration.Entities.DriverInstance
|
||||
{
|
||||
DriverInstanceId = "DRV-evil", ClusterId = "c", Name = "Evil", DriverType = DriverTypeNames.Galaxy, DriverConfig = "{}",
|
||||
});
|
||||
db.SaveChanges();
|
||||
}
|
||||
|
||||
private sealed class RecordingProbe(string driverType) : IDriverProbe
|
||||
{
|
||||
private int _calls;
|
||||
|
||||
Reference in New Issue
Block a user