feat(opcuaclient): opt-in server-certificate host-name check; NAT fixture keeps its PKI (#816, #818)

#816 finding: the SDK checks that the server certificate names the host only
when a session is created with checkDomain:true. The driver, the AdminUI
browser and Client.Shared all called the 8-argument
DefaultSessionFactory.CreateAsync, which forwards checkDomain:false — so no
host-name check ever ran (why a trusted NAT cert for *.invalid browsed fine
over an IP in #813). When enabled the SDK (Session.OpenAsync ->
ValidateDomains -> FindDomain) compares ConfiguredEndpoint.EndpointUrl.IdnHost
— the CONFIGURED host, because OpcUaEndpointSelection/EndpointSelector
rewrote the advertised one — against the cert's DNS/IP SANs; secured
sessions only, and the auto-accept handler accepts a mismatch.

Policy: certificateValidation.validateServerHostName, tri-state. Unset =
OpcUaCertificateValidationOptions.DefaultValidateServerHostName = false, the
pre-#816 behaviour, so nothing changes on upgrade; true = validate the
configured host; false = explicit NAT/port-publish opt-out. Threaded into the
driver, the AdminUI browser (same JSON) and the AdminUI form (a select that
keeps "unset" unset), Client.Shared ConnectionSettings.ValidateServerHostName
and the CLI --validate-host-name. A driver refusal names the opt-out.

#818: the NAT fixture's /app/pki is on the opc-plc-nat-pki volume (verified:
same thumbprint across --force-recreate), its PUBLIC cert is committed as
Docker/nat/opc-plc-nat-server.der, and NatPublishedEndpointBrowseTests run
every secure browse on a throwaway PKI (internal browser seam): refusal with
nothing trusted, positive with the cert trusted (unset/false host check), and
a BadCertificateHostNameInvalid refusal with the check on. The trusted cert is
OPCUA_NAT_SERVER_CERT or the committed one (skip on thumbprint mismatch);
OPCUA_NAT_SERVER_CERT_TRUSTED is retired. CI exports its throwaway NAT
container's public cert. ServerHostNameValidationTests pin the driver against
the plain opc-plc. MIN_EXECUTED not raised (needs a hosted run): +6 in
v2-integration (440 -> 446), documented in scripts/ci/README.md.
This commit is contained in:
Joseph Doherty
2026-11-11 01:33:00 -05:00
parent bde6cce2fc
commit ae91e6b7f7
30 changed files with 648 additions and 59 deletions
@@ -1,5 +1,6 @@
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using Opc.Ua;
using Opc.Ua.Client;
using Shouldly;
@@ -20,27 +21,54 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Browser.IntegrationTests;
/// # or locally / in CI (scripts/ci/integration-fixtures.sh starts the same shape as otopcua-ci-opcplc-nat):
/// docker run -d --rm --name otopcua-806-nat --hostname otopcua-806-nat-parity -p 32781:50000 \
/// mcr.microsoft.com/iotedge/opc-plc:2.14.10 --pn=50000 --ph=otopcua-806-nat-parity.invalid --autoaccept --ut
/// OPCUA_NAT_ENDPOINT=opc.tcp://127.0.0.1:32781 dotnet test --filter Fixture=opc-plc-nat
/// docker exec otopcua-806-nat bash -c 'cat /app/pki/own/certs/*.der' > /tmp/nat.der # public cert only
/// OPCUA_NAT_ENDPOINT=opc.tcp://127.0.0.1:32781 OPCUA_NAT_SERVER_CERT=/tmp/nat.der dotnet test --filter Fixture=opc-plc-nat
/// </code>
/// Skipped unless <c>OPCUA_NAT_ENDPOINT</c> is set and accepts TCP. Every test first proves the premise (the
/// advertised URL is NOT the configured host:port, and its host does not resolve here), so a fixture that
/// advertises a reachable address cannot make these pass vacuously. Before the fix the positive cases failed with
/// <c>SocketException: nodename nor servname provided, or not known</c>.
/// <para><b>Secure cases (#813/#816/#818).</b> Every browse here runs on a THROWAWAY browse PKI (the browser's
/// internal PKI-root seam), never the operator's <c>adminui-browse-pki</c>. The refusal case trusts nothing. The
/// positive and host-name cases trust the fixture's PUBLIC certificate — from <c>OPCUA_NAT_SERVER_CERT</c> (a DER or
/// PEM file; what CI exports after copying it out of its throwaway container) or else the committed
/// <c>Docker/nat/opc-plc-nat-server.der</c> (the shared-host stack's certificate, stable since #818 put its PKI on a
/// volume) — and SKIP when the committed certificate is not the one the server presents, so they can never pass
/// against a different server.</para>
/// </summary>
[Trait("Category", "Integration"), Trait("Fixture", "opc-plc-nat")]
public sealed class NatPublishedEndpointBrowseTests
public sealed class NatPublishedEndpointBrowseTests : IDisposable
{
private const string EnvVar = "OPCUA_NAT_ENDPOINT";
private const string CertEnvVar = "OPCUA_NAT_SERVER_CERT";
private const string CommittedCertFile = "opc-plc-nat-server.der";
private readonly string _pkiRoot = Path.Combine(Path.GetTempPath(), "otopcua-nat-pki-" + Guid.NewGuid().ToString("N"));
private static string? Endpoint => Environment.GetEnvironmentVariable(EnvVar) is { Length: > 0 } e ? e : null;
private static string Json(string endpoint, string policy = "None", string mode = "None") => $$"""
{
"EndpointUrl":"{{endpoint}}",
"SecurityPolicy":"{{policy}}","SecurityMode":"{{mode}}","AuthType":"Anonymous",
"SessionTimeout":"00:01:00","Timeout":"00:00:10","PerEndpointConnectTimeout":"00:00:10"
}
""";
/// <inheritdoc />
public void Dispose()
{
try { Directory.Delete(_pkiRoot, recursive: true); } catch { /* best-effort temp cleanup */ }
}
/// <summary>A browser on this test's throwaway PKI.</summary>
private OpcUaClientDriverBrowser Browser() => new(_pkiRoot);
private static string Json(string endpoint, string policy = "None", string mode = "None", bool? validateHostName = null)
{
var certValidation = validateHostName is { } v
? $$""","CertificateValidation":{"ValidateServerHostName":{{(v ? "true" : "false")}}}"""
: "";
return $$"""
{
"EndpointUrl":"{{endpoint}}",
"SecurityPolicy":"{{policy}}","SecurityMode":"{{mode}}","AuthType":"Anonymous",
"SessionTimeout":"00:01:00","Timeout":"00:00:10","PerEndpointConnectTimeout":"00:00:10"{{certValidation}}
}
""";
}
private static string RequireFixture()
{
@@ -60,8 +88,11 @@ public sealed class NatPublishedEndpointBrowseTests
return endpoint;
}
/// <summary>The premise: the server advertises a host:port other than the configured one, and that host is unresolvable.</summary>
private static async Task AssertAdvertisesUnreachableAddressAsync(string endpoint, CancellationToken ct)
/// <summary>
/// The premise: the server advertises a host:port other than the configured one, and that host is unresolvable.
/// Returns the DER certificate the server presents on its secure endpoint.
/// </summary>
private static async Task<byte[]> AssertAdvertisesUnreachableAddressAsync(string endpoint, CancellationToken ct)
{
var appConfig = new ApplicationConfiguration(DefaultTelemetry.Create(_ => { }))
{
@@ -84,6 +115,61 @@ public sealed class NatPublishedEndpointBrowseTests
await Should.ThrowAsync<SocketException>(() => Dns.GetHostAddressesAsync(advertised.Host, ct),
$"advertised host '{advertised.Host}' must be unresolvable from here, or this test proves nothing");
}
return endpoints.First(e => e.SecurityPolicyUri == SecurityPolicies.Basic256Sha256).ServerCertificate.ToArray();
}
/// <summary>
/// Trust the fixture's public certificate in this test's throwaway PKI, or SKIP when no certificate for THIS
/// server is available (see the class remarks). An explicit <c>OPCUA_NAT_SERVER_CERT</c> that does not match
/// FAILS: it names the certificate the operator meant, so a mismatch is a fixture problem worth seeing.
/// </summary>
/// <param name="presentedDer">The certificate the server presents (from its GetEndpoints answer).</param>
private void TrustFixtureCertificate(byte[] presentedDer)
{
using var presented = X509CertificateLoader.LoadCertificate(presentedDer);
X509Certificate2 trusted;
if (Environment.GetEnvironmentVariable(CertEnvVar) is { Length: > 0 } path)
{
trusted = LoadPublicCertificate(path);
trusted.Thumbprint.ShouldBe(presented.Thumbprint,
$"{CertEnvVar}={path} is not the certificate the NAT fixture presents");
}
else
{
var committed = Path.Combine(AppContext.BaseDirectory, CommittedCertFile);
if (!File.Exists(committed))
Assert.Skip($"{CommittedCertFile} is not deployed next to the tests and {CertEnvVar} is unset.");
trusted = LoadPublicCertificate(committed);
if (trusted.Thumbprint != presented.Thumbprint)
Assert.Skip($"the committed {CommittedCertFile} ({trusted.Thumbprint}) is not this fixture's certificate " +
$"({presented.Thumbprint}, expires {presented.NotAfter:yyyy-MM-dd}); set {CertEnvVar} or " +
"refresh the committed copy (see Docker/nat/docker-compose.yml).");
}
using (trusted)
{
trusted.HasPrivateKey.ShouldBeFalse("only a PUBLIC certificate is ever trusted from a file");
var certs = Path.Combine(_pkiRoot, "trusted", "certs");
Directory.CreateDirectory(certs);
File.WriteAllBytes(Path.Combine(certs, "opc-plc-nat.der"), trusted.RawData);
}
}
private static X509Certificate2 LoadPublicCertificate(string path)
{
var bytes = File.ReadAllBytes(path);
var text = System.Text.Encoding.ASCII.GetString(bytes);
return text.Contains("-----BEGIN CERTIFICATE-----", StringComparison.Ordinal)
? X509Certificate2.CreateFromPem(text)
: X509CertificateLoader.LoadCertificate(bytes);
}
private static StatusCode? FindStatus(Exception? ex)
{
for (; ex is not null; ex = ex.InnerException)
if (ex is ServiceResultException sre) return sre.StatusCode;
return null;
}
[Fact]
@@ -93,7 +179,7 @@ public sealed class NatPublishedEndpointBrowseTests
var ct = TestContext.Current.CancellationToken;
await AssertAdvertisesUnreachableAddressAsync(endpoint, ct);
await using var session = await new OpcUaClientDriverBrowser().OpenAsync(Json(endpoint), ct);
await using var session = await Browser().OpenAsync(Json(endpoint), ct);
var roots = await session.RootAsync(ct);
roots.Count.ShouldBeGreaterThan(0);
@@ -111,7 +197,7 @@ public sealed class NatPublishedEndpointBrowseTests
var ct = TestContext.Current.CancellationToken;
// A closed loopback port: the rewrite must not invent a reachable address; the open fails promptly.
var sw = System.Diagnostics.Stopwatch.StartNew();
await Should.ThrowAsync<Exception>(() => new OpcUaClientDriverBrowser().OpenAsync(Json("opc.tcp://127.0.0.1:1"), ct));
await Should.ThrowAsync<Exception>(() => Browser().OpenAsync(Json("opc.tcp://127.0.0.1:1"), ct));
sw.Elapsed.ShouldBeLessThan(TimeSpan.FromSeconds(30));
}
@@ -122,29 +208,59 @@ public sealed class NatPublishedEndpointBrowseTests
var ct = TestContext.Current.CancellationToken;
await AssertAdvertisesUnreachableAddressAsync(endpoint, ct);
// Basic256Sha256/SignAndEncrypt through the published port. The browse PKI never auto-accepts, so unless the
// operator trusted this fixture's certificate in the browse PKI (then set OPCUA_NAT_SERVER_CERT_TRUSTED=1) the
// open must be refused on the certificate — which proves the session reached the SERVER (no DNS failure on the
// advertised host) and that the rewrite did not relax trust.
var trusted = Environment.GetEnvironmentVariable("OPCUA_NAT_SERVER_CERT_TRUSTED") == "1";
var json = Json(endpoint, "Basic256Sha256", "SignAndEncrypt");
if (trusted)
{
await using var session = await new OpcUaClientDriverBrowser().OpenAsync(json, ct);
(await session.RootAsync(ct)).Count.ShouldBeGreaterThan(0);
return;
}
// Basic256Sha256/SignAndEncrypt through the published port, on a browse PKI that trusts NOTHING (the browse
// never auto-accepts): the open must be refused on the certificate — which proves the session reached the
// SERVER (no DNS failure on the advertised host) and that the rewrite did not relax trust.
var ex = await Should.ThrowAsync<Exception>(async () =>
{
await using var session = await new OpcUaClientDriverBrowser().OpenAsync(json, ct);
await using var session = await Browser().OpenAsync(Json(endpoint, "Basic256Sha256", "SignAndEncrypt"), ct);
});
TestContext.Current.TestOutputHelper?.WriteLine($"secure open refused: {ex.GetType().Name}: {ex.Message}");
ex.ShouldNotBeOfType<SocketException>($"must not fail on DNS for the advertised host: {ex}");
var sre = ex as ServiceResultException ?? ex.InnerException as ServiceResultException;
sre.ShouldNotBeNull($"expected a certificate refusal, got {ex.GetType().Name}: {ex.Message}");
sre.StatusCode.ShouldBeOneOf(
var status = FindStatus(ex);
status.ShouldNotBeNull($"expected a certificate refusal, got {ex.GetType().Name}: {ex.Message}");
status.Value.ShouldBeOneOf(
StatusCodes.BadCertificateUntrusted, StatusCodes.BadSecurityChecksFailed,
StatusCodes.BadCertificateChainIncomplete);
}
/// <summary>
/// #818 — the positive secure case, runnable in CI. #816 — with the host-name check unset (the default) or
/// explicitly off, a trusted certificate is accepted although it names <c>*-nat-private.invalid</c> and the
/// browse dialled the published address: the NAT opt-out.
/// </summary>
[Theory]
[InlineData(null)]
[InlineData(false)]
public async Task Secure_browse_with_the_fixture_certificate_trusted_succeeds_without_a_host_name_check(bool? validate)
{
var endpoint = RequireFixture();
var ct = TestContext.Current.CancellationToken;
TrustFixtureCertificate(await AssertAdvertisesUnreachableAddressAsync(endpoint, ct));
await using var session = await Browser().OpenAsync(
Json(endpoint, "Basic256Sha256", "SignAndEncrypt", validate), ct);
(await session.RootAsync(ct)).Count.ShouldBeGreaterThan(0);
}
/// <summary>
/// #816 — with the host-name check on, the SAME trusted certificate is refused, and the host checked is the one
/// the operator configured (the published address), not the server-advertised private name the certificate lists.
/// </summary>
[Fact]
public async Task Host_name_validation_checks_the_configured_host_and_refuses_the_NAT_certificate()
{
var endpoint = RequireFixture();
var ct = TestContext.Current.CancellationToken;
TrustFixtureCertificate(await AssertAdvertisesUnreachableAddressAsync(endpoint, ct));
var ex = await Should.ThrowAsync<Exception>(async () =>
{
await using var session = await Browser().OpenAsync(
Json(endpoint, "Basic256Sha256", "SignAndEncrypt", validateHostName: true), ct);
});
TestContext.Current.TestOutputHelper?.WriteLine($"secure open refused: {ex.GetType().Name}: {ex.Message}");
FindStatus(ex).ShouldBe(StatusCodes.BadCertificateHostNameInvalid, $"expected a host-name refusal, got {ex}");
ex.ToString().ShouldContain($"'{new Uri(endpoint).IdnHost}'");
}
}
@@ -24,4 +24,11 @@
<ProjectReference Include="..\..\..\src\Core\ZB.MOM.WW.OtOpcUa.Commons\ZB.MOM.WW.OtOpcUa.Commons.csproj" />
</ItemGroup>
<ItemGroup>
<!-- #818: the shared-host NAT fixture's PUBLIC server certificate (its PKI is on a persistent volume), trusted by
NatPublishedEndpointBrowseTests in a throwaway browse PKI. Never a private key. -->
<None Include="..\ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.IntegrationTests\Docker\nat\opc-plc-nat-server.der"
Link="opc-plc-nat-server.der" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</Project>
@@ -10,7 +10,8 @@ here since opc-plc ships pre-containerized.
| File | Purpose |
|---|---|
| [`docker-compose.yml`](docker-compose.yml) | Service definition for `otopcua-opc-plc` — image pin, port map, command flags. |
| [`nat/docker-compose.yml`](nat/docker-compose.yml) | `otopcua-opc-plc-nat` — a SEPARATE stack (`/opt/otopcua-opcuaclient-nat` on the shared host): opc-plc advertising a private `.invalid` host on internal port 50000, published on 50010. For `NatPublishedEndpointBrowseTests` (`OPCUA_NAT_ENDPOINT=opc.tcp://10.100.0.35:50010`, #806/#813); see the compose file's header. |
| [`nat/docker-compose.yml`](nat/docker-compose.yml) | `otopcua-opc-plc-nat` — a SEPARATE stack (`/opt/otopcua-opcuaclient-nat` on the shared host): opc-plc advertising a private `.invalid` host on internal port 50000, published on 50010. For `NatPublishedEndpointBrowseTests` (`OPCUA_NAT_ENDPOINT=opc.tcp://10.100.0.35:50010`, #806/#813); see the compose file's header. Its PKI is on a volume (#818). |
| [`nat/opc-plc-nat-server.der`](nat/opc-plc-nat-server.der) | The NAT stack's **public** server certificate (no key), trusted by the positive secure / host-name NAT tests in a throwaway browse PKI. Refresh it when the stack's certificate is rolled (`docker compose down -v`); expires 2027-11-10. |
| (this file) | How to run it. |
## Install
@@ -34,7 +35,8 @@ docker compose up
```
First run pulls the image (~250 MB). Startup takes ~5-10 seconds; the
healthcheck in the compose file surfaces ready state in `docker ps`.
healthcheck in the compose file surfaces ready state in `docker ps` (a bash `/dev/tcp` probe —
the image has no `netstat`, which kept the old check permanently "unhealthy", #817).
To run detached (CI pattern):
@@ -20,6 +20,16 @@
# ssh dohertj2@10.100.0.35 'cd /opt/otopcua-opcuaclient-nat && docker compose up -d'
# OPCUA_NAT_ENDPOINT=opc.tcp://10.100.0.35:50010 dotnet test \
# tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Browser.IntegrationTests --filter Fixture=opc-plc-nat
#
# #818: the server's PKI (/app/pki — own cert + private key, and the client certs --aa accepted) lives in the
# named volume `opc-plc-nat-pki`, so recreating the container keeps the SAME server certificate. Its PUBLIC half is
# committed next to this file (opc-plc-nat-server.der) and the secure tests trust it in a throwaway browse PKI. The
# private key never leaves the volume. To roll the certificate deliberately (e.g. at expiry, 2027-11-10):
# ssh dohertj2@10.100.0.35 'cd /opt/otopcua-opcuaclient-nat && docker compose down -v && docker compose up -d'
# ssh dohertj2@10.100.0.35 'docker exec otopcua-opc-plc-nat bash -c "cat /app/pki/own/certs/*.der"' \
# > tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.IntegrationTests/Docker/nat/opc-plc-nat-server.der
# (until the committed copy is refreshed the positive secure tests SKIP on a thumbprint mismatch — they never pass
# against a certificate other than the committed one).
services:
opc-plc-nat:
image: mcr.microsoft.com/iotedge/opc-plc:2.14.10
@@ -40,11 +50,20 @@ services:
# --aa: accept the browser's self-signed client cert. Trust in the OTHER direction (the browser trusting
# this server's cert) is deliberately not automatic — that is what the secure test pins.
- "--aa"
volumes:
- opc-plc-nat-pki:/app/pki
# The image runs as uid 1654 ("app") and ships no /app/pki, so Docker creates the volume mount point root-owned
# and opc-plc could not write its certificate there. A throwaway test simulator: run it as root rather than add a
# chown init container.
user: "0"
healthcheck:
# The image ships no netstat (the sibling ../docker-compose.yml healthcheck is permanently "unhealthy" for that
# reason); bash's /dev/tcp is there.
# The image ships no netstat (the sibling ../docker-compose.yml healthcheck was permanently "unhealthy" for that
# reason until #817 switched it to this probe too); bash's /dev/tcp is there.
test: ["CMD", "bash", "-c", "exec 3<>/dev/tcp/127.0.0.1/50000"]
interval: 5s
timeout: 2s
retries: 10
start_period: 10s
volumes:
opc-plc-nat-pki:
@@ -0,0 +1,108 @@
using Opc.Ua;
using Shouldly;
using Xunit;
namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.IntegrationTests;
/// <summary>
/// Gitea #816 — does the driver check the server certificate's host name? Against the plain opc-plc fixture, whose
/// certificate names only its container hostname (e.g. <c>DNS:1fc1de3fcb21</c>) while the driver dials the docker
/// host's address, so a host check MUST fail if it runs at all.
/// <para>Before #816 the driver called the SDK's 8-argument <c>DefaultSessionFactory.CreateAsync</c>, which hard-codes
/// <c>checkDomain: false</c>: the mismatch was never noticed. Now <c>certificateValidation.validateServerHostName</c>
/// decides; unset keeps the old behaviour.</para>
/// <para>Each test trusts the server's certificate in a THROWAWAY PKI (the driver's <c>PkiRootOverride</c>) with
/// auto-accept OFF — auto-accept also accepts a host-name mismatch and would hide the check. The certificate is
/// taken from the server's own GetEndpoints answer: what is under test is the host check, not how trust was
/// established.</para>
/// </summary>
[Collection(OpcPlcCollection.Name)]
[Trait("Category", "Integration")]
[Trait("Simulator", "opc-plc")]
public sealed class ServerHostNameValidationTests(OpcPlcFixture sim) : IDisposable
{
private readonly string _pkiRoot = Path.Combine(Path.GetTempPath(), "otopcua-816-" + Guid.NewGuid().ToString("N"));
/// <inheritdoc />
public void Dispose()
{
try { Directory.Delete(_pkiRoot, recursive: true); } catch { /* best-effort temp cleanup */ }
}
private OpcUaClientDriverOptions SecureOptions(bool? validateHostName) => OpcPlcProfile.BuildOptions(sim.EndpointUrl) with
{
SecurityPolicy = OpcUaSecurityPolicy.Basic256Sha256,
SecurityMode = OpcUaSecurityMode.SignAndEncrypt,
AutoAcceptCertificates = false,
CertificateValidation = new OpcUaCertificateValidationOptions { ValidateServerHostName = validateHostName },
};
/// <summary>Trust the fixture's server certificate (as advertised on its secure endpoint) in the throwaway PKI.</summary>
private async Task TrustServerCertificateAsync(CancellationToken ct)
{
var appConfig = new ApplicationConfiguration(DefaultTelemetry.Create(_ => { }))
{
ApplicationName = "OtOpcUa #816 trust",
ApplicationType = ApplicationType.Client,
SecurityConfiguration = new SecurityConfiguration(),
TransportQuotas = new TransportQuotas(),
ClientConfiguration = new ClientConfiguration(),
DisableHiResClock = true,
};
using var discovery = await DiscoveryClient.CreateAsync(appConfig, new Uri(sim.EndpointUrl), DiagnosticsMasks.None, ct);
var endpoints = await discovery.GetEndpointsAsync(default, ct);
var secure = endpoints.ToList().First(e => e.SecurityPolicyUri == SecurityPolicies.Basic256Sha256);
var der = secure.ServerCertificate.ToArray();
der.ShouldNotBeEmpty("the secure endpoint must carry the server certificate");
var certs = Path.Combine(_pkiRoot, "trusted", "certs");
Directory.CreateDirectory(certs);
await File.WriteAllBytesAsync(Path.Combine(certs, "opc-plc.der"), der, ct);
}
private async Task<OpcUaClientDriver> InitializeAsync(bool? validateHostName, string id, CancellationToken ct)
{
var drv = new OpcUaClientDriver(SecureOptions(validateHostName), driverInstanceId: id) { PkiRootOverride = _pkiRoot };
try
{
await drv.InitializeAsync("{}", ct);
return drv;
}
catch
{
await drv.DisposeAsync();
throw;
}
}
[Theory]
[InlineData(null)] // unset = the pre-#816 behaviour every existing deployment has
[InlineData(false)] // the explicit NAT / IP-addressed opt-out
public async Task Without_host_name_validation_a_trusted_certificate_for_another_host_connects(bool? validate)
{
if (sim.SkipReason is not null) Assert.Skip(sim.SkipReason);
var ct = TestContext.Current.CancellationToken;
await TrustServerCertificateAsync(ct);
await using var drv = await InitializeAsync(validate, $"opcua-816-off-{validate}", ct);
var snapshots = await drv.ReadAsync([OpcPlcProfile.StepUpRef], ct);
snapshots[0].StatusCode.ShouldBe(0u, "the secured session must read once the server certificate is trusted");
}
[Fact]
public async Task With_host_name_validation_the_certificate_is_checked_against_the_configured_host()
{
if (sim.SkipReason is not null) Assert.Skip(sim.SkipReason);
var ct = TestContext.Current.CancellationToken;
await TrustServerCertificateAsync(ct);
var ex = await Should.ThrowAsync<Exception>(() => InitializeAsync(true, "opcua-816-on", ct));
TestContext.Current.TestOutputHelper?.WriteLine($"refused: {ex}");
// The driver's failover aggregate keeps per-endpoint failures as text. The SDK message names the host it
// checked: the CONFIGURED one (the endpoint URL was rewritten to it), not whatever the server advertised.
var configuredHost = new Uri(sim.EndpointUrl).IdnHost;
var text = ex.ToString();
text.ShouldContain($"The domain '{configuredHost}' is not listed in the server certificate");
text.ShouldContain("validateServerHostName=false", Case.Sensitive, "the refusal must name the opt-out");
}
}
@@ -0,0 +1,57 @@
using Opc.Ua;
using Shouldly;
using Xunit;
namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests;
/// <summary>
/// Gitea #816 — <c>certificateValidation.validateServerHostName</c>. The wire behaviour (the SDK's checkDomain against
/// the CONFIGURED host) is pinned against real servers by <c>ServerHostNameValidationTests</c> (driver, plain opc-plc)
/// and <c>NatPublishedEndpointBrowseTests</c> (browser, NAT opc-plc); these pin the option contract.
/// </summary>
[Trait("Category", "Unit")]
public sealed class OpcUaClientServerHostNameOptionTests
{
[Fact]
public void Unset_resolves_to_off_so_existing_deployments_are_unchanged()
{
var o = new OpcUaClientDriverOptions();
o.CertificateValidation.ValidateServerHostName.ShouldBeNull();
o.CertificateValidation.EffectiveValidateServerHostName.ShouldBeFalse();
OpcUaCertificateValidationOptions.DefaultValidateServerHostName.ShouldBeFalse();
OpcUaClientDriverFactoryExtensions.ParseOptions("d", """{"endpointUrl":"opc.tcp://x:1"}""")
.CertificateValidation.EffectiveValidateServerHostName.ShouldBeFalse();
}
[Theory]
[InlineData("true", true)]
[InlineData("false", false)]
public void Factory_json_binds_the_explicit_choice(string json, bool expected)
{
var o = OpcUaClientDriverFactoryExtensions.ParseOptions("d",
$$$"""{"endpointUrl":"opc.tcp://x:1","certificateValidation":{"validateServerHostName":{{{json}}}}}""");
o.CertificateValidation.ValidateServerHostName.ShouldBe(expected);
o.CertificateValidation.EffectiveValidateServerHostName.ShouldBe(expected);
}
[Fact]
public void The_effective_value_is_not_serialised_back()
{
var json = System.Text.Json.JsonSerializer.Serialize(new OpcUaCertificateValidationOptions());
json.ShouldNotContain("Effective");
}
[Fact]
public void A_host_name_refusal_names_the_opt_out()
{
var hint = OpcUaClientDriver.HostNameRefusalHint(new ServiceResultException(
StatusCodes.BadCertificateHostNameInvalid, "The domain '10.1.2.3' is not listed in the server certificate."));
hint.ShouldContain("validateServerHostName=false");
OpcUaClientDriver.HostNameRefusalHint(new ServiceResultException(StatusCodes.BadCertificateUntrusted))
.ShouldBeEmpty();
OpcUaClientDriver.HostNameRefusalHint(new InvalidOperationException("x")).ShouldBeEmpty();
}
}