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:
Joseph Doherty
2026-11-11 03:52:48 -05:00
parent 481985e20b
commit 63331b0416
31 changed files with 1555 additions and 49 deletions
@@ -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; }
@@ -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");
}
}
@@ -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();
}
}
@@ -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;