fix(opcua): a configured OpcUa:EnabledSecurityProfiles list replaces the default, so None can be dropped (#879)
v2-ci / unit-tests (push) Has been cancelled
v2-ci / unit-tests (push) Has been cancelled
ConfigurationBinder appends configured collection items to an existing list, so the pre-filled [None, Sign, SignAndEncrypt] default made "drop None" a no-op: every deployment that listed only the secure profiles still advertised an unsigned/unencrypted None endpoint. EnabledSecurityProfiles is now null by default; ResolveEnabledSecurityProfiles() applies the unchanged three-profile default only when nothing is configured. A set-but-empty list fails startup validation and BuildSecurityPolicies no longer falls back to a None endpoint on empty input (it throws). Sweep of all options classes found no other non-empty pre-filled collection default. Tests: options binding (indexed, JSON, env forms, default, empty, bad name), a booted-server wire test (no None endpoint, None connection refused with BadSecurityPolicyRejected, secure connection works; default case is the control). Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
This commit is contained in:
+156
@@ -0,0 +1,156 @@
|
||||
using System.Text;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.Configuration;
|
||||
using ZB.MOM.WW.OtOpcUa.Host.Configuration;
|
||||
using ZB.MOM.WW.OtOpcUa.OpcUaServer;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Host.IntegrationTests;
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#879 — <c>ConfigurationBinder</c> appends configured collection items to a pre-filled list, so
|
||||
/// <c>OpcUa:EnabledSecurityProfiles</c> could never drop <c>None</c>. These tests pin "the configured list REPLACES
|
||||
/// the default" through the same <c>AddValidatedOptions</c> wiring <c>Program.cs</c> uses, for the indexed
|
||||
/// (env-var / in-memory) form and the JSON array form, plus the unchanged default and the empty-list rule.
|
||||
/// </summary>
|
||||
public sealed class OpcUaSecurityProfilesBindingTests
|
||||
{
|
||||
private static readonly OpcUaSecurityProfile[] AllThree =
|
||||
[
|
||||
OpcUaSecurityProfile.None,
|
||||
OpcUaSecurityProfile.Basic256Sha256Sign,
|
||||
OpcUaSecurityProfile.Basic256Sha256SignAndEncrypt,
|
||||
];
|
||||
|
||||
private static IOptions<OpcUaApplicationHostOptions> Resolve(IConfiguration configuration, out ServiceProvider provider)
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
services.AddSingleton(configuration);
|
||||
services.AddValidatedOptions<OpcUaApplicationHostOptions, OpcUaApplicationHostOptionsValidator>(configuration, "OpcUa");
|
||||
provider = services.BuildServiceProvider();
|
||||
return provider.GetRequiredService<IOptions<OpcUaApplicationHostOptions>>();
|
||||
}
|
||||
|
||||
/// <summary>The #879 repro: only the secure profiles configured gives exactly those, no None.</summary>
|
||||
[Fact]
|
||||
public void Configured_secure_profiles_replace_the_default_and_drop_None()
|
||||
{
|
||||
var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
["OpcUa:EnabledSecurityProfiles:0"] = "Basic256Sha256SignAndEncrypt",
|
||||
["OpcUa:EnabledSecurityProfiles:1"] = "Basic256Sha256Sign",
|
||||
}).Build();
|
||||
|
||||
var options = Resolve(configuration, out var provider);
|
||||
using var sp = provider;
|
||||
|
||||
options.Value.ResolveEnabledSecurityProfiles().ShouldBe(
|
||||
[OpcUaSecurityProfile.Basic256Sha256SignAndEncrypt, OpcUaSecurityProfile.Basic256Sha256Sign]);
|
||||
options.Value.ResolveEnabledSecurityProfiles().ShouldNotContain(OpcUaSecurityProfile.None);
|
||||
}
|
||||
|
||||
/// <summary>The JSON array form (appsettings.json, as docs/security.md shows) behaves the same as the indexed form.</summary>
|
||||
[Fact]
|
||||
public void Json_array_form_replaces_the_default_too()
|
||||
{
|
||||
var json = """{ "OpcUa": { "EnabledSecurityProfiles": [ "Basic256Sha256Sign", "Basic256Sha256SignAndEncrypt" ] } }""";
|
||||
var configuration = new ConfigurationBuilder()
|
||||
.AddJsonStream(new MemoryStream(Encoding.UTF8.GetBytes(json))).Build();
|
||||
|
||||
var options = Resolve(configuration, out var provider);
|
||||
using var sp = provider;
|
||||
|
||||
options.Value.ResolveEnabledSecurityProfiles().ShouldBe(
|
||||
[OpcUaSecurityProfile.Basic256Sha256Sign, OpcUaSecurityProfile.Basic256Sha256SignAndEncrypt]);
|
||||
}
|
||||
|
||||
/// <summary>The environment-variable form (<c>OpcUa__EnabledSecurityProfiles__0</c>) used by the Windows service gate.</summary>
|
||||
[Fact]
|
||||
public void Environment_variable_form_replaces_the_default()
|
||||
{
|
||||
const string prefix = "OTOPCUA_879_TEST_";
|
||||
Environment.SetEnvironmentVariable(prefix + "OpcUa__EnabledSecurityProfiles__0", "Basic256Sha256SignAndEncrypt");
|
||||
try
|
||||
{
|
||||
var configuration = new ConfigurationBuilder().AddEnvironmentVariables(prefix).Build();
|
||||
var options = Resolve(configuration, out var provider);
|
||||
using var sp = provider;
|
||||
|
||||
options.Value.ResolveEnabledSecurityProfiles().ShouldBe([OpcUaSecurityProfile.Basic256Sha256SignAndEncrypt]);
|
||||
}
|
||||
finally { Environment.SetEnvironmentVariable(prefix + "OpcUa__EnabledSecurityProfiles__0", null); }
|
||||
}
|
||||
|
||||
/// <summary>Configuring None explicitly alongside the secure profiles still works (an operator may want it).</summary>
|
||||
[Fact]
|
||||
public void Explicit_None_is_honoured_when_listed()
|
||||
{
|
||||
var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
["OpcUa:EnabledSecurityProfiles:0"] = "None",
|
||||
}).Build();
|
||||
|
||||
var options = Resolve(configuration, out var provider);
|
||||
using var sp = provider;
|
||||
|
||||
options.Value.ResolveEnabledSecurityProfiles().ShouldBe([OpcUaSecurityProfile.None]);
|
||||
}
|
||||
|
||||
/// <summary>Nothing configured: the three-profile default is applied, unchanged from before the fix.</summary>
|
||||
[Fact]
|
||||
public void Nothing_configured_keeps_the_three_profile_default()
|
||||
{
|
||||
var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
["OpcUa:OpcUaPort"] = "4841", // a section exists, the list key does not
|
||||
}).Build();
|
||||
|
||||
var options = Resolve(configuration, out var provider);
|
||||
using var sp = provider;
|
||||
|
||||
options.Value.ResolveEnabledSecurityProfiles().ShouldBe(AllThree);
|
||||
new OpcUaApplicationHostOptions().ResolveEnabledSecurityProfiles().ShouldBe(AllThree);
|
||||
}
|
||||
|
||||
/// <summary>An empty JSON array binds to nothing, i.e. "not configured": the default, never "None only".</summary>
|
||||
[Fact]
|
||||
public void Empty_json_array_is_treated_as_not_configured_and_yields_the_default()
|
||||
{
|
||||
var json = """{ "OpcUa": { "EnabledSecurityProfiles": [] } }""";
|
||||
var configuration = new ConfigurationBuilder()
|
||||
.AddJsonStream(new MemoryStream(Encoding.UTF8.GetBytes(json))).Build();
|
||||
|
||||
var options = Resolve(configuration, out var provider);
|
||||
using var sp = provider;
|
||||
|
||||
options.Value.ResolveEnabledSecurityProfiles().ShouldBe(AllThree);
|
||||
}
|
||||
|
||||
/// <summary>A list that is set but empty fails startup validation and cannot be resolved — it never means "None".</summary>
|
||||
[Fact]
|
||||
public void An_explicitly_empty_list_fails_validation_and_resolution()
|
||||
{
|
||||
var empty = new OpcUaApplicationHostOptions { EnabledSecurityProfiles = new List<OpcUaSecurityProfile>() };
|
||||
|
||||
new OpcUaApplicationHostOptionsValidator().Validate(null, empty).Failed.ShouldBeTrue();
|
||||
Should.Throw<InvalidOperationException>(() => empty.ResolveEnabledSecurityProfiles());
|
||||
}
|
||||
|
||||
/// <summary>An unparseable profile name fails startup rather than being ignored (which would otherwise leave the default).</summary>
|
||||
[Fact]
|
||||
public void An_unknown_profile_name_fails_options_resolution()
|
||||
{
|
||||
var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
["OpcUa:EnabledSecurityProfiles:0"] = "Basic256Sha256-SignAndEncrypt",
|
||||
}).Build();
|
||||
|
||||
var options = Resolve(configuration, out var provider);
|
||||
using var sp = provider;
|
||||
|
||||
Should.Throw<Exception>(() => _ = options.Value.ResolveEnabledSecurityProfiles());
|
||||
}
|
||||
}
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Opc.Ua;
|
||||
using Opc.Ua.Client;
|
||||
using Opc.Ua.Configuration;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests;
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#879 over the wire. The options come from a real <c>ConfigurationBinder</c> bind (the path the Host
|
||||
/// uses), so a regression to a pre-filled list shows up as an advertised <c>None</c> endpoint that admits a
|
||||
/// session. The default case is the positive control: the same probes must find and use <c>None</c> there.
|
||||
/// </summary>
|
||||
public sealed class SecurityProfilesReplaceWireTests
|
||||
{
|
||||
private static CancellationToken Ct => TestContext.Current.CancellationToken;
|
||||
|
||||
[Fact]
|
||||
public async Task Configuring_only_the_secure_profiles_removes_the_None_endpoint_and_refuses_a_None_connection()
|
||||
{
|
||||
await using var rig = await Rig.StartAsync(new Dictionary<string, string?>
|
||||
{
|
||||
["OpcUa:EnabledSecurityProfiles:0"] = "Basic256Sha256Sign",
|
||||
["OpcUa:EnabledSecurityProfiles:1"] = "Basic256Sha256SignAndEncrypt",
|
||||
}, Ct);
|
||||
|
||||
var modes = (await rig.GetEndpointModesAsync(Ct)).Distinct().Order().ToArray();
|
||||
modes.ShouldBe([MessageSecurityMode.Sign, MessageSecurityMode.SignAndEncrypt]);
|
||||
|
||||
// Positive control: the secure endpoint really is usable, so the refusal below is about None, not about the rig.
|
||||
using (var secure = await rig.ConnectAsync(MessageSecurityMode.SignAndEncrypt, Ct))
|
||||
secure.Connected.ShouldBeTrue();
|
||||
|
||||
var refusal = await Should.ThrowAsync<ServiceResultException>(() => rig.ConnectAsync(MessageSecurityMode.None, Ct));
|
||||
refusal.StatusCode.ShouldBe(StatusCodes.BadSecurityPolicyRejected);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Nothing_configured_still_advertises_all_three_and_a_None_connection_is_admitted()
|
||||
{
|
||||
await using var rig = await Rig.StartAsync(new Dictionary<string, string?>(), Ct);
|
||||
|
||||
(await rig.GetEndpointModesAsync(Ct)).Distinct().Order().ToArray()
|
||||
.ShouldBe([MessageSecurityMode.None, MessageSecurityMode.Sign, MessageSecurityMode.SignAndEncrypt]);
|
||||
using var none = await rig.ConnectAsync(MessageSecurityMode.None, Ct);
|
||||
none.Connected.ShouldBeTrue();
|
||||
}
|
||||
|
||||
private sealed class Rig : IAsyncDisposable
|
||||
{
|
||||
private readonly string _pki = TestClientSecurity.AllocatePkiRoot();
|
||||
private readonly string _clientPki = TestClientSecurity.AllocatePkiRoot();
|
||||
private OpcUaApplicationHost _host = null!;
|
||||
private int _port;
|
||||
|
||||
public static async Task<Rig> StartAsync(Dictionary<string, string?> values, CancellationToken ct)
|
||||
{
|
||||
var rig = new Rig();
|
||||
var section = new ConfigurationBuilder().AddInMemoryCollection(values).Build();
|
||||
try
|
||||
{
|
||||
(rig._host, _) = await OpcUaHostStart.StartAsync(port =>
|
||||
{
|
||||
var options = new OpcUaApplicationHostOptions
|
||||
{
|
||||
ApplicationName = "OtOpcUa.Sec879",
|
||||
ApplicationUri = $"urn:OtOpcUa.Sec879:{Guid.NewGuid():N}",
|
||||
PublicHostname = "127.0.0.1",
|
||||
PkiStoreRoot = rig._pki,
|
||||
AutoAcceptUntrustedClientCertificates = true,
|
||||
};
|
||||
section.GetSection("OpcUa").Bind(options); // the real binder, exactly what AddValidatedOptions does
|
||||
options.OpcUaPort = port;
|
||||
rig._port = port;
|
||||
return new OpcUaApplicationHost(options, NullLogger<OpcUaApplicationHost>.Instance);
|
||||
}, () => new OtOpcUaSdkServer(), ct);
|
||||
return rig;
|
||||
}
|
||||
catch { await rig.DisposeAsync(); throw; }
|
||||
}
|
||||
|
||||
private string Url => $"opc.tcp://127.0.0.1:{_port}/OtOpcUa";
|
||||
|
||||
private (ApplicationConfiguration Config, ApplicationInstance App)? _client;
|
||||
|
||||
private async Task<(ApplicationConfiguration Config, ApplicationInstance App)> ClientAsync(CancellationToken ct)
|
||||
{
|
||||
if (_client is { } cached) return cached;
|
||||
var security = TestClientSecurity.Build(_clientPki);
|
||||
security.ApplicationCertificate!.SubjectName = "CN=OtOpcUa.Sec879Client";
|
||||
var telemetry = DefaultTelemetry.Create(_ => { });
|
||||
var config = new ApplicationConfiguration(telemetry)
|
||||
{
|
||||
ApplicationName = "OtOpcUa.Sec879Client",
|
||||
ApplicationUri = $"urn:OtOpcUa.Sec879Client.{Guid.NewGuid():N}",
|
||||
ApplicationType = ApplicationType.Client,
|
||||
SecurityConfiguration = security,
|
||||
ClientConfiguration = new ClientConfiguration { DefaultSessionTimeout = 60_000 },
|
||||
};
|
||||
await config.ValidateAsync(ApplicationType.Client, ct);
|
||||
var app = new ApplicationInstance(telemetry) { ApplicationName = config.ApplicationName, ApplicationType = ApplicationType.Client };
|
||||
app.ApplicationConfiguration = config;
|
||||
await app.CheckApplicationInstanceCertificatesAsync(silent: true, lifeTimeInMonths: null, ct);
|
||||
_client = (config, app);
|
||||
return (config, app);
|
||||
}
|
||||
|
||||
public async Task<MessageSecurityMode[]> GetEndpointModesAsync(CancellationToken ct)
|
||||
{
|
||||
var (config, _) = await ClientAsync(ct);
|
||||
using var discovery = await DiscoveryClient.CreateAsync(config, new Uri(Url), DiagnosticsMasks.None, ct);
|
||||
var endpoints = await discovery.GetEndpointsAsync(default, ct);
|
||||
return endpoints.ToArray()!.Select(e => e.SecurityMode).ToArray();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens an anonymous session on the endpoint of the requested mode. For <c>None</c> the endpoint
|
||||
/// description is synthesised rather than discovered, so a server that no longer advertises it is
|
||||
/// probed with exactly what a downgrading client would send.
|
||||
/// </summary>
|
||||
public async Task<ISession> ConnectAsync(MessageSecurityMode mode, CancellationToken ct)
|
||||
{
|
||||
var (config, _) = await ClientAsync(ct);
|
||||
var telemetry = DefaultTelemetry.Create(_ => { });
|
||||
// Always start from a discovered secure endpoint (its token policies are what the server really sent);
|
||||
// None is a clone of it with the mode and policy downgraded, i.e. what a downgrading client sends.
|
||||
var description = await CoreClientUtils.SelectEndpointAsync(config, Url, true, telemetry, ct)
|
||||
?? throw new InvalidOperationException("No secure endpoint.");
|
||||
if (mode == MessageSecurityMode.None)
|
||||
{
|
||||
description = (EndpointDescription)description.Clone();
|
||||
description.SecurityMode = MessageSecurityMode.None;
|
||||
description.SecurityPolicyUri = SecurityPolicies.None;
|
||||
description.ServerCertificate = default;
|
||||
}
|
||||
else description.SecurityMode.ShouldBe(mode);
|
||||
return await new DefaultSessionFactory(telemetry).CreateAsync(
|
||||
config, new ConfiguredEndpoint(null, description, EndpointConfiguration.Create(config)),
|
||||
updateBeforeConnect: false, checkDomain: false, sessionName: "Sec879", sessionTimeout: 60_000,
|
||||
identity: new UserIdentity(new AnonymousIdentityToken()), preferredLocales: default, ct: ct);
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (_client is { } client) await client.App.DisposeAsync();
|
||||
if (_host is not null) await _host.DisposeAsync();
|
||||
foreach (var dir in new[] { _pki, _clientPki })
|
||||
if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
+5
-8
@@ -61,16 +61,13 @@ public sealed class OpcUaApplicationHostSecurityTests : IDisposable
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that BuildSecurityPolicies falls back to None when given empty input.
|
||||
/// lmxopcua#879: an empty profile list is an error, never a silent fallback to an unsecured None endpoint.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void BuildSecurityPolicies_empty_input_falls_back_to_none()
|
||||
public void BuildSecurityPolicies_empty_input_throws_instead_of_falling_back_to_none()
|
||||
{
|
||||
var policies = OpcUaApplicationHost.BuildSecurityPolicies(Array.Empty<OpcUaSecurityProfile>()).ToList();
|
||||
|
||||
policies.Count.ShouldBe(1);
|
||||
policies[0].SecurityMode.ShouldBe(MessageSecurityMode.None);
|
||||
policies[0].SecurityPolicyUri.ShouldBe(SecurityPolicies.None);
|
||||
Should.Throw<InvalidOperationException>(
|
||||
() => OpcUaApplicationHost.BuildSecurityPolicies(Array.Empty<OpcUaSecurityProfile>()).ToList());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -118,7 +115,7 @@ public sealed class OpcUaApplicationHostSecurityTests : IDisposable
|
||||
OpcUaPort = port,
|
||||
PublicHostname = "localhost",
|
||||
PkiStoreRoot = _pkiRoot,
|
||||
EnabledSecurityProfiles =
|
||||
EnabledSecurityProfiles = new List<OpcUaSecurityProfile>
|
||||
{
|
||||
OpcUaSecurityProfile.None,
|
||||
OpcUaSecurityProfile.Basic256Sha256Sign,
|
||||
|
||||
Reference in New Issue
Block a user