using Opc.Ua;
using Shouldly;
using Xunit;
namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests;
///
/// Gitea #816 — certificateValidation.validateServerHostName. The wire behaviour (the SDK's checkDomain against
/// the CONFIGURED host) is pinned against real servers by ServerHostNameValidationTests (driver, plain opc-plc)
/// and NatPublishedEndpointBrowseTests (browser, NAT opc-plc); these pin the option contract.
///
[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");
}
///
/// Review of #816: SDK 2.0.1 also checks the host in DefaultSessionFactory.CreateChannelAsync, against the
/// GetEndpoints certificate and before any security-mode test, so checkDomain is never passed for a None endpoint.
///
[Theory]
[InlineData(MessageSecurityMode.None, true, false)]
[InlineData(MessageSecurityMode.None, false, false)]
[InlineData(MessageSecurityMode.Sign, true, true)]
[InlineData(MessageSecurityMode.SignAndEncrypt, true, true)]
[InlineData(MessageSecurityMode.SignAndEncrypt, false, false)]
public void CheckDomain_is_passed_only_for_secured_endpoints(MessageSecurityMode mode, bool validate, bool expected)
{
OpcUaEndpointSelection.CheckDomainFor(new EndpointDescription { SecurityMode = mode }, validate).ShouldBe(expected);
}
[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();
}
}