29 Commits

Author SHA1 Message Date
romanett 5edb512ab7 Stricter validation and error handling in GDS server & Server Method Call validation (#3746)
* Stricter validation and error handling in GDS server

- Allow empty DatabaseStorePath for in-memory operation
- Select database type dynamically in GdsNodeManagerFactory
- Enforce required fields and argument validation in ApplicationsDatabaseBase
- Prevent duplicate application URIs in LinqApplicationsDatabase
- Propagate argument errors as OPC UA service exceptions in ApplicationsNodeManager
- Remove obsolete attribute from ParsedNodeId
- Refactor MasterNodeManager write/call validation to async with improved permission checks and attribute caching
- Update UAReferenceServer.ctt.xml test data with non-empty credentials
- Improves robustness, security, error reporting, and test coverage

* Add method-state resolver API for call validation and tests

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/0caf8699-f0e0-4dd5-8dcf-368b08912205

Co-authored-by: romanett <7413710+romanett@users.noreply.github.com>

* Refine call validation comments and test coverage naming

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/0caf8699-f0e0-4dd5-8dcf-368b08912205

Co-authored-by: romanett <7413710+romanett@users.noreply.github.com>

* Move method resolver onto core NodeManager interfaces

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/0bb87dfd-f432-431f-a0fe-dd4d1ba3197f

Co-authored-by: romanett <7413710+romanett@users.noreply.github.com>

* Align NodeManager interfaces and call paths for method resolver

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/0bb87dfd-f432-431f-a0fe-dd4d1ba3197f

Co-authored-by: romanett <7413710+romanett@users.noreply.github.com>

* fixes

* fix

* Fix GDS ClientTest expectations for stricter app validation

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/47d99514-94f9-4051-9e6d-8cb2b44555d0

Co-authored-by: romanett <7413710+romanett@users.noreply.github.com>

* fix tests

* Fix AOT GDS fixture for RSA secured endpoint

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/f6c8fba1-3dbf-41f0-b920-5e1766b9d6e1

Co-authored-by: romanett <7413710+romanett@users.noreply.github.com>

* Update app registration logic and audit event sources

Refactor application registration to separate update and create logic, introducing UpdateApplication in database interfaces and implementations. Improve error handling and validation, ensure unique ApplicationUris, and enhance certificate revocation logging. Standardize audit event source names and add ToString override to BaseVariableState. Update server queries for correct pagination.

* fixes

* Add wildcard match coverage for ApplicationsDatabaseBase

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/a2c1a6b0-e867-4610-bead-7e621e3764ff

Co-authored-by: romanett <7413710+romanett@users.noreply.github.com>

* Expand wildcard spec coverage in ApplicationsDatabaseBase tests

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/a2c1a6b0-e867-4610-bead-7e621e3764ff

Co-authored-by: romanett <7413710+romanett@users.noreply.github.com>

* Align UA wildcard matching and add spec coverage tests

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/a2c1a6b0-e867-4610-bead-7e621e3764ff

Co-authored-by: romanett <7413710+romanett@users.noreply.github.com>

* Fix GDS QueryServers test expectations for pagination semantics

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/efa1c64d-05c8-47ee-b308-c77e7d5a34c9

Co-authored-by: romanett <7413710+romanett@users.noreply.github.com>

* Add focused tests for LinqApplicationsDatabase behaviors

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/7e4ec1ce-722f-43fb-99db-06b854c3fa7a

Co-authored-by: romanett <7413710+romanett@users.noreply.github.com>

* Refine LinqApplicationsDatabase test method naming

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/7e4ec1ce-722f-43fb-99db-06b854c3fa7a

Co-authored-by: romanett <7413710+romanett@users.noreply.github.com>

* Merge origin/master and resolve PR merge conflicts

Agent-Logs-Url: https://github.com/OPCFoundation/UA-.NETStandard/sessions/69970cd4-4196-4fb4-9e4c-6ad86104bb5f

Co-authored-by: marcschier <11168470+marcschier@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: romanett <7413710+romanett@users.noreply.github.com>
Co-authored-by: marcschier <11168470+marcschier@users.noreply.github.com>
2026-05-17 18:47:50 +02:00
Marc Schier 94bc03b9f6 fix address space issues (#3705)
* fix missing mandatory children

* Source generator: fix encoding nodes, EventNotifier, and type RBAC

- Emit DataType encoding nodes (Default Binary/XML/JSON) into the
  generated address space. CollectEncodingNodes() discovers
  DataTypeEncodingType instances and builds synthetic hierarchies
  with their HasEncoding/HasDescription references.

- Auto-set EventNotifier=SubscribeToEvents on Object nodes that have
  forward HasEventSource or HasNotifier references. The fix works at
  two levels: ModelDesignValidator infers SupportsEvents on types with
  event references in design XML, and NodeStateGenerator checks the
  resolved reference set for merged instances that inherit references
  from their type definitions.

- Wrap AccessRestrictions/RolePermissions in if(forInstance) guards
  for ObjectType, VariableType, DataType, and ReferenceType templates
  so type definition nodes remain accessible to all users.

- Allow ModellingRule=None Object children on type definitions to be
  emitted (e.g. state machine states/transitions).

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* Update missing nodes analysis after source generator fixes

Retest with admin credentials against ConsoleReferenceServer v1.05.07.
Categorize 794 truly missing nodes (after filtering optional/placeholder):
- 384 encoding nodes (NodeSet2.xml-only, not in design XML)
- 172 role instance children
- 84 other nodes
- Remaining: trust list, PubSub, diagnostics, etc.

RBAC and EventNotifier fixes confirmed working.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* update

* plans: detailed analysis of 292 remaining missing nodes

Replaced the two previous analysis files with a single consolidated
validation report. Each of the 292 nodes is classified with a reason:

- 212 type-level children (ObjectType definitions not instantiated)
- 48 instance-level children (diagnostics, HA, FileSystem, PubSub)
- 32 orphan property templates (design-time canonical definitions)

Only 1 fix recommended: Server.Auditing (i=2994) should be exposed
as false per Part 5 section 6.3.3.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* feat: add GDS node manager to ConsoleReferenceServer

Add Global Discovery Server functionality to the reference server:
- Add Opc.Ua.Gds.Server.Common project reference
- Add GdsNodeManagerFactory that creates ApplicationsNodeManager
  with JsonApplicationsDatabase and CertificateGroup (auto-approve)
- Add GlobalDiscoveryServerConfiguration extension to config XML
- Add GDS to ServerCapabilities
- Registration is opt-in: only when config extension is present

Also fix pre-existing source generator test failures:
- Add missing CreateOrReplaceTransitionNumber stub method to
  StateMachineTransitionState in CompilerUtils.cs (8 tests fixed)

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* plans: update missing nodes report with GDS retest results

Retested after adding GDS node manager to ConsoleReferenceServer.
Total missing reduced from 1325 to 1243 (82 fewer).
335 remaining 'other' nodes fully classified with per-node reasons.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* plans: Server.Auditing is present (access-restricted, not missing)

Live validation confirmed i=2994 exists with value=true, visible to
admin users. Returns BadUserAccessDenied for anonymous. No fixes needed.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* Fix CttTestRunner build errors for v1.6 API and Jint 4.8.0

- Update System.CommandLine 2.0.7 API: SetHandler->SetAction, InvokeAsync->Parse().InvokeAsync()
- Remove ObjectInstance inheritance from CttAssert, CttServiceRegister, CttIdentifierConstants, CttMonitoredItemHelper; use ToJsObject() factory methods instead
- Replace Jint.Native.JsValueType with .IsObject()/.IsNumber()/.IsString() etc.
- Add missing using directives (Jint.Runtime, Microsoft.Extensions.Logging, etc.)
- Fix NodeId.Identifier obsolete -> TryGetIdentifier<uint>
- Fix DataValue.Value obsolete -> WrappedValue.AsBoxedObject()
- Fix ApplicationInstance() obsolete -> ApplicationInstance(ITelemetryContext)
- Fix LoadApplicationConfiguration -> LoadApplicationConfigurationAsync
- Fix CheckApplicationInstanceCertificate -> CheckApplicationInstanceCertificatesAsync
- Fix CoreClientUtils.SelectEndpointAsync signature (requires telemetry param)
- Fix DefaultSessionFactory() obsolete -> DefaultSessionFactory(ITelemetryContext)
- Fix DiscoveryClient.Create -> DiscoveryClient.CreateAsync
- Fix FindServers/GetEndpoints -> FindServersAsync/GetEndpointsAsync
- Fix StatusCode to uint conversions
- Fix ArrayOf<T> iteration (use foreach instead of LINQ on IConvertableToArray)
- Fix XmlNodeList null coalescing in CttProjectSettings
- Fix JsValue.False -> JsValue.FromObject(engine, false)
- Add --json option to Program.cs for machine-readable output

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* fix: emit type-level children with ModellingRule=None for all node classes

The source generator's GetChildren method only included
ModellingRule=None children when they were ObjectDesign instances
(state machine states/transitions). This excluded Variables and
Methods that are explicitly defined on types without a modelling
rule, such as:

- ConditionType.ConditionRefresh (Method)
- ConditionType.ConditionRefresh2 (Method)
- ConditionType.SupportsFilteredRetain (Variable)
- ProgramStateMachineType.Creatable (Variable)
- Various TrueState/FalseState display-hint properties

Remove the ObjectDesign restriction so all explicitly defined
type-level children with ModellingRule=None are included in the
generated address space. This adds ~52 previously missing nodes.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* plans: update report after ModellingRule=None generator fix

Type-level children dropped from 261 to 203 (-58) after fixing the
source generator to emit Variables and Methods with ModellingRule=None.
Total 'other' reduced from 335 to 283. No fixes needed for any
remaining nodes.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* plans: all 203 type-level children confirmed present via Read

Verified all 203 'type-level children' exist in the server (none
return BadNodeIdUnknown). They return Good, BadUserAccessDenied,
or BadSecurityModeInsufficient -- all confirming the node exists
but is access-restricted for anonymous users.

All 1,316 export-missing nodes are now accounted for. Zero nodes
are actually missing from the server address space.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* Fix CttTestRunner session service methods for CTT JS script compatibility

- Implement ServiceCreateSession with real Session.CreateAsync connection
- Implement ServiceActivateSession with proper response fields
- Implement ServiceCloseSession with session cleanup
- Fix UaSession constructor to provide service methods via CreateServiceObject
- Convert all type constructors from ClrFunction to JS functions for 'new' support
  (Jint 4.x ClrFunction does not support [[Construct]])
- Add UaChannel.connect/disconnect stubs for OpenSecureChannel flow
- Add UaDiscovery with getEndpoints/findServers from discovery session
- Add missing types: UaSubscriptionDiagnosticsDataType, UaHistoryUpdateResult, etc.
- Add missing enums: IdentifierType, Constants (DateTime/numeric limits)
- Add UaPkiCertificate.fromDER, UaByteString.fromStringData, PkiType, UaPkiUtility
- Add UaDateTime.Now constructor, equals/msecsTo methods
- Add UaStatusCode with isGood/isBad/isUncertain as JS constructor
- Fix response headers with Timestamp (UaDateTime), ServiceDiagnostics, StringTable
- Fix endpoint descriptions with Server, UserIdentityTokens, ServerCertificate
- Add CreateResponseHeader helper for consistent response header construction
- Override warnOnce.js loggers to avoid Function.caller incompatibility
- Add stopTest, checkResourceError (lowercase) global functions
- Add UaOpcServer constructor with all method stubs
- Handle JS parse errors in include() for malformed CTT files
- Test.Connect() now calls InstanciateHelpers with DiscoverySession

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* Add CttTestRunner: .NET replacement for CTT JavaScript host environment

Implements a Jint-based JavaScript engine that can execute the OPC Foundation's
Compliance Test Tool .js test scripts using the OPC UA .NET Standard stack.

Features:
- Parses CTT .ctt.xml project files (Qt AbstractItemModelData format)
- Loads and resolves CTT include() dependency chains (~100 library files)
- Registers ~250 Ua* type constructors for JavaScript
- Implements session.read/write/browse/getEndpoints/findServers
- Provides all OPC UA enumerations, NodeId constants, Assert methods
- CLI with --list, --file, --conformance-unit, --result, --json flags
- Headless operation for agent/CI integration

Current status: Framework connects to OPC UA server and loads CTT test
infrastructure. Session establishment flow needs additional property
compatibility for CreateSession/ActivateSession request objects.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* fix: do not apply DefaultAccessRestrictions/DefaultRolePermissions to type definitions

ObjectType and VariableType nodes should never have access
restrictions or role permissions from DefaultAccessRestrictions/
DefaultRolePermissions. These defaults are meant to apply to
instances of the type, not to the type definition node itself.

Previously, CertificateGroupType, TrustListType, SecurityGroupType
and other types were incorrectly emitted with AccessRestrictions
inherited from their DefaultAccessRestrictions, making them
unreadable without encryption even though the spec defines no
restrictions on these type definitions.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* CttTestRunner: fix session establishment flow

- Fix constructor patterns (new/no-new dual call support)
- Fix ResponseHeader with ServiceDiagnostics/StringTable
- Populate ServerNonce, ServerCertificate, ServerEndpoints in CreateSession response
- Add UaVariant setter methods (setNodeId/setString/setBoolean/etc.)
- Add UaCreateSessionRequest/ActivateSessionRequest with proper nested structures
- Fix UaPkiUtility/UaPkiCertificate with Thumbprint/toDERFile/loadCertificateFromFile
- Add missing enums: PerformUpdateType, SecurityPolicy, StructureType, etc.
- Add HostInfo, Bit helper, KeyPairCollection, ExpectedAndAcceptedResults
- Add _error.store(), MessageSecurityMode.toString()

Status: Session creates successfully, CreateSession validation runs,
hits validateCertificate in PKI chain (next to implement).

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* plans: update report after DefaultAccessRestrictions type definition fix

ObjectTypes no longer have incorrect access restrictions. Type
children reduced from 203 to 164 (39 now visible). Total export-
missing reduced from 1316 to 1146. Remaining 164 type children are
individual methods/variables with spec-correct access restrictions.

Two source generator fixes applied:
- ModellingRule=None children for Variables/Methods
- DefaultAccessRestrictions not applied to ObjectType/VariableType

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* CttTestRunner: fix PKI, cert validation, warnOnce, session response

- Intercept warnOnce.js with Jint-compatible replacement (no Function.caller)
- Add _log.store() global helper
- Add HOSTNAMES/HostnameFromUrl helpers for cert hostname validation
- Add UaPkiCertificate properties: PublicKey, Issuer, Subject, KeyUsage, Hostnames
- Add UaPkiUtility.validateCertificate stub
- Add UaByteString static helpers: FromByteArray, ToByteArray, fromHexString
- Use JS UaNodeId constructor for proper equals() support
- Fill AuthenticationToken and 32-byte ServerNonce in CreateSession response
- Add clone/append to ByteString objects

Session flow: CreateSession validates, ActivateSession reached, hits
Channel.ServerCertificate.clone() (IsSecure check — next to fix).

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* CttTestRunner: complete session establishment, crypto stubs, ByteString helpers

- Add _makeByteString() helper for consistent ByteString objects with clone/append/isEmpty
- Add UaCryptoProvider with asymmetricSign/Verify stubs
- Add UaExtensionObject setter methods (setAnonymousIdentityToken, etc.)
- Fix UaChannel with full properties (RequestedSecurityPolicyUri, IsSecure, etc.)
- Fix duplicate type registrations overriding custom constructors
- Fix ActivateSession response header with ServiceDiagnostics
- Remove UaCreateSessionResponse/ActivateSessionRequest/CloseSessionRequest duplicates

Status: Full session lifecycle works (GetEndpoints → OpenSecureChannel →
CreateSession → ActivateSession). Test scripts execute and hit server
capabilities initialization (MonitoredItem NodeId settings configuration).

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* update

* plans: add spec references for access restriction reasoning

Added links to Part 3 sections 5.2.9, 5.2.11, and 6.3.3 explaining
why DefaultRolePermissions are applied to instance children but not
to type definitions. The NodeSet2.xml has no explicit RolePermissions
on these 164 nodes -- restrictions come from model design defaults.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* fix: add GDS project references to ConsoleReferenceServer Dockerfile

Add Opc.Ua.Gds.Common and Opc.Ua.Gds.Server.Common csproj COPY
lines to the Docker restore layer, required since the GDS node
manager was added to the ConsoleReferenceServer.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* update

* feat: add IsPartOfTypeHierarchy flag to bypass access restrictions on types

Type hierarchy nodes (ObjectType/VariableType definitions and their
children) should be universally accessible regardless of
AccessRestrictions and RolePermissions.

Changes:
- Add IsPartOfTypeHierarchy property to NodeState
- Set flag on ObjectType/VariableType in generated code (!forInstance)
- Propagate flag from parent to children in AddPredefinedNode
- Add flag to NodeMetadata, propagate in GetPermissionMetadata
- Bypass ValidateRolePermissions and ValidateAccessRestrictions
  when IsPartOfTypeHierarchy is true
- Revert isTypeDefinition guard: AccessRestrictions and
  RolePermissions are now emitted on all nodes as metadata,
  but enforcement is skipped for type hierarchy nodes
- Fix forInstance propagation in type factories: use
  forInstance: forInstance for type children so deep children
  (TrueState/FalseState etc.) are included when !forInstance

Type-level missing nodes reduced from 201 to 99. Remaining 99 are
in the server but not reachable by the export tool's browse path.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* plans: update report with final IsPartOfTypeHierarchy results

Missing from export reduced to 998 (from 1325 original).
Type children: 201 -> 99 (forInstance propagation fix).
All nodes verified present via OPC UA Read.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* fix: propagate IsPartOfTypeHierarchy in GetNodeMetadataAsync

The Browse service's per-reference ValidateRolePermissionsAsync
calls GetNodeMetadataAsync (not GetPermissionMetadataAsync). The
IsPartOfTypeHierarchy flag was only set in GetPermissionMetadataAsync,
causing type hierarchy nodes to be filtered out of Browse results.

This fixes 99 ObjectType children that were previously invisible
in Browse from their parent types. Type-level missing: 99 -> 0.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* plans: final report -- 0 type-level children missing (694 total)

Type-level missing: 99 -> 0 after fixing IsPartOfTypeHierarchy
propagation in GetNodeMetadataAsync. Total export-missing: 694
(384 encoding + 236 access-restricted + 74 instance/orphan).

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* update

---------

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-04-28 14:20:37 +02:00
Marc Schier 6c8c1a6d29 Enable dispose analyzers CA2000 and CA2213 and fix all issues (#3670) 2026-04-17 13:39:34 +02:00
Marc Schier d1883832e1 Secure channel enhancements 2025 11 (Take 3) (#3665)
* merged security changes

* Tailor SecurityPolicyUri for format expected in s_securityPolicyUriToInfo

* Enhance security policy handling and key computation logic

* Merge SecurityEnhancements.

* Add support for SessionTransferToken. Removed obsolete SoftwareCertificate code.

* Fix NonceLength for None.

* Add support for RSA_DH, more fixes from IOP testings.

* Finish implementation of SecureChannelEnhancements.

* Rename EccUtils.cs to CryptoUtils.cs

* Address feedback from reviewers.

* Fix CoPilot flagged spelling errors.

* Rename EccUtils to CryptoUtils

* Update version from 1.5.378-preview to 1.5.378

* Fix unit tests.

* Allow SignatureData.Algorithm to be NULL or Empty.

* Fix issue with BrainPool_p256r1_ChaChaPoly

* Fix RSA_DH_AesGcm

* Fix OSC/padding by deriving HMAC keys, tightening symmetric size math, and correcting ECC_brainpoolP384r1/Basic128Rsa15 IV, signature, padding, and nonce parameters.

* Policies without asymmetric encryption (ECC) return the plaintext when encrypting user tokens; this prevents null payloads from causing BadIdentityTokenInvalid.

* Reserve outer CBC padding for avoiding SymetricEncryptAndSign->AddPadding to overwrite next fields (signature)

* Nonce stored as byte array in SessionConfiguration; Sesion snapshot restores ServerNonce and reconstructs ECC ephemeral key Nonce from bytes and policy

* Added _AesGcm and _ChaChaPoly variants to BuildSupportedSecurityPolicies() for all six ECC certificate types (nistP256, nistP384, brainpoolP256r1, brainpoolP384r1, curve25519, curve448) to SecurityConfiguration. Added Sign and SignAndEncrypt endpoints for the four ECC AesGcm/ChaChaPoly policy pairs (nistP256, nistP384, brainpoolP256r1, brainpoolP384r1) to ServerFixture.

* make ephemeralKeyPolicyUri nullable

* GenerateSecret also for NET7 and NET8

* Adjust Basic128Rsa15 policy properties for backword compatibility

* Exclude unsuported AEAD policies from .NET Framework client tests

* Addapt to new changes (still build fail)

* Addapt code to make it compile

* Fixed failing build on net48 (by ignoring potential null ref which is not reported on other newer targets)

* Preserve the certificate reference in Clone() so copied handlers can still sign

* Remove extra code and addapt to existing master configuration settings

* Filter *_AesGcm and *_ChaChaPoly security policies based on actual runtime support, so unsupported AEAD policies are not advertised or selected on older frameworks

* Expand ECC/RSA policy test coverage and keep Basic128Rsa15 nonce length backward-compatible

* Fix ReconnectSessionOnAlternateChannel _AES and _ChaCha policies

* Fixed IgnoreIfPolicyNotAdvertised so it now fetches endpoints on-demand (instead of relying on Endpoints being preloaded by earlier tests), which avoids false ignores when running tests directlyy

* Merge with commit 5e627f2ca1 from secure-channel-enhancements-2025-11 branch

* minor log mesatge formating

* Fix ClientLockoutTests

* Add ServerFixture policies upfront only if framework and runtime capability supports them

* A few cosmetic/config changes as review sugested

* Moved the session/security handling from StandardServer into a dedicated helper

* use X509IdentityTokenHandler from secure-channel-enhancements-2025-11

* Removed unused Opc.Ua.Types.UnitTests.csproj

* test(client): fix Basic128Rsa15 reconnect token-policy coverage

Advertise an explicit Basic128Rsa15 user token policy in the test fixture and tighten the reconnect test preconditions for non-advertised policies.

* test(client): fix session nonce persistence test helpers

Replace the generic reflection helpers in SessionTests with explicit client/server nonce accessors that match the actual field types.

Add a short Session comment to explain why client and server nonces currently use different representations.

* Merge branch 'master' into secure-channel-enhancements-2025-11-merge5

Merge with latest master and fix conflicts.

* Removed unused Opc.Ua.Types.UnitTests.csproj

* test(client): fix Basic128Rsa15 reconnect token-policy coverage

Advertise an explicit Basic128Rsa15 user token policy in the test fixture and tighten the reconnect test preconditions for non-advertised policies.

* test(client): fix session nonce persistence test helpers

Replace the generic reflection helpers in SessionTests with explicit client/server nonce accessors that match the actual field types.

Add a short Session comment to explain why client and server nonces currently use different representations.

* Build fixes

* Fix build

* update

* Minor updates

* Fix tests

* Add code to check all Endpoints.

* Update Design files to 1.05.7

* Run code fixers, add missing docs

* Fix build

* Revert removal of using

* Increase build timeout

---------

Co-authored-by: mrsuciu <Mircea-Adrian.Suciu@Softing.com>
Co-authored-by: Randy Armstrong <randy@sparhawksoftware.com>
2026-04-16 18:56:42 +00:00
romanett f7c3c4e18f Fix Server/ServerStatus/State SourceTimestamp. Fix Reference Server config, not loading OperationLimits due to wrong order. (#3454)
* fix ServerSourceTimestamp

* fix OperationLimits not being set for ReferenceServer
2026-01-12 13:09:15 +01:00
Marc Schier 9830e5d53e Enable roslynizer and fix all analyzer issues (#3157)
* Fix warnings and suggestions
* Enable roslynator
2025-08-16 04:10:24 -07:00
romanett ef9387b525 Enable Durable Subscriptions (#2978)
* Enable Durable Subscriptions (#9)

* [Server] Durable Subscriptions (#2683)

* Implement a system test for DurableSubscriptions (#2839)
* Client Side
Co-authored-by: ALTERNATE-DEV\Archie <archie@dreamsandadventures.ca>

* make a static Method CalculateRevisedQueueSize

* Adress review feedback

* fix FilterRetainTests

* Add MonitoredItem Id to Queues
Use NodeIdDictionary where possible
2025-02-28 13:46:49 +02:00
Martin Regen 5ed73fcd95 merge latest release 2024-12-07 17:30:58 +01:00
Suciu Mircea Adrian d0e89a3bf1 Support mutual TLS on server https endpoints (#2849)
A new configuration variable 
    <HttpsMutualTls>true</HttpsMutualTls>
enables the mutual TLS authentication support. The behavior of the TLS endpoint changes as the following:

HttpsMutualTls is true:
The server checks the trust on the certificate which is used by the client for TLS authentication. It must be a valid OPC UA application certificate which is trusted.
A client can still connect without providing a client certificate, but then it is only able to call discovery services.
In order to create a session, the client must use the same application certificate that was used for the TLS channel.

HttpsMutualTls is false:
- There is no application authentication. The server endpoint uses security None and there is no client application authentication.
Instead, only user authentication is used to secure the server, anonymous user authentication is disabled.
Discovery service calls are supported.

Co-authored-by: Martin Regen <mregen@microsoft.com>
2024-12-03 12:43:39 +01:00
Suciu Mircea Adrian f001eabcc8 Add support for ECC profiles (#2398)
- Port support for ECC NIST/Brainpool profiles from prototyping_ecc branch
- Implement CertProvider to load certs per connection / profile
- Backward compatibility of configuration for existing apps
- SecurityConfiguration specifies app cert types for each profile
- Autodetect the ECC support for brainpool/nist based on platform (mac OS 10 doesn't support brainpool)
- ECC supported on net48 / net5.0 / net 6.0 / netstandard2.1
- ECC supported on windows / linux / macOS (brainpool not < macOS11)
- Self signed certs for each profile are created on start similar to RSA
- RSA only profiles are supported on .NET standard 2.0

Co-authored-by: Martin Regen <mregen@microsoft.com>
2024-10-17 16:02:20 +02:00
Martin Regen 23b8502778 Server doesn't start up with mixed https endpoints (#2789)
* allow startup of mixed https endpoints
2024-10-10 07:01:48 +02:00
Martin Regen 1c6253a729 AddRejected method for ICertificateStore (#2720)
- Add a light weight AddRejected certificate store method to `ICertificateStore` to ensure rejected cert history remains small and doesn't have a lot of overhead.
- Number of history certificates is configurable using a new `MaxRejectedCertificates` entry.
- Rejected certs are only saved to directory cert store, others do ignore the attempt
- Fix the caching of `CertificateValidator` and flag some `ÒpenStore` methods deprecated which do not support the caching. Fixes across the board to support the methodology. Basically `store.Close` keeps the cache, `store.Dispose` clears the cache, so recommendation is to use `var store = certStoreIdentifier.OpenStore(); try { ... }-- finally { store.Close }`
2024-09-03 15:23:32 +02:00
Archie Miller 3e5ad45c6e Remove example of how to select unrecommended RSA15 Policy (#2728)
RSA 15 policy is deprecated
* Remove example of how to select RSA15 Policy in a server
* Add a Warning Message if the Rsa 15 policy is used
2024-08-22 16:18:41 +02:00
Suciu Mircea Adrian d1a9baa6c6 Added a limit to the Channels on the server side and removed "stale" channels (#2540)
* Added MaxChannelCount and detect and cleanup "stale" channels based on ChannelLifetime
* Add Environment.TickCount as time reference
* Set a socket backlog value to avoid socket open overflow
* Added a ChannelKeepAlive to signal when a session is still active
* Add options to console client to leak channels and run connect loop forever

Co-authored-by: Martin Regen <mregen@microsoft.com>
2024-04-22 13:28:19 +02:00
mtx500 d2e436d340 Fix typos in comments, strings and local variable names. No functional changes. (#2507)
Fixed a lot of typos in comments, strings and local variable names. 
No change to misspelled function names and file names.
2024-02-10 07:49:05 +01:00
Martin Regen c7bd19dc46 Support use of opc.https endpoint url for client and server. (#2140)
Currently the https protocol doesn't support a spec compliant endpoint with a `opc.https` prefix., as client and server.
Fix:
- Add the client and server support for the `opc.https` prefix. 
- Continue support for `https` prefix for non compliant implementations.
- Any CancellationTokenSource should be disposed after being used.
- Follow coding guidelines
- Use macOS cert callback
2023-06-12 09:05:10 +02:00
Martin Regen 1fec89b073 Complex types improvements (#1915)
Improvements for complex types.

- Support to encode/decode complex type structures with multidimensional arrays.
- Perf improvements for type loader using new NodeCache fetch multiple interfaces.
- DataTypeDictionary validation when dependencies are used.
- interface for complex type resolver, to build custom types in code.
- improvements of console client to demonstrate browse/read of custom values

+++ Breaking changes +++

IDecoder interface change of the `ReadArray` method

- Return type is now `Array` for all types of arrays. Previously the method returned an array for 1-dim and a `Matrix` type for multidimensional arrays. In addition the convention in generated code is to use `Collection` for all 1-dim arrays, and so was built the `BaseComplexType`. The new convention is to expose the native `Array` type from a complex type, in all cases, hence the return type of `ReadArray` was changed to reflect that for a consistent programming model.
- `ReadArray` has a new parameter `systemType` to efficiently read encodeable types. Previously the `Type` of an encodeable was determined by the encodingid and lookup in the type factory, even when the Type is already known by the caller.  The 'old' style is still supported.
- `ReadArray` supports to read encodeable type arrays which are directly encoded in structures. These arrays differ from standard encoding of arrays and they are handled when `BuiltInType.Null` is used as parameter.
2022-10-04 19:45:26 +02:00
Martin Regen 0ad5c4c3a3 Refactor audit events (#1895)
- Move the auditing flag to server internal
- Hook up new configuration setting to the Auditing node
- A Security Admin can change the Audit setting.
- Refactor audit events to be extensions in one class.
- enable auditing and diagnostics by default for higher test coverage.
- refactor dependency of some events to bindings, e.g. TcpServerChannel should not be used as reportevent parameter
2022-08-12 20:04:02 +02:00
Martin Regen 8ddda78aff Fix for Usertokenpolicy Anonymous, security policy default should be None (#1756)
- Only an issue if the configuration does not specify the security policy uri for anonymous token
- If the config does not specify the security policy, for anonymous user token the security profile Basic256Sha256 was chosen. 
- This setting requires for the client to trust the server certificate if it tries to connect with security None, may cause IOP issues when no security is chosen and encryption is required for the anonymous user token.
2022-03-30 09:20:13 +02:00
Martin Regen 7d9be41cf5 Doc updates and fixes for .368 preview, ref server improvements (#1695)
- Doc, docs, docs updates for new 368 support
- fix a missing null pointer check when ConditionRefresh is run
- Ref server: move NodeManager factory API to StandardServer, decoupling the NodeManager implementation from Ref server
- Ref server: add shadow mode flag, to allow to map a docker configuration in a mapped folder.
- Ref server: sample batch files how to run Github CR and local docker images
- Improve some misleading 'delete application certificate' log messages.
2022-02-11 09:19:40 +01:00
Martin Regen 8c1a659ecf Reference Server updates running CTT (#1689)
- Provide the CTT configuration used for 1.4.9.398: Added tests with arrays except Variant
- Match the Reference server config for CTT run (Console Server was used, others tbd)
- add a few cases in ref server node manager to enable skipped tests
- preset random generators to create deterministic node data 
CTT fixes:
- Trigger: fix a regression introduced with the TransferSubscription support, Trigger stopped working, revert change to remove LinkedList in MonitoredItems
- return BadDataEncodingUnsupported creating MonitoredItems
- ensure that MonitoredItem node data reported as required by CTT after initial reading, transfer and SetMonitoring

note: not yet 100% passy, a few uncritical failing tests are still under investigation

Co-authored-by: mrsuciu <Mircea-Adrian.Suciu@softing.com>
2022-01-31 13:32:58 +01:00
Martin Regen a147eb55c5 Tracing and Logging improvements for the UA Core and libraries (#1631)
- support for Microsoft.Extensions.Logger.ILogger in Opc.Ua.Core as the new logging interface
- backward compatible with config and TraceEvents
- new API Utils.SetLogger allows to set ILogger
- updated Console samples to demonstrate ILogger support with Serilog
- support for EventSource logging
- see Docs/Logging.md for more info
2021-12-16 00:20:08 +01:00
Martin Regen 14e7c67a5c Add sample node managers to ref server (#1535)
- add boiler, data and memory buffer sample node managers to reference server
- exclude Quickstarts.Servers from code coverage
2021-10-15 21:12:04 +02:00
Alin Moldovean b5421ea391 Compliance fixes for OperationLimits and SetTriggering (#1469) 2021-07-26 11:33:41 +03:00
Martin Regen 0236d082b1 Create client and server test projects, increase test coverage (#1434)
- Add Operation limit parameter and fix server. Fixes #1363 
- Add client/server test projects
- Add client and server fixture for test runs
- Server tests can test services without client connection
- Client tests can use common services to write tests which can run directly on server on via client server connection
- Increase code coverage > 50%
- Code coverage excludes the generated code
- Improve codecoverage local tests with report (see Tests/codecoverage scripts)
- Add a benchmark framework to client server tests
2021-07-06 18:01:54 +02:00
Alin Moldovean 333aadc6f3 Compliance fixes in ReferenceServer (#1241)
Compliance fixes for certificate validation.
Add config flag in ReferenceServer to specify whether  Certificate dialog should be displayed.
2021-01-14 13:52:51 +02:00
Alin Moldovean cf44debd5e ReverseConnectServer improvements (#1083)
* ReverseConnectServer improvements.
2020-08-07 10:48:28 +03:00
Martin Regen 46cd2d990a - Add the reverse connect in the reference server and a few bug fixes (#1071)
- Support the reverse connections in the reference server
- fix an issue when the anonymous token is sent as a null value by the aggregation server
- fix docker build files
2020-07-30 11:48:28 +02:00
Alin Moldovean 5faf85a7b9 Create Applications folder with ReferenceClient/Server (#1015)
* Clean UA Reference solution

* Move ReferenceClient/Server

* Copy Client/ServerControls libraries
Fix project references

* Rename docs to Docs

* Rename GDS libraries according to naming convention
2020-06-15 09:36:09 +03:00