Files
UA-.NETStandard/tests/Opc.Ua.Core.Security.Tests/PushCertManagementTests.cs
romanett 9b034f8291 Enable nullable reference types centrally; migrate all unset and annotations-only projects (#4700)
# Description

Nullable reference types are now enabled once, in `common.props`, and
every project in the repository builds warning-clean with them.

**Configuration**
- `<Nullable>enable</Nullable>` lives in `common.props`. All per-project
`<Nullable>` settings are removed: 178 project files (enable,
annotations, and the `disable` in the three Aot test projects).
- 419 per-file `#nullable enable`/`restore` directives and the 4
`#nullable disable` directives are removed.
- Kept on purpose:
- The 5 `<auto-generated>` schema files (`UANodeSet.cs`, `UA Type
Dictionary.cs`, `OPCBinarySchema.cs`, `SecuredApplication.cs`,
`PInvokeHelper.cs`) keep `#nullable enable`. The compiler ignores the
project setting in generated code, so the directive is required there.
- `tests/Opc.Ua.Interop.LegacyPeer` keeps `disable`. It builds against
the 1.5.378 packages and does not import the repository props.
- `docs/DeveloperGuide.md` and `.github/copilot-instructions.md` now
describe the central setting.

**Migration** (the 43 unset and 13 annotations-only projects, roughly
10k diagnostics)
- **Production code: annotated at the declarations.** Covers
`tools/Opc.Ua.SourceGeneration.Core`, `src/Opc.Ua.Lds.Server` and the
LDS sample.
- Members, parameters and returns are nullable where null actually
flows.
- Null-check helpers carry `[NotNullWhen]` (`IsNull`, `IsValidXmlName`,
`IsMethodTypeDesign`).
- `CoreUtils.Format`, `Utils.Format`, `ITemplateWriter.WriteLine` take
`params object?[]`. `Template.AddReplacement` takes `string?` (rendering
already skips null replacements).
- `IRegisteredServerStore.RegisterAsync` returns
`Task<RegistrationEntry?>`: it returns null when a registration is
removed.
- Dereferences backed by an invariant (for example, the validated model)
use `!`, so runtime behaviour is unchanged.
- **Behavioural changes in production code** (small, deliberate):
- `NodeSetToModelDesign` throws `InvalidOperationException` when the
file is not a NodeSet. Before, it threw a NullReferenceException on the
next line.
- `ModelDesignValidator` starts its lookup tables empty instead of null.
A redundant `if (m_nodes == null) return;` guard is gone.
- **Test code: minimal annotations.**
  - `?` on values that can be null, `!` where the test asserts non-null.
  - `= null!` for fixture members assigned in SetUp.
- `TryGetStructure<T>(out T? x)` where the inferred `T?` broke the
`IEncodeable` constraint.
- A few redundant `== null` checks on structs (`NodeId`, `ArrayOf<T>`)
folded into the adjacent `IsNull`/`Count` checks.

**Notes for reviewers**
- The diff is large (~1,500 files) but almost entirely mechanical: `?`,
`!` and directive removal. The non-annotation changes are listed above.
- Known follow-up, not done here:
`IModelDesign.Namespaces/TargetNamespace/NamespaceUris` stay
non-nullable even though the validator returns null before it loads a
dictionary. Making them nullable would ripple through every generator
call site.

## Related Issues

- Fixes #4439

## Checklist

- [ ] I have signed the
[CLA](https://opcfoundation.org/license/cla/ContributorLicenseAgreementv1.0.pdf)
and read the
[CONTRIBUTING](https://github.com/OPCFoundation/UA-.NETStandard/blob/master/CONTRIBUTING.md)
doc.
- [ ] I have added tests that prove my fix is effective or that my
feature works and increased code coverage.
- [x] I have added all necessary documentation.
- [x] I have verified that my changes do not introduce (new) build or
analyzer warnings.
- [ ] I ran **all** tests locally using the **UA.slnx** solution against
at least .net **framework** and .net **10**, and all passed.
- [ ] I fixed **all** failing and flaky tests in the CI pipelines and
**all** CodeQL warnings.
- [ ] I have addressed **all** PR feedback received.

The "no new warnings" box covers net10.0 and net48: full non-incremental
builds of `UA.slnx`, `tools/SourceGeneration.slnx`,
`tools/MigrationAnalyzer.slnx` and the Aot test projects finished with 0
warnings and 0 errors under the repository's warnings-as-errors
settings. net9.0 and net8.0 also had no nullable diagnostics, but they
were not rebuilt after the final fixes. Tests have not been run locally
yet.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-08 08:48:13 +02:00

1156 lines
45 KiB
C#

/* ========================================================================
* 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.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using NUnit.Framework;
using Opc.Ua.Client;
using Opc.Ua.Client.TestFramework;
namespace Opc.Ua.Core.Security.Tests
{
/// <summary>
/// compliance tests for the Push Certificate Management model
/// (ServerConfiguration object and related methods).
/// </summary>
[TestFixture]
[Category("Conformance")]
[Category("Security")]
[Category("PushCertManagement")]
public class PushCertManagementTests : TestFixture
{
[Test]
public async Task BrowseServerConfigurationExistsAsync()
{
ArrayOf<ReferenceDescription> refs = await BrowseChildrenAsync(
Session, ServerNodeId).ConfigureAwait(false);
bool found = refs.ToArray()!.Any(r => r.BrowseName.Name == "ServerConfiguration");
Assert.That(found, Is.True,
"Server should have a ServerConfiguration component.");
}
[Test]
public async Task BrowseCertificateGroupsExistsAsync()
{
NodeId certGroupsId = await FindChildAsync(
Session, ServerConfigurationNodeId, "CertificateGroups")
.ConfigureAwait(false);
Assert.That(certGroupsId.IsNull, Is.False,
"ServerConfiguration should have CertificateGroups.");
}
[Test]
public async Task BrowseDefaultApplicationGroupExistsAsync()
{
NodeId defaultGroup = await FindDefaultApplicationGroupAsync(Session)
.ConfigureAwait(false);
Assert.That(defaultGroup.IsNull, Is.False,
"CertificateGroups should contain DefaultApplicationGroup.");
}
[Test]
public async Task BrowseDefaultApplicationGroupHasCertificateTypesAsync()
{
NodeId defaultGroup = await FindDefaultApplicationGroupAsync(Session)
.ConfigureAwait(false);
if (defaultGroup.IsNull)
{
Assert.Fail("DefaultApplicationGroup not found.");
}
NodeId certTypes = await FindChildAsync(
Session, defaultGroup, "CertificateTypes").ConfigureAwait(false);
Assert.That(certTypes.IsNull, Is.False,
"DefaultApplicationGroup should have CertificateTypes.");
}
[Test]
public async Task BrowseDefaultApplicationGroupHasTrustListAsync()
{
NodeId defaultGroup = await FindDefaultApplicationGroupAsync(Session)
.ConfigureAwait(false);
if (defaultGroup.IsNull)
{
Assert.Fail("DefaultApplicationGroup not found.");
}
NodeId trustList = await FindChildAsync(
Session, defaultGroup, "TrustList").ConfigureAwait(false);
Assert.That(trustList.IsNull, Is.False,
"DefaultApplicationGroup should have TrustList.");
}
[Test]
public async Task BrowseDefaultHttpsGroupIfExistsAsync()
{
NodeId certGroupsId = await FindChildAsync(
Session, ServerConfigurationNodeId, "CertificateGroups")
.ConfigureAwait(false);
if (certGroupsId.IsNull)
{
Assert.Fail("CertificateGroups not found.");
}
NodeId httpsGroup = await FindChildAsync(
Session, certGroupsId, "DefaultHttpsGroup").ConfigureAwait(false);
if (httpsGroup.IsNull)
{
Assert.Fail("DefaultHttpsGroup not present on this server.");
}
NodeId certTypes = await FindChildAsync(
Session, httpsGroup, "CertificateTypes").ConfigureAwait(false);
Assert.That(certTypes.IsNull, Is.False,
"DefaultHttpsGroup should have CertificateTypes if present.");
}
[Test]
public async Task BrowseDefaultUserTokenGroupIfExistsAsync()
{
NodeId certGroupsId = await FindChildAsync(
Session, ServerConfigurationNodeId, "CertificateGroups")
.ConfigureAwait(false);
if (certGroupsId.IsNull)
{
Assert.Fail("CertificateGroups not found.");
}
NodeId userTokenGroup = await FindChildAsync(
Session, certGroupsId, "DefaultUserTokenGroup")
.ConfigureAwait(false);
if (userTokenGroup.IsNull)
{
Assert.Fail("DefaultUserTokenGroup not present on this server.");
}
NodeId certTypes = await FindChildAsync(
Session, userTokenGroup, "CertificateTypes").ConfigureAwait(false);
Assert.That(certTypes.IsNull, Is.False,
"DefaultUserTokenGroup should have CertificateTypes if present.");
}
[Test]
public async Task BrowseServerConfigurationMethodsAsync()
{
ArrayOf<ReferenceDescription> refs = await BrowseChildrenAsync(
Session, ServerConfigurationNodeId).ConfigureAwait(false);
var names = refs.ToArray()!.Select(r => r.BrowseName.Name).ToList();
Assert.That(names, Does.Not.Contain("UpdateCertificate"));
Assert.That(names, Does.Not.Contain("CreateSigningRequest"));
Assert.That(names, Does.Not.Contain("ApplyChanges"));
Assert.That(names, Does.Not.Contain("GetRejectedList"));
}
[Test]
public async Task VerifyPushModelMethodsExistOnTypeDefinitionAsync()
{
// ServerConfigurationType = i=12581
var typeId = new NodeId(12581u);
ArrayOf<ReferenceDescription> refs = await BrowseChildrenAsync(
Session, typeId).ConfigureAwait(false);
var names = refs.ToArray()!.Select(r => r.BrowseName.Name).ToList();
// Some servers may define these methods only on the instance,
// not on the type definition. Fall back to the instance if needed.
if (!names.Contains("UpdateCertificate"))
{
refs = await BrowseChildrenAsync(
Session, ServerConfigurationNodeId).ConfigureAwait(false);
names = [.. refs.ToArray()!.Select(r => r.BrowseName.Name)];
}
Assert.That(names, Does.Contain("UpdateCertificate"));
Assert.That(names, Does.Contain("CreateSigningRequest"));
Assert.That(names, Does.Contain("ApplyChanges"));
Assert.That(names, Does.Contain("GetRejectedList"));
}
[Test]
public async Task ReadCertificateTypesFromDefaultApplicationGroupAsync()
{
NodeId defaultGroup = await FindDefaultApplicationGroupAsync(Session)
.ConfigureAwait(false);
if (defaultGroup.IsNull)
{
Assert.Fail("DefaultApplicationGroup not found.");
}
NodeId certTypesId = await FindChildAsync(
Session, defaultGroup, "CertificateTypes").ConfigureAwait(false);
if (certTypesId.IsNull)
{
Assert.Fail("CertificateTypes not found.");
}
DataValue value = await Session.ReadValueAsync(
certTypesId, CancellationToken.None).ConfigureAwait(false);
Assert.That(value.StatusCode, Is.EqualTo(StatusCodes.Good));
Assert.That(value.WrappedValue.TryGetValue(out ArrayOf<NodeId> _), Is.True);
}
[Test]
public async Task ReadMaxTrustListSizeAsync()
{
NodeId maxTrustListId = await FindChildAsync(
Session, ServerConfigurationNodeId, "MaxTrustListSize")
.ConfigureAwait(false);
if (maxTrustListId.IsNull)
{
Assert.Fail("MaxTrustListSize not found.");
}
DataValue value = await Session.ReadValueAsync(
maxTrustListId, CancellationToken.None).ConfigureAwait(false);
Assert.That(value.StatusCode, Is.EqualTo(StatusCodes.Good));
}
[Test]
public async Task ReadMulticastDnsEnabledAsync()
{
NodeId multicastId = await FindChildAsync(
Session, ServerConfigurationNodeId, "MulticastDnsEnabled")
.ConfigureAwait(false);
if (multicastId.IsNull)
{
Assert.Fail("MulticastDnsEnabled not found on this server.");
}
DataValue value = await Session.ReadValueAsync(
multicastId, CancellationToken.None).ConfigureAwait(false);
Assert.That(value.StatusCode, Is.EqualTo(StatusCodes.Good));
}
[Test]
public async Task ReadServerCapabilitiesAsync()
{
NodeId capabilitiesId = await FindChildAsync(
Session, ServerConfigurationNodeId, "ServerCapabilities")
.ConfigureAwait(false);
if (capabilitiesId.IsNull)
{
Assert.Fail("ServerCapabilities not found.");
}
DataValue value = await Session.ReadValueAsync(
capabilitiesId, CancellationToken.None).ConfigureAwait(false);
Assert.That(value.StatusCode, Is.EqualTo(StatusCodes.Good));
}
[Test]
public async Task ReadSupportedPrivateKeyFormatsAsync()
{
NodeId formatsId = await FindChildAsync(
Session, ServerConfigurationNodeId, "SupportedPrivateKeyFormats")
.ConfigureAwait(false);
if (formatsId.IsNull)
{
Assert.Fail("SupportedPrivateKeyFormats not found.");
}
DataValue value = await Session.ReadValueAsync(
formatsId, CancellationToken.None).ConfigureAwait(false);
Assert.That(value.StatusCode, Is.EqualTo(StatusCodes.Good));
}
[Test]
public async Task TrustListOpenReadCloseAsync()
{
using ISession session = await TryConnectAsAdminAsync().ConfigureAwait(false);
if (session == null)
{
Assert.Ignore("Admin session not available on this endpoint.");
}
NodeId defaultGroup = await FindDefaultApplicationGroupAsync(session)
.ConfigureAwait(false);
if (defaultGroup.IsNull)
{
Assert.Ignore("DefaultApplicationGroup not found.");
}
NodeId trustListId = await FindChildAsync(
session, defaultGroup, "TrustList").ConfigureAwait(false);
if (trustListId.IsNull)
{
Assert.Ignore("TrustList not found.");
}
NodeId openMethodId = await FindChildAsync(
session, trustListId, "Open").ConfigureAwait(false);
if (openMethodId.IsNull)
{
Assert.Ignore("TrustList.Open not found.");
}
try
{
// Open for reading (mode = 1)
CallMethodResult openResult = await CallMethodAsync(
session, trustListId, openMethodId,
new Variant((byte)1)).ConfigureAwait(false);
if (openResult.StatusCode == StatusCodes.BadNotImplemented ||
openResult.StatusCode == StatusCodes.BadServiceUnsupported ||
openResult.StatusCode == StatusCodes.BadUserAccessDenied)
{
Assert.Ignore($"TrustList.Open not implemented: {openResult.StatusCode}");
}
Assert.That(StatusCode.IsGood(openResult.StatusCode), Is.True);
Assert.That(openResult.OutputArguments.Count, Is.GreaterThan(0));
uint fileHandle = (uint)openResult.OutputArguments[0];
// Read
NodeId readMethodId = await FindChildAsync(
session, trustListId, "Read").ConfigureAwait(false);
if (!readMethodId.IsNull)
{
CallMethodResult readResult = await CallMethodAsync(
session, trustListId, readMethodId,
new Variant(fileHandle),
new Variant(65536)).ConfigureAwait(false);
Assert.That(StatusCode.IsGood(readResult.StatusCode), Is.True);
}
// Close
NodeId closeMethodId = await FindChildAsync(
session, trustListId, "Close").ConfigureAwait(false);
if (!closeMethodId.IsNull)
{
await CallMethodAsync(
session, trustListId, closeMethodId,
new Variant(fileHandle)).ConfigureAwait(false);
}
}
catch (ServiceResultException sre)
when (sre.StatusCode == StatusCodes.BadNotImplemented ||
sre.StatusCode == StatusCodes.BadServiceUnsupported ||
sre.StatusCode == StatusCodes.BadUserAccessDenied)
{
Assert.Ignore($"TrustList operations not supported: {sre.StatusCode}");
}
}
[Test]
public async Task TrustListSizePropertyAsync()
{
NodeId defaultGroup = await FindDefaultApplicationGroupAsync(Session)
.ConfigureAwait(false);
if (defaultGroup.IsNull)
{
Assert.Fail("DefaultApplicationGroup not found.");
}
NodeId trustListId = await FindChildAsync(
Session, defaultGroup, "TrustList").ConfigureAwait(false);
if (trustListId.IsNull)
{
Assert.Fail("TrustList not found.");
}
NodeId sizeId = await FindChildAsync(
Session, trustListId, "Size").ConfigureAwait(false);
if (sizeId.IsNull)
{
Assert.Fail("TrustList.Size not found.");
}
DataValue value = await Session.ReadValueAsync(
sizeId, CancellationToken.None).ConfigureAwait(false);
Assert.That(value.StatusCode, Is.EqualTo(StatusCodes.Good));
}
[Test]
public async Task TrustListGetPositionSetPositionAsync()
{
using ISession session = await TryConnectAsAdminAsync().ConfigureAwait(false);
if (session == null)
{
Assert.Ignore("Admin session not available on this endpoint.");
}
NodeId defaultGroup = await FindDefaultApplicationGroupAsync(session)
.ConfigureAwait(false);
if (defaultGroup.IsNull)
{
Assert.Ignore("DefaultApplicationGroup not found.");
}
NodeId trustListId = await FindChildAsync(
session, defaultGroup, "TrustList").ConfigureAwait(false);
if (trustListId.IsNull)
{
Assert.Ignore("TrustList not found.");
}
NodeId openMethodId = await FindChildAsync(
session, trustListId, "Open").ConfigureAwait(false);
if (openMethodId.IsNull)
{
Assert.Ignore("TrustList.Open not found.");
}
try
{
CallMethodResult openResult = await CallMethodAsync(
session, trustListId, openMethodId,
new Variant((byte)1)).ConfigureAwait(false);
if (openResult.StatusCode == StatusCodes.BadNotImplemented ||
openResult.StatusCode == StatusCodes.BadServiceUnsupported ||
openResult.StatusCode == StatusCodes.BadUserAccessDenied)
{
Assert.Ignore($"TrustList.Open not implemented: {openResult.StatusCode}");
}
uint fileHandle = (uint)openResult.OutputArguments[0];
try
{
NodeId getPosId = await FindChildAsync(
session, trustListId, "GetPosition").ConfigureAwait(false);
if (!getPosId.IsNull)
{
CallMethodResult posResult = await CallMethodAsync(
session, trustListId, getPosId,
new Variant(fileHandle)).ConfigureAwait(false);
// GetPosition may not be implemented on the TrustList
// FileType subtype — accept BadNotImplemented /
// BadServiceUnsupported as a "feature-not-supported"
// outcome rather than failing the test.
if (StatusCode.IsBad(posResult.StatusCode) &&
posResult.StatusCode != StatusCodes.BadNotImplemented &&
posResult.StatusCode != StatusCodes.BadServiceUnsupported &&
posResult.StatusCode != StatusCodes.BadNotSupported)
{
Assert.That(
StatusCode.IsGood(posResult.StatusCode), Is.True);
}
}
NodeId setPosId = await FindChildAsync(
session, trustListId, "SetPosition").ConfigureAwait(false);
if (!setPosId.IsNull)
{
CallMethodResult setResult = await CallMethodAsync(
session, trustListId, setPosId,
new Variant(fileHandle),
new Variant((ulong)0)).ConfigureAwait(false);
if (StatusCode.IsBad(setResult.StatusCode) &&
setResult.StatusCode != StatusCodes.BadNotImplemented &&
setResult.StatusCode != StatusCodes.BadServiceUnsupported &&
setResult.StatusCode != StatusCodes.BadNotSupported)
{
Assert.That(
StatusCode.IsGood(setResult.StatusCode), Is.True);
}
}
}
finally
{
NodeId closeMethodId = await FindChildAsync(
session, trustListId, "Close").ConfigureAwait(false);
if (!closeMethodId.IsNull)
{
await CallMethodAsync(
session, trustListId, closeMethodId,
new Variant(fileHandle)).ConfigureAwait(false);
}
}
}
catch (ServiceResultException sre)
when (sre.StatusCode == StatusCodes.BadNotImplemented ||
sre.StatusCode == StatusCodes.BadServiceUnsupported ||
sre.StatusCode == StatusCodes.BadUserAccessDenied)
{
Assert.Ignore(
$"TrustList operations not supported: {sre.StatusCode}");
}
}
[Test]
public async Task GetRejectedListReturnsResultAsync()
{
using ISession session = await TryConnectAsAdminAsync().ConfigureAwait(false);
if (session == null)
{
Assert.Ignore("Admin session not available on this endpoint.");
}
NodeId methodId = await FindChildAsync(
session, ServerConfigurationNodeId, "GetRejectedList")
.ConfigureAwait(false);
if (methodId.IsNull)
{
Assert.Ignore("GetRejectedList not found.");
}
try
{
CallMethodResult result = await CallMethodAsync(
session, ServerConfigurationNodeId, methodId)
.ConfigureAwait(false);
if (result.StatusCode == StatusCodes.BadNotImplemented ||
result.StatusCode == StatusCodes.BadServiceUnsupported ||
result.StatusCode == StatusCodes.BadUserAccessDenied)
{
Assert.Ignore($"GetRejectedList not implemented: {result.StatusCode}");
}
Assert.That(StatusCode.IsGood(result.StatusCode), Is.True,
$"GetRejectedList returned: 0x{result.StatusCode.Code:X8}");
}
catch (ServiceResultException sre)
when (sre.StatusCode == StatusCodes.BadNotImplemented ||
sre.StatusCode == StatusCodes.BadServiceUnsupported)
{
Assert.Ignore(
$"GetRejectedList not implemented: {sre.StatusCode}");
}
}
[Test]
public async Task GetCertificatesForDefaultApplicationGroupAsync()
{
using ISession session = await TryConnectAsAdminAsync().ConfigureAwait(false);
if (session == null)
{
Assert.Ignore("Admin session not available on this endpoint.");
}
NodeId getCertsId = await FindChildAsync(
session, ServerConfigurationNodeId, "GetCertificates")
.ConfigureAwait(false);
if (getCertsId.IsNull)
{
Assert.Ignore("GetCertificates not found.");
}
NodeId defaultGroup = await FindDefaultApplicationGroupAsync(session)
.ConfigureAwait(false);
if (defaultGroup.IsNull)
{
Assert.Ignore("DefaultApplicationGroup not found.");
}
try
{
CallMethodResult result = await CallMethodAsync(
session, ServerConfigurationNodeId, getCertsId,
new Variant(defaultGroup)).ConfigureAwait(false);
if (result.StatusCode == StatusCodes.BadNotImplemented ||
result.StatusCode == StatusCodes.BadServiceUnsupported ||
result.StatusCode == StatusCodes.BadUserAccessDenied)
{
Assert.Ignore($"GetCertificates not implemented: {result.StatusCode}");
}
Assert.That(StatusCode.IsGood(result.StatusCode), Is.True);
}
catch (ServiceResultException sre)
when (sre.StatusCode == StatusCodes.BadNotImplemented ||
sre.StatusCode == StatusCodes.BadServiceUnsupported)
{
Assert.Ignore(
$"GetCertificates not implemented: {sre.StatusCode}");
}
}
[Test]
public async Task GetCertificatesReturnsProperStructureAsync()
{
using ISession session = await TryConnectAsAdminAsync().ConfigureAwait(false);
if (session == null)
{
Assert.Ignore("Admin session not available on this endpoint.");
}
NodeId getCertsId = await FindChildAsync(
session, ServerConfigurationNodeId, "GetCertificates")
.ConfigureAwait(false);
if (getCertsId.IsNull)
{
Assert.Ignore("GetCertificates not found.");
}
NodeId defaultGroup = await FindDefaultApplicationGroupAsync(session)
.ConfigureAwait(false);
if (defaultGroup.IsNull)
{
Assert.Ignore("DefaultApplicationGroup not found.");
}
try
{
CallMethodResult result = await CallMethodAsync(
session, ServerConfigurationNodeId, getCertsId,
new Variant(defaultGroup)).ConfigureAwait(false);
if (result.StatusCode == StatusCodes.BadNotImplemented ||
result.StatusCode == StatusCodes.BadServiceUnsupported ||
result.StatusCode == StatusCodes.BadUserAccessDenied)
{
Assert.Ignore($"GetCertificates not implemented: {result.StatusCode}");
}
Assert.That(StatusCode.IsGood(result.StatusCode), Is.True);
Assert.That(result.OutputArguments.Count, Is.GreaterThanOrEqualTo(1));
}
catch (ServiceResultException sre)
when (sre.StatusCode == StatusCodes.BadNotImplemented ||
sre.StatusCode == StatusCodes.BadServiceUnsupported)
{
Assert.Ignore(
$"GetCertificates not implemented: {sre.StatusCode}");
}
}
[Test]
public async Task CreateSigningRequestWithValidParametersAsync()
{
using ISession session = await TryConnectAsAdminAsync().ConfigureAwait(false);
if (session == null)
{
Assert.Ignore("Admin session not available on this endpoint.");
}
NodeId csrId = await FindChildAsync(
session, ServerConfigurationNodeId, "CreateSigningRequest")
.ConfigureAwait(false);
if (csrId.IsNull)
{
Assert.Ignore("CreateSigningRequest not found.");
}
NodeId defaultGroup = await FindDefaultApplicationGroupAsync(session)
.ConfigureAwait(false);
if (defaultGroup.IsNull)
{
Assert.Ignore("DefaultApplicationGroup not found.");
}
// RsaSha256 certificate type = i=12560
var rsaCertType = new NodeId(12560u);
try
{
CallMethodResult result = await CallMethodAsync(
session, ServerConfigurationNodeId, csrId,
new Variant(defaultGroup),
new Variant(rsaCertType),
new Variant((string)null!),
new Variant(false),
new Variant((byte[])null!)).ConfigureAwait(false);
if (result.StatusCode == StatusCodes.BadNotImplemented ||
result.StatusCode == StatusCodes.BadServiceUnsupported ||
result.StatusCode == StatusCodes.BadUserAccessDenied ||
result.StatusCode == StatusCodes.BadInvalidArgument ||
result.StatusCode == StatusCodes.BadNotSupported)
{
Assert.Ignore($"CreateSigningRequest not supported: {result.StatusCode}");
}
Assert.That(StatusCode.IsGood(result.StatusCode), Is.True,
$"CreateSigningRequest failed: 0x{result.StatusCode.Code:X8}");
}
catch (ServiceResultException sre)
when (sre.StatusCode == StatusCodes.BadNotImplemented ||
sre.StatusCode == StatusCodes.BadServiceUnsupported ||
sre.StatusCode == StatusCodes.BadInvalidArgument ||
sre.StatusCode == StatusCodes.BadNotSupported)
{
Assert.Ignore(
$"CreateSigningRequest not supported: {sre.StatusCode}");
}
}
[Test]
public async Task CreateSigningRequestWithInvalidGroupFailsAsync()
{
using ISession session = await TryConnectAsAdminAsync().ConfigureAwait(false);
if (session == null)
{
Assert.Fail("Admin session not available on this endpoint.");
}
NodeId csrId = await FindChildAsync(
session!, ServerConfigurationNodeId, "CreateSigningRequest")
.ConfigureAwait(false);
if (csrId.IsNull)
{
Assert.Fail("CreateSigningRequest not found.");
}
var invalidGroup = new NodeId(99999u);
var rsaCertType = new NodeId(12560u);
try
{
CallMethodResult result = await CallMethodAsync(
session!, ServerConfigurationNodeId, csrId,
new Variant(invalidGroup),
new Variant(rsaCertType),
new Variant((string)null!),
new Variant(false),
new Variant((byte[])null!)).ConfigureAwait(false);
Assert.That(StatusCode.IsBad(result.StatusCode), Is.True,
"Expected Bad status for invalid group.");
}
catch (ServiceResultException sre)
{
Assert.That(StatusCode.IsBad(sre.StatusCode), Is.True,
"Expected Bad status for invalid group.");
}
}
[Test]
public async Task ApplyChangesSucceedsAsync()
{
using ISession session = await TryConnectAsAdminAsync().ConfigureAwait(false);
if (session == null)
{
Assert.Ignore("Admin session not available on this endpoint.");
}
NodeId applyId = await FindChildAsync(
session, ServerConfigurationNodeId, "ApplyChanges")
.ConfigureAwait(false);
if (applyId.IsNull)
{
Assert.Ignore("ApplyChanges not found.");
}
try
{
CallMethodResult result = await CallMethodAsync(
session, ServerConfigurationNodeId, applyId)
.ConfigureAwait(false);
if (result.StatusCode == StatusCodes.BadNotImplemented ||
result.StatusCode == StatusCodes.BadServiceUnsupported ||
result.StatusCode == StatusCodes.BadNothingToDo ||
result.StatusCode == StatusCodes.BadUserAccessDenied)
{
Assert.Ignore($"ApplyChanges: {result.StatusCode}");
}
Assert.That(StatusCode.IsGood(result.StatusCode), Is.True);
}
catch (ServiceResultException sre)
when (sre.StatusCode == StatusCodes.BadNotImplemented ||
sre.StatusCode == StatusCodes.BadServiceUnsupported ||
sre.StatusCode == StatusCodes.BadNothingToDo)
{
Assert.Ignore($"ApplyChanges: {sre.StatusCode}");
}
}
[Test]
public async Task UpdateCertificateWithEmptyCertFailsAsync()
{
using ISession session = await TryConnectAsAdminAsync().ConfigureAwait(false);
if (session == null)
{
Assert.Fail("Admin session not available on this endpoint.");
}
NodeId updateId = await FindChildAsync(
session!, ServerConfigurationNodeId, "UpdateCertificate")
.ConfigureAwait(false);
if (updateId.IsNull)
{
Assert.Fail("UpdateCertificate not found.");
}
NodeId defaultGroup = await FindDefaultApplicationGroupAsync(session!)
.ConfigureAwait(false);
if (defaultGroup.IsNull)
{
Assert.Fail("DefaultApplicationGroup not found.");
}
var rsaCertType = new NodeId(12560u);
try
{
CallMethodResult result = await CallMethodAsync(
session!, ServerConfigurationNodeId, updateId,
new Variant(defaultGroup),
new Variant(rsaCertType),
new Variant(System.Array.Empty<byte>()),
Variant.From(System.Array.Empty<ByteString>()),
new Variant((string)null!),
new Variant((byte[])null!)).ConfigureAwait(false);
Assert.That(StatusCode.IsBad(result.StatusCode), Is.True,
"UpdateCertificate with empty cert should fail.");
}
catch (ServiceResultException sre)
{
Assert.That(StatusCode.IsBad(sre.StatusCode), Is.True);
}
}
[Test]
public async Task UpdateCertificateWithInvalidCertFailsAsync()
{
using ISession session = await TryConnectAsAdminAsync().ConfigureAwait(false);
if (session == null)
{
Assert.Fail("Admin session not available on this endpoint.");
}
NodeId updateId = await FindChildAsync(
session!, ServerConfigurationNodeId, "UpdateCertificate")
.ConfigureAwait(false);
if (updateId.IsNull)
{
Assert.Fail("UpdateCertificate not found.");
}
NodeId defaultGroup = await FindDefaultApplicationGroupAsync(session!)
.ConfigureAwait(false);
if (defaultGroup.IsNull)
{
Assert.Fail("DefaultApplicationGroup not found.");
}
var rsaCertType = new NodeId(12560u);
byte[] invalidCert = [0x30, 0x82, 0x00, 0x01];
try
{
CallMethodResult result = await CallMethodAsync(
session!, ServerConfigurationNodeId, updateId,
new Variant(defaultGroup),
new Variant(rsaCertType),
new Variant(invalidCert),
Variant.From(System.Array.Empty<ByteString>()),
new Variant((string)null!),
new Variant((byte[])null!)).ConfigureAwait(false);
Assert.That(StatusCode.IsBad(result.StatusCode), Is.True,
"UpdateCertificate with invalid cert should fail.");
}
catch (ServiceResultException sre)
{
Assert.That(StatusCode.IsBad(sre.StatusCode), Is.True);
}
}
[Test]
public async Task GetCertificateStatusIfPresentAsync()
{
using ISession session = await TryConnectAsAdminAsync().ConfigureAwait(false);
if (session == null)
{
Assert.Ignore("Admin session not available on this endpoint.");
}
NodeId statusId = await FindChildAsync(
session, ServerConfigurationNodeId, "GetCertificateStatus")
.ConfigureAwait(false);
if (statusId.IsNull)
{
Assert.Ignore("GetCertificateStatus not found.");
}
NodeId defaultGroup = await FindDefaultApplicationGroupAsync(session)
.ConfigureAwait(false);
if (defaultGroup.IsNull)
{
Assert.Ignore("DefaultApplicationGroup not found.");
}
var rsaCertType = new NodeId(12560u);
try
{
CallMethodResult result = await CallMethodAsync(
session, ServerConfigurationNodeId, statusId,
new Variant(defaultGroup),
new Variant(rsaCertType)).ConfigureAwait(false);
Assert.That(StatusCode.IsGood(result.StatusCode), Is.True);
Assert.That(result.OutputArguments.Count, Is.GreaterThan(0));
}
catch (ServiceResultException sre)
when (sre.StatusCode == StatusCodes.BadNotImplemented)
{
Assert.Ignore(
$"GetCertificateStatus not implemented: {sre.StatusCode}");
}
}
[Test]
public async Task NonAdminCannotCallCreateSigningRequestAsync()
{
ISession userSession;
try
{
userSession = await ClientFixture
.ConnectAsync(ServerUrl, SecurityPolicies.None,
userIdentity: new UserIdentity("user1", "password"u8))
.ConfigureAwait(false);
}
catch (ServiceResultException)
{
Assert.Fail("Cannot connect as user1.");
return;
}
using (userSession)
{
NodeId csrId = await FindChildAsync(
userSession, ServerConfigurationNodeId, "CreateSigningRequest")
.ConfigureAwait(false);
Assert.That(csrId.IsNull, Is.True,
"Method should not be browseable by non-admin.");
}
}
[Test]
public async Task NonAdminCannotCallGetRejectedListAsync()
{
ISession userSession;
try
{
userSession = await ClientFixture
.ConnectAsync(ServerUrl, SecurityPolicies.None,
userIdentity: new UserIdentity("user1", "password"u8))
.ConfigureAwait(false);
}
catch (ServiceResultException)
{
Assert.Fail("Cannot connect as user1.");
return;
}
using (userSession)
{
NodeId methodId = await FindChildAsync(
userSession, ServerConfigurationNodeId, "GetRejectedList")
.ConfigureAwait(false);
Assert.That(methodId.IsNull, Is.True,
"Method should not be browseable by non-admin.");
}
}
[Test]
public async Task NonAdminCannotCallApplyChangesAsync()
{
ISession userSession;
try
{
userSession = await ClientFixture
.ConnectAsync(ServerUrl, SecurityPolicies.None,
userIdentity: new UserIdentity("user1", "password"u8))
.ConfigureAwait(false);
}
catch (ServiceResultException)
{
Assert.Fail("Cannot connect as user1.");
return;
}
using (userSession)
{
NodeId applyId = await FindChildAsync(
userSession, ServerConfigurationNodeId, "ApplyChanges")
.ConfigureAwait(false);
Assert.That(applyId.IsNull, Is.True,
"Method should not be browseable by non-admin.");
}
}
/// <summary>
/// OPC UA well-known NodeIds (namespace 0)
/// </summary>
private static readonly NodeId ServerNodeId = new(2253u);
private static readonly NodeId ServerConfigurationNodeId = new(12637u);
private async Task<ISession> TryConnectAsAdminAsync()
{
// ServerConfiguration / TrustList push methods require
// a SignAndEncrypt channel per Part 12 §7.10.3 — try to find a
// SignAndEncrypt endpoint with username token first, fall back
// to SecurityPolicies.None (which preserves prior behavior for
// tests that don't strictly require an encrypted channel).
try
{
var endpointConfiguration = EndpointConfiguration.Create(ClientFixture.Config);
using DiscoveryClient client = await DiscoveryClient.CreateAsync(
ServerUrl,
endpointConfiguration,
Telemetry,
ct: CancellationToken.None).ConfigureAwait(false);
ArrayOf<EndpointDescription> endpoints = await client.GetEndpointsAsync(
default, CancellationToken.None).ConfigureAwait(false);
await client.CloseAsync(CancellationToken.None).ConfigureAwait(false);
string? preferred = null;
foreach (EndpointDescription ep in endpoints)
{
if (ep.SecurityMode != MessageSecurityMode.SignAndEncrypt ||
ep.UserIdentityTokens == default!)
{
continue;
}
foreach (UserTokenPolicy t in ep.UserIdentityTokens)
{
if (t.TokenType == UserTokenType.UserName)
{
preferred = ep.SecurityPolicyUri!;
break;
}
}
if (preferred != null)
{
break;
}
}
return await ClientFixture
.ConnectAsync(ServerUrl, preferred ?? SecurityPolicies.None,
userIdentity: new UserIdentity("sysadmin", "demo"u8))
.ConfigureAwait(false);
}
catch (ServiceResultException)
{
return null!;
}
}
private async Task<ArrayOf<ReferenceDescription>> BrowseChildrenAsync(
ISession session, NodeId nodeId)
{
BrowseResponse response = await session.BrowseAsync(
null, null, 0,
new BrowseDescription[]
{
new() {
NodeId = nodeId,
BrowseDirection = BrowseDirection.Forward,
ReferenceTypeId = ReferenceTypeIds.HierarchicalReferences,
IncludeSubtypes = true,
NodeClassMask = 0,
ResultMask = (uint)BrowseResultMask.All
}
}.ToArrayOf(),
CancellationToken.None).ConfigureAwait(false);
if (response.Results.Count == 0)
{
return default;
}
ArrayOf<ReferenceDescription> refs = response.Results[0].References;
// Handle continuation
ByteString cp = response.Results[0].ContinuationPoint;
while (!cp.IsEmpty)
{
BrowseNextResponse next = await session.BrowseNextAsync(
null, false,
new ByteString[] { cp }.ToArrayOf(),
CancellationToken.None).ConfigureAwait(false);
if (next.Results.Count > 0)
{
var more = new List<ReferenceDescription>(refs.ToArray()!);
more.AddRange(next.Results[0].References.ToArray()!);
refs = more.ToArrayOf();
cp = next.Results[0].ContinuationPoint;
}
else
{
break;
}
}
return refs;
}
private async Task<NodeId> FindChildAsync(
ISession session, NodeId parentId, string browseName)
{
ArrayOf<ReferenceDescription> refs = await BrowseChildrenAsync(
session, parentId).ConfigureAwait(false);
foreach (ReferenceDescription rd in refs)
{
if (rd.BrowseName.Name == browseName)
{
return ExpandedNodeId.ToNodeId(rd.NodeId, session.NamespaceUris);
}
}
return NodeId.Null;
}
private async Task<NodeId> FindDefaultApplicationGroupAsync(ISession session)
{
NodeId certGroupsId = await FindChildAsync(
session, ServerConfigurationNodeId, "CertificateGroups")
.ConfigureAwait(false);
if (certGroupsId.IsNull)
{
return NodeId.Null;
}
return await FindChildAsync(
session, certGroupsId, "DefaultApplicationGroup")
.ConfigureAwait(false);
}
private async Task<CallMethodResult> CallMethodAsync(
ISession session,
NodeId objectId,
NodeId methodId,
params Variant[] args)
{
CallResponse response = await session.CallAsync(
null,
new CallMethodRequest[]
{
new() {
ObjectId = objectId,
MethodId = methodId,
InputArguments = args.Length > 0 ? args.ToArrayOf() : default
}
}.ToArrayOf(),
CancellationToken.None).ConfigureAwait(false);
Assert.That(response.Results.Count, Is.EqualTo(1));
return response.Results[0];
}
}
}