mirror of
https://github.com/OPCFoundation/UA-.NETStandard.git
synced 2026-10-26 04:19:53 +08:00
# Description
Brings the stack's fuzz testing to parity with the fork
(`aio-opcua-sdk`), then fixes every defect the resulting campaigns
exposed.
The fork's fuzzing was used as the behavioural baseline: all **28
fork-local callbacks** and **13 OneFuzz registrations** are now
accounted for by an explicit mapping, not just by a larger target count.
The work extends the existing SharpFuzz/NUnit infrastructure rather than
introducing another framework.
### Coverage
- **84 continuous libFuzzer targets** and **81 AFL adapters** across
Encoders, Certificates, Network and PubSub.
- **PubSub area integrated** (Corpus/Tools/Tests siblings, solution
entries) — it previously had host source only and was absent from the
solution and replay infrastructure.
- Segmented binary adapters, binary-to-JSON and XML-to-JSON conversions,
standalone certificate loading, both chain-parser variants, CRL encoding
and canonical TBS round-trips.
- The 12 original fork message inputs are retained byte-identically
alongside richer deterministic generators; the three historical
crash/slow/timeout reproducers are unchanged (verified identical by
SHA-256).
### Production fixes found by fuzzing
These are real robustness and data-integrity bugs, each with a retained
regression input:
- `UadpBinaryReader.Advance` accepted attacker-controlled lengths on the
receive path. Declared payload sizes are now authoritative bounded
sections, with negative-count rejection and overflow-safe reassembly
arithmetic.
- PubSub JSON decoding leaked `InvalidOperationException` for invalid
UTF-8.
- `JsonEncoder.WriteExtensionObject` leaked
`System.Text.Json.JsonReaderException`.
- `JsonEncoder` silently emitted a lossy `{}` for an `ExtensionObject`
whose TypeId could not be represented in JSON.
- `JsonDecoder` wrapped a bodyless `ExtensionObject` envelope as a raw
JSON body instead of preserving `ExtensionObjectEncoding.None`.
- `Node.Encode` lost the null/empty collection distinction.
- Binary/XML Variant matrix dimensions are prevalidated rather than
relying on a caught `ArgumentException`.
- `X509CRL.ReadTime` pre-validates strict RFC 5280 whole-second Zulu
time forms.
- `Utils.ParseCertificateChainBlob` disposes correctly on partial-chain
failure.
- **`nodeid.dict` was unloadable by libFuzzer** (empty token, unescaped
quote). libFuzzer rejects the whole file on one bad line, so four parser
targets silently executed **zero** inputs. Fixed and now guarded by
dictionary validation.
### Infrastructure
- `fuzzing/fuzz-targets.json` manifest recording adapters, corpora,
dictionaries, oracles and fork-behaviour mappings, with
`validate-fuzz-manifest.ps1` and **27 negative controls**.
- Strict host/tools discovery and replay: `--list`, `--replay`, non-zero
exits on unknown targets, missing or empty corpora, and failed callbacks
(playback previously logged failures and returned success).
- A real process watchdog for the timeout/slow regressions — NUnit
`CancelAfter` cannot interrupt a synchronous fuzz callback.
- Runner scripts made non-destructive (unique work directories, no
generic `bin`/findings deletion) and corrected to the native driver's
single-`--target_arg` apphost contract.
- Opt-in `OneFuzz=true` class-library publication producing a
relocatable, **uninstrumented** drop, validated by exact callback
discovery, dependency closure, corpora and dictionaries.
- CI: fuzz replay matrix plus a public drop gate, triggered by corpus-,
dictionary- and script-only changes.
### Verification
| Gate | Result |
|---|---|
| Bounded campaigns, all 84 targets (1,000 inputs, seed 1) | 84/84,
84,000 executions, zero findings |
| OneFuzz drop | 84/84 published callbacks replayed, zero skips |
| Fuzz replay net10.0 / net8.0 / net9.0 | 9,470 passed each, 0 failed |
| Fuzz replay net48 | 8,996 passed, 0 failed (Network/PubSub are
modern-only) |
| `Opc.Ua.Types.Tests` / `Opc.Ua.Core.Tests` | 9,800 and 4,442 passed, 0
failed |
| Retained regression assets | 132 `crash-*` inputs replayed by every
target each run |
### Known gaps (deliberately not closed)
- **Fidelity is not enforced against the pipeline crash corpus.** The
differential binary-to-JSON targets assert both robustness (no unhandled
exception, expected of arbitrary bytes) and fidelity (a decoded value
re-encodes equivalently, a property of well formed values). The pipeline
supplies 22,293 blobs collected for the targets that existed before this
PR, none of which asserted fidelity; 522 of them violate it, and that
count did not move across two rounds of genuine fixes because each fix
only lets the mutator reach the next representability gap. Rather than
weaken the assertion, the two contracts are separated: fidelity failures
raise `EncodingFidelityException`; curated assets under `Assets/Repo`,
the curated `Testcases` corpus and every continuous libFuzzer campaign
stay strictly enforced, while externally supplied assets are gated on
robustness only and their fidelity findings are reported with counts and
bounded base64 reproducers.
- **Internal MSFT OneFuzz canary has not been run.** It needs an
owner-supplied ownership profile, pipeline authorisation and corpus
snapshot; none were available. The drop builds and validates locally and
records `serviceCanaryPerformed: false`. A build or upload is not a
successful worker run.
- **Legacy JSON wire forms are a partial mapping.** The fork accepts its
four original `TypeId`/`Body` messages; this stack rejects that retired
envelope (measured JSON-only control: fork `JsonEncoder` 630/1356 lines
vs 0/1007 here). Recorded as an explicit unresolved mapping rather than
an exemption. `LegacyNonReversible` is a RawData-derived profile and is
not counted as independent coverage.
## Related Issues
_No tracking issue was supplied for this work; happy to open one and
link it if maintainers prefer._
- Fixes #github-issue-number, ...
## 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.
- [x] 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.
- [x] 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.
> Note on the checklist: the fuzz replay matrix, `Opc.Ua.Types.Tests`
and `Opc.Ua.Core.Tests` were run locally on **net48** and **net10.0**
(plus net8.0/net9.0) and all passed. CI and CodeQL results are not yet
available for this branch, so those boxes are left unchecked. The CLA
box is for the author to confirm.
512 lines
22 KiB
C#
512 lines
22 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;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Text;
|
|
|
|
namespace Opc.Ua.Fuzzing
|
|
{
|
|
public static partial class Testcases
|
|
{
|
|
public enum TestCaseEncoders
|
|
{
|
|
Binary = 0,
|
|
Json = 1,
|
|
Xml = 2
|
|
}
|
|
|
|
/// <summary>
|
|
/// Run the encoder test cases
|
|
/// </summary>
|
|
/// <param name="workPath"></param>
|
|
/// <param name="telemetry">Unused; retained for the common fuzz-tool signature.</param>
|
|
public static void Run(string workPath, ITelemetryContext telemetry)
|
|
{
|
|
_ = telemetry;
|
|
string pathSuffix = GetTestcaseEncoderSuffix(TestCaseEncoders.Binary);
|
|
string pathTarget = workPath + pathSuffix + Path.DirectorySeparatorChar;
|
|
Directory.CreateDirectory(pathTarget);
|
|
foreach (MessageEncoder messageEncoder in GetMessageEncoders())
|
|
{
|
|
byte[] message;
|
|
using (var encoder = new BinaryEncoder(FuzzableCode.MessageContext))
|
|
{
|
|
messageEncoder(encoder);
|
|
message = encoder.CloseAndReturnBuffer();
|
|
}
|
|
|
|
// Test the fuzz targets with the message.
|
|
FuzzableCode.LibfuzzBinaryDecoder(message);
|
|
FuzzableCode.LibfuzzBinaryEncoder(message);
|
|
FuzzableCode.LibfuzzBinaryEncoderIndempotent(message);
|
|
FuzzableCode.LibfuzzBinaryDecoderSegmented(message);
|
|
FuzzableCode.LibfuzzBinaryEncoderSegmented(message);
|
|
FuzzableCode.LibfuzzBinaryEncoderIndempotentSegmented(message);
|
|
using (var stream = new MemoryStream(message))
|
|
{
|
|
FuzzableCode.AflfuzzBinaryDecoder(stream);
|
|
}
|
|
using (var stream = new MemoryStream(message))
|
|
{
|
|
FuzzableCode.AflfuzzBinaryEncoder(stream);
|
|
}
|
|
using (var stream = new MemoryStream(message))
|
|
{
|
|
IEncodeable decoded = FuzzableCode.FuzzBinaryDecoderCore(stream, true);
|
|
foreach (JsonEncoderOptions options in FuzzableCode.JsonEncodingModes)
|
|
{
|
|
FuzzableCode.FuzzJsonRoundTripCore(decoded, options);
|
|
}
|
|
}
|
|
|
|
string fileName = Path.Combine(
|
|
pathTarget,
|
|
$"{messageEncoder.Method.Name}.bin".ToLowerInvariant());
|
|
File.WriteAllBytes(fileName, message);
|
|
}
|
|
|
|
// Create the Testcases for the json decoder.
|
|
pathSuffix = GetTestcaseEncoderSuffix(TestCaseEncoders.Json);
|
|
pathTarget = workPath + pathSuffix + Path.DirectorySeparatorChar;
|
|
Directory.CreateDirectory(pathTarget);
|
|
foreach (MessageEncoder messageEncoder in GetMessageEncoders())
|
|
{
|
|
byte[] message;
|
|
using (var memoryStream = new MemoryStream(0x1000))
|
|
using (var encoder = new JsonEncoder(memoryStream, FuzzableCode.MessageContext))
|
|
{
|
|
messageEncoder(encoder);
|
|
encoder.Close();
|
|
message = memoryStream.ToArray();
|
|
}
|
|
|
|
// Test the fuzz targets with the message.
|
|
FuzzableCode.LibfuzzJsonDecoder(message);
|
|
FuzzableCode.LibfuzzJsonEncoder(message);
|
|
string json = Encoding.UTF8.GetString(message);
|
|
FuzzableCode.AflfuzzJsonDecoder(json);
|
|
FuzzableCode.AflfuzzJsonEncoder(json);
|
|
IEncodeable decoded = FuzzableCode.FuzzJsonDecoderCore(json, true);
|
|
foreach (JsonEncoderOptions options in FuzzableCode.JsonEncodingModes)
|
|
{
|
|
FuzzableCode.FuzzJsonRoundTripCore(decoded, options);
|
|
}
|
|
|
|
string fileName = Path.Combine(
|
|
pathTarget,
|
|
$"{messageEncoder.Method.Name}.json".ToLowerInvariant());
|
|
File.WriteAllBytes(fileName, message);
|
|
}
|
|
|
|
// Create the Testcases for the xml decoder.
|
|
pathSuffix = GetTestcaseEncoderSuffix(TestCaseEncoders.Xml);
|
|
pathTarget = workPath + pathSuffix + Path.DirectorySeparatorChar;
|
|
Directory.CreateDirectory(pathTarget);
|
|
foreach (MessageEncoder messageEncoder in GetMessageEncoders())
|
|
{
|
|
string xml;
|
|
using (var encoder = new XmlEncoder(FuzzableCode.MessageContext))
|
|
{
|
|
encoder.SetMappingTables(
|
|
FuzzableCode.MessageContext.NamespaceUris,
|
|
FuzzableCode.MessageContext.ServerUris);
|
|
messageEncoder(encoder);
|
|
xml = encoder.CloseAndReturnText();
|
|
}
|
|
|
|
// Test the fuzz targets with the message.
|
|
byte[] message = Encoding.UTF8.GetBytes(xml);
|
|
using (var stream = new MemoryStream(message))
|
|
{
|
|
FuzzableCode.AflfuzzXmlDecoder(stream);
|
|
}
|
|
using (var stream = new MemoryStream(message))
|
|
{
|
|
FuzzableCode.AflfuzzXmlEncoder(stream);
|
|
}
|
|
using (var stream = new MemoryStream(message))
|
|
{
|
|
IEncodeable decoded = FuzzableCode.FuzzXmlDecoderCore(stream, true);
|
|
foreach (JsonEncoderOptions options in FuzzableCode.JsonEncodingModes)
|
|
{
|
|
FuzzableCode.FuzzJsonRoundTripCore(decoded, options);
|
|
}
|
|
}
|
|
FuzzableCode.LibfuzzXmlDecoder(message);
|
|
FuzzableCode.LibfuzzXmlEncoder(message);
|
|
FuzzableCode.LibfuzzXmlEncoderIndempotent(message);
|
|
|
|
string fileName = Path.Combine(
|
|
pathTarget,
|
|
$"{messageEncoder.Method.Name}.xml".ToLowerInvariant());
|
|
File.WriteAllBytes(fileName, Encoding.UTF8.GetBytes(xml));
|
|
}
|
|
|
|
WriteBuiltInTypeTestcases(workPath);
|
|
WriteParserTestcases(workPath);
|
|
}
|
|
|
|
private static string GetTestcaseEncoderSuffix(TestCaseEncoders encoder)
|
|
{
|
|
return "." + encoder;
|
|
}
|
|
|
|
private delegate void BuiltInEncoder(IEncoder encoder);
|
|
|
|
internal static IEnumerable<MessageEncoder> GetMessageEncoders()
|
|
{
|
|
yield return ReadRequestRich;
|
|
yield return ReadResponseRich;
|
|
yield return PublishResponse;
|
|
yield return BrowseRequest;
|
|
yield return WriteRequestRich;
|
|
yield return DataTypeNodeMessage;
|
|
yield return VariableNodeMessage;
|
|
}
|
|
|
|
private static void ReadRequestRich(IEncoder encoder)
|
|
{
|
|
ReadRequest(encoder);
|
|
}
|
|
|
|
private static void ReadResponseRich(IEncoder encoder)
|
|
{
|
|
ReadResponse(encoder);
|
|
}
|
|
|
|
private static void BrowseRequest(IEncoder encoder)
|
|
{
|
|
var browseRequest = new BrowseRequest
|
|
{
|
|
RequestHeader = CreateRequestHeader(),
|
|
RequestedMaxReferencesPerNode = 10,
|
|
NodesToBrowse =
|
|
[
|
|
new BrowseDescription
|
|
{
|
|
NodeId = ObjectIds.ObjectsFolder,
|
|
BrowseDirection = BrowseDirection.Forward,
|
|
ReferenceTypeId = ReferenceTypeIds.HierarchicalReferences,
|
|
IncludeSubtypes = true,
|
|
NodeClassMask = (uint)(NodeClass.Object | NodeClass.Variable),
|
|
ResultMask = (uint)BrowseResultMask.All
|
|
}
|
|
]
|
|
};
|
|
|
|
encoder.EncodeMessage(browseRequest);
|
|
}
|
|
|
|
private static void WriteRequestRich(IEncoder encoder)
|
|
{
|
|
WriteRequest(encoder);
|
|
}
|
|
|
|
private static RequestHeader CreateRequestHeader()
|
|
{
|
|
return new RequestHeader
|
|
{
|
|
Timestamp = SeedTimestamp,
|
|
RequestHandle = 42,
|
|
AdditionalHeader = new ExtensionObject(new ReadValueId
|
|
{
|
|
NodeId = new NodeId(2253),
|
|
AttributeId = Attributes.Value
|
|
})
|
|
};
|
|
}
|
|
|
|
// The two Node seeds below are permanent regression coverage for
|
|
// https://github.com/OPCFoundation/UA-.NETStandard/issues/3546 — they
|
|
// populate the fields (References, RolePermissions, DataTypeDefinition,
|
|
// multi-dim Value Variant) that the original failure-pattern exercises.
|
|
// Keeping them as seeds means FuzzGoodTestcases (the assertive theory
|
|
// in FuzzTargetTestsBase) covers the IsEqual round-trip end-to-end on
|
|
// every run, not only when the libfuzz pipeline happens to mutate
|
|
// into these shapes.
|
|
|
|
private static void DataTypeNodeMessage(IEncoder encoder)
|
|
{
|
|
var dataTypeNode = new DataTypeNode
|
|
{
|
|
NodeId = new NodeId(1234, 2),
|
|
NodeClass = NodeClass.DataType,
|
|
BrowseName = new QualifiedName("Issue3546DataType", 2),
|
|
DisplayName = new LocalizedText("en", "Issue 3546 DataType"),
|
|
Description = new LocalizedText("en", "Round-trip regression seed"),
|
|
IsAbstract = false,
|
|
DataTypeDefinition = new ExtensionObject(
|
|
new StructureDefinition
|
|
{
|
|
DefaultEncodingId = new NodeId(5678, 2),
|
|
BaseDataType = DataTypeIds.Structure,
|
|
StructureType = StructureType.Structure,
|
|
Fields =
|
|
[
|
|
new StructureField
|
|
{
|
|
Name = "Field0",
|
|
DataType = DataTypeIds.UInt32,
|
|
ValueRank = ValueRanks.Scalar,
|
|
IsOptional = false
|
|
},
|
|
new StructureField
|
|
{
|
|
Name = "Field1",
|
|
DataType = DataTypeIds.String,
|
|
ValueRank = ValueRanks.Scalar,
|
|
IsOptional = false
|
|
}
|
|
]
|
|
}),
|
|
References =
|
|
[
|
|
new ReferenceNode
|
|
{
|
|
ReferenceTypeId = ReferenceTypeIds.HasSubtype,
|
|
IsInverse = true,
|
|
TargetId = (ExpandedNodeId)DataTypeIds.Structure
|
|
},
|
|
new ReferenceNode
|
|
{
|
|
ReferenceTypeId = ReferenceTypeIds.HasEncoding,
|
|
IsInverse = false,
|
|
TargetId = new ExpandedNodeId(new NodeId(5678, 2))
|
|
}
|
|
],
|
|
RolePermissions =
|
|
[
|
|
new RolePermissionType
|
|
{
|
|
RoleId = ObjectIds.WellKnownRole_AuthenticatedUser,
|
|
Permissions = (uint)PermissionType.Read
|
|
}
|
|
],
|
|
UserRolePermissions =
|
|
[
|
|
new RolePermissionType
|
|
{
|
|
RoleId = ObjectIds.WellKnownRole_AuthenticatedUser,
|
|
Permissions = (uint)PermissionType.Read
|
|
}
|
|
]
|
|
};
|
|
|
|
encoder.EncodeMessage(dataTypeNode);
|
|
}
|
|
|
|
private static void VariableNodeMessage(IEncoder encoder)
|
|
{
|
|
var variableNode = new VariableNode
|
|
{
|
|
NodeId = new NodeId(4321, 2),
|
|
NodeClass = NodeClass.Variable,
|
|
BrowseName = new QualifiedName("Issue3546Variable", 2),
|
|
DisplayName = new LocalizedText("en", "Issue 3546 Variable"),
|
|
Description = new LocalizedText("en", "Round-trip regression seed"),
|
|
Value = Variant.From(new ExtensionObject(
|
|
new Argument
|
|
{
|
|
Name = "Sample",
|
|
DataType = DataTypeIds.UInt32,
|
|
ValueRank = ValueRanks.Scalar,
|
|
Description = new LocalizedText("en", "fuzz #3546 sample")
|
|
})),
|
|
DataType = DataTypeIds.Argument,
|
|
ValueRank = ValueRanks.Scalar,
|
|
ArrayDimensions = new ArrayOf<uint>(s_arrayDimensions),
|
|
AccessLevel = AccessLevels.CurrentRead | AccessLevels.CurrentWrite,
|
|
UserAccessLevel = AccessLevels.CurrentRead,
|
|
MinimumSamplingInterval = 0,
|
|
Historizing = false,
|
|
AccessLevelEx = 0,
|
|
References =
|
|
[
|
|
new ReferenceNode
|
|
{
|
|
ReferenceTypeId = ReferenceTypeIds.HasTypeDefinition,
|
|
IsInverse = false,
|
|
TargetId = (ExpandedNodeId)VariableTypeIds.BaseDataVariableType
|
|
},
|
|
new ReferenceNode
|
|
{
|
|
ReferenceTypeId = ReferenceTypeIds.Organizes,
|
|
IsInverse = true,
|
|
TargetId = (ExpandedNodeId)ObjectIds.ObjectsFolder
|
|
}
|
|
],
|
|
RolePermissions =
|
|
[
|
|
new RolePermissionType
|
|
{
|
|
RoleId = ObjectIds.WellKnownRole_Anonymous,
|
|
Permissions = (uint)PermissionType.Read
|
|
}
|
|
],
|
|
UserRolePermissions =
|
|
[
|
|
new RolePermissionType
|
|
{
|
|
RoleId = ObjectIds.WellKnownRole_Anonymous,
|
|
Permissions = (uint)PermissionType.Read
|
|
}
|
|
]
|
|
};
|
|
|
|
encoder.EncodeMessage(variableNode);
|
|
}
|
|
|
|
private static readonly uint[] s_arrayDimensions = [1u, 2u];
|
|
|
|
private static void WriteBuiltInTypeTestcases(string workPath)
|
|
{
|
|
string builtInPath = workPath + ".BuiltInTypes" + Path.DirectorySeparatorChar;
|
|
Directory.CreateDirectory(builtInPath);
|
|
|
|
foreach ((string name, BuiltInEncoder builtInEncoder) in GetBuiltInEncoders())
|
|
{
|
|
string binaryPath = Path.Combine(builtInPath, "Binary");
|
|
Directory.CreateDirectory(binaryPath);
|
|
using (var encoder = new BinaryEncoder(FuzzableCode.MessageContext))
|
|
{
|
|
builtInEncoder(encoder);
|
|
File.WriteAllBytes(
|
|
Path.Combine(binaryPath, name + ".bin"),
|
|
encoder.CloseAndReturnBuffer() ?? []);
|
|
}
|
|
|
|
string jsonPath = Path.Combine(builtInPath, "Json");
|
|
Directory.CreateDirectory(jsonPath);
|
|
using (var memoryStream = new MemoryStream(0x1000))
|
|
using (var encoder = new JsonEncoder(memoryStream, FuzzableCode.MessageContext))
|
|
{
|
|
builtInEncoder(encoder);
|
|
encoder.Close();
|
|
File.WriteAllBytes(Path.Combine(jsonPath, name + ".json"), memoryStream.ToArray());
|
|
}
|
|
|
|
string xmlPath = Path.Combine(builtInPath, "Xml");
|
|
Directory.CreateDirectory(xmlPath);
|
|
File.WriteAllText(
|
|
Path.Combine(xmlPath, name + ".xml"),
|
|
GetXmlBuiltInSeed(name),
|
|
Encoding.UTF8);
|
|
}
|
|
}
|
|
|
|
private static IEnumerable<(string Name, BuiltInEncoder Encoder)> GetBuiltInEncoders()
|
|
{
|
|
yield return ("nodeid", encoder => encoder.WriteNodeId("Value", new NodeId(1000, 2)));
|
|
yield return ("expandednodeid", encoder => encoder.WriteExpandedNodeId(
|
|
"Value",
|
|
new ExpandedNodeId(new NodeId(1000, 2), "urn:example:namespace", 1)));
|
|
yield return ("variant", encoder => encoder.WriteVariant(
|
|
"Value",
|
|
Variant.From(new LocalizedText("en-US", "Hello World"))));
|
|
yield return ("extensionobject", encoder => encoder.WriteExtensionObject(
|
|
"Value",
|
|
new ExtensionObject(new ReadValueId
|
|
{
|
|
NodeId = new NodeId(2253),
|
|
AttributeId = Attributes.Value
|
|
})));
|
|
yield return ("datavalue", encoder => encoder.WriteDataValue(
|
|
"Value",
|
|
new DataValue(
|
|
Variant.From(new QualifiedName("Temperature", 2)),
|
|
StatusCodes.Good,
|
|
SeedTimestamp)));
|
|
yield return ("diagnosticinfo", encoder => encoder.WriteDiagnosticInfo(
|
|
"Value",
|
|
new DiagnosticInfo
|
|
{
|
|
AdditionalInfo = "seed diagnostic",
|
|
InnerStatusCode = StatusCodes.BadNodeIdUnknown,
|
|
InnerDiagnosticInfo = new DiagnosticInfo
|
|
{
|
|
AdditionalInfo = "inner diagnostic",
|
|
InnerStatusCode = StatusCodes.BadDecodingError
|
|
}
|
|
}));
|
|
yield return ("qualifiedname", encoder => encoder.WriteQualifiedName(
|
|
"Value",
|
|
new QualifiedName("Temperature", 2)));
|
|
yield return ("localizedtext", encoder => encoder.WriteLocalizedText(
|
|
"Value",
|
|
new LocalizedText("en-US", "Hello World")));
|
|
}
|
|
|
|
private static string GetXmlBuiltInSeed(string name)
|
|
{
|
|
const string ns = " xmlns=\"http://opcfoundation.org/UA/2008/02/Types.xsd\"";
|
|
return name switch
|
|
{
|
|
"nodeid" => $"<Value{ns}><Identifier>ns=2;i=1000</Identifier></Value>",
|
|
"expandednodeid" => $"<Value{ns}><Identifier>svr=1;nsu=urn:example:namespace;i=1000" +
|
|
"</Identifier></Value>",
|
|
"variant" => $"<Value{ns}><Value><String>Hello World</String></Value></Value>",
|
|
"extensionobject" => $"<Value{ns}><TypeId><Identifier>i=628</Identifier></TypeId></Value>",
|
|
"datavalue" => $"<Value{ns}><Value><Value><String>Hello World</String></Value></Value></Value>",
|
|
"diagnosticinfo" => $"<Value{ns}><AdditionalInfo>seed diagnostic</AdditionalInfo></Value>",
|
|
"qualifiedname" => $"<Value{ns}><NamespaceIndex>2</NamespaceIndex><Name>Temperature</Name></Value>",
|
|
"localizedtext" => $"<Value{ns}><Locale>en-US</Locale><Text>Hello World</Text></Value>",
|
|
_ => $"<Value{ns} />"
|
|
};
|
|
}
|
|
|
|
private static void WriteParserTestcases(string workPath)
|
|
{
|
|
string parserPath = workPath + ".Parsers" + Path.DirectorySeparatorChar;
|
|
Directory.CreateDirectory(parserPath);
|
|
|
|
foreach ((string name, string text) in GetParserSeeds())
|
|
{
|
|
File.WriteAllText(Path.Combine(parserPath, name + ".txt"), text, Encoding.UTF8);
|
|
}
|
|
}
|
|
|
|
private static IEnumerable<(string Name, string Text)> GetParserSeeds()
|
|
{
|
|
yield return ("nodeid_numeric", "i=85");
|
|
yield return ("nodeid_string", "ns=2;s=Demo.Node");
|
|
yield return ("nodeid_guid", "ns=2;g=00000000-0000-0000-0000-000000000001");
|
|
yield return ("expandednodeid_uri", "svr=1;nsu=http://opcfoundation.org/UA/;i=85");
|
|
yield return ("expandednodeid_string", "nsu=urn:example:namespace;s=Demo");
|
|
yield return ("relativepath_child", "/2:Block/2:Parameter");
|
|
yield return ("relativepath_property", ".2:EngineeringUnits");
|
|
yield return ("qualifiedname", "2:Temperature");
|
|
yield return ("numericrange_single", "0");
|
|
yield return ("numericrange_matrix", "0:10,1:2");
|
|
yield return ("uuid", "00000000-0000-0000-0000-000000000001");
|
|
}
|
|
}
|
|
}
|