From 14085bb92ada9cac4ffc386a8cc18414cfc3f0cb Mon Sep 17 00:00:00 2001 From: Marc Date: Thu, 12 Nov 2026 09:46:50 +0100 Subject: [PATCH 1/8] Notify certificate manager when GDS revokes a certificate RevokeCertificate and UnregisterApplication wrote the CRL to the stores but never raised CrlUpdated, so the trust material enforcement pump did not revalidate already open channels and sessions using the revoked certificate. --- .../ApplicationsNodeManager.cs | 60 +++++++++++++++++++ tests/Opc.Ua.Gds.Tests/ClientTest.cs | 15 +++++ 2 files changed, 75 insertions(+) diff --git a/src/Opc.Ua.Gds.Server/ApplicationsNodeManager.cs b/src/Opc.Ua.Gds.Server/ApplicationsNodeManager.cs index 779e0356c8..57af6d69a5 100644 --- a/src/Opc.Ua.Gds.Server/ApplicationsNodeManager.cs +++ b/src/Opc.Ua.Gds.Server/ApplicationsNodeManager.cs @@ -842,11 +842,63 @@ private async Task RevokeCertificateAsync( { m_logger.UnexpectedErrorRevokingCertificate(e, x509.Subject, certificateGroup.Id); } + + if (revoked) + { + NotifyRevocationListChanged(certificateGroup); + } } } return revoked; } + /// + /// Tells the server's certificate manager that a revocation wrote a + /// new CRL into the trust stores that the server itself validates + /// against. The manager drops its cached validation state and raises + /// , which drives the + /// trust-material enforcement of the configuration node manager: + /// SecureChannels and Sessions that present the revoked certificate + /// are revalidated and closed, instead of staying usable until they + /// are renewed. + /// + private void NotifyRevocationListChanged(ICertificateGroup certificateGroup) + { + ICertificateManager? certificateManager = m_configuration.CertificateManager; + if (certificateManager == null) + { + return; + } + + // The CRL always lands in the server's TrustedIssuerCertificates + // store, which backs the peer trust list. The HTTPS and user + // token groups additionally map to their own validation scopes. + var scopes = new List { TrustListIdentifier.Peers }; + if (certificateGroup.Id == m_defaultHttpsGroupId) + { + scopes.Add(TrustListIdentifier.Https); + } + else if (certificateGroup.Id == m_defaultUserTokenGroupId) + { + scopes.Add(TrustListIdentifier.Users); + } + + foreach (TrustListIdentifier scope in scopes) + { + try + { + certificateManager.NotifyTrustListChanged( + scope, + trustChanged: false, + crlChanged: true); + } + catch (Exception ex) + { + m_logger.RevocationNotificationFailed(ex, scope.ToString(), certificateGroup.Id); + } + } + } + /// /// Builds the issuer-certificate chain for a newly issued /// per OPC 10000-12 §7.6.6. @@ -3699,5 +3751,13 @@ public static partial void FinishRequestIssueFailed( Exception exception, NodeId requestId, [ApplicationIdentity] string? applicationUri); + + [LoggerMessage(EventId = GdsServerCommonEventIds.ApplicationsNodeManager + 22, Level = LogLevel.Error, + Message = "Failed to notify the {TrustList} trust list of the revocation in certificate group {CertificateGroupId}.")] + public static partial void RevocationNotificationFailed( + this ILogger logger, + Exception exception, + string trustList, + NodeId certificateGroupId); } } diff --git a/tests/Opc.Ua.Gds.Tests/ClientTest.cs b/tests/Opc.Ua.Gds.Tests/ClientTest.cs index b9ca2c2867..cd99f83115 100644 --- a/tests/Opc.Ua.Gds.Tests/ClientTest.cs +++ b/tests/Opc.Ua.Gds.Tests/ClientTest.cs @@ -35,6 +35,7 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; +using Moq; using NUnit.Framework; using Opc.Ua.Gds.Server; using Opc.Ua.Security.Certificates; @@ -1745,12 +1746,26 @@ public async Task RevokeGoodCertificatesAsync() AssertIgnoreTestWithoutInvalidRegistration(); AssertIgnoreTestWithoutGoodNewKeyPairRequest(); await ConnectGDSAsync(true).ConfigureAwait(false); + + // A revocation must reach the server's certificate manager so + // that already open channels and sessions using the revoked + // certificate are revalidated, not only new connections. + var crlUpdates = new Mock>(); + using IDisposable subscription = m_server.Config.CertificateManager.CertificateChanges + .Subscribe(crlUpdates.Object); + int revocations = 0; foreach (ApplicationTestData application in m_goodApplicationTestSet) { await m_gdsClient.GDSClient.RevokeCertificateAsync( application.ApplicationRecord.ApplicationId, application.Certificate.ToByteString()).ConfigureAwait(false); + revocations++; } + crlUpdates.Verify( + observer => observer.OnNext(It.Is(change => + change.Kind == CertificateChangeKind.CrlUpdated && + change.TrustList == TrustListIdentifier.Peers)), + Times.AtLeast(revocations)); foreach (ApplicationTestData application in m_invalidApplicationTestSet) { await Assert.ThatAsync( From 011031eb4459aec7adf519a79839fa2768724914 Mon Sep 17 00:00:00 2001 From: Marc Date: Thu, 12 Nov 2026 13:22:46 +0100 Subject: [PATCH 2/8] Fix scoped GDS certificate revocation --- .../ApplicationsNodeManager.cs | 93 ++++++++- .../CustomCertificateGroupIntegrationTest.cs | 196 +++++++++++++++++- .../GlobalDiscoveryTestServer.cs | 24 +++ ...pc.Ua.GlobalDiscoveryTestServer.Config.xml | 16 ++ 4 files changed, 321 insertions(+), 8 deletions(-) diff --git a/src/Opc.Ua.Gds.Server/ApplicationsNodeManager.cs b/src/Opc.Ua.Gds.Server/ApplicationsNodeManager.cs index 57af6d69a5..e717e11193 100644 --- a/src/Opc.Ua.Gds.Server/ApplicationsNodeManager.cs +++ b/src/Opc.Ua.Gds.Server/ApplicationsNodeManager.cs @@ -789,12 +789,11 @@ private NodeId GetTrustListId(NodeId certificateGroupId) return null; } - private ICertificateGroup? GetGroupForCertificate(ByteString certificate) + private ICertificateGroup? GetGroupForCertificate(ByteString certificate, NodeId certificateType) { if (certificate.Length > 0) { using var x509 = Certificate.FromRawData(certificate); - NodeId certificateType = CertificateIdentifier.GetCertificateType(x509); foreach (ICertificateGroup certificateGroup in m_certificateGroups.Values) { KeyValuePair matchingCert = certificateGroup @@ -818,12 +817,13 @@ private NodeId GetTrustListId(NodeId certificateGroupId) private async Task RevokeCertificateAsync( ByteString certificate, + NodeId certificateType, CancellationToken cancellationToken = default) { bool revoked = false; if (certificate.Length > 0) { - ICertificateGroup? certificateGroup = GetGroupForCertificate(certificate); + ICertificateGroup? certificateGroup = GetGroupForCertificate(certificate, certificateType); if (certificateGroup != null) { @@ -835,6 +835,9 @@ private async Task RevokeCertificateAsync( .ConfigureAwait(false); if (crl != null) { + await UpdateScopedIssuerCertificatesStoreAsync( + certificateGroup, + cancellationToken).ConfigureAwait(false); revoked = true; } } @@ -1030,10 +1033,91 @@ protected async Task InitializeCertificateGroupAsync( m_ownedCertificateGroups.Add(certificateGroup); await certificateGroup.InitAsync().ConfigureAwait(false); + await UpdateScopedIssuerCertificatesStoreAsync(certificateGroup) + .ConfigureAwait(false); return certificateGroup; } + private string? GetScopedIssuerCertificatesStorePath( + CertificateGroupConfiguration certificateGroupConfiguration) + { + SecurityConfiguration securityConfiguration = m_configuration.SecurityConfiguration; + if (string.Equals( + certificateGroupConfiguration.Id, + "DefaultHttpsGroup", + StringComparison.OrdinalIgnoreCase)) + { + return securityConfiguration.HttpsIssuerCertificates?.StorePath; + } + if (string.Equals( + certificateGroupConfiguration.Id, + "DefaultUserTokenGroup", + StringComparison.OrdinalIgnoreCase)) + { + return securityConfiguration.UserIssuerCertificates?.StorePath; + } + + return null; + } + + private async Task UpdateScopedIssuerCertificatesStoreAsync( + ICertificateGroup certificateGroup, + CancellationToken cancellationToken = default) + { + string? scopedIssuerStorePath = + GetScopedIssuerCertificatesStorePath(certificateGroup.Configuration); + if (string.IsNullOrEmpty(scopedIssuerStorePath) || + string.Equals( + scopedIssuerStorePath, + m_configuration.SecurityConfiguration.TrustedIssuerCertificates.StorePath, + StringComparison.Ordinal)) + { + return; + } + + using ICertificateStore authorityStore = certificateGroup.AuthoritiesStore.OpenStore(Server.Telemetry); + using ICertificateStore scopedIssuerStore = + new CertificateStoreIdentifier(scopedIssuerStorePath).OpenStore(Server.Telemetry); + + foreach (Certificate? certificate in certificateGroup.Certificates.Values) + { + if (certificate == null) + { + continue; + } + + using CertificateCollection storedCertificates = await scopedIssuerStore + .FindByThumbprintAsync(certificate.Thumbprint, cancellationToken) + .ConfigureAwait(false); + if (storedCertificates.Count == 0) + { + using var publicCertificate = Certificate.FromRawData(certificate.RawData); + await scopedIssuerStore.AddAsync(publicCertificate, ct: cancellationToken) + .ConfigureAwait(false); + } + + foreach (X509CRL crl in await scopedIssuerStore + .EnumerateCRLsAsync(certificate, false, cancellationToken) + .ConfigureAwait(false)) + { + if (crl.VerifySignature(certificate, false)) + { + await scopedIssuerStore.DeleteCRLAsync(crl, cancellationToken) + .ConfigureAwait(false); + } + } + + foreach (X509CRL crl in await authorityStore + .EnumerateCRLsAsync(certificate, true, cancellationToken) + .ConfigureAwait(false)) + { + await scopedIssuerStore.AddCRLAsync(crl, cancellationToken) + .ConfigureAwait(false); + } + } + } + /// /// The certificate types this GDS understands, by NodeId /// (OPC 10000-12 V1.04). @@ -1377,7 +1461,7 @@ private async ValueTask out ByteString certificate) && !certificate.IsEmpty) { - await RevokeCertificateAsync(certificate, cancellationToken) + await RevokeCertificateAsync(certificate, certType.Key, cancellationToken) .ConfigureAwait(false); } } @@ -1459,6 +1543,7 @@ private async ValueTask OnRevokeCertificateA revoked = await RevokeCertificateAsync( certificate, + certType.Key, cancellationToken).ConfigureAwait(false); if (revoked) { diff --git a/tests/Opc.Ua.Gds.Tests/CustomCertificateGroupIntegrationTest.cs b/tests/Opc.Ua.Gds.Tests/CustomCertificateGroupIntegrationTest.cs index f236501de9..17ffd872dc 100644 --- a/tests/Opc.Ua.Gds.Tests/CustomCertificateGroupIntegrationTest.cs +++ b/tests/Opc.Ua.Gds.Tests/CustomCertificateGroupIntegrationTest.cs @@ -27,13 +27,18 @@ * http://opcfoundation.org/License/MIT/1.00/ * ======================================================================*/ +using System; +using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; +using Moq; using NUnit.Framework; using Opc.Ua.Client; using Opc.Ua.Gds.Server; +using Opc.Ua.Security.Certificates; using Opc.Ua.Tests; +using Ua = Opc.Ua; namespace Opc.Ua.Gds.Tests { @@ -47,6 +52,8 @@ public class CustomCertificateGroupIntegrationTest { private const string kCustomGroupId = "MyCustomGroup"; private const string kCustomGroupSubjectName = "CN=GDS Custom CA, O=OPC Foundation"; + private const string kHttpsGroupSubjectName = "CN=GDS HTTPS CA, O=OPC Foundation"; + private const string kUserGroupSubjectName = "CN=GDS User CA, O=OPC Foundation"; private GlobalDiscoveryTestServer m_server; private GlobalDiscoveryTestClient m_gdsClient; @@ -71,10 +78,36 @@ public async Task OneTimeSetUpAsync() CACertificateKeySize = 4096, CACertificateHashSize = 512 }; + var httpsGroup = new CertificateGroupConfiguration + { + Id = "DefaultHttpsGroup", + CertificateTypes = [nameof(Ua.ObjectTypeIds.HttpsCertificateType)], + SubjectName = kHttpsGroupSubjectName, + BaseStorePath = Path.Combine(Path.GetTempPath(), "OPC", "GDS", "CA", "https"), + DefaultCertificateLifetime = 12, + DefaultCertificateKeySize = 2048, + DefaultCertificateHashSize = 256, + CACertificateLifetime = 60, + CACertificateKeySize = 4096, + CACertificateHashSize = 512 + }; + var userGroup = new CertificateGroupConfiguration + { + Id = "DefaultUserTokenGroup", + CertificateTypes = [nameof(Ua.ObjectTypeIds.UserCertificateType)], + SubjectName = kUserGroupSubjectName, + BaseStorePath = Path.Combine(Path.GetTempPath(), "OPC", "GDS", "CA", "users"), + DefaultCertificateLifetime = 12, + DefaultCertificateKeySize = 2048, + DefaultCertificateHashSize = 256, + CACertificateLifetime = 60, + CACertificateKeySize = 4096, + CACertificateHashSize = 512 + }; m_server = await TestUtils.StartGDSAsync( clean: true, - additionalCertGroups: [customGroup]).ConfigureAwait(false); + additionalCertGroups: [customGroup, httpsGroup, userGroup]).ConfigureAwait(false); m_gdsClient = new GlobalDiscoveryTestClient(true, m_telemetry); await m_gdsClient.LoadClientConfigurationAsync(m_server.BasePort).ConfigureAwait(false); @@ -120,14 +153,14 @@ public async Task CustomCertificateGroupAppearsInGetCertificateGroupsAsync() Assert.That(appId.IsNull, Is.False); - // GetCertificateGroups should return both the default group and the custom group + // GetCertificateGroups should return the default groups and the custom group. ArrayOf groups = await m_gdsClient.GDSClient .GetCertificateGroupsAsync(appId) .ConfigureAwait(false); Assert.That(groups.IsNull, Is.False); - Assert.That(groups.Count, Is.EqualTo(2), - "Expected 2 certificate groups: default + custom"); + Assert.That(groups.Count, Is.EqualTo(4), + "Expected 4 certificate groups: default, HTTPS, user-token, and custom"); // Verify that each group's TrustList is accessible foreach (NodeId groupId in groups.ToList()) @@ -255,5 +288,160 @@ public async Task DefaultApplicationGroupAdvertisesConfiguredCertificateTypesAsy await m_gdsClient.GDSClient.DisconnectAsync().ConfigureAwait(false); } } + + [Test] + public async Task RevokingHttpsAndUserCertificatesUpdatesTheirIssuerStoresAndNotifiesScopesAsync() + { + m_gdsClient.GDSClient.AdminCredentials = m_gdsClient.AdminUser; + await m_gdsClient.GDSClient.ConnectAsync().ConfigureAwait(false); + + var issuerStores = new[] + { + m_server.Config.SecurityConfiguration.TrustedIssuerCertificates, + m_server.Config.SecurityConfiguration.HttpsIssuerCertificates!, + m_server.Config.SecurityConfiguration.UserIssuerCertificates! + }; + Assert.That( + issuerStores.Select(store => Path.GetFullPath(store.StorePath!)).Distinct().Count(), + Is.EqualTo(issuerStores.Length), + "Peer, HTTPS, and user-token issuer stores must be distinct."); + + try + { + var appTestDataGenerator = new ApplicationTestDataGenerator(3, m_telemetry); + ApplicationTestData appData = appTestDataGenerator.ApplicationTestSet(1, false)[0]; + appData.ApplicationRecord.ApplicationType = ApplicationType.Server; + appData.ApplicationRecord.DiscoveryUrls = ["https://localhost:4843"]; + NodeId appId = await m_gdsClient.GDSClient + .RegisterApplicationAsync(appData.ApplicationRecord) + .ConfigureAwait(false); + + var revocationCases = new[] + { + ( + GroupId: "DefaultHttpsGroup", + CertificateType: Ua.ObjectTypeIds.HttpsCertificateType, + Scope: TrustListIdentifier.Https), + ( + GroupId: "DefaultUserTokenGroup", + CertificateType: Ua.ObjectTypeIds.UserCertificateType, + Scope: TrustListIdentifier.Users) + }; + + foreach ((string groupId, NodeId certificateType, TrustListIdentifier scope) in revocationCases) + { + NodeId certificateGroupId = GetCertificateGroupId(groupId); + NodeId requestId = await m_gdsClient.GDSClient.StartNewKeyPairRequestAsync( + appId, + certificateGroupId, + certificateType, + appData.Subject, + appData.DomainNames, + appData.PrivateKeyFormat, + appData.PrivateKeyPassword).ConfigureAwait(false); + + (Certificate certificate, Certificate issuer) = + await FinishRequestAsync(appId, requestId).ConfigureAwait(false); + try + { + var observer = new Mock>(); + using IDisposable subscription = m_server.Config.CertificateManager.CertificateChanges + .Subscribe(observer.Object); + + await m_gdsClient.GDSClient + .RevokeCertificateAsync(appId, ByteString.From(certificate.RawData)) + .ConfigureAwait(false); + + observer.Verify( + item => item.OnNext(It.Is( + change => change.Kind == CertificateChangeKind.CrlUpdated && + change.TrustList == TrustListIdentifier.Peers)), + Times.Once); + observer.Verify( + item => item.OnNext(It.Is( + change => change.Kind == CertificateChangeKind.CrlUpdated && + change.TrustList == scope)), + Times.Once); + + await AssertRevocationCrlExistsAsync( + TrustListIdentifier.Peers, + issuer, + certificate) + .ConfigureAwait(false); + await AssertRevocationCrlExistsAsync(scope, issuer, certificate).ConfigureAwait(false); + } + finally + { + certificate.Dispose(); + issuer.Dispose(); + } + } + + await m_gdsClient.GDSClient.UnregisterApplicationAsync(appId).ConfigureAwait(false); + } + finally + { + await m_gdsClient.GDSClient.DisconnectAsync().ConfigureAwait(false); + } + } + + /// + /// Resolves a predefined certificate group using the active GDS session namespace table. + /// + private NodeId GetCertificateGroupId(string groupId) + { + return groupId switch + { + "DefaultHttpsGroup" => ExpandedNodeId.ToNodeId( + ObjectIds.Directory_CertificateGroups_DefaultHttpsGroup, + m_gdsClient.GDSClient.Session!.NamespaceUris), + "DefaultUserTokenGroup" => ExpandedNodeId.ToNodeId( + ObjectIds.Directory_CertificateGroups_DefaultUserTokenGroup, + m_gdsClient.GDSClient.Session!.NamespaceUris), + _ => throw new ArgumentOutOfRangeException(nameof(groupId)) + }; + } + + /// + /// Waits for the GDS to finish issuing a certificate for the request. + /// + private async Task<(Certificate certificate, Certificate issuer)> FinishRequestAsync( + NodeId appId, + NodeId requestId) + { + DateTime deadline = DateTime.UtcNow.AddMinutes(5); + while (DateTime.UtcNow < deadline) + { + (ByteString certificate, _, ArrayOf issuerCertificates) = await m_gdsClient.GDSClient + .FinishRequestAsync(appId, requestId).ConfigureAwait(false); + if (!certificate.IsEmpty) + { + return ( + Certificate.FromRawData(certificate), + Certificate.FromRawData(issuerCertificates[0])); + } + await Task.Delay(1000).ConfigureAwait(false); + } + + throw new TimeoutException("Timed out waiting for the GDS certificate request to finish."); + } + + /// + /// Verifies that an issuer store contains the CRL for a revoked certificate. + /// + private async Task AssertRevocationCrlExistsAsync( + TrustListIdentifier scope, + Certificate issuer, + Certificate certificate) + { + using ICertificateStore issuerStore = m_server.Config.CertificateManager.OpenIssuerStore(scope)!; + X509CRLCollection crls = await issuerStore + .EnumerateCRLsAsync(issuer).ConfigureAwait(false); + Assert.That(crls, Has.Count.EqualTo(1), $"Expected a CRL in the {scope} issuer store."); + Assert.That(crls[0].RevokedCertificates, Has.Count.EqualTo(1)); + Assert.That( + crls[0].RevokedCertificates[0].UserCertificate, + Is.EqualTo(certificate.GetSerialNumber())); + } } } diff --git a/tests/Opc.Ua.Gds.Tests/GlobalDiscoveryTestServer.cs b/tests/Opc.Ua.Gds.Tests/GlobalDiscoveryTestServer.cs index 6295d7066f..4fc7992f63 100644 --- a/tests/Opc.Ua.Gds.Tests/GlobalDiscoveryTestServer.cs +++ b/tests/Opc.Ua.Gds.Tests/GlobalDiscoveryTestServer.cs @@ -130,10 +130,34 @@ await TestUtils .CleanupTrustListAsync( Config.SecurityConfiguration.TrustedIssuerCertificates, m_telemetry) .ConfigureAwait(false); + if (Config.SecurityConfiguration.UserIssuerCertificates != null) + { + await TestUtils.CleanupTrustListAsync( + Config.SecurityConfiguration.UserIssuerCertificates, + m_telemetry).ConfigureAwait(false); + } + if (Config.SecurityConfiguration.HttpsIssuerCertificates != null) + { + await TestUtils.CleanupTrustListAsync( + Config.SecurityConfiguration.HttpsIssuerCertificates, + m_telemetry).ConfigureAwait(false); + } await TestUtils .CleanupTrustListAsync( Config.SecurityConfiguration.TrustedPeerCertificates, m_telemetry) .ConfigureAwait(false); + if (Config.SecurityConfiguration.TrustedUserCertificates != null) + { + await TestUtils.CleanupTrustListAsync( + Config.SecurityConfiguration.TrustedUserCertificates, + m_telemetry).ConfigureAwait(false); + } + if (Config.SecurityConfiguration.TrustedHttpsCertificates != null) + { + await TestUtils.CleanupTrustListAsync( + Config.SecurityConfiguration.TrustedHttpsCertificates, + m_telemetry).ConfigureAwait(false); + } await TestUtils .CleanupTrustListAsync( Config.SecurityConfiguration.RejectedCertificateStore!, m_telemetry) diff --git a/tests/Opc.Ua.Gds.Tests/Opc.Ua.GlobalDiscoveryTestServer.Config.xml b/tests/Opc.Ua.Gds.Tests/Opc.Ua.GlobalDiscoveryTestServer.Config.xml index 179036f953..64092ea6bb 100644 --- a/tests/Opc.Ua.Gds.Tests/Opc.Ua.GlobalDiscoveryTestServer.Config.xml +++ b/tests/Opc.Ua.Gds.Tests/Opc.Ua.GlobalDiscoveryTestServer.Config.xml @@ -49,6 +49,22 @@ Directory %LocalApplicationData%/OPC/GDS/trusted + + Directory + %LocalApplicationData%/OPC/GDS/trustedUsers + + + Directory + %LocalApplicationData%/OPC/GDS/userIssuers + + + Directory + %LocalApplicationData%/OPC/GDS/trustedHttps + + + Directory + %LocalApplicationData%/OPC/GDS/httpsIssuers + Directory %LocalApplicationData%/OPC/GDS/rejected From 7281329d2ae744bbcd888d131767a5c53a8201a2 Mon Sep 17 00:00:00 2001 From: Marc Date: Thu, 12 Nov 2026 14:46:06 +0100 Subject: [PATCH 3/8] Harden scoped GDS revocation updates --- .../ApplicationsNodeManager.cs | 186 ++++++++--- .../CustomCertificateGroupIntegrationTest.cs | 297 +++++++++++++++++- .../GlobalDiscoveryTestServer.cs | 3 + 3 files changed, 427 insertions(+), 59 deletions(-) diff --git a/src/Opc.Ua.Gds.Server/ApplicationsNodeManager.cs b/src/Opc.Ua.Gds.Server/ApplicationsNodeManager.cs index e717e11193..aa4682d611 100644 --- a/src/Opc.Ua.Gds.Server/ApplicationsNodeManager.cs +++ b/src/Opc.Ua.Gds.Server/ApplicationsNodeManager.cs @@ -828,27 +828,57 @@ private async Task RevokeCertificateAsync( if (certificateGroup != null) { using var x509 = Certificate.FromRawData(certificate); + X509CRL? crl; try { - X509CRL crl = await certificateGroup + crl = await certificateGroup .RevokeCertificateAsync(x509, cancellationToken) .ConfigureAwait(false); - if (crl != null) - { - await UpdateScopedIssuerCertificatesStoreAsync( - certificateGroup, - cancellationToken).ConfigureAwait(false); - revoked = true; - } } catch (Exception e) { m_logger.UnexpectedErrorRevokingCertificate(e, x509.Subject, certificateGroup.Id); + return false; } - if (revoked) + if (crl != null) { - NotifyRevocationListChanged(certificateGroup); + revoked = true; + NotifyRevocationListChanged( + TrustListIdentifier.Peers, + certificateGroup); + + TrustListIdentifier? scopedTrustList = + GetScopedTrustListIdentifier(certificateGroup); + if (scopedTrustList != null) + { + try + { + if (await UpdateScopedIssuerCertificatesStoreAsync( + certificateGroup, + cancellationToken).ConfigureAwait(false)) + { + NotifyRevocationListChanged( + scopedTrustList, + certificateGroup); + } + } + catch (Exception ex) + { + m_logger.RevocationScopeStoreUpdateFailed( + ex, + scopedTrustList.ToString(), + certificateGroup.Id); + if (ex is OperationCanceledException && cancellationToken.IsCancellationRequested) + { + throw; + } + throw new ServiceResultException( + StatusCodes.BadUnexpectedError, + $"The certificate was revoked, but the {scopedTrustList} issuer store could not be updated.", + ex); + } + } } } } @@ -865,7 +895,9 @@ await UpdateScopedIssuerCertificatesStoreAsync( /// are revalidated and closed, instead of staying usable until they /// are renewed. /// - private void NotifyRevocationListChanged(ICertificateGroup certificateGroup) + private void NotifyRevocationListChanged( + TrustListIdentifier scope, + ICertificateGroup certificateGroup) { ICertificateManager? certificateManager = m_configuration.CertificateManager; if (certificateManager == null) @@ -873,32 +905,16 @@ private void NotifyRevocationListChanged(ICertificateGroup certificateGroup) return; } - // The CRL always lands in the server's TrustedIssuerCertificates - // store, which backs the peer trust list. The HTTPS and user - // token groups additionally map to their own validation scopes. - var scopes = new List { TrustListIdentifier.Peers }; - if (certificateGroup.Id == m_defaultHttpsGroupId) - { - scopes.Add(TrustListIdentifier.Https); - } - else if (certificateGroup.Id == m_defaultUserTokenGroupId) + try { - scopes.Add(TrustListIdentifier.Users); + certificateManager.NotifyTrustListChanged( + scope, + trustChanged: false, + crlChanged: true); } - - foreach (TrustListIdentifier scope in scopes) + catch (Exception ex) { - try - { - certificateManager.NotifyTrustListChanged( - scope, - trustChanged: false, - crlChanged: true); - } - catch (Exception ex) - { - m_logger.RevocationNotificationFailed(ex, scope.ToString(), certificateGroup.Id); - } + m_logger.RevocationNotificationFailed(ex, scope.ToString(), certificateGroup.Id); } } @@ -1022,10 +1038,12 @@ protected async Task InitializeCertificateGroupAsync( "BaseStorePath not specified"); } + CertificateStoreIdentifier peerIssuerStore = + m_configuration.SecurityConfiguration.TrustedIssuerCertificates; ICertificateGroup certificateGroup = m_certificateGroupFactory.Create( m_globalDiscoveryServerConfiguration.AuthoritiesStorePath!, certificateGroupConfiguration, - m_configuration.SecurityConfiguration.TrustedIssuerCertificates.StorePath); + peerIssuerStore.StorePath); // Take ownership before the first call that can throw: InitAsync // opens certificate stores, so a group that fails half way through @@ -1039,7 +1057,7 @@ await UpdateScopedIssuerCertificatesStoreAsync(certificateGroup) return certificateGroup; } - private string? GetScopedIssuerCertificatesStorePath( + private CertificateTrustList? GetScopedIssuerCertificatesStore( CertificateGroupConfiguration certificateGroupConfiguration) { SecurityConfiguration securityConfiguration = m_configuration.SecurityConfiguration; @@ -1048,41 +1066,67 @@ await UpdateScopedIssuerCertificatesStoreAsync(certificateGroup) "DefaultHttpsGroup", StringComparison.OrdinalIgnoreCase)) { - return securityConfiguration.HttpsIssuerCertificates?.StorePath; + return securityConfiguration.HttpsIssuerCertificates; } if (string.Equals( certificateGroupConfiguration.Id, "DefaultUserTokenGroup", StringComparison.OrdinalIgnoreCase)) { - return securityConfiguration.UserIssuerCertificates?.StorePath; + return securityConfiguration.UserIssuerCertificates; } return null; } - private async Task UpdateScopedIssuerCertificatesStoreAsync( + private TrustListIdentifier? GetScopedTrustListIdentifier(ICertificateGroup certificateGroup) + { + if (certificateGroup.Id == m_defaultHttpsGroupId) + { + return TrustListIdentifier.Https; + } + if (certificateGroup.Id == m_defaultUserTokenGroupId) + { + return TrustListIdentifier.Users; + } + + return null; + } + + private async Task UpdateScopedIssuerCertificatesStoreAsync( ICertificateGroup certificateGroup, CancellationToken cancellationToken = default) { - string? scopedIssuerStorePath = - GetScopedIssuerCertificatesStorePath(certificateGroup.Configuration); - if (string.IsNullOrEmpty(scopedIssuerStorePath) || - string.Equals( - scopedIssuerStorePath, - m_configuration.SecurityConfiguration.TrustedIssuerCertificates.StorePath, - StringComparison.Ordinal)) + CertificateStoreIdentifier? scopedIssuerStoreIdentifier = + GetScopedIssuerCertificatesStore(certificateGroup.Configuration); + if (scopedIssuerStoreIdentifier == null || + string.IsNullOrEmpty(scopedIssuerStoreIdentifier.StorePath)) { - return; + return false; + } + + CertificateStoreIdentifier peerIssuerStoreIdentifier = + m_configuration.SecurityConfiguration.TrustedIssuerCertificates; + if (IsSameStore(scopedIssuerStoreIdentifier, peerIssuerStoreIdentifier)) + { + return true; } using ICertificateStore authorityStore = certificateGroup.AuthoritiesStore.OpenStore(Server.Telemetry); - using ICertificateStore scopedIssuerStore = - new CertificateStoreIdentifier(scopedIssuerStorePath).OpenStore(Server.Telemetry); + using ICertificateStore scopedIssuerStore = OpenCertificateStore(scopedIssuerStoreIdentifier); + using CertificateCollection authorities = await authorityStore + .EnumerateAsync(cancellationToken) + .ConfigureAwait(false); + string authoritySubject = certificateGroup.Certificates.Values + .FirstOrDefault(static certificate => certificate != null)?.Subject + ?? certificateGroup.Configuration.SubjectName! + .Replace("localhost", Utils.GetHostName(), StringComparison.Ordinal); - foreach (Certificate? certificate in certificateGroup.Certificates.Values) + foreach (Certificate certificate in authorities) { - if (certificate == null) + if (!X509Utils.CompareDistinguishedName( + certificate.Subject, + authoritySubject)) { continue; } @@ -1116,6 +1160,38 @@ await scopedIssuerStore.AddCRLAsync(crl, cancellationToken) .ConfigureAwait(false); } } + + return true; + } + + private ICertificateStore OpenCertificateStore(CertificateStoreIdentifier storeIdentifier) + { + if (m_configuration.CertificateManager is ICertificateStoreResolver storeResolver) + { + return storeResolver.OpenCertificateStore( + storeIdentifier.StorePath!, + storeIdentifier.StoreType); + } + + return storeIdentifier.OpenStore(Server.Telemetry); + } + + private static bool IsSameStore( + CertificateStoreIdentifier first, + CertificateStoreIdentifier second) + { + return string.Equals(first.StorePath, second.StorePath, StringComparison.Ordinal) && + string.Equals( + ResolveStoreType(first), + ResolveStoreType(second), + StringComparison.OrdinalIgnoreCase); + } + + private static string ResolveStoreType(CertificateStoreIdentifier storeIdentifier) + { + return string.IsNullOrEmpty(storeIdentifier.StoreType) + ? CertificateStoreIdentifier.DetermineStoreType(storeIdentifier.StorePath!) + : storeIdentifier.StoreType; } /// @@ -3844,5 +3920,13 @@ public static partial void RevocationNotificationFailed( Exception exception, string trustList, NodeId certificateGroupId); + + [LoggerMessage(EventId = GdsServerCommonEventIds.ApplicationsNodeManager + 23, Level = LogLevel.Error, + Message = "Failed to persist the revocation CRL to the {TrustList} issuer store for certificate group {CertificateGroupId}.")] + public static partial void RevocationScopeStoreUpdateFailed( + this ILogger logger, + Exception exception, + string trustList, + NodeId certificateGroupId); } } diff --git a/tests/Opc.Ua.Gds.Tests/CustomCertificateGroupIntegrationTest.cs b/tests/Opc.Ua.Gds.Tests/CustomCertificateGroupIntegrationTest.cs index 17ffd872dc..95110d017f 100644 --- a/tests/Opc.Ua.Gds.Tests/CustomCertificateGroupIntegrationTest.cs +++ b/tests/Opc.Ua.Gds.Tests/CustomCertificateGroupIntegrationTest.cs @@ -51,6 +51,7 @@ namespace Opc.Ua.Gds.Tests public class CustomCertificateGroupIntegrationTest { private const string kCustomGroupId = "MyCustomGroup"; + private const string kTestDirectoryStoreType = "GdsTestDirectory"; private const string kCustomGroupSubjectName = "CN=GDS Custom CA, O=OPC Foundation"; private const string kHttpsGroupSubjectName = "CN=GDS HTTPS CA, O=OPC Foundation"; private const string kUserGroupSubjectName = "CN=GDS User CA, O=OPC Foundation"; @@ -292,13 +293,15 @@ public async Task DefaultApplicationGroupAdvertisesConfiguredCertificateTypesAsy [Test] public async Task RevokingHttpsAndUserCertificatesUpdatesTheirIssuerStoresAndNotifiesScopesAsync() { - m_gdsClient.GDSClient.AdminCredentials = m_gdsClient.AdminUser; - await m_gdsClient.GDSClient.ConnectAsync().ConfigureAwait(false); - + ICertificateManager originalCertificateManager = m_server.Config.CertificateManager; + CertificateTrustList httpsIssuerStore = + m_server.Config.SecurityConfiguration.HttpsIssuerCertificates!; + string? originalHttpsStorePath = httpsIssuerStore.StorePath; + string? originalHttpsStoreType = httpsIssuerStore.StoreType; var issuerStores = new[] { m_server.Config.SecurityConfiguration.TrustedIssuerCertificates, - m_server.Config.SecurityConfiguration.HttpsIssuerCertificates!, + httpsIssuerStore, m_server.Config.SecurityConfiguration.UserIssuerCertificates! }; Assert.That( @@ -308,6 +311,17 @@ public async Task RevokingHttpsAndUserCertificatesUpdatesTheirIssuerStoresAndNot try { + httpsIssuerStore.StoreType = kTestDirectoryStoreType; + var storeProvider = new TestDirectoryCertificateStoreProvider(); + using CertificateManager testCertificateManager = CertificateManagerFactory.Create( + m_server.Config.SecurityConfiguration, + m_telemetry, + options => options.AddStoreProvider(storeProvider)); + m_server.Config.CertificateManager = testCertificateManager; + + m_gdsClient.GDSClient.AdminCredentials = m_gdsClient.AdminUser; + await m_gdsClient.GDSClient.ConnectAsync().ConfigureAwait(false); + var appTestDataGenerator = new ApplicationTestDataGenerator(3, m_telemetry); ApplicationTestData appData = appTestDataGenerator.ApplicationTestSet(1, false)[0]; appData.ApplicationRecord.ApplicationType = ApplicationType.Server; @@ -377,6 +391,246 @@ await AssertRevocationCrlExistsAsync( } } + int storeCreationsBeforeCancellation = storeProvider.CreateStoreCount; + httpsIssuerStore.StorePath = + m_server.Config.SecurityConfiguration.TrustedIssuerCertificates.StorePath; + NodeId cancelledRequestId = await m_gdsClient.GDSClient.StartNewKeyPairRequestAsync( + appId, + GetCertificateGroupId("DefaultHttpsGroup"), + Ua.ObjectTypeIds.HttpsCertificateType, + appData.Subject, + appData.DomainNames, + appData.PrivateKeyFormat, + appData.PrivateKeyPassword).ConfigureAwait(false); + (Certificate cancelledCertificate, Certificate cancelledIssuer) = + await FinishRequestAsync(appId, cancelledRequestId).ConfigureAwait(false); + try + { + storeProvider.CancelNextStoreCreation = true; + var observer = new Mock>(); + using IDisposable subscription = m_server.Config.CertificateManager.CertificateChanges + .Subscribe(observer.Object); + + ServiceResultException scopedStoreCancellation = await Assert.ThrowsAsync( + async () => await m_gdsClient.GDSClient + .RevokeCertificateAsync(appId, ByteString.From(cancelledCertificate.RawData)) + .ConfigureAwait(false)); + Assert.That( + scopedStoreCancellation.StatusCode, + Is.EqualTo(StatusCodes.BadUnexpectedError)); + + observer.Verify( + item => item.OnNext(It.Is( + change => change.Kind == CertificateChangeKind.CrlUpdated && + change.TrustList == TrustListIdentifier.Peers)), + Times.Once); + observer.Verify( + item => item.OnNext(It.Is( + change => change.Kind == CertificateChangeKind.CrlUpdated && + change.TrustList == TrustListIdentifier.Https)), + Times.Never); + await AssertRevocationCrlExistsAsync( + TrustListIdentifier.Peers, + cancelledIssuer, + cancelledCertificate).ConfigureAwait(false); + } + finally + { + cancelledCertificate.Dispose(); + cancelledIssuer.Dispose(); + httpsIssuerStore.StorePath = originalHttpsStorePath; + } + + Assert.That( + storeProvider.CreateStoreCount, + Is.GreaterThan(storeCreationsBeforeCancellation), + "The distinct HTTPS store and the same-path, different-type store must use the injected provider."); + Assert.That( + storeProvider.CancelNextStoreCreation, + Is.False, + "The configured provider must be invoked when the scoped store is updated."); + + await m_gdsClient.GDSClient.UnregisterApplicationAsync(appId).ConfigureAwait(false); + } + finally + { + await m_gdsClient.GDSClient.DisconnectAsync().ConfigureAwait(false); + m_server.Config.CertificateManager = originalCertificateManager; + httpsIssuerStore.StorePath = originalHttpsStorePath; + httpsIssuerStore.StoreType = originalHttpsStoreType; + } + } + + [Test] + public async Task FailedScopedStoreUpdateStillNotifiesPeersAndDoesNotReportInvalidArgumentAsync() + { + m_gdsClient.GDSClient.AdminCredentials = m_gdsClient.AdminUser; + await m_gdsClient.GDSClient.ConnectAsync().ConfigureAwait(false); + + string originalStorePath = + m_server.Config.SecurityConfiguration.HttpsIssuerCertificates!.StorePath!; + string failingStorePath = typeof(CustomCertificateGroupIntegrationTest).Assembly.Location; + + try + { + var appTestDataGenerator = new ApplicationTestDataGenerator(1, m_telemetry); + ApplicationTestData appData = appTestDataGenerator.ApplicationTestSet(1, false)[0]; + appData.ApplicationRecord.ApplicationType = ApplicationType.Server; + appData.ApplicationRecord.DiscoveryUrls = ["https://localhost:4843"]; + NodeId appId = await m_gdsClient.GDSClient + .RegisterApplicationAsync(appData.ApplicationRecord) + .ConfigureAwait(false); + + NodeId requestId = await m_gdsClient.GDSClient.StartNewKeyPairRequestAsync( + appId, + GetCertificateGroupId("DefaultHttpsGroup"), + Ua.ObjectTypeIds.HttpsCertificateType, + appData.Subject, + appData.DomainNames, + appData.PrivateKeyFormat, + appData.PrivateKeyPassword).ConfigureAwait(false); + (Certificate certificate, Certificate issuer) = + await FinishRequestAsync(appId, requestId).ConfigureAwait(false); + + try + { + m_server.Config.SecurityConfiguration.HttpsIssuerCertificates!.StorePath = + failingStorePath; + var observer = new Mock>(); + using IDisposable subscription = m_server.Config.CertificateManager.CertificateChanges + .Subscribe(observer.Object); + + ServiceResultException scopedStoreFailure = await Assert.ThrowsAsync( + async () => await m_gdsClient.GDSClient + .RevokeCertificateAsync(appId, ByteString.From(certificate.RawData)) + .ConfigureAwait(false)); + Assert.That( + scopedStoreFailure.StatusCode, + Is.EqualTo(StatusCodes.BadUnexpectedError)); + + observer.Verify( + item => item.OnNext(It.Is( + change => change.Kind == CertificateChangeKind.CrlUpdated && + change.TrustList == TrustListIdentifier.Peers)), + Times.Once); + observer.Verify( + item => item.OnNext(It.Is( + change => change.Kind == CertificateChangeKind.CrlUpdated && + change.TrustList == TrustListIdentifier.Https)), + Times.Never); + await AssertRevocationCrlExistsAsync( + TrustListIdentifier.Peers, + issuer, + certificate).ConfigureAwait(false); + } + finally + { + certificate.Dispose(); + issuer.Dispose(); + m_server.Config.SecurityConfiguration.HttpsIssuerCertificates!.StorePath = + originalStorePath; + } + + await m_gdsClient.GDSClient.UnregisterApplicationAsync(appId).ConfigureAwait(false); + } + finally + { + m_server.Config.SecurityConfiguration.HttpsIssuerCertificates!.StorePath = originalStorePath; + await m_gdsClient.GDSClient.DisconnectAsync().ConfigureAwait(false); + } + } + + [Test] + public async Task RevokingHttpsAndUserCertificatesMirrorsHistoricalIssuerCrlsAsync() + { + m_gdsClient.GDSClient.AdminCredentials = m_gdsClient.AdminUser; + await m_gdsClient.GDSClient.ConnectAsync().ConfigureAwait(false); + + try + { + var appTestDataGenerator = new ApplicationTestDataGenerator(2, m_telemetry); + ApplicationTestData appData = appTestDataGenerator.ApplicationTestSet(1, false)[0]; + appData.ApplicationRecord.ApplicationType = ApplicationType.Server; + appData.ApplicationRecord.DiscoveryUrls = ["https://localhost:4843"]; + NodeId appId = await m_gdsClient.GDSClient + .RegisterApplicationAsync(appData.ApplicationRecord) + .ConfigureAwait(false); + + GlobalDiscoveryServerConfiguration gdsConfiguration = + m_server.Config.ParseExtension()!; + foreach ((TrustListIdentifier scope, string subjectName, string certificateTypeName) in + new[] + { + ( + TrustListIdentifier.Https, + kHttpsGroupSubjectName, + "HttpsCertificateType"), + ( + TrustListIdentifier.Users, + kUserGroupSubjectName, + "UserCertificateType") + }) + { + using Certificate historicalIssuer = CertificateBuilder.Create(subjectName) + .SetCAConstraint() + .CreateForRSA(); + using Certificate revokedByHistoricalIssuer = CertificateBuilder.Create("CN=Historical Issuer Test") + .SetIssuer(historicalIssuer) + .CreateForRSA(); + using Certificate previouslyRevokedByHistoricalIssuer = + CertificateBuilder.Create("CN=Previously Revoked Test") + .SetIssuer(historicalIssuer) + .CreateForRSA(); + var authoritiesStoreIdentifier = new CertificateStoreIdentifier( + gdsConfiguration!.AuthoritiesStorePath!, + noPrivateKeys: false); + using ICertificateStore authoritiesStore = + authoritiesStoreIdentifier.OpenStore(m_telemetry); + await authoritiesStore.AddAsync(historicalIssuer).ConfigureAwait(false); + X509CRL staleCrl = await CertificateGroup.RevokeCertificateAsync( + authoritiesStoreIdentifier, + previouslyRevokedByHistoricalIssuer, + issuerKeyFilePassword: null, + telemetry: m_telemetry).ConfigureAwait(false); + + using ICertificateStore scopedIssuerStore = + m_server.Config.CertificateManager.OpenIssuerStore(scope)!; + using Certificate publicHistoricalIssuer = + Certificate.FromRawData(historicalIssuer.RawData); + await scopedIssuerStore.AddAsync(publicHistoricalIssuer).ConfigureAwait(false); + await scopedIssuerStore.AddCRLAsync(staleCrl).ConfigureAwait(false); + + Assert.That( + m_server.ApplicationsDatabase.SetApplicationCertificate( + appId, + certificateTypeName, + ByteString.From(revokedByHistoricalIssuer.RawData)), + Is.True); + + await m_gdsClient.GDSClient + .RevokeCertificateAsync( + appId, + ByteString.From(revokedByHistoricalIssuer.RawData)) + .ConfigureAwait(false); + + using CertificateCollection copiedIssuer = await scopedIssuerStore + .FindByThumbprintAsync(historicalIssuer.Thumbprint).ConfigureAwait(false); + Assert.That(copiedIssuer, Is.Not.Empty); + X509CRLCollection historicalCrls = await scopedIssuerStore + .EnumerateCRLsAsync(historicalIssuer).ConfigureAwait(false); + Assert.That(historicalCrls, Has.Count.EqualTo(1)); + Assert.That( + historicalCrls[0].RevokedCertificates.Any( + entry => entry.UserCertificate.SequenceEqual( + previouslyRevokedByHistoricalIssuer.GetSerialNumber())), + Is.True); + Assert.That( + historicalCrls[0].RevokedCertificates.Any( + entry => entry.UserCertificate.SequenceEqual( + revokedByHistoricalIssuer.GetSerialNumber())), + Is.True); + } + await m_gdsClient.GDSClient.UnregisterApplicationAsync(appId).ConfigureAwait(false); } finally @@ -437,11 +691,38 @@ private async Task AssertRevocationCrlExistsAsync( using ICertificateStore issuerStore = m_server.Config.CertificateManager.OpenIssuerStore(scope)!; X509CRLCollection crls = await issuerStore .EnumerateCRLsAsync(issuer).ConfigureAwait(false); - Assert.That(crls, Has.Count.EqualTo(1), $"Expected a CRL in the {scope} issuer store."); - Assert.That(crls[0].RevokedCertificates, Has.Count.EqualTo(1)); Assert.That( - crls[0].RevokedCertificates[0].UserCertificate, - Is.EqualTo(certificate.GetSerialNumber())); + crls.Any(crl => crl.RevokedCertificates.Any( + revoked => revoked.UserCertificate.SequenceEqual(certificate.GetSerialNumber()))), + Is.True, + $"Expected a CRL revoking the certificate in the {scope} issuer store."); + } + + private sealed class TestDirectoryCertificateStoreProvider : ICertificateStoreProvider + { + private readonly DirectoryStoreProvider m_directoryStoreProvider = new(); + + public string StoreTypeName => kTestDirectoryStoreType; + + public int CreateStoreCount { get; private set; } + + public bool CancelNextStoreCreation { get; set; } + + public bool SupportsStorePath(string storePath) + { + return false; + } + + public ICertificateStore CreateStore(ITelemetryContext telemetry) + { + CreateStoreCount++; + if (CancelNextStoreCreation) + { + CancelNextStoreCreation = false; + throw new OperationCanceledException("Cancelled test store open."); + } + return m_directoryStoreProvider.CreateStore(telemetry); + } } } } diff --git a/tests/Opc.Ua.Gds.Tests/GlobalDiscoveryTestServer.cs b/tests/Opc.Ua.Gds.Tests/GlobalDiscoveryTestServer.cs index 4fc7992f63..478f59ff6e 100644 --- a/tests/Opc.Ua.Gds.Tests/GlobalDiscoveryTestServer.cs +++ b/tests/Opc.Ua.Gds.Tests/GlobalDiscoveryTestServer.cs @@ -35,6 +35,7 @@ using Microsoft.Extensions.Logging; using Opc.Ua.Configuration; using Opc.Ua.Gds.Server; +using Opc.Ua.Gds.Server.Database; using Opc.Ua.Gds.Server.Database.Linq; using Opc.Ua.Security.Certificates; using Opc.Ua.Server; @@ -45,6 +46,7 @@ namespace Opc.Ua.Gds.Tests public class GlobalDiscoveryTestServer : IAsyncDisposable { public GlobalDiscoverySampleServer Server { get; private set; } = null!; + public IApplicationsDatabase ApplicationsDatabase { get; private set; } = null!; public IApplicationInstance Application { get; private set; } = null!; public ApplicationConfiguration Config { get; private set; } = null!; public int BasePort { get; private set; } @@ -222,6 +224,7 @@ await TestUtils } var applicationsDatabase = JsonApplicationsDatabase.Load(databaseStorePath!); + ApplicationsDatabase = applicationsDatabase; IUserDatabase userDatabase = JsonUserDatabase.Load(usersDatabaseStorePath!, m_telemetry); RegisterDefaultUsers(userDatabase); From 40c00ecdeace48f30137c81b35b1f4d74774d75b Mon Sep 17 00:00:00 2001 From: Marc Date: Thu, 12 Nov 2026 17:01:13 +0100 Subject: [PATCH 4/8] Simplify GDS revocation fix and add end-to-end test Per review: drop the scoped HTTPS/Users store CRL sync, notify the certificate manager once for the Peers scope when the CRL is updated and log notification failures. Keep passing the certificate type to GetGroupForCertificate so the group is selected by the type the certificate was issued for. Add an end-to-end test that opens a self-admin session with a GDS issued certificate, revokes the certificate through the GDS and asserts that the session can no longer be used. --- .../ApplicationsNodeManager.cs | 243 +-------- .../CustomCertificateGroupIntegrationTest.cs | 477 +----------------- .../GlobalDiscoveryTestServer.cs | 27 - ...pc.Ua.GlobalDiscoveryTestServer.Config.xml | 16 - .../RevokeCertificateSessionTest.cs | 148 ++++++ 5 files changed, 171 insertions(+), 740 deletions(-) create mode 100644 tests/Opc.Ua.Gds.Tests/RevokeCertificateSessionTest.cs diff --git a/src/Opc.Ua.Gds.Server/ApplicationsNodeManager.cs b/src/Opc.Ua.Gds.Server/ApplicationsNodeManager.cs index aa4682d611..ddb17e0dc1 100644 --- a/src/Opc.Ua.Gds.Server/ApplicationsNodeManager.cs +++ b/src/Opc.Ua.Gds.Server/ApplicationsNodeManager.cs @@ -828,96 +828,41 @@ private async Task RevokeCertificateAsync( if (certificateGroup != null) { using var x509 = Certificate.FromRawData(certificate); - X509CRL? crl; try { - crl = await certificateGroup + X509CRL crl = await certificateGroup .RevokeCertificateAsync(x509, cancellationToken) .ConfigureAwait(false); - } - catch (Exception e) - { - m_logger.UnexpectedErrorRevokingCertificate(e, x509.Subject, certificateGroup.Id); - return false; - } - - if (crl != null) - { - revoked = true; - NotifyRevocationListChanged( - TrustListIdentifier.Peers, - certificateGroup); - - TrustListIdentifier? scopedTrustList = - GetScopedTrustListIdentifier(certificateGroup); - if (scopedTrustList != null) + if (crl != null) { + revoked = true; + + // The new CRL is in the server's issuer store. Notify the + // certificate manager so that it revalidates the open + // SecureChannels and closes those that use the revoked + // certificate. try { - if (await UpdateScopedIssuerCertificatesStoreAsync( - certificateGroup, - cancellationToken).ConfigureAwait(false)) - { - NotifyRevocationListChanged( - scopedTrustList, - certificateGroup); - } + m_configuration.CertificateManager?.NotifyTrustListChanged( + TrustListIdentifier.Peers, + trustChanged: false, + crlChanged: true); } catch (Exception ex) { - m_logger.RevocationScopeStoreUpdateFailed( - ex, - scopedTrustList.ToString(), - certificateGroup.Id); - if (ex is OperationCanceledException && cancellationToken.IsCancellationRequested) - { - throw; - } - throw new ServiceResultException( - StatusCodes.BadUnexpectedError, - $"The certificate was revoked, but the {scopedTrustList} issuer store could not be updated.", - ex); + m_logger.RevocationNotificationFailed(ex, certificateGroup.Id); } } } + catch (Exception e) + { + m_logger.UnexpectedErrorRevokingCertificate(e, x509.Subject, certificateGroup.Id); + } } } return revoked; } - /// - /// Tells the server's certificate manager that a revocation wrote a - /// new CRL into the trust stores that the server itself validates - /// against. The manager drops its cached validation state and raises - /// , which drives the - /// trust-material enforcement of the configuration node manager: - /// SecureChannels and Sessions that present the revoked certificate - /// are revalidated and closed, instead of staying usable until they - /// are renewed. - /// - private void NotifyRevocationListChanged( - TrustListIdentifier scope, - ICertificateGroup certificateGroup) - { - ICertificateManager? certificateManager = m_configuration.CertificateManager; - if (certificateManager == null) - { - return; - } - - try - { - certificateManager.NotifyTrustListChanged( - scope, - trustChanged: false, - crlChanged: true); - } - catch (Exception ex) - { - m_logger.RevocationNotificationFailed(ex, scope.ToString(), certificateGroup.Id); - } - } - /// /// Builds the issuer-certificate chain for a newly issued /// per OPC 10000-12 §7.6.6. @@ -1038,12 +983,10 @@ protected async Task InitializeCertificateGroupAsync( "BaseStorePath not specified"); } - CertificateStoreIdentifier peerIssuerStore = - m_configuration.SecurityConfiguration.TrustedIssuerCertificates; ICertificateGroup certificateGroup = m_certificateGroupFactory.Create( m_globalDiscoveryServerConfiguration.AuthoritiesStorePath!, certificateGroupConfiguration, - peerIssuerStore.StorePath); + m_configuration.SecurityConfiguration.TrustedIssuerCertificates.StorePath); // Take ownership before the first call that can throw: InitAsync // opens certificate stores, so a group that fails half way through @@ -1051,149 +994,10 @@ protected async Task InitializeCertificateGroupAsync( m_ownedCertificateGroups.Add(certificateGroup); await certificateGroup.InitAsync().ConfigureAwait(false); - await UpdateScopedIssuerCertificatesStoreAsync(certificateGroup) - .ConfigureAwait(false); return certificateGroup; } - private CertificateTrustList? GetScopedIssuerCertificatesStore( - CertificateGroupConfiguration certificateGroupConfiguration) - { - SecurityConfiguration securityConfiguration = m_configuration.SecurityConfiguration; - if (string.Equals( - certificateGroupConfiguration.Id, - "DefaultHttpsGroup", - StringComparison.OrdinalIgnoreCase)) - { - return securityConfiguration.HttpsIssuerCertificates; - } - if (string.Equals( - certificateGroupConfiguration.Id, - "DefaultUserTokenGroup", - StringComparison.OrdinalIgnoreCase)) - { - return securityConfiguration.UserIssuerCertificates; - } - - return null; - } - - private TrustListIdentifier? GetScopedTrustListIdentifier(ICertificateGroup certificateGroup) - { - if (certificateGroup.Id == m_defaultHttpsGroupId) - { - return TrustListIdentifier.Https; - } - if (certificateGroup.Id == m_defaultUserTokenGroupId) - { - return TrustListIdentifier.Users; - } - - return null; - } - - private async Task UpdateScopedIssuerCertificatesStoreAsync( - ICertificateGroup certificateGroup, - CancellationToken cancellationToken = default) - { - CertificateStoreIdentifier? scopedIssuerStoreIdentifier = - GetScopedIssuerCertificatesStore(certificateGroup.Configuration); - if (scopedIssuerStoreIdentifier == null || - string.IsNullOrEmpty(scopedIssuerStoreIdentifier.StorePath)) - { - return false; - } - - CertificateStoreIdentifier peerIssuerStoreIdentifier = - m_configuration.SecurityConfiguration.TrustedIssuerCertificates; - if (IsSameStore(scopedIssuerStoreIdentifier, peerIssuerStoreIdentifier)) - { - return true; - } - - using ICertificateStore authorityStore = certificateGroup.AuthoritiesStore.OpenStore(Server.Telemetry); - using ICertificateStore scopedIssuerStore = OpenCertificateStore(scopedIssuerStoreIdentifier); - using CertificateCollection authorities = await authorityStore - .EnumerateAsync(cancellationToken) - .ConfigureAwait(false); - string authoritySubject = certificateGroup.Certificates.Values - .FirstOrDefault(static certificate => certificate != null)?.Subject - ?? certificateGroup.Configuration.SubjectName! - .Replace("localhost", Utils.GetHostName(), StringComparison.Ordinal); - - foreach (Certificate certificate in authorities) - { - if (!X509Utils.CompareDistinguishedName( - certificate.Subject, - authoritySubject)) - { - continue; - } - - using CertificateCollection storedCertificates = await scopedIssuerStore - .FindByThumbprintAsync(certificate.Thumbprint, cancellationToken) - .ConfigureAwait(false); - if (storedCertificates.Count == 0) - { - using var publicCertificate = Certificate.FromRawData(certificate.RawData); - await scopedIssuerStore.AddAsync(publicCertificate, ct: cancellationToken) - .ConfigureAwait(false); - } - - foreach (X509CRL crl in await scopedIssuerStore - .EnumerateCRLsAsync(certificate, false, cancellationToken) - .ConfigureAwait(false)) - { - if (crl.VerifySignature(certificate, false)) - { - await scopedIssuerStore.DeleteCRLAsync(crl, cancellationToken) - .ConfigureAwait(false); - } - } - - foreach (X509CRL crl in await authorityStore - .EnumerateCRLsAsync(certificate, true, cancellationToken) - .ConfigureAwait(false)) - { - await scopedIssuerStore.AddCRLAsync(crl, cancellationToken) - .ConfigureAwait(false); - } - } - - return true; - } - - private ICertificateStore OpenCertificateStore(CertificateStoreIdentifier storeIdentifier) - { - if (m_configuration.CertificateManager is ICertificateStoreResolver storeResolver) - { - return storeResolver.OpenCertificateStore( - storeIdentifier.StorePath!, - storeIdentifier.StoreType); - } - - return storeIdentifier.OpenStore(Server.Telemetry); - } - - private static bool IsSameStore( - CertificateStoreIdentifier first, - CertificateStoreIdentifier second) - { - return string.Equals(first.StorePath, second.StorePath, StringComparison.Ordinal) && - string.Equals( - ResolveStoreType(first), - ResolveStoreType(second), - StringComparison.OrdinalIgnoreCase); - } - - private static string ResolveStoreType(CertificateStoreIdentifier storeIdentifier) - { - return string.IsNullOrEmpty(storeIdentifier.StoreType) - ? CertificateStoreIdentifier.DetermineStoreType(storeIdentifier.StorePath!) - : storeIdentifier.StoreType; - } - /// /// The certificate types this GDS understands, by NodeId /// (OPC 10000-12 V1.04). @@ -3914,19 +3718,10 @@ public static partial void FinishRequestIssueFailed( [ApplicationIdentity] string? applicationUri); [LoggerMessage(EventId = GdsServerCommonEventIds.ApplicationsNodeManager + 22, Level = LogLevel.Error, - Message = "Failed to notify the {TrustList} trust list of the revocation in certificate group {CertificateGroupId}.")] + Message = "Failed to notify the server of the revocation in certificate group {CertificateGroupId}.")] public static partial void RevocationNotificationFailed( this ILogger logger, Exception exception, - string trustList, - NodeId certificateGroupId); - - [LoggerMessage(EventId = GdsServerCommonEventIds.ApplicationsNodeManager + 23, Level = LogLevel.Error, - Message = "Failed to persist the revocation CRL to the {TrustList} issuer store for certificate group {CertificateGroupId}.")] - public static partial void RevocationScopeStoreUpdateFailed( - this ILogger logger, - Exception exception, - string trustList, NodeId certificateGroupId); } } diff --git a/tests/Opc.Ua.Gds.Tests/CustomCertificateGroupIntegrationTest.cs b/tests/Opc.Ua.Gds.Tests/CustomCertificateGroupIntegrationTest.cs index 95110d017f..f236501de9 100644 --- a/tests/Opc.Ua.Gds.Tests/CustomCertificateGroupIntegrationTest.cs +++ b/tests/Opc.Ua.Gds.Tests/CustomCertificateGroupIntegrationTest.cs @@ -27,18 +27,13 @@ * http://opcfoundation.org/License/MIT/1.00/ * ======================================================================*/ -using System; -using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; -using Moq; using NUnit.Framework; using Opc.Ua.Client; using Opc.Ua.Gds.Server; -using Opc.Ua.Security.Certificates; using Opc.Ua.Tests; -using Ua = Opc.Ua; namespace Opc.Ua.Gds.Tests { @@ -51,10 +46,7 @@ namespace Opc.Ua.Gds.Tests public class CustomCertificateGroupIntegrationTest { private const string kCustomGroupId = "MyCustomGroup"; - private const string kTestDirectoryStoreType = "GdsTestDirectory"; private const string kCustomGroupSubjectName = "CN=GDS Custom CA, O=OPC Foundation"; - private const string kHttpsGroupSubjectName = "CN=GDS HTTPS CA, O=OPC Foundation"; - private const string kUserGroupSubjectName = "CN=GDS User CA, O=OPC Foundation"; private GlobalDiscoveryTestServer m_server; private GlobalDiscoveryTestClient m_gdsClient; @@ -79,36 +71,10 @@ public async Task OneTimeSetUpAsync() CACertificateKeySize = 4096, CACertificateHashSize = 512 }; - var httpsGroup = new CertificateGroupConfiguration - { - Id = "DefaultHttpsGroup", - CertificateTypes = [nameof(Ua.ObjectTypeIds.HttpsCertificateType)], - SubjectName = kHttpsGroupSubjectName, - BaseStorePath = Path.Combine(Path.GetTempPath(), "OPC", "GDS", "CA", "https"), - DefaultCertificateLifetime = 12, - DefaultCertificateKeySize = 2048, - DefaultCertificateHashSize = 256, - CACertificateLifetime = 60, - CACertificateKeySize = 4096, - CACertificateHashSize = 512 - }; - var userGroup = new CertificateGroupConfiguration - { - Id = "DefaultUserTokenGroup", - CertificateTypes = [nameof(Ua.ObjectTypeIds.UserCertificateType)], - SubjectName = kUserGroupSubjectName, - BaseStorePath = Path.Combine(Path.GetTempPath(), "OPC", "GDS", "CA", "users"), - DefaultCertificateLifetime = 12, - DefaultCertificateKeySize = 2048, - DefaultCertificateHashSize = 256, - CACertificateLifetime = 60, - CACertificateKeySize = 4096, - CACertificateHashSize = 512 - }; m_server = await TestUtils.StartGDSAsync( clean: true, - additionalCertGroups: [customGroup, httpsGroup, userGroup]).ConfigureAwait(false); + additionalCertGroups: [customGroup]).ConfigureAwait(false); m_gdsClient = new GlobalDiscoveryTestClient(true, m_telemetry); await m_gdsClient.LoadClientConfigurationAsync(m_server.BasePort).ConfigureAwait(false); @@ -154,14 +120,14 @@ public async Task CustomCertificateGroupAppearsInGetCertificateGroupsAsync() Assert.That(appId.IsNull, Is.False); - // GetCertificateGroups should return the default groups and the custom group. + // GetCertificateGroups should return both the default group and the custom group ArrayOf groups = await m_gdsClient.GDSClient .GetCertificateGroupsAsync(appId) .ConfigureAwait(false); Assert.That(groups.IsNull, Is.False); - Assert.That(groups.Count, Is.EqualTo(4), - "Expected 4 certificate groups: default, HTTPS, user-token, and custom"); + Assert.That(groups.Count, Is.EqualTo(2), + "Expected 2 certificate groups: default + custom"); // Verify that each group's TrustList is accessible foreach (NodeId groupId in groups.ToList()) @@ -289,440 +255,5 @@ public async Task DefaultApplicationGroupAdvertisesConfiguredCertificateTypesAsy await m_gdsClient.GDSClient.DisconnectAsync().ConfigureAwait(false); } } - - [Test] - public async Task RevokingHttpsAndUserCertificatesUpdatesTheirIssuerStoresAndNotifiesScopesAsync() - { - ICertificateManager originalCertificateManager = m_server.Config.CertificateManager; - CertificateTrustList httpsIssuerStore = - m_server.Config.SecurityConfiguration.HttpsIssuerCertificates!; - string? originalHttpsStorePath = httpsIssuerStore.StorePath; - string? originalHttpsStoreType = httpsIssuerStore.StoreType; - var issuerStores = new[] - { - m_server.Config.SecurityConfiguration.TrustedIssuerCertificates, - httpsIssuerStore, - m_server.Config.SecurityConfiguration.UserIssuerCertificates! - }; - Assert.That( - issuerStores.Select(store => Path.GetFullPath(store.StorePath!)).Distinct().Count(), - Is.EqualTo(issuerStores.Length), - "Peer, HTTPS, and user-token issuer stores must be distinct."); - - try - { - httpsIssuerStore.StoreType = kTestDirectoryStoreType; - var storeProvider = new TestDirectoryCertificateStoreProvider(); - using CertificateManager testCertificateManager = CertificateManagerFactory.Create( - m_server.Config.SecurityConfiguration, - m_telemetry, - options => options.AddStoreProvider(storeProvider)); - m_server.Config.CertificateManager = testCertificateManager; - - m_gdsClient.GDSClient.AdminCredentials = m_gdsClient.AdminUser; - await m_gdsClient.GDSClient.ConnectAsync().ConfigureAwait(false); - - var appTestDataGenerator = new ApplicationTestDataGenerator(3, m_telemetry); - ApplicationTestData appData = appTestDataGenerator.ApplicationTestSet(1, false)[0]; - appData.ApplicationRecord.ApplicationType = ApplicationType.Server; - appData.ApplicationRecord.DiscoveryUrls = ["https://localhost:4843"]; - NodeId appId = await m_gdsClient.GDSClient - .RegisterApplicationAsync(appData.ApplicationRecord) - .ConfigureAwait(false); - - var revocationCases = new[] - { - ( - GroupId: "DefaultHttpsGroup", - CertificateType: Ua.ObjectTypeIds.HttpsCertificateType, - Scope: TrustListIdentifier.Https), - ( - GroupId: "DefaultUserTokenGroup", - CertificateType: Ua.ObjectTypeIds.UserCertificateType, - Scope: TrustListIdentifier.Users) - }; - - foreach ((string groupId, NodeId certificateType, TrustListIdentifier scope) in revocationCases) - { - NodeId certificateGroupId = GetCertificateGroupId(groupId); - NodeId requestId = await m_gdsClient.GDSClient.StartNewKeyPairRequestAsync( - appId, - certificateGroupId, - certificateType, - appData.Subject, - appData.DomainNames, - appData.PrivateKeyFormat, - appData.PrivateKeyPassword).ConfigureAwait(false); - - (Certificate certificate, Certificate issuer) = - await FinishRequestAsync(appId, requestId).ConfigureAwait(false); - try - { - var observer = new Mock>(); - using IDisposable subscription = m_server.Config.CertificateManager.CertificateChanges - .Subscribe(observer.Object); - - await m_gdsClient.GDSClient - .RevokeCertificateAsync(appId, ByteString.From(certificate.RawData)) - .ConfigureAwait(false); - - observer.Verify( - item => item.OnNext(It.Is( - change => change.Kind == CertificateChangeKind.CrlUpdated && - change.TrustList == TrustListIdentifier.Peers)), - Times.Once); - observer.Verify( - item => item.OnNext(It.Is( - change => change.Kind == CertificateChangeKind.CrlUpdated && - change.TrustList == scope)), - Times.Once); - - await AssertRevocationCrlExistsAsync( - TrustListIdentifier.Peers, - issuer, - certificate) - .ConfigureAwait(false); - await AssertRevocationCrlExistsAsync(scope, issuer, certificate).ConfigureAwait(false); - } - finally - { - certificate.Dispose(); - issuer.Dispose(); - } - } - - int storeCreationsBeforeCancellation = storeProvider.CreateStoreCount; - httpsIssuerStore.StorePath = - m_server.Config.SecurityConfiguration.TrustedIssuerCertificates.StorePath; - NodeId cancelledRequestId = await m_gdsClient.GDSClient.StartNewKeyPairRequestAsync( - appId, - GetCertificateGroupId("DefaultHttpsGroup"), - Ua.ObjectTypeIds.HttpsCertificateType, - appData.Subject, - appData.DomainNames, - appData.PrivateKeyFormat, - appData.PrivateKeyPassword).ConfigureAwait(false); - (Certificate cancelledCertificate, Certificate cancelledIssuer) = - await FinishRequestAsync(appId, cancelledRequestId).ConfigureAwait(false); - try - { - storeProvider.CancelNextStoreCreation = true; - var observer = new Mock>(); - using IDisposable subscription = m_server.Config.CertificateManager.CertificateChanges - .Subscribe(observer.Object); - - ServiceResultException scopedStoreCancellation = await Assert.ThrowsAsync( - async () => await m_gdsClient.GDSClient - .RevokeCertificateAsync(appId, ByteString.From(cancelledCertificate.RawData)) - .ConfigureAwait(false)); - Assert.That( - scopedStoreCancellation.StatusCode, - Is.EqualTo(StatusCodes.BadUnexpectedError)); - - observer.Verify( - item => item.OnNext(It.Is( - change => change.Kind == CertificateChangeKind.CrlUpdated && - change.TrustList == TrustListIdentifier.Peers)), - Times.Once); - observer.Verify( - item => item.OnNext(It.Is( - change => change.Kind == CertificateChangeKind.CrlUpdated && - change.TrustList == TrustListIdentifier.Https)), - Times.Never); - await AssertRevocationCrlExistsAsync( - TrustListIdentifier.Peers, - cancelledIssuer, - cancelledCertificate).ConfigureAwait(false); - } - finally - { - cancelledCertificate.Dispose(); - cancelledIssuer.Dispose(); - httpsIssuerStore.StorePath = originalHttpsStorePath; - } - - Assert.That( - storeProvider.CreateStoreCount, - Is.GreaterThan(storeCreationsBeforeCancellation), - "The distinct HTTPS store and the same-path, different-type store must use the injected provider."); - Assert.That( - storeProvider.CancelNextStoreCreation, - Is.False, - "The configured provider must be invoked when the scoped store is updated."); - - await m_gdsClient.GDSClient.UnregisterApplicationAsync(appId).ConfigureAwait(false); - } - finally - { - await m_gdsClient.GDSClient.DisconnectAsync().ConfigureAwait(false); - m_server.Config.CertificateManager = originalCertificateManager; - httpsIssuerStore.StorePath = originalHttpsStorePath; - httpsIssuerStore.StoreType = originalHttpsStoreType; - } - } - - [Test] - public async Task FailedScopedStoreUpdateStillNotifiesPeersAndDoesNotReportInvalidArgumentAsync() - { - m_gdsClient.GDSClient.AdminCredentials = m_gdsClient.AdminUser; - await m_gdsClient.GDSClient.ConnectAsync().ConfigureAwait(false); - - string originalStorePath = - m_server.Config.SecurityConfiguration.HttpsIssuerCertificates!.StorePath!; - string failingStorePath = typeof(CustomCertificateGroupIntegrationTest).Assembly.Location; - - try - { - var appTestDataGenerator = new ApplicationTestDataGenerator(1, m_telemetry); - ApplicationTestData appData = appTestDataGenerator.ApplicationTestSet(1, false)[0]; - appData.ApplicationRecord.ApplicationType = ApplicationType.Server; - appData.ApplicationRecord.DiscoveryUrls = ["https://localhost:4843"]; - NodeId appId = await m_gdsClient.GDSClient - .RegisterApplicationAsync(appData.ApplicationRecord) - .ConfigureAwait(false); - - NodeId requestId = await m_gdsClient.GDSClient.StartNewKeyPairRequestAsync( - appId, - GetCertificateGroupId("DefaultHttpsGroup"), - Ua.ObjectTypeIds.HttpsCertificateType, - appData.Subject, - appData.DomainNames, - appData.PrivateKeyFormat, - appData.PrivateKeyPassword).ConfigureAwait(false); - (Certificate certificate, Certificate issuer) = - await FinishRequestAsync(appId, requestId).ConfigureAwait(false); - - try - { - m_server.Config.SecurityConfiguration.HttpsIssuerCertificates!.StorePath = - failingStorePath; - var observer = new Mock>(); - using IDisposable subscription = m_server.Config.CertificateManager.CertificateChanges - .Subscribe(observer.Object); - - ServiceResultException scopedStoreFailure = await Assert.ThrowsAsync( - async () => await m_gdsClient.GDSClient - .RevokeCertificateAsync(appId, ByteString.From(certificate.RawData)) - .ConfigureAwait(false)); - Assert.That( - scopedStoreFailure.StatusCode, - Is.EqualTo(StatusCodes.BadUnexpectedError)); - - observer.Verify( - item => item.OnNext(It.Is( - change => change.Kind == CertificateChangeKind.CrlUpdated && - change.TrustList == TrustListIdentifier.Peers)), - Times.Once); - observer.Verify( - item => item.OnNext(It.Is( - change => change.Kind == CertificateChangeKind.CrlUpdated && - change.TrustList == TrustListIdentifier.Https)), - Times.Never); - await AssertRevocationCrlExistsAsync( - TrustListIdentifier.Peers, - issuer, - certificate).ConfigureAwait(false); - } - finally - { - certificate.Dispose(); - issuer.Dispose(); - m_server.Config.SecurityConfiguration.HttpsIssuerCertificates!.StorePath = - originalStorePath; - } - - await m_gdsClient.GDSClient.UnregisterApplicationAsync(appId).ConfigureAwait(false); - } - finally - { - m_server.Config.SecurityConfiguration.HttpsIssuerCertificates!.StorePath = originalStorePath; - await m_gdsClient.GDSClient.DisconnectAsync().ConfigureAwait(false); - } - } - - [Test] - public async Task RevokingHttpsAndUserCertificatesMirrorsHistoricalIssuerCrlsAsync() - { - m_gdsClient.GDSClient.AdminCredentials = m_gdsClient.AdminUser; - await m_gdsClient.GDSClient.ConnectAsync().ConfigureAwait(false); - - try - { - var appTestDataGenerator = new ApplicationTestDataGenerator(2, m_telemetry); - ApplicationTestData appData = appTestDataGenerator.ApplicationTestSet(1, false)[0]; - appData.ApplicationRecord.ApplicationType = ApplicationType.Server; - appData.ApplicationRecord.DiscoveryUrls = ["https://localhost:4843"]; - NodeId appId = await m_gdsClient.GDSClient - .RegisterApplicationAsync(appData.ApplicationRecord) - .ConfigureAwait(false); - - GlobalDiscoveryServerConfiguration gdsConfiguration = - m_server.Config.ParseExtension()!; - foreach ((TrustListIdentifier scope, string subjectName, string certificateTypeName) in - new[] - { - ( - TrustListIdentifier.Https, - kHttpsGroupSubjectName, - "HttpsCertificateType"), - ( - TrustListIdentifier.Users, - kUserGroupSubjectName, - "UserCertificateType") - }) - { - using Certificate historicalIssuer = CertificateBuilder.Create(subjectName) - .SetCAConstraint() - .CreateForRSA(); - using Certificate revokedByHistoricalIssuer = CertificateBuilder.Create("CN=Historical Issuer Test") - .SetIssuer(historicalIssuer) - .CreateForRSA(); - using Certificate previouslyRevokedByHistoricalIssuer = - CertificateBuilder.Create("CN=Previously Revoked Test") - .SetIssuer(historicalIssuer) - .CreateForRSA(); - var authoritiesStoreIdentifier = new CertificateStoreIdentifier( - gdsConfiguration!.AuthoritiesStorePath!, - noPrivateKeys: false); - using ICertificateStore authoritiesStore = - authoritiesStoreIdentifier.OpenStore(m_telemetry); - await authoritiesStore.AddAsync(historicalIssuer).ConfigureAwait(false); - X509CRL staleCrl = await CertificateGroup.RevokeCertificateAsync( - authoritiesStoreIdentifier, - previouslyRevokedByHistoricalIssuer, - issuerKeyFilePassword: null, - telemetry: m_telemetry).ConfigureAwait(false); - - using ICertificateStore scopedIssuerStore = - m_server.Config.CertificateManager.OpenIssuerStore(scope)!; - using Certificate publicHistoricalIssuer = - Certificate.FromRawData(historicalIssuer.RawData); - await scopedIssuerStore.AddAsync(publicHistoricalIssuer).ConfigureAwait(false); - await scopedIssuerStore.AddCRLAsync(staleCrl).ConfigureAwait(false); - - Assert.That( - m_server.ApplicationsDatabase.SetApplicationCertificate( - appId, - certificateTypeName, - ByteString.From(revokedByHistoricalIssuer.RawData)), - Is.True); - - await m_gdsClient.GDSClient - .RevokeCertificateAsync( - appId, - ByteString.From(revokedByHistoricalIssuer.RawData)) - .ConfigureAwait(false); - - using CertificateCollection copiedIssuer = await scopedIssuerStore - .FindByThumbprintAsync(historicalIssuer.Thumbprint).ConfigureAwait(false); - Assert.That(copiedIssuer, Is.Not.Empty); - X509CRLCollection historicalCrls = await scopedIssuerStore - .EnumerateCRLsAsync(historicalIssuer).ConfigureAwait(false); - Assert.That(historicalCrls, Has.Count.EqualTo(1)); - Assert.That( - historicalCrls[0].RevokedCertificates.Any( - entry => entry.UserCertificate.SequenceEqual( - previouslyRevokedByHistoricalIssuer.GetSerialNumber())), - Is.True); - Assert.That( - historicalCrls[0].RevokedCertificates.Any( - entry => entry.UserCertificate.SequenceEqual( - revokedByHistoricalIssuer.GetSerialNumber())), - Is.True); - } - - await m_gdsClient.GDSClient.UnregisterApplicationAsync(appId).ConfigureAwait(false); - } - finally - { - await m_gdsClient.GDSClient.DisconnectAsync().ConfigureAwait(false); - } - } - - /// - /// Resolves a predefined certificate group using the active GDS session namespace table. - /// - private NodeId GetCertificateGroupId(string groupId) - { - return groupId switch - { - "DefaultHttpsGroup" => ExpandedNodeId.ToNodeId( - ObjectIds.Directory_CertificateGroups_DefaultHttpsGroup, - m_gdsClient.GDSClient.Session!.NamespaceUris), - "DefaultUserTokenGroup" => ExpandedNodeId.ToNodeId( - ObjectIds.Directory_CertificateGroups_DefaultUserTokenGroup, - m_gdsClient.GDSClient.Session!.NamespaceUris), - _ => throw new ArgumentOutOfRangeException(nameof(groupId)) - }; - } - - /// - /// Waits for the GDS to finish issuing a certificate for the request. - /// - private async Task<(Certificate certificate, Certificate issuer)> FinishRequestAsync( - NodeId appId, - NodeId requestId) - { - DateTime deadline = DateTime.UtcNow.AddMinutes(5); - while (DateTime.UtcNow < deadline) - { - (ByteString certificate, _, ArrayOf issuerCertificates) = await m_gdsClient.GDSClient - .FinishRequestAsync(appId, requestId).ConfigureAwait(false); - if (!certificate.IsEmpty) - { - return ( - Certificate.FromRawData(certificate), - Certificate.FromRawData(issuerCertificates[0])); - } - await Task.Delay(1000).ConfigureAwait(false); - } - - throw new TimeoutException("Timed out waiting for the GDS certificate request to finish."); - } - - /// - /// Verifies that an issuer store contains the CRL for a revoked certificate. - /// - private async Task AssertRevocationCrlExistsAsync( - TrustListIdentifier scope, - Certificate issuer, - Certificate certificate) - { - using ICertificateStore issuerStore = m_server.Config.CertificateManager.OpenIssuerStore(scope)!; - X509CRLCollection crls = await issuerStore - .EnumerateCRLsAsync(issuer).ConfigureAwait(false); - Assert.That( - crls.Any(crl => crl.RevokedCertificates.Any( - revoked => revoked.UserCertificate.SequenceEqual(certificate.GetSerialNumber()))), - Is.True, - $"Expected a CRL revoking the certificate in the {scope} issuer store."); - } - - private sealed class TestDirectoryCertificateStoreProvider : ICertificateStoreProvider - { - private readonly DirectoryStoreProvider m_directoryStoreProvider = new(); - - public string StoreTypeName => kTestDirectoryStoreType; - - public int CreateStoreCount { get; private set; } - - public bool CancelNextStoreCreation { get; set; } - - public bool SupportsStorePath(string storePath) - { - return false; - } - - public ICertificateStore CreateStore(ITelemetryContext telemetry) - { - CreateStoreCount++; - if (CancelNextStoreCreation) - { - CancelNextStoreCreation = false; - throw new OperationCanceledException("Cancelled test store open."); - } - return m_directoryStoreProvider.CreateStore(telemetry); - } - } } } diff --git a/tests/Opc.Ua.Gds.Tests/GlobalDiscoveryTestServer.cs b/tests/Opc.Ua.Gds.Tests/GlobalDiscoveryTestServer.cs index 478f59ff6e..6295d7066f 100644 --- a/tests/Opc.Ua.Gds.Tests/GlobalDiscoveryTestServer.cs +++ b/tests/Opc.Ua.Gds.Tests/GlobalDiscoveryTestServer.cs @@ -35,7 +35,6 @@ using Microsoft.Extensions.Logging; using Opc.Ua.Configuration; using Opc.Ua.Gds.Server; -using Opc.Ua.Gds.Server.Database; using Opc.Ua.Gds.Server.Database.Linq; using Opc.Ua.Security.Certificates; using Opc.Ua.Server; @@ -46,7 +45,6 @@ namespace Opc.Ua.Gds.Tests public class GlobalDiscoveryTestServer : IAsyncDisposable { public GlobalDiscoverySampleServer Server { get; private set; } = null!; - public IApplicationsDatabase ApplicationsDatabase { get; private set; } = null!; public IApplicationInstance Application { get; private set; } = null!; public ApplicationConfiguration Config { get; private set; } = null!; public int BasePort { get; private set; } @@ -132,34 +130,10 @@ await TestUtils .CleanupTrustListAsync( Config.SecurityConfiguration.TrustedIssuerCertificates, m_telemetry) .ConfigureAwait(false); - if (Config.SecurityConfiguration.UserIssuerCertificates != null) - { - await TestUtils.CleanupTrustListAsync( - Config.SecurityConfiguration.UserIssuerCertificates, - m_telemetry).ConfigureAwait(false); - } - if (Config.SecurityConfiguration.HttpsIssuerCertificates != null) - { - await TestUtils.CleanupTrustListAsync( - Config.SecurityConfiguration.HttpsIssuerCertificates, - m_telemetry).ConfigureAwait(false); - } await TestUtils .CleanupTrustListAsync( Config.SecurityConfiguration.TrustedPeerCertificates, m_telemetry) .ConfigureAwait(false); - if (Config.SecurityConfiguration.TrustedUserCertificates != null) - { - await TestUtils.CleanupTrustListAsync( - Config.SecurityConfiguration.TrustedUserCertificates, - m_telemetry).ConfigureAwait(false); - } - if (Config.SecurityConfiguration.TrustedHttpsCertificates != null) - { - await TestUtils.CleanupTrustListAsync( - Config.SecurityConfiguration.TrustedHttpsCertificates, - m_telemetry).ConfigureAwait(false); - } await TestUtils .CleanupTrustListAsync( Config.SecurityConfiguration.RejectedCertificateStore!, m_telemetry) @@ -224,7 +198,6 @@ await TestUtils } var applicationsDatabase = JsonApplicationsDatabase.Load(databaseStorePath!); - ApplicationsDatabase = applicationsDatabase; IUserDatabase userDatabase = JsonUserDatabase.Load(usersDatabaseStorePath!, m_telemetry); RegisterDefaultUsers(userDatabase); diff --git a/tests/Opc.Ua.Gds.Tests/Opc.Ua.GlobalDiscoveryTestServer.Config.xml b/tests/Opc.Ua.Gds.Tests/Opc.Ua.GlobalDiscoveryTestServer.Config.xml index 64092ea6bb..179036f953 100644 --- a/tests/Opc.Ua.Gds.Tests/Opc.Ua.GlobalDiscoveryTestServer.Config.xml +++ b/tests/Opc.Ua.Gds.Tests/Opc.Ua.GlobalDiscoveryTestServer.Config.xml @@ -49,22 +49,6 @@ Directory %LocalApplicationData%/OPC/GDS/trusted - - Directory - %LocalApplicationData%/OPC/GDS/trustedUsers - - - Directory - %LocalApplicationData%/OPC/GDS/userIssuers - - - Directory - %LocalApplicationData%/OPC/GDS/trustedHttps - - - Directory - %LocalApplicationData%/OPC/GDS/httpsIssuers - Directory %LocalApplicationData%/OPC/GDS/rejected diff --git a/tests/Opc.Ua.Gds.Tests/RevokeCertificateSessionTest.cs b/tests/Opc.Ua.Gds.Tests/RevokeCertificateSessionTest.cs new file mode 100644 index 0000000000..d14112dd13 --- /dev/null +++ b/tests/Opc.Ua.Gds.Tests/RevokeCertificateSessionTest.cs @@ -0,0 +1,148 @@ +/* ======================================================================== + * Copyright (c) 2005-2025 The OPC Foundation, Inc. All rights reserved. + * + * OPC Foundation MIT License 1.00 + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + * The complete license agreement can be found here: + * http://opcfoundation.org/License/MIT/1.00/ + * ======================================================================*/ + +using System; +using System.Threading.Tasks; +using NUnit.Framework; +using Opc.Ua.Gds.Client; +using Opc.Ua.Tests; + +namespace Opc.Ua.Gds.Tests +{ + /// + /// End-to-end test verifying that revoking an application certificate through the + /// GDS cuts off a session that is already open with that certificate. + /// + [TestFixture] + [Category("GDS")] + [NonParallelizable] + public class RevokeCertificateSessionTest + { + private static readonly TimeSpan s_enforcementTimeout = TimeSpan.FromSeconds(30); + + private GlobalDiscoveryTestServer m_server = null!; + private GlobalDiscoveryTestClient m_gdsClient = null!; + + [OneTimeSetUp] + public async Task OneTimeSetUpAsync() + { + m_server = await TestUtils.StartGDSAsync(clean: true).ConfigureAwait(false); + m_gdsClient = new GlobalDiscoveryTestClient(true, NUnitTelemetryContext.Create()); + await m_gdsClient.LoadClientConfigurationAsync(m_server.BasePort).ConfigureAwait(false); + } + + [OneTimeTearDown] + public async Task OneTimeTearDownAsync() + { + if (m_gdsClient != null) + { + await m_gdsClient.DisconnectClientAsync().ConfigureAwait(false); + m_gdsClient.Dispose(); + m_gdsClient = null!; + } + if (m_server != null) + { + await m_server.DisposeAsync().ConfigureAwait(false); + m_server = null!; + } + } + + [Test] + public async Task RevokeCertificateCutsOffOpenSessionOfRevokedCertificateAsync() + { + ApplicationConfiguration configuration = m_gdsClient.Configuration; + CertificateIdentifier adminCertificate = + configuration.SecurityConfiguration.ApplicationCertificate!; + + // Issue a GDS certificate to the test client. This replaces the + // application certificate the next session is created with. + Assert.That(await m_gdsClient.RegisterTestClientAtGdsAsync().ConfigureAwait(false), Is.True); + ApplicationTestData application = m_gdsClient.OwnApplicationTestData; + + var victim = new GlobalDiscoveryServerClient(configuration, m_gdsClient.Anonymous) + { + Endpoint = new ConfiguredEndpoint( + null, + m_gdsClient.GDSClient.Endpoint!.Description, + EndpointConfiguration.Create(configuration)) + }; + try + { + // The certificate grants the session ApplicationSelfAdmin rights. + NodeId applicationId = application.ApplicationRecord.ApplicationId; + await victim.ConnectAsync().ConfigureAwait(false); + ApplicationRecordDataType record = + await victim.GetApplicationAsync(applicationId).ConfigureAwait(false); + Assert.That(record.ApplicationId, Is.EqualTo(applicationId)); + + // Revoke from an admin session which uses the original certificate, + // so that only the victim session holds the revoked certificate. + configuration.SecurityConfiguration.ApplicationCertificate = adminCertificate; + m_gdsClient.GDSClient.AdminCredentials = m_gdsClient.AdminUser; + await m_gdsClient.GDSClient.ConnectAsync().ConfigureAwait(false); + try + { + await m_gdsClient.GDSClient.RevokeCertificateAsync( + applicationId, + application.Certificate.ToByteString()).ConfigureAwait(false); + } + finally + { + await m_gdsClient.GDSClient.DisconnectAsync().ConfigureAwait(false); + } + + // The server revalidates the open SecureChannels asynchronously + // after the CRL update and closes the one using the revoked + // certificate, so the session can no longer be used. + ServiceResultException? failure = null; + DateTime deadline = DateTime.UtcNow + s_enforcementTimeout; + while (failure == null && DateTime.UtcNow < deadline) + { + try + { + await victim.GetApplicationAsync(applicationId).ConfigureAwait(false); + await Task.Delay(100).ConfigureAwait(false); + } + catch (ServiceResultException ex) + { + failure = ex; + } + } + Assert.That( + failure, + Is.Not.Null, + "The session using the revoked certificate can still be used."); + } + finally + { + await victim.DisposeAsync().ConfigureAwait(false); + } + } + } +} From 75fea75f946ad34463a8aba72466c0d70a238b49 Mon Sep 17 00:00:00 2001 From: Marc Date: Thu, 12 Nov 2026 18:22:17 +0100 Subject: [PATCH 5/8] Pin CI to the global.json SDK and pre-provision the Aspire bundle GitHub-hosted runner images now preinstall the .NET 11 SDK. global.json pins 10.0.403 with rollForward latestMajor, so setup-dotnet resolved the preinstalled SDK 11 and its new analyzers (CA2027 and others) failed the build-UA and test jobs. The new setup-repository-dotnet composite action installs the exact global.json SDK, plus any extra SDKs a job needs, into a job-private directory under RUNNER_TEMP, and fails the job unless dotnet resolves that exact SDK from that directory. Every workflow except release.yml uses it; the release job checks out a candidate commit that can predate the action and only pushes packages that were already built. Jobs that build the Aspire AppHost install the Aspire CLI bundle first, so the AppHost build does not run 'aspire setup' itself under a two-minute timeout, which intermittently failed with ASPIRE009. --- .github/actions/run-dotnet-tests/action.yml | 9 +- .../setup-repository-dotnet/action.yml | 55 ++++++++ .github/scripts/install-aspire-bundle.ps1 | 81 ++++++++++++ .github/scripts/select-repository-sdk.ps1 | 98 +++++++++++++++ .github/workflows/buildandtest.yml | 38 +++--- .github/workflows/codeql-analysis.yml | 8 +- .github/workflows/docker-image.yml | 8 +- .github/workflows/interop-foreign.yml | 4 +- .github/workflows/mcpgrade.yml | 4 +- .github/workflows/nightly.yml | 21 ++-- .github/workflows/nuget-publish.yml | 8 +- .github/workflows/sample-ha-longhaul.yml | 4 +- .github/workflows/stability-test.yml | 4 +- .github/workflows/stress-test.yml | 8 +- .github/workflows/ualens-artifacts.yml | 20 +-- docs/DeveloperGuide.md | 2 +- .../TestMatrixScriptTests.cs | 119 +++++++++++++++++- 17 files changed, 402 insertions(+), 89 deletions(-) create mode 100644 .github/actions/setup-repository-dotnet/action.yml create mode 100644 .github/scripts/install-aspire-bundle.ps1 create mode 100644 .github/scripts/select-repository-sdk.ps1 diff --git a/.github/actions/run-dotnet-tests/action.yml b/.github/actions/run-dotnet-tests/action.yml index 7081760c90..3d4d195a7b 100644 --- a/.github/actions/run-dotnet-tests/action.yml +++ b/.github/actions/run-dotnet-tests/action.yml @@ -53,15 +53,10 @@ inputs: runs: using: composite steps: - - name: Setup .NET - uses: actions/setup-dotnet@v6 - with: - dotnet-version: ${{ inputs.dotnet }} - - name: Setup repository .NET SDK - uses: actions/setup-dotnet@v6 + uses: ./.github/actions/setup-repository-dotnet with: - global-json-file: global.json + dotnet-version: ${{ inputs.dotnet }} - name: Set cloud version shell: pwsh diff --git a/.github/actions/setup-repository-dotnet/action.yml b/.github/actions/setup-repository-dotnet/action.yml new file mode 100644 index 0000000000..328dd1b8b5 --- /dev/null +++ b/.github/actions/setup-repository-dotnet/action.yml @@ -0,0 +1,55 @@ +name: Setup repository .NET SDK +description: >- + Installs the exact .NET SDK pinned in global.json, plus any additional SDKs + the job needs, into a job-private directory and verifies that the build + resolves the pinned version. global.json rolls forward to the latest major + SDK for contributors; runner images preinstall newer SDKs into the default + directory, which that policy would otherwise select on CI. See + .github/scripts/select-repository-sdk.ps1. + +inputs: + dotnet-version: + description: >- + Newline-separated additional .NET SDK versions, for example the 8.0.x and + 9.0.x SDKs whose runtimes older target frameworks execute on. The + global.json SDK is always installed and always selected. + required: false + default: '' + +outputs: + sdk: + description: The exact .NET SDK version the job builds with. + value: ${{ steps.select.outputs.sdk }} + +runs: + using: composite + steps: + - name: Select the repository .NET SDK + id: select + shell: pwsh + env: + ADDITIONAL_SDKS: ${{ inputs.dotnet-version }} + run: ./.github/scripts/select-repository-sdk.ps1 -AdditionalSdks $env:ADDITIONAL_SDKS + + - name: Install .NET SDKs + uses: actions/setup-dotnet@v6 + with: + dotnet-version: ${{ steps.select.outputs.versions }} + + - name: Verify the repository .NET SDK + shell: pwsh + env: + EXPECTED_SDK: ${{ steps.select.outputs.sdk }} + run: | + $dotnet = (Get-Command dotnet).Source + dotnet --list-sdks + $actual = (dotnet --version | Out-String).Trim() + if ($actual -cne $env:EXPECTED_SDK) { + Write-Host "::error::'$dotnet' selected .NET SDK '$actual' instead of the global.json SDK '$($env:EXPECTED_SDK)'." + exit 1 + } + if (-not $dotnet.StartsWith($env:DOTNET_INSTALL_DIR, [StringComparison]::OrdinalIgnoreCase)) { + Write-Host "::error::'$dotnet' is not the job-private installation in '$($env:DOTNET_INSTALL_DIR)'." + exit 1 + } + Write-Host "Using .NET SDK $actual from '$dotnet'." diff --git a/.github/scripts/install-aspire-bundle.ps1 b/.github/scripts/install-aspire-bundle.ps1 new file mode 100644 index 0000000000..c79d43fcad --- /dev/null +++ b/.github/scripts/install-aspire-bundle.ps1 @@ -0,0 +1,81 @@ +<# + .SYNOPSIS + Installs the Aspire CLI bundle before a solution build that contains an Aspire AppHost. + + .DESCRIPTION + tools/Opc.Ua.Lens.AppHost builds with AspireUseCliBundle. When Aspire home + holds no bundle, the AppHost build downloads it (about 350 MB) by running + 'aspire setup' itself under a two-minute timeout. On cold CI runners that + in-build setup intermittently fails, and the build then fails with + ASPIRE009. Installing the bundle up front, without that timeout and with + retries, lets the AppHost build resolve the existing layout instead. + + The bundle version is the Aspire.Hosting.AppHost version that + Directory.Packages.props pins. + + .PARAMETER PackagesPropsPath + Path to Directory.Packages.props. + + .PARAMETER AspireHome + Aspire home that receives the bundle. Defaults to ASPIRE_HOME or, when that + is not set, to the .aspire directory in the user profile, which is where the + AppHost build looks. + + .PARAMETER Attempts + Number of install attempts before the script fails. +#> +param( + [string] $PackagesPropsPath = 'Directory.Packages.props', + [string] $AspireHome = '', + [int] $Attempts = 3 +) + +$ErrorActionPreference = 'Stop' + +if (-not (Test-Path -LiteralPath $PackagesPropsPath -PathType Leaf)) +{ + Write-Host "::error::'$PackagesPropsPath' does not exist; check out the repository first." + exit 1 +} + +[xml] $props = Get-Content -LiteralPath $PackagesPropsPath -Raw +$version = @($props.Project.ItemGroup.PackageVersion | + Where-Object { $_.Include -ceq 'Aspire.Hosting.AppHost' } | + ForEach-Object { $_.Version }) +if ($version.Count -ne 1 -or $version[0] -notmatch '^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$') +{ + Write-Host "::error::'$PackagesPropsPath' must pin exactly one Aspire.Hosting.AppHost version." + exit 1 +} +$version = $version[0] + +if ([string]::IsNullOrWhiteSpace($AspireHome)) +{ + $AspireHome = if ([string]::IsNullOrWhiteSpace($env:ASPIRE_HOME)) + { + Join-Path ([Environment]::GetFolderPath('UserProfile')) '.aspire' + } + else + { + $env:ASPIRE_HOME + } +} + +$bundle = Join-Path $AspireHome 'bundle' +for ($attempt = 1; $attempt -le $Attempts; $attempt++) +{ + Write-Host "Installing the Aspire $version CLI bundle into '$AspireHome' (attempt $attempt of $Attempts)." + dotnet dnx --yes "aspire.cli@$version" -- setup --install-path $AspireHome + $exitCode = $LASTEXITCODE + if ($exitCode -eq 0 -and + (Test-Path -LiteralPath (Join-Path $bundle 'dcp') -PathType Container) -and + (Test-Path -LiteralPath (Join-Path $bundle 'dashboard') -PathType Container)) + { + Write-Host "Installed the Aspire $version CLI bundle into '$bundle'." + exit 0 + } + Write-Host "::warning::Aspire bundle setup attempt $attempt exited with $exitCode or left no complete bundle." +} + +Write-Host "::error::Could not install the Aspire $version CLI bundle into '$AspireHome' after $Attempts attempts." +exit 1 diff --git a/.github/scripts/select-repository-sdk.ps1 b/.github/scripts/select-repository-sdk.ps1 new file mode 100644 index 0000000000..fd899f4ef7 --- /dev/null +++ b/.github/scripts/select-repository-sdk.ps1 @@ -0,0 +1,98 @@ +<# + .SYNOPSIS + Selects the exact repository .NET SDK and a job-private install directory. + + .DESCRIPTION + global.json pins the SDK version with rollForward 'latestMajor' so that + contributors can build with any newer SDK they have installed. The dotnet + host applies that policy to every SDK in its own installation directory, and + GitHub-hosted runner images preinstall newer SDKs (including new major + versions) into the default directory. A job that installs the repository SDK + there therefore builds with whatever newer SDK the image happens to carry, + and that SDK's new analyzers can break the build. + + This script points actions/setup-dotnet at a directory under RUNNER_TEMP + that contains only the SDKs the job installs, so the host can resolve + nothing newer than the global.json version. It writes: + + DOTNET_INSTALL_DIR (GITHUB_ENV) The job-private install directory. + sdk (GITHUB_OUTPUT) The exact global.json SDK version. + versions (GITHUB_OUTPUT) The SDKs to install, the global.json + version last. + + .PARAMETER AdditionalSdks + Newline-separated SDK versions the job needs besides the global.json SDK, + for example the 8.0.x and 9.0.x SDKs whose runtimes the older target + frameworks' tests execute on. + + .PARAMETER GlobalJsonPath + Path to the repository global.json. + + .PARAMETER InstallDirectory + Directory that receives the SDKs. Defaults to RUNNER_TEMP/dotnet, which is + empty at the start of every job. +#> +param( + [string] $AdditionalSdks = '', + [string] $GlobalJsonPath = 'global.json', + [string] $InstallDirectory = '' +) + +$ErrorActionPreference = 'Stop' + +if (-not (Test-Path -LiteralPath $GlobalJsonPath -PathType Leaf)) +{ + Write-Host "::error::'$GlobalJsonPath' does not exist; check out the repository first." + exit 1 +} + +$sdk = (Get-Content -LiteralPath $GlobalJsonPath -Raw | ConvertFrom-Json).sdk.version +if ([string]::IsNullOrWhiteSpace($sdk) -or $sdk -notmatch '^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$') +{ + Write-Host "::error::'$GlobalJsonPath' must pin an exact sdk.version; found '$sdk'." + exit 1 +} + +if ([string]::IsNullOrWhiteSpace($InstallDirectory)) +{ + if ([string]::IsNullOrWhiteSpace($env:RUNNER_TEMP)) + { + Write-Host '::error::RUNNER_TEMP is not set; pass -InstallDirectory explicitly.' + exit 1 + } + $InstallDirectory = Join-Path $env:RUNNER_TEMP 'dotnet' +} + +$versions = [System.Collections.Generic.List[string]]::new() +foreach ($line in $AdditionalSdks -split '\r?\n') +{ + $version = $line.Trim() + if ($version.Length -eq 0 -or $version -ceq $sdk -or $versions.Contains($version)) + { + continue + } + if ($version -notmatch '^\d+(\.(\d+|x)){1,2}(-[0-9A-Za-z.-]+)?$') + { + Write-Host "::error::'$version' is not a .NET SDK version that actions/setup-dotnet accepts." + exit 1 + } + $versions.Add($version) +} +$versions.Add($sdk) + +if (-not [string]::IsNullOrWhiteSpace($env:GITHUB_ENV)) +{ + "DOTNET_INSTALL_DIR=$InstallDirectory" | Out-File -FilePath $env:GITHUB_ENV -Append -Encoding utf8 +} +if (-not [string]::IsNullOrWhiteSpace($env:GITHUB_OUTPUT)) +{ + $delimiter = "versions_$([guid]::NewGuid().ToString('N'))" + @( + "sdk=$sdk" + "versions<<$delimiter" + $versions + $delimiter + ) | Out-File -FilePath $env:GITHUB_OUTPUT -Append -Encoding utf8 +} + +Write-Host "Installing .NET SDK(s) $($versions -join ', ') into '$InstallDirectory'; the build uses $sdk." diff --git a/.github/workflows/buildandtest.yml b/.github/workflows/buildandtest.yml index 2d3443e270..f6de64f368 100644 --- a/.github/workflows/buildandtest.yml +++ b/.github/workflows/buildandtest.yml @@ -317,9 +317,7 @@ jobs: fetch-depth: 0 - name: Setup .NET - uses: actions/setup-dotnet@v6 - with: - global-json-file: global.json + uses: ./.github/actions/setup-repository-dotnet - name: Download test results uses: actions/download-artifact@v8 @@ -490,9 +488,7 @@ jobs: fetch-depth: 0 - name: Setup .NET from global.json - uses: actions/setup-dotnet@v6 - with: - global-json-file: global.json + uses: ./.github/actions/setup-repository-dotnet - name: Set Cloud Version shell: pwsh @@ -560,20 +556,24 @@ jobs: # a shallow clone. fetch-depth: 0 - - name: Setup .NET SDKs for build matrix - uses: actions/setup-dotnet@v6 - with: - dotnet-version: ${{ matrix.entry.dotnet }} - - name: Setup repository .NET SDK - uses: actions/setup-dotnet@v6 + uses: ./.github/actions/setup-repository-dotnet with: - global-json-file: global.json + dotnet-version: ${{ matrix.entry.dotnet }} - name: Set cloud version shell: pwsh run: ./.azurepipelines/set-version.ps1 + # Only UA.slnx contains the Aspire AppHost, which imports the Aspire SDK + # when CustomTestTarget is empty or net10.0. + - name: Install the Aspire CLI bundle + if: >- + ${{ matrix.entry.solution == 'UA.slnx' && + (matrix.entry.customTestTarget == 'net10.0' || matrix.entry.customTestTarget == '') }} + shell: pwsh + run: ./.github/scripts/install-aspire-bundle.ps1 + - name: Build ${{ matrix.entry.solution }} (${{ matrix.entry.customTestTarget }}) shell: pwsh env: @@ -602,9 +602,7 @@ jobs: # Full history: Nerdbank.GitVersioning refuses to compute a version from # a shallow clone, which fails the build before any test runs. fetch-depth: 0 - - uses: actions/setup-dotnet@v6 - with: - global-json-file: global.json + - uses: ./.github/actions/setup-repository-dotnet - name: Validate manifest and negative controls shell: pwsh run: ./fuzzing/Scripts/validate-fuzz-manifest.ps1 -SelfTest @@ -655,16 +653,12 @@ jobs: # Full history: Nerdbank.GitVersioning refuses to compute a version from # a shallow clone, which fails the build before any test runs. fetch-depth: 0 - - name: Setup .NET 8 and 9 runtimes - uses: actions/setup-dotnet@v6 + - name: Setup repository .NET SDK with .NET 8 and 9 + uses: ./.github/actions/setup-repository-dotnet with: dotnet-version: | 8.0.x 9.0.x - - name: Setup repository .NET SDK - uses: actions/setup-dotnet@v6 - with: - global-json-file: global.json - name: Run fuzz regressions shell: pwsh run: ./fuzzing/Scripts/test-fuzzing.ps1 -Framework '${{ matrix.framework }}' -ResultsDirectory '${{ runner.temp }}/fuzz-results' diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 1f85d928c0..191b615f51 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -52,9 +52,11 @@ jobs: # queries: ./path/to/local/query, your-org/your-repo/queries@main - name: Set up .NET - uses: actions/setup-dotnet@v6 - with: - global-json-file: global.json + uses: ./.github/actions/setup-repository-dotnet + # UA.slnx contains the Aspire AppHost, which needs the Aspire CLI bundle. + - name: Install the Aspire CLI bundle + shell: pwsh + run: ./.github/scripts/install-aspire-bundle.ps1 # https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/codeql-code-scanning-for-compiled-languages#c-compiler-flags-injected-by-codeql-for-manual-builds # # CustomTestTarget pins the build to a single target framework (see diff --git a/.github/workflows/docker-image.yml b/.github/workflows/docker-image.yml index dbec6ca2f8..e4636a514e 100644 --- a/.github/workflows/docker-image.yml +++ b/.github/workflows/docker-image.yml @@ -147,9 +147,7 @@ jobs: fetch-depth: 0 - name: Set up .NET 10 - uses: actions/setup-dotnet@v6 - with: - global-json-file: global.json + uses: ./.github/actions/setup-repository-dotnet - name: Set Version shell: pwsh @@ -217,9 +215,7 @@ jobs: fetch-depth: 0 - name: Set up .NET 10 - uses: actions/setup-dotnet@v6 - with: - global-json-file: global.json + uses: ./.github/actions/setup-repository-dotnet - name: Set Version shell: pwsh diff --git a/.github/workflows/interop-foreign.yml b/.github/workflows/interop-foreign.yml index bef5b62542..cd3b17a59f 100644 --- a/.github/workflows/interop-foreign.yml +++ b/.github/workflows/interop-foreign.yml @@ -58,9 +58,7 @@ jobs: fetch-depth: 0 - name: Setup .NET - uses: actions/setup-dotnet@v6 - with: - global-json-file: global.json + uses: ./.github/actions/setup-repository-dotnet # ---------------------------------------------------------------- node-opcua - name: Setup Node.js diff --git a/.github/workflows/mcpgrade.yml b/.github/workflows/mcpgrade.yml index 63c86fa7ee..0dcab87476 100644 --- a/.github/workflows/mcpgrade.yml +++ b/.github/workflows/mcpgrade.yml @@ -36,9 +36,7 @@ jobs: fetch-depth: 0 - name: Setup .NET 10 - uses: actions/setup-dotnet@v6 - with: - global-json-file: global.json + uses: ./.github/actions/setup-repository-dotnet - name: Setup Node.js uses: actions/setup-node@v7 diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index bab31de99b..d19c1a76e8 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -108,8 +108,8 @@ jobs: with: fetch-depth: 0 - - name: Setup .NET - uses: actions/setup-dotnet@v6 + - name: Setup repository .NET SDK + uses: ./.github/actions/setup-repository-dotnet with: dotnet-version: ${{ matrix.entry.dotnet }} @@ -117,6 +117,15 @@ jobs: shell: pwsh run: ./.azurepipelines/set-version.ps1 + # Only UA.slnx contains the Aspire AppHost, which imports the Aspire SDK + # when CustomTestTarget is empty or net10.0. + - name: Install the Aspire CLI bundle + if: >- + ${{ matrix.entry.solution == 'UA.slnx' && + (matrix.entry.customTestTarget == 'net10.0' || matrix.entry.customTestTarget == '') }} + shell: pwsh + run: ./.github/scripts/install-aspire-bundle.ps1 + - name: Build ${{ matrix.entry.solution }} (${{ matrix.entry.customTestTarget }}) shell: pwsh env: @@ -179,9 +188,7 @@ jobs: fetch-depth: 0 - name: Setup .NET - uses: actions/setup-dotnet@v6 - with: - global-json-file: global.json + uses: ./.github/actions/setup-repository-dotnet - name: Set cloud version shell: pwsh @@ -274,9 +281,7 @@ jobs: fetch-depth: 0 - name: Setup .NET - uses: actions/setup-dotnet@v6 - with: - global-json-file: global.json + uses: ./.github/actions/setup-repository-dotnet - name: Download test results uses: actions/download-artifact@v8 diff --git a/.github/workflows/nuget-publish.yml b/.github/workflows/nuget-publish.yml index 775e2f0eb4..3841111aa3 100644 --- a/.github/workflows/nuget-publish.yml +++ b/.github/workflows/nuget-publish.yml @@ -126,9 +126,7 @@ jobs: fetch-depth: 0 - name: Setup .NET 10.0 - uses: actions/setup-dotnet@v6 - with: - global-json-file: global.json + uses: ./.github/actions/setup-repository-dotnet - name: Decode strong-name key shell: pwsh @@ -477,9 +475,7 @@ jobs: uses: actions/checkout@v6 - name: Setup .NET 10.0 - uses: actions/setup-dotnet@v6 - with: - global-json-file: global.json + uses: ./.github/actions/setup-repository-dotnet - name: Download signed package sets uses: actions/download-artifact@v8 diff --git a/.github/workflows/sample-ha-longhaul.yml b/.github/workflows/sample-ha-longhaul.yml index edca65f13d..6112858546 100644 --- a/.github/workflows/sample-ha-longhaul.yml +++ b/.github/workflows/sample-ha-longhaul.yml @@ -66,9 +66,7 @@ jobs: fetch-depth: 0 - name: Setup .NET from global.json - uses: actions/setup-dotnet@v6 - with: - global-json-file: global.json + uses: ./.github/actions/setup-repository-dotnet - name: Set Cloud Version shell: pwsh diff --git a/.github/workflows/stability-test.yml b/.github/workflows/stability-test.yml index c74391a816..74b5ec5eac 100644 --- a/.github/workflows/stability-test.yml +++ b/.github/workflows/stability-test.yml @@ -55,9 +55,7 @@ jobs: fetch-depth: 0 - name: Setup .NET from global.json - uses: actions/setup-dotnet@v6 - with: - global-json-file: global.json + uses: ./.github/actions/setup-repository-dotnet - name: Set Cloud Version shell: pwsh diff --git a/.github/workflows/stress-test.yml b/.github/workflows/stress-test.yml index 32c8a6c85c..cf12ef858b 100644 --- a/.github/workflows/stress-test.yml +++ b/.github/workflows/stress-test.yml @@ -57,9 +57,7 @@ jobs: fetch-depth: 0 - name: Setup .NET from global.json - uses: actions/setup-dotnet@v6 - with: - global-json-file: global.json + uses: ./.github/actions/setup-repository-dotnet - name: Set Cloud Version shell: pwsh @@ -125,9 +123,7 @@ jobs: fetch-depth: 0 - name: Setup .NET from global.json - uses: actions/setup-dotnet@v6 - with: - global-json-file: global.json + uses: ./.github/actions/setup-repository-dotnet - name: Set Cloud Version shell: pwsh diff --git a/.github/workflows/ualens-artifacts.yml b/.github/workflows/ualens-artifacts.yml index 63db2b871f..91152553c7 100644 --- a/.github/workflows/ualens-artifacts.yml +++ b/.github/workflows/ualens-artifacts.yml @@ -61,9 +61,7 @@ jobs: - uses: actions/checkout@v7 with: fetch-depth: 0 - - uses: actions/setup-dotnet@v6 - with: - global-json-file: global.json + - uses: ./.github/actions/setup-repository-dotnet - name: Run artifact validation unit tests with NUnit if: matrix.tfm == 'net10.0' shell: pwsh @@ -91,9 +89,7 @@ jobs: - uses: actions/checkout@v7 with: fetch-depth: 0 - - uses: actions/setup-dotnet@v6 - with: - global-json-file: global.json + - uses: ./.github/actions/setup-repository-dotnet - name: Build the desktop regression harness shell: pwsh run: | @@ -143,9 +139,7 @@ jobs: - uses: actions/checkout@v7 with: fetch-depth: 0 - - uses: actions/setup-dotnet@v6 - with: - global-json-file: global.json + - uses: ./.github/actions/setup-repository-dotnet - name: Linux native compiler and desktop prerequisites if: runner.os == 'Linux' run: | @@ -190,9 +184,7 @@ jobs: - uses: actions/checkout@v7 with: fetch-depth: 0 - - uses: actions/setup-dotnet@v6 - with: - global-json-file: global.json + - uses: ./.github/actions/setup-repository-dotnet - name: Restore and pack managed tool (never reuse native output) shell: pwsh run: | @@ -231,9 +223,7 @@ jobs: - uses: actions/checkout@v7 with: fetch-depth: 0 - - uses: actions/setup-dotnet@v6 - with: - global-json-file: global.json + - uses: ./.github/actions/setup-repository-dotnet - uses: actions/download-artifact@v8 with: name: ualens-managed-packages diff --git a/docs/DeveloperGuide.md b/docs/DeveloperGuide.md index 3d8e9f4f7f..79ad94fd8a 100644 --- a/docs/DeveloperGuide.md +++ b/docs/DeveloperGuide.md @@ -34,7 +34,7 @@ If you are new here, read the sections in order: [Prerequisites](#prerequisites) ## Prerequisites -- **.NET SDK 10.0.400 or later** — `global.json` sets this minimum and selects the highest installed stable SDK through `rollForward: latestMajor`; prerelease SDKs are excluded. CI selects its SDK version explicitly. The class libraries still *target* older frameworks (see [Packages, platform support, and versioning](#packages-platform-support-and-versioning)); those target frameworks do not determine the SDK used to build the repository. +- **.NET SDK 10.0.400 or later** — `global.json` sets this minimum and selects the highest installed stable SDK through `rollForward: latestMajor`; prerelease SDKs are excluded. CI installs the exact `global.json` SDK into a job-private directory through `.github/actions/setup-repository-dotnet`, so newer SDKs preinstalled on the runner image are not selected. The class libraries still *target* older frameworks (see [Packages, platform support, and versioning](#packages-platform-support-and-versioning)); those target frameworks do not determine the SDK used to build the repository. - **An IDE (optional but recommended)** — Visual Studio 2026, Visual Studio Code with the C# Dev Kit, or JetBrains Rider. Everything can also be done from the command line with `dotnet`. - **git** — to clone and to create feature branches. - **Docker Desktop (optional)** — only needed to run the containerized reference server; see [ContainerReferenceServer.md](ContainerReferenceServer.md). diff --git a/tests/Opc.Ua.Tools.Tests/TestMatrixScriptTests.cs b/tests/Opc.Ua.Tools.Tests/TestMatrixScriptTests.cs index cb92ccaa0c..085f04e111 100644 --- a/tests/Opc.Ua.Tools.Tests/TestMatrixScriptTests.cs +++ b/tests/Opc.Ua.Tools.Tests/TestMatrixScriptTests.cs @@ -44,7 +44,7 @@ namespace Opc.Ua.Tools.Tests public sealed class TestMatrixScriptTests { /// - /// Artifact qualification installs the exact repository SDK instead of a floating patch. + /// Artifact qualification installs only the exact repository SDK through the shared action. /// [Test] public async Task ArtifactJobsInstallTheRepositorySdkAsync() @@ -53,16 +53,98 @@ public async Task ArtifactJobsInstallTheRepositorySdkAsync() string source = await File.ReadAllTextAsync(path).ConfigureAwait(false); string[] steps = [.. source.ReplaceLineEndings("\n") .Split("\n - ", StringSplitOptions.None) - .Where(step => step.StartsWith("uses: actions/setup-dotnet@", StringComparison.Ordinal))]; + .Where(step => step.StartsWith(RepositorySdkAction, StringComparison.Ordinal))]; Assert.That(steps, Is.Not.Empty); foreach (string step in steps) { - Assert.That(step.Split('\n'), Does.Contain(" global-json-file: global.json")); Assert.That(step, Does.Not.Contain("dotnet-version:")); } } + /// + /// Runner images preinstall newer SDKs that the global.json roll-forward policy would + /// select, so every workflow installs .NET through the action that isolates the SDK. + /// + [Test] + public async Task WorkflowsInstallDotnetOnlyThroughTheRepositorySdkActionAsync() + { + string github = Path.Combine(FindRepositoryRoot(), ".github"); + string sharedAction = Path.Combine(github, "actions", "setup-repository-dotnet", "action.yml"); + // The release job checks out the candidate commit, which can predate the shared + // action, and only pushes packages that were already built. + string release = Path.Combine(github, "workflows", "release.yml"); + string[] files = [.. Directory.GetFiles(Path.Combine(github, "workflows"), "*.yml") + .Concat(Directory.GetFiles(Path.Combine(github, "actions"), "action.yml", SearchOption.AllDirectories)) + .Where(file => file != sharedAction && file != release)]; + + int uses = 0; + foreach (string file in files) + { + string source = await File.ReadAllTextAsync(file).ConfigureAwait(false); + Assert.That(source, Does.Not.Contain("actions/setup-dotnet@"), file); + uses += source.Split(RepositorySdkAction, StringSplitOptions.None).Length - 1; + } + Assert.That(uses, Is.GreaterThan(0)); + } + + /// + /// The SDK selection installs extra SDKs first, the global.json SDK last, into the + /// job-private directory. + /// + [Test] + public async Task RepositorySdkSelectionPinsTheGlobalJsonSdkLastAsync() + { + string directory = CreateSdkSelectionDirectory(); + try + { + string install = Path.Combine(directory, "dotnet"); + ScriptResult result = await RunSdkSelectionAsync( + directory, "8.0.x\n10.0.403\n 9.0.x \n8.0.x\n", install).ConfigureAwait(false); + + Assert.That(result.ExitCode, Is.Zero, result.Output); + string[] environment = await File.ReadAllLinesAsync( + Path.Combine(directory, "env")).ConfigureAwait(false); + Assert.That(environment, Is.EqualTo(new[] { "DOTNET_INSTALL_DIR=" + install })); + string[] output = await File.ReadAllLinesAsync( + Path.Combine(directory, "output")).ConfigureAwait(false); + Assert.That(output, Has.Length.EqualTo(6)); + Assert.That(output[0], Is.EqualTo("sdk=10.0.403")); + Assert.That(output[1], Does.StartWith("versions<<")); + Assert.That(string.Join(',', output[2..5]), Is.EqualTo("8.0.x,9.0.x,10.0.403")); + Assert.That(output[5], Is.EqualTo(output[1]["versions<<".Length..])); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + + /// + /// The SDK selection rejects a malformed extra version before anything is installed. + /// + [TestCase("latest")] + [TestCase("10")] + [TestCase("8.0.x; rm -rf /")] + public async Task RepositorySdkSelectionRejectsInvalidVersionsAsync(string version) + { + string directory = CreateSdkSelectionDirectory(); + try + { + ScriptResult result = await RunSdkSelectionAsync( + directory, version, Path.Combine(directory, "dotnet")).ConfigureAwait(false); + + Assert.That(result.ExitCode, Is.EqualTo(1), result.Output); + Assert.That(result.Output, Does.Contain("::error::")); + Assert.That(File.Exists(Path.Combine(directory, "env")), Is.False); + Assert.That(File.Exists(Path.Combine(directory, "output")), Is.False); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + /// /// Every artifact job that builds a project has the history needed by Git versioning. /// @@ -259,6 +341,35 @@ public async Task GitHubBatchScopesNativePathsToTheLinuxTestProcessAsync( Assert.That(document.RootElement.GetProperty("parent").GetString(), Is.EqualTo(inherited)); } + private static string CreateSdkSelectionDirectory() + { + string directory = Path.Combine(Path.GetTempPath(), "sdk-selection-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); + File.WriteAllText( + Path.Combine(directory, "global.json"), + """{"sdk":{"version":"10.0.403","rollForward":"latestMajor"}}"""); + return directory; + } + + private static Task RunSdkSelectionAsync( + string directory, + string additionalSdks, + string installDirectory) + { + string root = FindRepositoryRoot(); + string script = Path.Combine(root, ".github", "scripts", "select-repository-sdk.ps1"); + string command = $$""" + $env:GITHUB_ENV = {{QuotePowerShell(Path.Combine(directory, "env"))}} + $env:GITHUB_OUTPUT = {{QuotePowerShell(Path.Combine(directory, "output"))}} + & {{QuotePowerShell(script)}} ` + -AdditionalSdks {{QuotePowerShell(additionalSdks)}} ` + -GlobalJsonPath {{QuotePowerShell(Path.Combine(directory, "global.json"))}} ` + -InstallDirectory {{QuotePowerShell(installDirectory)}} + exit $LASTEXITCODE + """; + return RunPowerShellAsync(root, command); + } + private static Task RunGitHubFunctionAsync( string discovery, string invocation, @@ -344,6 +455,8 @@ private static string QuotePowerShell(string value) private const string LensProjectFile = "tests/Opc.Ua.Lens.Workflow.Tests/Opc.Ua.Lens.Workflow.Tests.csproj"; + private const string RepositorySdkAction = "uses: ./.github/actions/setup-repository-dotnet"; + private sealed record ScriptResult(int ExitCode, string Output); } } From 0cd9d71b1e9a92fba2a5038ea710495e7f5417bb Mon Sep 17 00:00:00 2001 From: Marc Date: Thu, 12 Nov 2026 19:49:30 +0100 Subject: [PATCH 6/8] Retry unload publications after predecision reference conflicts The WoT registry reconcile queue writes registry node references while a lifecycle publication is being prepared. The server then rejects the reservation with "Serving references changed during preparation." before the durable decision starts, so nothing was published. Activation units already retried this conflict, but unload and retire-only publications (an empty activation plan) called RefreshPreparedUnitAsync directly and surfaced the conflict to the caller. This made ProgrammaticUnloadAppliesPolicyWithoutReactivatingItsResolutionInput fail intermittently in CI. Both paths now share one helper that rebuilds the unit from live serving state within the existing three-attempt budget, with a short backoff so the concurrent writer can finish. Conflicts after the decision and unrelated failures are still propagated without a retry. --- ...tMaterializationCoordinator.Publication.cs | 78 +++++++++++++------ ...AtomicPublicationNativeTests.Boundaries.cs | 58 ++++++++++++++ 2 files changed, 112 insertions(+), 24 deletions(-) diff --git a/src/Opc.Ua.WotCon.Server/Materialization/WotMaterializationCoordinator.Publication.cs b/src/Opc.Ua.WotCon.Server/Materialization/WotMaterializationCoordinator.Publication.cs index 3b0dec01dd..ee4e9ebcfa 100644 --- a/src/Opc.Ua.WotCon.Server/Materialization/WotMaterializationCoordinator.Publication.cs +++ b/src/Opc.Ua.WotCon.Server/Materialization/WotMaterializationCoordinator.Publication.cs @@ -145,27 +145,10 @@ private async ValueTask RefreshPreparedUnitsAsync( WotRefreshResult result; try { - for (int attempt = 0; ; attempt++) - { - bool decisionStarted = false; - try - { - result = await RefreshPreparedUnitAsync( - unitCapture, snapshot, start, unit, includeSkipped, - publication, registryPublication, preview, cancellationToken, mutation, - () => decisionStarted = true) - .ConfigureAwait(false); - break; - } - catch (InvalidOperationException failure) when ( - !decisionStarted && attempt < 2 && - failure.Message is - "Serving references changed during batch preparation." or - "Serving references changed during preparation.") - { - await Task.Yield(); - } - } + result = await RefreshPreparedUnitWithRetryAsync( + unitCapture, snapshot, start, unit, includeSkipped, + publication, registryPublication, preview, mutation, cancellationToken) + .ConfigureAwait(false); } catch (WotRegistryCommitNotCommittedException failure) when ( rows.Any(row => row.Outcome is WoTOutcomeEnum.Success or WoTOutcomeEnum.Warning)) @@ -198,9 +181,9 @@ failure.Message is } if (plan.Units.IsEmpty) { - WotRefreshResult empty = await RefreshPreparedUnitAsync( - refresh, snapshot, start, [], true, publication, registryPublication, preview, cancellationToken, - mutation) + WotRefreshResult empty = await RefreshPreparedUnitWithRetryAsync( + refresh, snapshot, start, [], true, publication, registryPublication, preview, mutation, + cancellationToken) .ConfigureAwait(false); rows.AddRange(empty.Results); retired = empty.Summary.Retired; @@ -281,6 +264,52 @@ .. rows.GroupBy(row => (row.GroupId, row.ResourceId)).Select(group => return completed; } + /// + /// Publishes one prepared unit and rebuilds it when a concurrent serving-reference write + /// invalidates the prepared candidate before the durable decision starts. + /// + /// + /// Other server components, such as the registry projection, can write references of a node + /// that the publication prepared. The server then rejects the reservation before the decision, + /// so nothing was published and the unit is rebuilt from the live serving state. Unload and + /// retire-only publications without activation units use the same budget as activations. + /// + private async ValueTask RefreshPreparedUnitWithRetryAsync( + WotRefreshCapture refresh, + WotRegistrySnapshot snapshot, + DateTime start, + ArrayOf unit, + bool includeSkipped, + IWotProjectionPublication? publication, + IWotRegistryPublication? registryPublication, + PublicationCapture? preview, + WotRegistryMutationImage? mutation, + CancellationToken cancellationToken) + { + for (int attempt = 1; ; attempt++) + { + bool decisionStarted = false; + try + { + return await RefreshPreparedUnitAsync( + refresh, snapshot, start, unit, includeSkipped, + publication, registryPublication, preview, cancellationToken, mutation, + () => decisionStarted = true) + .ConfigureAwait(false); + } + catch (InvalidOperationException failure) when ( + !decisionStarted && attempt < kMaxPreparedPublicationAttempts && + failure.Message is + "Serving references changed during batch preparation." or + "Serving references changed during preparation.") + { + // Let the concurrent writer finish before the unit is prepared again. + await Task.Delay(TimeSpan.FromMilliseconds(10 * attempt), cancellationToken) + .ConfigureAwait(false); + } + } + } + private async ValueTask RefreshPreparedUnitAsync( WotRefreshCapture refresh, WotRegistrySnapshot snapshot, @@ -1526,6 +1555,7 @@ public ValueTask DeactivateAsync(WotBindingPlan plan, CancellationToken cancella } } + private const int kMaxPreparedPublicationAttempts = 3; private readonly IWotProjectionHost m_sourceHost; private readonly IWotViewProjectionHost m_sourceViewHost; private readonly IWotBinderRegistry m_sourceBinders; diff --git a/tests/Opc.Ua.WotCon.Tests/Materialization/WotAtomicPublicationNativeTests.Boundaries.cs b/tests/Opc.Ua.WotCon.Tests/Materialization/WotAtomicPublicationNativeTests.Boundaries.cs index 1e1d528e13..fe5f2c2daf 100644 --- a/tests/Opc.Ua.WotCon.Tests/Materialization/WotAtomicPublicationNativeTests.Boundaries.cs +++ b/tests/Opc.Ua.WotCon.Tests/Materialization/WotAtomicPublicationNativeTests.Boundaries.cs @@ -233,6 +233,64 @@ await Assert.ThatAsync(async () => await coordinator.RefreshAsync(HandoffRequest Assert.That(host.DisposedPublications, Is.EqualTo(attempts)); } + /// + /// Verifies that an unload without activation units rebuilds its publication after a + /// predecision reference conflict and stops at the publication budget. + /// + /// The number of predecision conflicts injected before success. + [TestCase(1)] + [TestCase(2)] + [TestCase(3)] + public async Task UnloadPublicationRetriesPredecisionReferenceConflictsWithinThePublicationBudget( + int conflicts) + { + m_coordinator.Dispose(); + var host = new PausableWotProjectionHost(new LifecycleWotProjectionHost(m_server.NodeManagerLifecycle)); + m_coordinator = new WotMaterializationCoordinator(m_registry, host, documentConverter: m_converter) + { + ServerNamespaceUris = m_server.CurrentInstance.NamespaceUris, + DeletePolicy = WoTDeletePolicyEnum.Force + }; + WotResource resource = await AddAsync("unload-conflict").ConfigureAwait(false); + WotRefreshResult loaded = await m_coordinator.RefreshAsync(HandoffRequest("unload-conflict-load")) + .ConfigureAwait(false); + Assert.That(loaded.NewGeneration, Is.EqualTo(1u)); + WotRegistrySnapshot before = m_registry.Current; + int disposedBefore = host.DisposedPublications; + int attempts = 0; + host.BeforeCommit = () => + { + if (++attempts <= conflicts) + { + throw new InvalidOperationException("Serving references changed during preparation."); + } + }; + + if (conflicts < 3) + { + WotRegistryMutationResult result = await m_coordinator.SetEnabledAsync( + resource.GroupId, resource.ResourceId, false).ConfigureAwait(false); + + Assert.That(result.Outcome, Is.EqualTo(WoTOutcomeEnum.Success), result.Message); + Assert.That(m_registry.Current.FindResourceByXid(resource.Xid)!.Enabled, Is.False); + Assert.That((await ReadNodeClassAsync(Root(resource)).ConfigureAwait(false)).StatusCode, + Is.EqualTo(StatusCodes.BadNodeIdUnknown)); + } + else + { + await Assert.ThatAsync(async () => await m_coordinator.SetEnabledAsync( + resource.GroupId, resource.ResourceId, false).ConfigureAwait(false), + Throws.TypeOf() + .With.Message.EqualTo("Serving references changed during preparation.")).ConfigureAwait(false); + + Assert.That(m_registry.Current, Is.SameAs(before)); + Assert.That((await ReadNodeClassAsync(Root(resource)).ConfigureAwait(false)).StatusCode, + Is.EqualTo(StatusCodes.Good)); + } + Assert.That(attempts, Is.EqualTo(Math.Min(conflicts + 1, 3))); + Assert.That(host.DisposedPublications - disposedBefore, Is.EqualTo(attempts)); + } + /// /// Verifies that an unrelated publication error is propagated immediately without retry. /// From 5818d402fc1c6c0d085808d8ca91d86632919c79 Mon Sep 17 00:00:00 2001 From: Marc Date: Thu, 12 Nov 2026 21:16:06 +0100 Subject: [PATCH 7/8] Ignore the initial connect notification in redundancy state tests FailoverAsyncSwitchesToExplicitTargetAsync failed intermittently in CI with "Expected: Failover But was: Connected". ConnectionStateMachine releases the ConnectAsync waiters before it dispatches the Connecting -> Connected notification, so a handler subscribed right after ConnectAsync returns can still receive that initial transition. Injecting a delay before the dispatch reproduced the failure in this test and in two reverse-connect redundancy tests that subscribe the same way. The tests now record only transitions that do not start in Connecting, via a shared RecordStatesAfterConnect helper. All 25 redundancy tests pass with and without the injected delay. --- ...ionServerRedundancyTests.ReverseConnect.cs | 6 ++---- .../ManagedSessionServerRedundancyTests.cs | 21 +++++++++++++++++-- 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/tests/Opc.Ua.Client.Tests/Session/ManagedSessionServerRedundancyTests.ReverseConnect.cs b/tests/Opc.Ua.Client.Tests/Session/ManagedSessionServerRedundancyTests.ReverseConnect.cs index c8cc63dd8b..817fe72c6e 100644 --- a/tests/Opc.Ua.Client.Tests/Session/ManagedSessionServerRedundancyTests.ReverseConnect.cs +++ b/tests/Opc.Ua.Client.Tests/Session/ManagedSessionServerRedundancyTests.ReverseConnect.cs @@ -104,8 +104,7 @@ public async Task ReverseConnectServiceLevelDropFailsOverOverMemberConnectionAsy await using UaManagedSession session = await set.ConnectAsync(options, null, timeout.Token) .ConfigureAwait(false); Assert.That(ServerUriOf(session), Is.EqualTo(set.Primary.ApplicationUri)); - var states = new ConcurrentQueue(); - session.ConnectionStateChanged += (_, e) => states.Enqueue(e.NewState); + ConcurrentQueue states = RecordStatesAfterConnect(session); set.Primary.SetServiceLevel(150); await WaitUntilAsync( @@ -203,8 +202,7 @@ public async Task ReverseConnectMemberWithoutConnectionIsNeverSelectedAsync() }; await using UaManagedSession session = await set.ConnectAsync(options, null, timeout.Token) .ConfigureAwait(false); - var states = new ConcurrentQueue(); - session.ConnectionStateChanged += (_, e) => states.Enqueue(e.NewState); + ConcurrentQueue states = RecordStatesAfterConnect(session); ServerRedundancyInfo info = await WaitForMemberAsync( session, set.Backup, server => server.ResolutionError != null, timeout.Token).ConfigureAwait(false); diff --git a/tests/Opc.Ua.Client.Tests/Session/ManagedSessionServerRedundancyTests.cs b/tests/Opc.Ua.Client.Tests/Session/ManagedSessionServerRedundancyTests.cs index 68c2230113..b8ce9922e8 100644 --- a/tests/Opc.Ua.Client.Tests/Session/ManagedSessionServerRedundancyTests.cs +++ b/tests/Opc.Ua.Client.Tests/Session/ManagedSessionServerRedundancyTests.cs @@ -391,8 +391,7 @@ public async Task FailoverAsyncSwitchesToExplicitTargetAsync(bool useChannelMana await using UaManagedSession session = await set.ConnectAsync( new ServerRedundancyOptions(), timeout.Token, channelManager: channels).ConfigureAwait(false); Assert.That(set.Primary.SessionCount, Is.EqualTo(1)); - var states = new ConcurrentQueue(); - session.ConnectionStateChanged += (_, e) => states.Enqueue(e.NewState); + ConcurrentQueue states = RecordStatesAfterConnect(session); await session.FailoverAsync(set.Backup.Endpoint, timeout.Token).ConfigureAwait(false); await WaitUntilAsync(() => states.Contains(ConnectionState.Connected), timeout.Token).ConfigureAwait(false); @@ -456,6 +455,24 @@ await Assert.ThatAsync( return session.ConfiguredEndpoint.Description.Server?.ApplicationUri; } + /// + /// Records the connection states the session enters from now on. The connect + /// call can return before the notification of the initial Connecting to Connected + /// transition is delivered, so that late notification is not recorded. + /// + private static ConcurrentQueue RecordStatesAfterConnect(UaManagedSession session) + { + var states = new ConcurrentQueue(); + session.ConnectionStateChanged += (_, e) => + { + if (e.PreviousState != ConnectionState.Connecting) + { + states.Enqueue(e.NewState); + } + }; + return states; + } + private static async Task WaitUntilAsync(Func condition, CancellationToken ct) { while (!condition()) From 24449c1c83961d85301b5f3e5a9c1742124bfa13 Mon Sep 17 00:00:00 2001 From: Marc Date: Fri, 13 Nov 2026 08:54:58 +0100 Subject: [PATCH 8/8] Install .NET 10 runtime for MCP grading --- .github/workflows/mcpgrade.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/mcpgrade.yml b/.github/workflows/mcpgrade.yml index 0dcab87476..fa79b70bbd 100644 --- a/.github/workflows/mcpgrade.yml +++ b/.github/workflows/mcpgrade.yml @@ -37,6 +37,8 @@ jobs: - name: Setup .NET 10 uses: ./.github/actions/setup-repository-dotnet + with: + dotnet-version: 10.0.x - name: Setup Node.js uses: actions/setup-node@v7