diff --git a/Applications/Quickstarts.Servers/ReferenceServer/ReferenceServer.cs b/Applications/Quickstarts.Servers/ReferenceServer/ReferenceServer.cs index 5b3785778..e29605422 100644 --- a/Applications/Quickstarts.Servers/ReferenceServer/ReferenceServer.cs +++ b/Applications/Quickstarts.Servers/ReferenceServer/ReferenceServer.cs @@ -405,11 +405,11 @@ private void VerifyX509IdentityToken(X509IdentityToken token) { if (m_userCertificateValidator != null) { - m_userCertificateValidator.Validate(certificate); + m_userCertificateValidator.ValidateAsync(certificate, default).GetAwaiter().GetResult(); } else { - CertificateValidator.Validate(certificate); + CertificateValidator.ValidateAsync(certificate, default).GetAwaiter().GetResult(); } } catch (Exception e) diff --git a/Libraries/Opc.Ua.Client/Session/Session.cs b/Libraries/Opc.Ua.Client/Session/Session.cs index 06562bf9b..891f2e0ed 100644 --- a/Libraries/Opc.Ua.Client/Session/Session.cs +++ b/Libraries/Opc.Ua.Client/Session/Session.cs @@ -1455,7 +1455,7 @@ public async Task UpdateSessionAsync( requireEncryption && identity.TokenType != UserTokenType.Anonymous) { - m_configuration.CertificateValidator.Validate(m_serverCertificate); + await m_configuration.CertificateValidator.ValidateAsync(m_serverCertificate, ct).ConfigureAwait(false); } // validate server nonce and security parameters for user identity. diff --git a/Libraries/Opc.Ua.Gds.Server.Common/GlobalDiscoverySampleServer.cs b/Libraries/Opc.Ua.Gds.Server.Common/GlobalDiscoverySampleServer.cs index fb9e8c9d2..f5fba3e5e 100644 --- a/Libraries/Opc.Ua.Gds.Server.Common/GlobalDiscoverySampleServer.cs +++ b/Libraries/Opc.Ua.Gds.Server.Common/GlobalDiscoverySampleServer.cs @@ -296,7 +296,7 @@ private void VerifyX509IdentityToken(X509IdentityToken token) X509Certificate2 certificate = token.GetOrCreateCertificate(MessageContext.Telemetry); try { - CertificateValidator.Validate(certificate); + CertificateValidator.ValidateAsync(certificate, default).GetAwaiter().GetResult(); } catch (Exception e) { diff --git a/Libraries/Opc.Ua.PubSub/Transport/MqttPubSubConnection.cs b/Libraries/Opc.Ua.PubSub/Transport/MqttPubSubConnection.cs index 7fa1aeaa6..edbf85704 100644 --- a/Libraries/Opc.Ua.PubSub/Transport/MqttPubSubConnection.cs +++ b/Libraries/Opc.Ua.PubSub/Transport/MqttPubSubConnection.cs @@ -789,7 +789,7 @@ private MqttClientOptions GetMqttClientOptions() UrlScheme = connectionUri.Scheme; } - MqttClientProtocolConfiguration transportProtocolConfiguration = + var transportProtocolConfiguration = new MqttClientProtocolConfiguration(PubSubConnectionConfiguration.ConnectionProperties, m_logger); var mqttProtocolVersion = (MqttProtocolVersion) @@ -940,7 +940,7 @@ private bool ValidateBrokerCertificate(MqttClientCertificateValidationEventArgs return Application.OnValidateBrokerCertificate(brokerCertificate); } - m_certificateValidator?.Validate(brokerCertificate); + m_certificateValidator?.ValidateAsync(brokerCertificate, default).GetAwaiter().GetResult(); } catch (Exception ex) { diff --git a/Libraries/Opc.Ua.Server/Configuration/ConfigurationNodeManager.cs b/Libraries/Opc.Ua.Server/Configuration/ConfigurationNodeManager.cs index 7645329e2..8e38212fd 100644 --- a/Libraries/Opc.Ua.Server/Configuration/ConfigurationNodeManager.cs +++ b/Libraries/Opc.Ua.Server/Configuration/ConfigurationNodeManager.cs @@ -577,7 +577,7 @@ private async ValueTask UpdateCertificateAsy } issuerStore.TrustedCertificates = issuerCollection; certValidator.Update(issuerStore, issuerStore, null); - certValidator.Validate(newCert); + await certValidator.ValidateAsync(newCert, ct).ConfigureAwait(false); } catch (Exception ex) { diff --git a/Libraries/Opc.Ua.Server/Server/StandardServer.cs b/Libraries/Opc.Ua.Server/Server/StandardServer.cs index 6f80b89c1..a30259c8e 100644 --- a/Libraries/Opc.Ua.Server/Server/StandardServer.cs +++ b/Libraries/Opc.Ua.Server/Server/StandardServer.cs @@ -334,10 +334,10 @@ public override async Task CreateSessionAsync( uint maxResponseMessageSize, CancellationToken ct) { - NodeId sessionId = 0; - NodeId authenticationToken = null; + NodeId sessionId; + NodeId authenticationToken; double revisedSessionTimeout = 0; - byte[] serverNonce = null; + byte[] serverNonce; byte[] serverCertificate = null; EndpointDescriptionCollection serverEndpoints = null; SignedSoftwareCertificateCollection serverSoftwareCertificates = null; @@ -407,7 +407,7 @@ X509Certificate2Collection clientCertificateChain clientDescription.ApplicationUri); } - CertificateValidator.Validate(clientCertificateChain); + await CertificateValidator.ValidateAsync(clientCertificateChain, ct).ConfigureAwait(false); } } } @@ -711,7 +711,7 @@ public override async Task ActivateSessionAsync( SignatureData userTokenSignature, CancellationToken ct) { - byte[] serverNonce = null; + byte[] serverNonce; StatusCodeCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; @@ -2515,11 +2515,8 @@ private async void OnRegisterServerAsync(object state) lock (m_registrationLock) { // halt any outstanding timer. - if (m_registrationTimer != null) - { - m_registrationTimer.Dispose(); - m_registrationTimer = null; - } + m_registrationTimer?.Dispose(); + m_registrationTimer = null; } if (await RegisterWithDiscoveryServerAsync().ConfigureAwait(false)) @@ -3130,11 +3127,10 @@ await masterNodeManager.StartupAsync(cancellationToken) m_serverInternal.SetAggregateManager( CreateAggregateManager(m_serverInternal, configuration)); - // create the manager responsible for modelling rules. - m_logger.LogInformation(Utils.TraceMasks.StartStop, "Server - CreateModellingRulesManager."); - m_serverInternal.SetModellingRulesManager( - CreateModellingRulesManager(m_serverInternal, configuration)); - + // create the manager responsible for modelling rules. + m_logger.LogInformation(Utils.TraceMasks.StartStop, "Server - CreateModellingRulesManager."); + m_serverInternal.SetModellingRulesManager( + CreateModellingRulesManager(m_serverInternal, configuration)); // start the session manager. m_logger.LogInformation(Utils.TraceMasks.StartStop, "Server - CreateSessionManager."); @@ -3241,11 +3237,8 @@ IMonitoredItemQueueFactory monitoredItemQueueFactory m_lastRegistrationInterval = m_minRegistrationInterval; // start registration timer. - if (m_registrationTimer != null) - { - m_registrationTimer.Dispose(); - m_registrationTimer = null; - } + m_registrationTimer?.Dispose(); + m_registrationTimer = null; if (m_maxRegistrationInterval > 0) { @@ -3303,11 +3296,8 @@ protected override async ValueTask OnServerStoppingAsync(CancellationToken cance // halt any outstanding timer. lock (m_registrationLock) { - if (m_registrationTimer != null) - { - m_registrationTimer.Dispose(); - m_registrationTimer = null; - } + m_registrationTimer?.Dispose(); + m_registrationTimer = null; } // attempt graceful shutdown the server. diff --git a/Stack/Opc.Ua.Bindings.Https/Stack/Https/HttpsTransportListener.cs b/Stack/Opc.Ua.Bindings.Https/Stack/Https/HttpsTransportListener.cs index 9ba82dbae..b0baaf413 100644 --- a/Stack/Opc.Ua.Bindings.Https/Stack/Https/HttpsTransportListener.cs +++ b/Stack/Opc.Ua.Bindings.Https/Stack/Https/HttpsTransportListener.cs @@ -259,7 +259,7 @@ public void Start() m_host = new HostBuilder() .ConfigureWebHostDefaults(ConfigureWebHost) .Build(); - m_host.StartAsync(CancellationToken.None).GetAwaiter().GetResult(); + m_host.StartAsync(CancellationToken.None).GetAwaiter().GetResult(); #else var hostBuilder = new WebHostBuilder(); ConfigureWebHost(hostBuilder); @@ -577,7 +577,7 @@ private bool ValidateClientCertificate( try { - m_quotas.CertificateValidator.Validate(clientCertificate); + m_quotas.CertificateValidator.ValidateAsync(clientCertificate, default).GetAwaiter().GetResult(); } catch (Exception) { diff --git a/Stack/Opc.Ua.Core/Security/Certificates/CertificateValidator.cs b/Stack/Opc.Ua.Core/Security/Certificates/CertificateValidator.cs index cdb384ab7..5cad563af 100644 --- a/Stack/Opc.Ua.Core/Security/Certificates/CertificateValidator.cs +++ b/Stack/Opc.Ua.Core/Security/Certificates/CertificateValidator.cs @@ -497,29 +497,6 @@ public int MaxRejectedCertificates } } - /// - /// Validates the specified certificate against the trust list. - /// - /// The certificate. - public void Validate(X509Certificate2 certificate) - { - Validate([certificate]); - } - - /// - /// Validates a certificate. - /// - /// - /// Each UA application may have a list of trusted certificates that is different from - /// all other UA applications that may be running on the same machine. As a result, the - /// certificate validator cannot rely completely on the Windows certificate store and - /// user or machine specific CTLs (certificate trust lists). - /// - public virtual void Validate(X509Certificate2Collection certificateChain) - { - Validate(certificateChain, null); - } - /// public Task ValidateAsync(X509Certificate2 certificate, CancellationToken ct) { @@ -590,8 +567,8 @@ public virtual async Task ValidateAsync( /// /// Validates a certificate with domain validation check. - /// /// + [Obsolete("Use ValidateAsync")] public virtual void Validate(X509Certificate2Collection chain, ConfiguredEndpoint endpoint) { X509Certificate2 certificate = chain[0]; @@ -754,10 +731,7 @@ public async Task GetIssuersNoExceptionsOnGetIssuerAsync( if (issuer != null) { - if (validationErrors != null) - { - validationErrors[certificate] = revocationStatus; - } + validationErrors?[certificate] = revocationStatus; if (issuers.Find(iss => string.Equals( diff --git a/Stack/Opc.Ua.Core/Security/Certificates/CertificateValidatorObsolete.cs b/Stack/Opc.Ua.Core/Security/Certificates/CertificateValidatorObsolete.cs new file mode 100644 index 000000000..b460cb1dc --- /dev/null +++ b/Stack/Opc.Ua.Core/Security/Certificates/CertificateValidatorObsolete.cs @@ -0,0 +1,42 @@ +/* Copyright (c) 1996-2022 The OPC Foundation. All rights reserved. + The source code in this file is covered under a dual-license scenario: + - RCL: for OPC Foundation Corporate Members in good-standing + - GPL V2: everybody else + RCL license terms accompanied with this source code. See http://opcfoundation.org/License/RCL/1.00/ + GNU General Public License as published by the Free Software Foundation; + version 2 of the License are accompanied with this source code. See http://opcfoundation.org/License/GPLv2 + This source code is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +*/ + +using System; +using System.Security.Cryptography.X509Certificates; +using System.Threading; + +namespace Opc.Ua +{ + /// + /// Extension methods for ICertificateValidator. + /// + public static class CertificateValidatorObsolete + { + /// + /// Validates a certificate. + /// + [Obsolete("Use ValidateAsync")] + public static void Validate(this ICertificateValidator validator, X509Certificate2 certificate) + { + validator.ValidateAsync(certificate, CancellationToken.None).GetAwaiter().GetResult(); + } + + /// + /// Validates a certificate chain. + /// + [Obsolete("Use ValidateAsync")] + public static void Validate(this ICertificateValidator validator, X509Certificate2Collection certificateChain) + { + validator.ValidateAsync(certificateChain, CancellationToken.None).GetAwaiter().GetResult(); + } + } +} diff --git a/Stack/Opc.Ua.Core/Security/Certificates/EccUtils.cs b/Stack/Opc.Ua.Core/Security/Certificates/EccUtils.cs index 4bbc34a56..29dc0e7d5 100644 --- a/Stack/Opc.Ua.Core/Security/Certificates/EccUtils.cs +++ b/Stack/Opc.Ua.Core/Security/Certificates/EccUtils.cs @@ -1120,7 +1120,7 @@ private ArraySegment VerifyHeaderForEcc( } // validate the sender. - Validator?.Validate(senderCertificateChain); + Validator?.ValidateAsync(senderCertificateChain, default).GetAwaiter().GetResult(); } // extract the send certificate and any chain. diff --git a/Stack/Opc.Ua.Core/Security/Certificates/ICertificateValidator.cs b/Stack/Opc.Ua.Core/Security/Certificates/ICertificateValidator.cs index 256350525..c0f244855 100644 --- a/Stack/Opc.Ua.Core/Security/Certificates/ICertificateValidator.cs +++ b/Stack/Opc.Ua.Core/Security/Certificates/ICertificateValidator.cs @@ -21,16 +21,6 @@ namespace Opc.Ua /// public interface ICertificateValidator { - /// - /// Validates a certificate. - /// - void Validate(X509Certificate2 certificate); - - /// - /// Validates a certificate chain. - /// - void Validate(X509Certificate2Collection certificateChain); - /// /// Validates a certificate. /// diff --git a/Stack/Opc.Ua.Core/Stack/Https/HttpsTransportChannel.cs b/Stack/Opc.Ua.Core/Stack/Https/HttpsTransportChannel.cs index 95d97f4d5..d6a05714f 100644 --- a/Stack/Opc.Ua.Core/Stack/Https/HttpsTransportChannel.cs +++ b/Stack/Opc.Ua.Core/Stack/Https/HttpsTransportChannel.cs @@ -371,9 +371,7 @@ private void CreateHttpClient() }; // limit the number of concurrent connections, if supported - PropertyInfo? maxConnectionsPerServerProperty = handler.GetType() - .GetProperty("MaxConnectionsPerServer"); - maxConnectionsPerServerProperty?.SetValue(handler, kMaxConnectionsPerServer); + handler.MaxConnectionsPerServer = kMaxConnectionsPerServer; // send client certificate for servers that require TLS client authentication if (m_settings!.ClientCertificate != null) @@ -396,86 +394,76 @@ private void CreateHttpClient() m_logger.LogError(ce, "Copy of the private key for https was denied"); } #endif - PropertyInfo? certProperty = handler.GetType().GetProperty("ClientCertificates"); - if (certProperty != null) - { - var clientCertificates = (X509CertificateCollection?)certProperty.GetValue( - handler); - _ = clientCertificates?.Add(clientCertificate); - } + handler.ClientCertificates.Add(clientCertificate); } - PropertyInfo? propertyInfo = handler.GetType() - .GetProperty("ServerCertificateCustomValidationCallback"); - if (propertyInfo != null) - { - Func< - HttpRequestMessage, - X509Certificate2, - X509Chain, - SslPolicyErrors, - bool - >? serverCertificateCustomValidationCallback; + Func< + HttpRequestMessage, + X509Certificate2, + X509Chain, + SslPolicyErrors, + bool + >? serverCertificateCustomValidationCallback; - try + try + { + serverCertificateCustomValidationCallback = (_, cert, chain, _) => { - serverCertificateCustomValidationCallback = (_, cert, chain, _) => + try { - try + var validationChain = new X509Certificate2Collection(); + if (chain != null && chain.ChainElements != null) { - var validationChain = new X509Certificate2Collection(); - if (chain != null && chain.ChainElements != null) - { - int i = 0; - m_logger.LogInformation( - Utils.TraceMasks.Security, - "{ChannelType} Validate server chain:", - nameof(HttpsTransportChannel)); - foreach (X509ChainElement element in chain.ChainElements) - { - m_logger.LogInformation( - Utils.TraceMasks.Security, - "{Index}: {Certificate}", - i, - element.Certificate.AsLogSafeString()); - validationChain.Add(element.Certificate); - i++; - } - } - else + int i = 0; + m_logger.LogInformation( + Utils.TraceMasks.Security, + "{ChannelType} Validate server chain:", + nameof(HttpsTransportChannel)); + foreach (X509ChainElement element in chain.ChainElements) { m_logger.LogInformation( Utils.TraceMasks.Security, - "{ChannelType} Validate Server Certificate: {Certificate}", - cert.AsLogSafeString(), - nameof(HttpsTransportChannel)); - validationChain.Add(cert); + "{Index}: {Certificate}", + i, + element.Certificate.AsLogSafeString()); + validationChain.Add(element.Certificate); + i++; } - - m_quotas.CertificateValidator?.Validate(validationChain); - - return true; } - catch (Exception ex) + else { - m_logger.LogError( - ex, - "{ChannelType} Failed to validate certificate.", + m_logger.LogInformation( + Utils.TraceMasks.Security, + "{ChannelType} Validate Server Certificate: {Certificate}", + cert.AsLogSafeString(), nameof(HttpsTransportChannel)); + validationChain.Add(cert); } - return false; - }; - propertyInfo.SetValue(handler, serverCertificateCustomValidationCallback); - m_logger.LogInformation( - "{ChannelType} ServerCertificate callback enabled.", - nameof(HttpsTransportChannel)); - } - catch (PlatformNotSupportedException) - { - // client may throw if not supported (e.g. UWP) - serverCertificateCustomValidationCallback = null; - } + m_quotas.CertificateValidator?.ValidateAsync(validationChain, default).GetAwaiter().GetResult(); + + return true; + } + catch (Exception ex) + { + m_logger.LogError( + ex, + "{ChannelType} Failed to validate certificate.", + nameof(HttpsTransportChannel)); + } + return false; + }; + + handler.ServerCertificateCustomValidationCallback = serverCertificateCustomValidationCallback!; + + m_logger.LogInformation( + "{ChannelType} ServerCertificate callback enabled.", + nameof(HttpsTransportChannel)); + } + catch (PlatformNotSupportedException) + { + // client may throw if not supported (e.g. UWP) + serverCertificateCustomValidationCallback = null; } #pragma warning disable CA5399 // HttpClient is created without enabling CheckCertificateRevocationList diff --git a/Stack/Opc.Ua.Core/Stack/Tcp/UaSCBinaryChannel.Asymmetric.cs b/Stack/Opc.Ua.Core/Stack/Tcp/UaSCBinaryChannel.Asymmetric.cs index 46e32053a..b878de8d1 100644 --- a/Stack/Opc.Ua.Core/Stack/Tcp/UaSCBinaryChannel.Asymmetric.cs +++ b/Stack/Opc.Ua.Core/Stack/Tcp/UaSCBinaryChannel.Asymmetric.cs @@ -1000,11 +1000,11 @@ protected ArraySegment ReadAsymmetricMessage( { if (Quotas.CertificateValidator is CertificateValidator certificateValidator) { - certificateValidator.Validate(senderCertificateChain); + certificateValidator.ValidateAsync(senderCertificateChain, default).GetAwaiter().GetResult(); } else { - Quotas.CertificateValidator.Validate(senderCertificate); + Quotas.CertificateValidator.ValidateAsync(senderCertificate, default).GetAwaiter().GetResult(); } } diff --git a/Stack/Opc.Ua.Core/Stack/Types/SoftwareCertificate.cs b/Stack/Opc.Ua.Core/Stack/Types/SoftwareCertificate.cs index ab418c4b8..c4763644c 100644 --- a/Stack/Opc.Ua.Core/Stack/Types/SoftwareCertificate.cs +++ b/Stack/Opc.Ua.Core/Stack/Types/SoftwareCertificate.cs @@ -43,7 +43,7 @@ public static ServiceResult Validate( try { certificate = CertificateFactory.Create(signedCertificate); - validator.Validate(certificate); + validator.ValidateAsync(certificate, default).GetAwaiter().GetResult(); } catch (Exception e) { diff --git a/Tests/Opc.Ua.Core.Tests/Security/Certificates/CertificateValidatorAlternate.cs b/Tests/Opc.Ua.Core.Tests/Security/Certificates/CertificateValidatorAlternate.cs index a93fa3b2b..49e8f9128 100644 --- a/Tests/Opc.Ua.Core.Tests/Security/Certificates/CertificateValidatorAlternate.cs +++ b/Tests/Opc.Ua.Core.Tests/Security/Certificates/CertificateValidatorAlternate.cs @@ -186,7 +186,7 @@ public void TearDown() /// A signed app cert that has no keyid information. /// [Test] - public void CertificateWithoutKeyID() + public async Task CertificateWithoutKeyIDAsync() { // a valid app cert using X509Certificate2 appCert = CertificateFactory @@ -196,14 +196,14 @@ public void CertificateWithoutKeyID() Assert.NotNull(appCert); m_certValidator.RejectUnknownRevocationStatus = true; - m_certValidator.Validate(appCert); + await m_certValidator.ValidateAsync(appCert, CancellationToken.None).ConfigureAwait(false); } /// /// Certificate with combinations of optional fields in the AKI. /// [Theory] - public void CertificateWithAuthorityKeyID( + public async Task CertificateWithAuthorityKeyIDAsync( bool subjectKeyIdentifier, bool issuerName, bool serialNumber) @@ -231,13 +231,13 @@ public void CertificateWithAuthorityKeyID( if (!subjectKeyIdentifier && !serialNumber) { ServiceResultException result = NUnit.Framework.Assert - .Throws(() => - m_certValidator.Validate(appCert)); + .ThrowsAsync(async () => + await m_certValidator.ValidateAsync(appCert, CancellationToken.None).ConfigureAwait(false)); TestContext.Out.WriteLine($"{result.Result}: {result.Message}"); } else { - m_certValidator.Validate(appCert); + await m_certValidator.ValidateAsync(appCert, CancellationToken.None).ConfigureAwait(false); } } @@ -245,7 +245,7 @@ public void CertificateWithAuthorityKeyID( /// App cert from alternate Root without KeyID. /// [Theory] - public void AlternateRootCertificateWithoutAuthorityKeyID( + public async Task AlternateRootCertificateWithoutAuthorityKeyIDAsync( bool rejectUnknownRevocationStatus) { ICertificateBuilder certBuilder = CertificateFactory.CreateCertificate( @@ -261,8 +261,8 @@ public void AlternateRootCertificateWithoutAuthorityKeyID( m_certValidator.RejectUnknownRevocationStatus = rejectUnknownRevocationStatus; ServiceResultException result = NUnit.Framework.Assert - .Throws(() => - m_certValidator.Validate(altAppCert)); + .ThrowsAsync(async () => + await m_certValidator.ValidateAsync(altAppCert, CancellationToken.None).ConfigureAwait(false)); TestContext.Out.WriteLine($"{result.Result}: {result.Message}"); } @@ -272,7 +272,7 @@ public void AlternateRootCertificateWithoutAuthorityKeyID( /// validate that any combination of AKI is not validated. /// [Theory] - public void AlternateRootCertificateWithAuthorityKeyID( + public async Task AlternateRootCertificateWithAuthorityKeyIDAsync( bool subjectKeyIdentifier, bool issuerName, bool serialNumber) @@ -304,8 +304,8 @@ public void AlternateRootCertificateWithAuthorityKeyID( // should not pass! m_certValidator.RejectUnknownRevocationStatus = false; ServiceResultException result = NUnit.Framework.Assert - .Throws(() => - m_certValidator.Validate(altAppCert)); + .ThrowsAsync(async () => + await m_certValidator.ValidateAsync(altAppCert, CancellationToken.None).ConfigureAwait(false)); TestContext.Out.WriteLine($"{result.Result}: {result.Message}"); } @@ -352,7 +352,7 @@ public async Task VerifyLoopChainIsDetectedAsync() await validator.IssuerStore.AddAsync(rootCert).ConfigureAwait(false); await validator.TrustedStore.AddAsync(subCACert).ConfigureAwait(false); CertificateValidator certValidator = validator.Update(); - certValidator.Validate(leafCert); + await certValidator.ValidateAsync(leafCert, CancellationToken.None).ConfigureAwait(false); } // validate using server/client chain sent over the wire @@ -364,8 +364,8 @@ public async Task VerifyLoopChainIsDetectedAsync() { CertificateValidator certValidator = validator.Update(); ServiceResultException result = NUnit.Framework.Assert - .Throws(() => - certValidator.Validate(collection)); + .ThrowsAsync(async () => + await certValidator.ValidateAsync(collection, CancellationToken.None).ConfigureAwait(false)); TestContext.Out.WriteLine($"{result.Result}: {result.Message}"); } @@ -377,8 +377,8 @@ public async Task VerifyLoopChainIsDetectedAsync() await validator.TrustedStore.AddAsync(subCACert).ConfigureAwait(false); CertificateValidator certValidator = validator.Update(); ServiceResultException result = NUnit.Framework.Assert - .Throws(() => - certValidator.Validate(collection)); + .ThrowsAsync(async () => + await certValidator.ValidateAsync(collection, CancellationToken.None).ConfigureAwait(false)); TestContext.Out.WriteLine($"{result.Result}: {result.Message}"); } diff --git a/Tests/Opc.Ua.Core.Tests/Security/Certificates/CertificateValidatorTest.cs b/Tests/Opc.Ua.Core.Tests/Security/Certificates/CertificateValidatorTest.cs index b83b2543a..a04be404b 100644 --- a/Tests/Opc.Ua.Core.Tests/Security/Certificates/CertificateValidatorTest.cs +++ b/Tests/Opc.Ua.Core.Tests/Security/Certificates/CertificateValidatorTest.cs @@ -248,7 +248,7 @@ protected void TearDown() /// Verify self signed app certs are not trusted. /// [Test] - public void VerifySelfSignedAppCertsNotTrusted() + public async Task VerifySelfSignedAppCertsNotTrustedAsync() { ITelemetryContext telemetry = NUnitTelemetryContext.Create(); @@ -258,16 +258,16 @@ public void VerifySelfSignedAppCertsNotTrusted() foreach (X509Certificate2 cert in m_appSelfSignedCerts) { ServiceResultException serviceResultException = NUnit.Framework.Assert - .Throws( - () => - certValidator.Validate(new X509Certificate2(cert))); + .ThrowsAsync( + async () => + await certValidator.ValidateAsync(new X509Certificate2(cert), CancellationToken.None).ConfigureAwait(false)); Assert.AreEqual( (StatusCode)StatusCodes.BadCertificateUntrusted, (StatusCode)serviceResultException.StatusCode, serviceResultException.Message); } - Thread.Sleep(1500); + await Task.Delay(1500).ConfigureAwait(false); Assert.AreEqual( m_appSelfSignedCerts.Count, validator.RejectedStore.EnumerateAsync().GetAwaiter().GetResult().Count, @@ -279,7 +279,7 @@ public void VerifySelfSignedAppCertsNotTrusted() foreach (X509Certificate2 cert in m_appSelfSignedCerts) { using var publicKey = new X509Certificate2(cert); - certValidator.Validate(publicKey); + await certValidator.ValidateAsync(publicKey, CancellationToken.None).ConfigureAwait(false); } // count certs written to rejected store Assert.AreEqual(m_appSelfSignedCerts.Count, approver.AcceptedCount, @@ -314,9 +314,9 @@ public async Task VerifySelfSignedAppCertsNotTrustedWithCAAsync() foreach (X509Certificate2 cert in m_appSelfSignedCerts) { ServiceResultException serviceResultException = NUnit.Framework.Assert - .Throws( - () => - certValidator.Validate(new X509Certificate2(cert))); + .ThrowsAsync( + async () => + await certValidator.ValidateAsync(new X509Certificate2(cert), CancellationToken.None).ConfigureAwait(false)); Assert.AreEqual( (StatusCode)StatusCodes.BadCertificateUntrusted, (StatusCode)serviceResultException.StatusCode, @@ -347,8 +347,8 @@ public async Task VerifySelfSignedAppCertsThrowAsync() foreach (X509Certificate2 cert in m_appSelfSignedCerts) { ServiceResultException serviceResultException = - NUnit.Framework.Assert.Throws(() => - certValidator.Validate(new X509Certificate2(cert))); + NUnit.Framework.Assert.ThrowsAsync(async () => + await certValidator.ValidateAsync(new X509Certificate2(cert), CancellationToken.None).ConfigureAwait(false)); Assert.AreEqual( (StatusCode)StatusCodes.BadCertificateUntrusted, (StatusCode)serviceResultException.StatusCode, @@ -395,8 +395,8 @@ public async Task VerifyRejectedCertsDoNotOverflowStoreAsync() var certs = new X509Certificate2Collection(cert); certs.AddRange(m_caChain); ServiceResultException serviceResultException = - NUnit.Framework.Assert - .Throws(() => certValidator.Validate(certs)); + NUnit.Framework.Assert.ThrowsAsync(async () => + await certValidator.ValidateAsync(certs, CancellationToken.None).ConfigureAwait(false)); Assert.AreEqual( (StatusCode)StatusCodes.BadCertificateUntrusted, (StatusCode)serviceResultException.StatusCode, @@ -408,8 +408,8 @@ public async Task VerifyRejectedCertsDoNotOverflowStoreAsync() var certs = new X509Certificate2Collection(cert); certs.AddRange(m_caChain); ServiceResultException serviceResultException = - NUnit.Framework.Assert - .Throws(() => certValidator.Validate(certs)); + NUnit.Framework.Assert.ThrowsAsync(async () => + await certValidator.ValidateAsync(certs, CancellationToken.None).ConfigureAwait(false)); Assert.AreEqual( (StatusCode)StatusCodes.BadCertificateUntrusted, (StatusCode)serviceResultException.StatusCode, @@ -425,8 +425,8 @@ public async Task VerifyRejectedCertsDoNotOverflowStoreAsync() foreach (X509Certificate2 cert in m_appSelfSignedCerts) { ServiceResultException serviceResultException = - NUnit.Framework.Assert.Throws(() => - certValidator.Validate(new X509Certificate2Collection(cert))); + NUnit.Framework.Assert.ThrowsAsync(async () => + await certValidator.ValidateAsync(new X509Certificate2Collection(cert), CancellationToken.None).ConfigureAwait(false)); Assert.AreEqual( (StatusCode)StatusCodes.BadCertificateUntrusted, (StatusCode)serviceResultException.StatusCode, @@ -520,7 +520,7 @@ public async Task VerifySelfSignedAppCertsTrustedAsync() CertificateValidator certValidator = validator.Update(); foreach (X509Certificate2 cert in m_appSelfSignedCerts) { - certValidator.Validate(new X509Certificate2(cert)); + await certValidator.ValidateAsync(new X509Certificate2(cert), default).ConfigureAwait(false); } } @@ -542,7 +542,7 @@ public async Task VerifySelfSignedAppCertsAllStoresAsync() CertificateValidator certValidator = validator.Update(); foreach (X509Certificate2 cert in m_appSelfSignedCerts) { - certValidator.Validate(new X509Certificate2(cert)); + await certValidator.ValidateAsync(new X509Certificate2(cert), CancellationToken.None).ConfigureAwait(false); } } @@ -577,7 +577,7 @@ public async Task VerifyAppChainsOneTrustedAsync() .WriteLine($"InitValidator: {stopWatch.ElapsedMilliseconds - start}"); foreach (ApplicationTestData app in m_goodApplicationTestSet) { - certValidator.Validate(CertificateFactory.Create(app.Certificate)); + await certValidator.ValidateAsync(CertificateFactory.Create(app.Certificate), CancellationToken.None).ConfigureAwait(false); } TestContext.Out.WriteLine($"Validation: {stopWatch.ElapsedMilliseconds - start}"); } @@ -608,7 +608,7 @@ public async Task VerifyAppChainsAllButOneTrustedAsync() CertificateValidator certValidator = validator.Update(); foreach (ApplicationTestData app in m_goodApplicationTestSet) { - certValidator.Validate(CertificateFactory.Create(app.Certificate)); + await certValidator.ValidateAsync(CertificateFactory.Create(app.Certificate), CancellationToken.None).ConfigureAwait(false); } } } @@ -638,9 +638,9 @@ await validator.TrustedStore.AddCRLAsync(m_crlChain[i]) foreach (ApplicationTestData app in m_goodApplicationTestSet) { ServiceResultException serviceResultException = - NUnit.Framework.Assert.Throws(() => - certValidator.Validate( - CertificateFactory.Create(app.Certificate))); + NUnit.Framework.Assert.ThrowsAsync(async () => + await certValidator.ValidateAsync( + CertificateFactory.Create(app.Certificate), CancellationToken.None).ConfigureAwait(false)); Assert.AreEqual( (StatusCode)StatusCodes.BadCertificateChainIncomplete, (StatusCode)serviceResultException.StatusCode, @@ -681,9 +681,9 @@ await validator.TrustedStore.AddCRLAsync(m_crlDupeChain[i]) foreach (ApplicationTestData app in m_goodApplicationTestSet) { ServiceResultException serviceResultException = - NUnit.Framework.Assert.Throws(() => - certValidator.Validate( - CertificateFactory.Create(app.Certificate))); + NUnit.Framework.Assert.ThrowsAsync(async () => + await certValidator.ValidateAsync( + CertificateFactory.Create(app.Certificate), CancellationToken.None).ConfigureAwait(false)); Assert.AreEqual( (StatusCode)StatusCodes.BadCertificateChainIncomplete, (StatusCode)serviceResultException.StatusCode, @@ -717,7 +717,7 @@ public async Task VerifyAppChainsWithGoodAndInvalidChainAsync() CertificateValidator certValidator = validator.Update(); foreach (ApplicationTestData app in m_goodApplicationTestSet) { - certValidator.Validate(CertificateFactory.Create(app.Certificate)); + await certValidator.ValidateAsync(CertificateFactory.Create(app.Certificate), CancellationToken.None).ConfigureAwait(false); } } } @@ -753,9 +753,9 @@ await validator.IssuerStore.AddCRLAsync(m_crlChain[i]) foreach (ApplicationTestData app in m_goodApplicationTestSet) { ServiceResultException serviceResultException = - NUnit.Framework.Assert.Throws(() => - certValidator.Validate( - CertificateFactory.Create(app.Certificate))); + NUnit.Framework.Assert.ThrowsAsync(async () => + await certValidator.ValidateAsync( + CertificateFactory.Create(app.Certificate), CancellationToken.None).ConfigureAwait(false)); Assert.AreEqual( v == kCaChainCount - 1 ? StatusCodes.BadCertificateRevoked @@ -796,9 +796,9 @@ await validator.TrustedStore.AddCRLAsync(m_crlChain[i]) foreach (ApplicationTestData app in m_goodApplicationTestSet) { ServiceResultException serviceResultException = - NUnit.Framework.Assert.Throws(() => - certValidator.Validate( - CertificateFactory.Create(app.Certificate))); + NUnit.Framework.Assert.ThrowsAsync(async () => + await certValidator.ValidateAsync( + CertificateFactory.Create(app.Certificate), CancellationToken.None).ConfigureAwait(false)); Assert.AreEqual( v == kCaChainCount - 1 ? StatusCodes.BadCertificateRevoked @@ -846,9 +846,9 @@ await validator foreach (ApplicationTestData app in m_goodApplicationTestSet) { ServiceResultException serviceResultException = - NUnit.Framework.Assert.Throws(() => - certValidator.Validate( - CertificateFactory.Create(app.Certificate))); + NUnit.Framework.Assert.ThrowsAsync(async () => + await certValidator.ValidateAsync( + CertificateFactory.Create(app.Certificate), CancellationToken.None).ConfigureAwait(false)); Assert.AreEqual( v == kCaChainCount - 1 ? StatusCodes.BadCertificateRevoked @@ -888,9 +888,9 @@ await validator.TrustedStore.AddCRLAsync(m_crlChain[i]) foreach (ApplicationTestData app in m_goodApplicationTestSet) { ServiceResultException serviceResultException = - NUnit.Framework.Assert.Throws(() => - certValidator.Validate( - CertificateFactory.Create(app.Certificate))); + NUnit.Framework.Assert.ThrowsAsync(async () => + await certValidator.ValidateAsync( + CertificateFactory.Create(app.Certificate), CancellationToken.None).ConfigureAwait(false)); Assert.AreEqual( v == kCaChainCount - 1 ? StatusCodes.BadCertificateRevoked @@ -937,9 +937,9 @@ await validator foreach (ApplicationTestData app in m_goodApplicationTestSet) { ServiceResultException serviceResultException = - NUnit.Framework.Assert.Throws(() => - certValidator.Validate( - CertificateFactory.Create(app.Certificate))); + NUnit.Framework.Assert.ThrowsAsync(async () => + await certValidator.ValidateAsync( + CertificateFactory.Create(app.Certificate), CancellationToken.None).ConfigureAwait(false)); Assert.AreEqual( v == kCaChainCount - 1 ? StatusCodes.BadCertificateRevoked @@ -977,7 +977,7 @@ await validator CertificateValidator certValidator = validator.Update(); foreach (ApplicationTestData app in m_goodApplicationTestSet) { - certValidator.Validate(CertificateFactory.Create(app.Certificate)); + await certValidator.ValidateAsync(CertificateFactory.Create(app.Certificate), CancellationToken.None).ConfigureAwait(false); } } @@ -1017,9 +1017,9 @@ await validator foreach (ApplicationTestData app in m_goodApplicationTestSet) { ServiceResultException serviceResultException = - NUnit.Framework.Assert.Throws(() => - certValidator.Validate( - CertificateFactory.Create(app.Certificate))); + NUnit.Framework.Assert.ThrowsAsync(async () => + await certValidator.ValidateAsync( + CertificateFactory.Create(app.Certificate), CancellationToken.None).ConfigureAwait(false)); Assert.AreEqual( (StatusCode)StatusCodes.BadCertificateChainIncomplete, (StatusCode)serviceResultException.StatusCode, @@ -1156,8 +1156,8 @@ public async Task VerifyNotBeforeInvalidAsync(bool trusted) } CertificateValidator certValidator = validator.Update(); ServiceResultException serviceResultException = NUnit.Framework.Assert - .Throws(() => - certValidator.Validate(cert)); + .ThrowsAsync(async () => + await certValidator.ValidateAsync(cert, CancellationToken.None).ConfigureAwait(false)); if (!trusted) { Assert.AreEqual( @@ -1211,8 +1211,8 @@ public async Task VerifyNotAfterInvalidAsync(bool trusted) } CertificateValidator certValidator = validator.Update(); ServiceResultException serviceResultException = NUnit.Framework.Assert - .Throws(() => - certValidator.Validate(cert)); + .ThrowsAsync(async () => + await certValidator.ValidateAsync(cert, CancellationToken.None).ConfigureAwait(false)); if (!trusted) { Assert.AreEqual( @@ -1260,8 +1260,8 @@ public async Task VerifySignedNotAfterInvalidAsync(bool trusted) } CertificateValidator certValidator = validator.Update(); ServiceResultException serviceResultException = NUnit.Framework.Assert - .Throws(() => - certValidator.Validate(cert)); + .ThrowsAsync(async () => + await certValidator.ValidateAsync(cert, CancellationToken.None).ConfigureAwait(false)); Assert.AreEqual( (StatusCode)StatusCodes.BadCertificateChainIncomplete, (StatusCode)serviceResultException.StatusCode, @@ -1335,9 +1335,9 @@ public async Task TestSHA1RejectedAsync(bool trusted, bool rejectSHA1) if (rejectSHA1) { ServiceResultException serviceResultException = NUnit.Framework.Assert - .Throws( - () => - certValidator.Validate(cert)); + .ThrowsAsync( + async () => + await certValidator.ValidateAsync(cert, CancellationToken.None).ConfigureAwait(false)); Assert.AreEqual( (StatusCode)StatusCodes.BadCertificatePolicyCheckFailed, (StatusCode)serviceResultException.StatusCode, @@ -1359,14 +1359,14 @@ public async Task TestSHA1RejectedAsync(bool trusted, bool rejectSHA1) } else if (trusted) { - certValidator.Validate(cert); + await certValidator.ValidateAsync(cert, CancellationToken.None).ConfigureAwait(false); } else { ServiceResultException serviceResultException = NUnit.Framework.Assert - .Throws( - () => - certValidator.Validate(cert)); + .ThrowsAsync( + async () => + await certValidator.ValidateAsync(cert, CancellationToken.None).ConfigureAwait(false)); Assert.AreEqual( (StatusCode)StatusCodes.BadCertificateUntrusted, (StatusCode)serviceResultException.StatusCode, @@ -1398,8 +1398,8 @@ public async Task TestInvalidKeyUsageAsync(bool trusted) } CertificateValidator certValidator = validator.Update(); ServiceResultException serviceResultException = NUnit.Framework.Assert - .Throws(() => - certValidator.Validate(cert)); + .ThrowsAsync(async () => + await certValidator.ValidateAsync(cert, CancellationToken.None).ConfigureAwait(false)); Assert.AreEqual( (StatusCode)StatusCodes.BadCertificateUseNotAllowed, (StatusCode)serviceResultException.StatusCode, @@ -1465,8 +1465,8 @@ public async Task TestInvalidSignatureAsync(bool ca, bool trusted) certValidator.CertificateValidation += approver.OnCertificateValidation; ServiceResult innerResult; ServiceResultException serviceResultException = NUnit.Framework.Assert - .Throws(() => - certValidator.Validate(cert)); + .ThrowsAsync(async () => + await certValidator.ValidateAsync(cert, CancellationToken.None).ConfigureAwait(false)); if (ca) { // The CA version fails for the key usage flags @@ -1520,8 +1520,8 @@ public async Task TestMinimumKeyRejectedAsync(bool trusted) } CertificateValidator certValidator = validator.Update(); ServiceResultException serviceResultException = NUnit.Framework.Assert - .Throws(() => - certValidator.Validate(cert)); + .ThrowsAsync(async () => + await certValidator.ValidateAsync(cert, CancellationToken.None).ConfigureAwait(false)); Assert.AreEqual( (StatusCode)StatusCodes.BadCertificatePolicyCheckFailed, (StatusCode)serviceResultException.StatusCode, @@ -1547,12 +1547,12 @@ public async Task TestMinimumKeyRejectedAsync(bool trusted) certValidator.CertificateValidation += approver.OnCertificateValidation; if (trusted) { - certValidator.Validate(cert); + await certValidator.ValidateAsync(cert, CancellationToken.None).ConfigureAwait(false); } else { - serviceResultException = NUnit.Framework.Assert.Throws(() => - certValidator.Validate(cert)); + serviceResultException = NUnit.Framework.Assert.ThrowsAsync(async () => + await certValidator.ValidateAsync(cert, CancellationToken.None).ConfigureAwait(false)); Assert.AreEqual( (StatusCode)StatusCodes.BadCertificateUntrusted, (StatusCode)serviceResultException.StatusCode, @@ -1583,9 +1583,9 @@ public async Task ECDsaHashSizeLowerThanPublicKeySizeAsync(ECCurveHashPair ecCur CertificateValidator certValidator = validator.Update(); ServiceResultException serviceResultException = NUnit.Framework.Assert - .Throws( - () => - certValidator.Validate(cert)); + .ThrowsAsync( + async () => + await certValidator.ValidateAsync(cert, CancellationToken.None).ConfigureAwait(false)); Assert.AreEqual( (StatusCode)StatusCodes.BadCertificatePolicyCheckFailed, (StatusCode)serviceResultException.StatusCode, @@ -1619,14 +1619,14 @@ public async Task TestAutoAcceptAsync(bool trusted, bool autoAccept) certValidator.AutoAcceptUntrustedCertificates = autoAccept; if (autoAccept || trusted) { - certValidator.Validate(cert); + await certValidator.ValidateAsync(cert, CancellationToken.None).ConfigureAwait(false); } else { ServiceResultException serviceResultException = NUnit.Framework.Assert - .Throws( - () => - certValidator.Validate(cert)); + .ThrowsAsync( + async () => + await certValidator.ValidateAsync(cert, CancellationToken.None).ConfigureAwait(false)); Assert.AreEqual( (StatusCode)StatusCodes.BadCertificateUntrusted, (StatusCode)serviceResultException.StatusCode, @@ -1641,7 +1641,7 @@ public async Task TestAutoAcceptAsync(bool trusted, bool autoAccept) certValidator.AutoAcceptUntrustedCertificates = autoAccept; CertValidationApprover approver = new([StatusCodes.BadCertificateUntrusted]); certValidator.CertificateValidation += approver.OnCertificateValidation; - certValidator.Validate(cert); + await certValidator.ValidateAsync(cert, CancellationToken.None).ConfigureAwait(false); certValidator.CertificateValidation -= approver.OnCertificateValidation; // override the autoaccept flag, but do not approve @@ -1651,14 +1651,14 @@ public async Task TestAutoAcceptAsync(bool trusted, bool autoAccept) certValidator.CertificateValidation += approver.OnCertificateValidation; if (trusted) { - certValidator.Validate(cert); + await certValidator.ValidateAsync(cert, CancellationToken.None).ConfigureAwait(false); } else { ServiceResultException serviceResultException = NUnit.Framework.Assert - .Throws( - () => - certValidator.Validate(cert)); + .ThrowsAsync( + async () => + await certValidator.ValidateAsync(cert, CancellationToken.None).ConfigureAwait(false)); Assert.AreEqual( (StatusCode)StatusCodes.BadCertificateUntrusted, (StatusCode)serviceResultException.StatusCode, @@ -1725,9 +1725,9 @@ await validator.TrustedStore.AddCRLAsync(m_crlRevokedChain[i]) foreach (ApplicationTestData app in m_goodApplicationTestSet) { ServiceResultException serviceResultException = - NUnit.Framework.Assert.Throws(() => - certValidator.Validate( - CertificateFactory.Create(app.Certificate))); + NUnit.Framework.Assert.ThrowsAsync(async () => + await certValidator.ValidateAsync( + CertificateFactory.Create(app.Certificate), CancellationToken.None).ConfigureAwait(false)); Assert.AreEqual( v == kCaChainCount - 1 @@ -1775,9 +1775,9 @@ public async Task VerifyAllMissingCRLRevokedTrustedStoreAppChainsAsync() foreach (ApplicationTestData app in m_goodApplicationTestSet) { ServiceResultException serviceResultException = - NUnit.Framework.Assert.Throws(() => - certValidator.Validate( - CertificateFactory.Create(app.Certificate))); + NUnit.Framework.Assert.ThrowsAsync(async () => + await certValidator.ValidateAsync( + CertificateFactory.Create(app.Certificate), CancellationToken.None).ConfigureAwait(false)); Assert.IsTrue( StatusCodes.BadCertificateRevocationUnknown == serviceResultException @@ -1844,9 +1844,9 @@ await validator.IssuerStore.AddCRLAsync(m_crlChain[i]) if (rejectUnknownRevocationStatus) { ServiceResultException serviceResultException = - NUnit.Framework.Assert.Throws(() => - certValidator.Validate( - CertificateFactory.Create(app.Certificate))); + NUnit.Framework.Assert.ThrowsAsync(async () => + await certValidator.ValidateAsync( + CertificateFactory.Create(app.Certificate), CancellationToken.None).ConfigureAwait(false)); Assert.AreEqual( v == kCaChainCount - 1 @@ -1857,8 +1857,8 @@ await validator.IssuerStore.AddCRLAsync(m_crlChain[i]) } else { - certValidator.Validate( - CertificateFactory.Create(app.Certificate)); + await certValidator.ValidateAsync( + CertificateFactory.Create(app.Certificate), CancellationToken.None).ConfigureAwait(false); } } } @@ -1892,9 +1892,9 @@ public async Task VerifyMissingCRLANDAppChainsIncompleteChainAsync( foreach (ApplicationTestData app in m_goodApplicationTestSet) { ServiceResultException serviceResultException = - NUnit.Framework.Assert.Throws(() => - certValidator.Validate( - CertificateFactory.Create(app.Certificate))); + NUnit.Framework.Assert.ThrowsAsync(async () => + await certValidator.ValidateAsync( + CertificateFactory.Create(app.Certificate), CancellationToken.None).ConfigureAwait(false)); Assert.AreEqual( (StatusCode)StatusCodes.BadCertificateChainIncomplete, (StatusCode)serviceResultException.StatusCode, @@ -1947,9 +1947,9 @@ await validator.IssuerStore.AddCRLAsync(m_crlChain[i]) foreach (ApplicationTestData app in m_notYetValidCertsApplicationTestSet) { ServiceResultException serviceResultException = - NUnit.Framework.Assert.Throws(() => - certValidator.Validate( - CertificateFactory.Create(app.Certificate))); + NUnit.Framework.Assert.ThrowsAsync(async () => + await certValidator.ValidateAsync( + CertificateFactory.Create(app.Certificate), CancellationToken.None).ConfigureAwait(false)); Assert.AreEqual( (StatusCode)StatusCodes.BadCertificateTimeInvalid, (StatusCode)serviceResultException.StatusCode, @@ -1993,9 +1993,9 @@ public async Task VerifyMissingCRLAppChainsExpiredCertificatesAsync( foreach (ApplicationTestData app in m_notYetValidCertsApplicationTestSet) { ServiceResultException serviceResultException = - NUnit.Framework.Assert.Throws(() => - certValidator.Validate( - CertificateFactory.Create(app.Certificate))); + NUnit.Framework.Assert.ThrowsAsync(async () => + await certValidator.ValidateAsync( + CertificateFactory.Create(app.Certificate), CancellationToken.None).ConfigureAwait(false)); Assert.AreEqual( (StatusCode)StatusCodes.BadCertificateTimeInvalid, (StatusCode)serviceResultException.StatusCode, @@ -2062,9 +2062,9 @@ await validator.IssuerStore.AddCRLAsync(m_crlChain[i]) foreach (ApplicationTestData app in m_goodApplicationTestSet) { ServiceResultException serviceResultException = - NUnit.Framework.Assert.Throws(() => - certValidator.Validate( - CertificateFactory.Create(app.Certificate))); + NUnit.Framework.Assert.ThrowsAsync(async () => + await certValidator.ValidateAsync( + CertificateFactory.Create(app.Certificate), CancellationToken.None).ConfigureAwait(false)); Assert.AreEqual( (StatusCode)StatusCodes.BadCertificateUntrusted, (StatusCode)serviceResultException.StatusCode, diff --git a/Tests/Opc.Ua.Gds.Tests/ClientTest.cs b/Tests/Opc.Ua.Gds.Tests/ClientTest.cs index fdaba0dcc..cc357c6e1 100644 --- a/Tests/Opc.Ua.Gds.Tests/ClientTest.cs +++ b/Tests/Opc.Ua.Gds.Tests/ClientTest.cs @@ -887,13 +887,13 @@ public async Task FinishGoodNewKeyPairRequestsAsync() application, certificate, issuerCertificates); - X509TestUtils.VerifyApplicationCertIntegrity( + await X509TestUtils.VerifyApplicationCertIntegrityAsync( certificate, privateKey, application.PrivateKeyPassword, application.PrivateKeyFormat, issuerCertificates, - telemetry); + telemetry).ConfigureAwait(false); } else { @@ -925,22 +925,6 @@ public async Task FinishGoodNewKeyPairRequestsAsync() } while (requestBusy); } - [Test] - [Order(512)] - public async Task FinishInvalidNewKeyPairRequestsAsync() - { - AssertIgnoreTestWithoutInvalidRegistration(); - await ConnectGDSAsync(true).ConfigureAwait(false); - foreach (ApplicationTestData application in m_invalidApplicationTestSet) - { - await NUnit.Framework.Assert.ThatAsync( - () => m_gdsClient.GDSClient.FinishRequestAsync( - application.ApplicationRecord.ApplicationId, - new NodeId(Guid.NewGuid())), - Throws.Exception).ConfigureAwait(false); - } - } - [Test] [Order(520)] public async Task StartGoodSigningRequestsAsync() @@ -1016,13 +1000,13 @@ public async Task FinishGoodSigningRequestsAsync() application, certificate, issuerCertificates); - X509TestUtils.VerifyApplicationCertIntegrity( + await X509TestUtils.VerifyApplicationCertIntegrityAsync( certificate, application.PrivateKey, application.PrivateKeyPassword, application.PrivateKeyFormat, issuerCertificates, - telemetry); + telemetry).ConfigureAwait(false); } else { @@ -1369,13 +1353,13 @@ public async Task GoodSigningRequestAsSelfAdminAsync() application, certificate, issuerCertificates); - X509TestUtils.VerifyApplicationCertIntegrity( + await X509TestUtils.VerifyApplicationCertIntegrityAsync( certificate, application.PrivateKey, application.PrivateKeyPassword, application.PrivateKeyFormat, issuerCertificates, - telemetry); + telemetry).ConfigureAwait(false); } else { @@ -1487,13 +1471,13 @@ public async Task GoodKeyPairRequestAsSelfAdminAsync() application, certificate, issuerCertificates); - X509TestUtils.VerifyApplicationCertIntegrity( + await X509TestUtils.VerifyApplicationCertIntegrityAsync( certificate, privateKey, application.PrivateKeyPassword, application.PrivateKeyFormat, issuerCertificates, - telemetry); + telemetry).ConfigureAwait(false); } else { diff --git a/Tests/Opc.Ua.Gds.Tests/X509TestUtils.cs b/Tests/Opc.Ua.Gds.Tests/X509TestUtils.cs index a088af37c..18377052a 100644 --- a/Tests/Opc.Ua.Gds.Tests/X509TestUtils.cs +++ b/Tests/Opc.Ua.Gds.Tests/X509TestUtils.cs @@ -31,6 +31,8 @@ using System.Collections.Generic; using System.Linq; using System.Security.Cryptography.X509Certificates; +using System.Threading; +using System.Threading.Tasks; using NUnit.Framework; using Opc.Ua.Security.Certificates; using Assert = NUnit.Framework.Legacy.ClassicAssert; @@ -40,7 +42,7 @@ namespace Opc.Ua.Gds.Tests { public static class X509TestUtils { - public static void VerifyApplicationCertIntegrity( + public static async Task VerifyApplicationCertIntegrityAsync( byte[] certificate, byte[] privateKey, char[] privateKeyPassword, @@ -88,10 +90,10 @@ public static void VerifyApplicationCertIntegrity( TrustedCertificates = issuerCertIdCollection }; certValidator.Update(trustedStore, issuerStore, null); - NUnit.Framework.Assert.That(() => certValidator.Validate(newCert), Throws.Exception); + NUnit.Framework.Assert.That(async () => await certValidator.ValidateAsync(newCert, CancellationToken.None).ConfigureAwait(false), Throws.Exception); issuerStore.TrustedCertificates = issuerCertIdCollection; certValidator.Update(issuerStore, trustedStore, null); - certValidator.Validate(newCert); + await certValidator.ValidateAsync(newCert, CancellationToken.None).ConfigureAwait(false); } public static void VerifySignedApplicationCert(