using System.Text.Json;
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions;
/// One credential field of a driver config and whether it may carry a literal.
/// The JSON property name (matched case-insensitively, as every driver binds).
/// The literal policy.
public sealed record CredentialField(string Name, CredentialLiteralPolicy Literals);
/// The credential scope + fields of one driver type.
/// The value.
/// The namespace its references are confined to.
/// The credential fields its DriverConfig/DeviceConfig may carry.
/// Fields naming a node-local key-material file, confined to a node directory (lmxopcua#836).
///
/// The keys (any depth, case-insensitive) that say WHERE the driver sends its credentials — the endpoint a Test Connect
/// or browse dials (#835 review I-1: an unsaved endpoint may not borrow the stored driver's own secrets).
///
public sealed record DriverCredentialRules(
string DriverType, CredentialScope Scope, IReadOnlyList Fields, IReadOnlyList? PathFields = null,
IReadOnlyList? EndpointFields = null)
{
/// The path fields (never null).
public IReadOnlyList PathFieldList => PathFields ?? [];
/// The endpoint fields (never null).
public IReadOnlyList EndpointFieldList => EndpointFields ?? [];
}
/// The identity of one driver instance, as the cross-instance rule (lmxopcua#835) matches it.
/// The instance id.
/// The instance's display name.
/// The instance's driver type.
public sealed record DriverInstanceIdentity(string DriverInstanceId, string Name, string DriverType);
///
/// The per-driver credential namespaces (lmxopcua#815) — the single table the AdminUI save path, the deploy gate,
/// Test Connect, live browse and every driver's resolve-time check read.
///
///
/// Every driver that RESOLVES a secret:/env: reference from operator-authored config and sends the
/// value to an operator-chosen endpoint is listed here. Drivers that resolve nothing (literal credentials only —
/// MQTT, MTConnect URI user-info) or whose resolved value carries its own endpoint (Sql's
/// Sql__ConnectionStrings__<ref>, already a fixed prefix) are not.
///
public static class DriverCredentialPolicy
{
/// Heidenhain LSV2 passwords: secret:heidenhain/… / env:OTOPCUA_HEIDENHAIN_… (#803).
public static readonly CredentialScope HeidenhainScope = new("Heidenhain", ["heidenhain/"], ["OTOPCUA_HEIDENHAIN_"]);
///
/// Galaxy gateway API key + fallback ack password: secret:galaxy/… (or secret:otopcua/galaxy/…, the
/// form the ack-fallback docs used) / env:OTOPCUA_GALAXY_…, plus the
/// legacy env:GALAXY_MXGW_… prefix the docker-dev rig and the parity-rig docs already use
/// (GALAXY_MXGW_API_KEY) — a variable provisioned to be sent to an mxaccessgw.
///
public static readonly CredentialScope GalaxyScope = new("Galaxy", ["galaxy/", "otopcua/galaxy/"], ["OTOPCUA_GALAXY_", "GALAXY_MXGW_"]);
/// OPC UA Client user / certificate passwords: secret:opcuaclient/… / env:OTOPCUA_OPCUACLIENT_….
public static readonly CredentialScope OpcUaClientScope = new("OpcUaClient", ["opcuaclient/"], ["OTOPCUA_OPCUACLIENT_"]);
/// The node config key of the OpcUaClient user-certificate directory (lmxopcua#836).
public const string OpcUaClientUserCertificateDirectoryKey = "Drivers:OpcUaClient:UserCertificateDirectory";
/// OpcUaClient UserCertificatePath: a relative path inside the node's user-certificate directory (#836).
public static readonly CredentialPathField OpcUaClientUserCertificatePathField = new(
"UserCertificatePath",
OpcUaClientUserCertificateDirectoryKey + ", default /OtOpcUa/pki/user-certificates",
ActiveWhenKey: "AuthType", ActiveWhenValue: "Certificate", ActiveWhenOrdinal: 2);
/// Galaxy Gateway.ApiKeySecretRef (literal accepted for back-compat, with a warning at resolve).
public static readonly CredentialField GalaxyApiKeyField = new("ApiKeySecretRef", CredentialLiteralPolicy.Allowed);
/// Galaxy AlarmAck.FallbackPasswordSecretRef (reference or explicit dev: only).
public static readonly CredentialField GalaxyAckPasswordField = new("FallbackPasswordSecretRef", CredentialLiteralPolicy.DevPrefixOnly);
private static readonly IReadOnlyDictionary Rules =
new Dictionary(StringComparer.OrdinalIgnoreCase)
{
[DriverTypeNames.Heidenhain] = new(DriverTypeNames.Heidenhain, HeidenhainScope,
[
new("InspectPassword", CredentialLiteralPolicy.Refused),
new("DncPassword", CredentialLiteralPolicy.Refused),
new("DataPassword", CredentialLiteralPolicy.Refused),
], EndpointFields: ["Host", "Port"]),
[DriverTypeNames.Galaxy] = new(DriverTypeNames.Galaxy, GalaxyScope, [GalaxyApiKeyField, GalaxyAckPasswordField],
EndpointFields: ["Endpoint"]),
[DriverTypeNames.OpcUaClient] = new(DriverTypeNames.OpcUaClient, OpcUaClientScope,
[
new("Password", CredentialLiteralPolicy.Allowed),
new("UserCertificatePassword", CredentialLiteralPolicy.Allowed),
], [OpcUaClientUserCertificatePathField], ["EndpointUrl", "EndpointUrls", "DiscoveryUrl"]),
};
/// The rules for a driver type, if it resolves credential references.
/// The driver type.
/// The rules.
/// Whether the type has rules.
public static bool TryGet(string? driverType, out DriverCredentialRules rules)
{
if (driverType is not null && Rules.TryGetValue(driverType, out var r))
{
rules = r;
return true;
}
rules = null!;
return false;
}
///
/// Scans a RAW DriverConfig / DeviceConfig / merged config document for credential fields of
/// whose value is not acceptable — at ANY depth (a field is bound wherever the
/// driver's merge places it), keys matched case-insensitively. Messages name the field path, never the value.
/// Unreadable JSON is reported for a type with rules (it cannot be checked); other types return empty.
///
/// The owning driver's type.
/// The config JSON.
/// The problems; empty when acceptable or the type has no credential rules.
public static IReadOnlyList DescribeProblems(string? driverType, string? json)
{
var problems = new List();
if (!TryGet(driverType, out var rules) || string.IsNullOrWhiteSpace(json)) return problems;
JsonDocument doc;
try
{
doc = JsonDocument.Parse(json, new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true });
}
catch (JsonException)
{
problems.Add($"{rules.Scope.Label} config is not valid JSON, so its credential fields cannot be checked.");
return problems;
}
using (doc)
{
Scan(doc.RootElement, "", rules, problems, 0);
}
return problems;
}
private static void Scan(JsonElement element, string path, DriverCredentialRules rules, List problems, int depth) =>
Visit(element, path, rules, depth, (fieldPath, value, field, pathField) =>
{
if (field is not null)
{
var ok = value.ValueKind switch
{
JsonValueKind.Null => true,
JsonValueKind.String => CredentialReferences.IsAcceptable(value.GetString(), rules.Scope, field.Literals),
_ => false,
};
if (!ok) problems.Add(CredentialReferences.RuleMessage(fieldPath, rules.Scope, field.Literals));
}
else if (pathField is not null)
{
var ok = value.ValueKind switch
{
JsonValueKind.Null => true,
JsonValueKind.String => CredentialFilePaths.IsAcceptable(value.GetString()),
_ => false,
};
if (!ok) problems.Add(CredentialFilePaths.RuleMessage(fieldPath, pathField.DirectoryDescription));
}
});
/// Walks every credential / path field of at any depth, keys matched case-insensitively.
private static void Visit(
JsonElement element, string path, DriverCredentialRules rules, int depth,
Action onField)
{
if (depth > 32) return;
if (element.ValueKind == JsonValueKind.Array)
{
var i = 0;
foreach (var item in element.EnumerateArray())
{
Visit(item, $"{path}[{i}]", rules, depth + 1, onField);
i++;
}
return;
}
if (element.ValueKind != JsonValueKind.Object) return;
foreach (var p in element.EnumerateObject())
{
var fieldPath = path.Length == 0 ? p.Name : $"{path}.{p.Name}";
var field = rules.Fields.FirstOrDefault(f => string.Equals(f.Name, p.Name, StringComparison.OrdinalIgnoreCase));
var pathField = field is null
? rules.PathFieldList.FirstOrDefault(f => string.Equals(f.Name, p.Name, StringComparison.OrdinalIgnoreCase))
: null;
if (field is null && pathField is null)
{
Visit(p.Value, fieldPath, rules, depth + 1, onField);
continue;
}
// #836 review L-1: a path field explicitly switched off in its own object (OpcUaClient AuthType ≠ Certificate)
// is never loaded by the driver, so it is not checked; an absent switch keeps it checked.
if (pathField is not null && !pathField.IsActiveIn(element)) continue;
onField(fieldPath, p.Value, field, pathField);
}
}
// ---------------------------------------------------------------------------------------------------------------
// lmxopcua#835 — cross-instance references inside one namespace
// ---------------------------------------------------------------------------------------------------------------
///
/// The instance-identifying segment of an in-scope secret: reference: the first path segment after the
/// matched namespace (secret:galaxy/<X>/apikey ⇒ X; secret:otopcua/galaxy/<X> ⇒
/// X). Null for anything else — env: references use , and literals
/// and out-of-scope references are the #815 rule's business.
///
/// The authored field value.
/// The driver's scope.
/// The segment, or null.
public static string? InstanceSegment(string? value, CredentialScope scope)
{
ArgumentNullException.ThrowIfNull(scope);
if (CredentialReferences.Parse(value, scope, out var name) != CredentialReferenceKind.Secret) return null;
var ns = scope.SecretNamespaces
.Where(n => name.StartsWith(n, StringComparison.Ordinal))
.OrderByDescending(n => n.Length)
.FirstOrDefault();
if (ns is null) return null;
var rest = name[ns.Length..];
var slash = rest.IndexOf('/');
return slash < 0 ? rest : rest[..slash];
}
///
/// lmxopcua#849: the part of an in-scope env: reference after the matched (longest) prefix —
/// env:OTOPCUA_GALAXY_<REST> ⇒ REST. The per-instance convention is
/// env:<PREFIX><INSTANCE>_…, INSTANCE being a driver id or name in
/// form; the part NAMES an instance when it equals that form or starts
/// with it followed by _ (see / ). Null for anything but an in-scope env:.
///
/// The authored field value.
/// The driver's scope.
/// The remainder, or null.
public static string? EnvironmentInstancePart(string? value, CredentialScope scope)
{
ArgumentNullException.ThrowIfNull(scope);
if (CredentialReferences.Parse(value, scope, out var name) != CredentialReferenceKind.Environment) return null;
var prefix = scope.EnvVariablePrefixes
.Where(p => name.StartsWith(p, StringComparison.Ordinal))
.OrderByDescending(p => p.Length)
.FirstOrDefault();
return prefix is null ? null : name[prefix.Length..];
}
///
/// lmxopcua#849: a driver id or name in environment-variable form — ASCII letters upper-cased, digits kept, every
/// other character _ (DRV-1a2b ⇒ DRV_1A2B, Line 1 ⇒ LINE_1). Empty when the
/// identifier has no letter or digit (such an identifier names no variable).
///
/// The id or name.
/// The normalised form.
public static string NormalizeEnvironmentIdentifier(string? identifier)
{
if (string.IsNullOrEmpty(identifier) || !identifier.Any(char.IsAsciiLetterOrDigit)) return "";
return string.Create(identifier.Length, identifier, static (span, id) =>
{
for (var i = 0; i < id.Length; i++)
span[i] = char.IsAsciiLetterOrDigit(id[i]) ? char.ToUpperInvariant(id[i]) : '_';
});
}
/// The prefix of every system-generated driver instance id (DRV- + 12 hex, RawTreeService.NewId).
public const string DriverIdPrefix = "DRV";
private const int DriverIdHexLength = 12;
///
/// Whether an instance reference () names the driver id
/// : a secret: segment equal to it (case-insensitive), or an env:
/// part equal to its form or starting with that form plus _.
///
/// The reference.
/// A driver instance id.
/// Whether it names it.
public static bool ReferenceNamesId(InstanceReference reference, string? driverInstanceId) =>
Matches(reference, driverInstanceId);
///
/// Whether an instance reference names the driver NAME — as ,
/// except that a reference whose instance part has the shape of a system-generated id
/// (: secret:…/DRV-<12 hex>/…, env:<PREFIX>DRV_<12 HEX>[_…]) is
/// matched by id only. Otherwise a driver NAMED drv (env form DRV) would "own" the id-form variable of
/// every other driver of its type, and the recommended id convention would break fleet-wide — including for a
/// name that pre-dates the rule (lmxopcua#849 review).
///
/// The reference.
/// A driver name.
/// Whether it names it.
public static bool ReferenceNamesName(InstanceReference reference, string? name) =>
!IsIdShaped(reference) && Matches(reference, name);
///
/// Whether the reference's instance part has the shape of a system-generated driver id: a secret: segment
/// DRV-<12 hex> (case-insensitive), or an env: part DRV_<12 HEX> alone or followed by _.
///
/// The reference.
/// Whether it is id-shaped.
public static bool IsIdShaped(InstanceReference reference) =>
reference.Kind == CredentialReferenceKind.Secret
? reference.Part.Length == DriverIdPrefix.Length + 1 + DriverIdHexLength && StartsWithIdForm(reference.Part, '-', ignoreCase: true)
: StartsWithIdForm(reference.Part, '_', ignoreCase: false)
&& (reference.Part.Length == DriverIdPrefix.Length + 1 + DriverIdHexLength
|| reference.Part[DriverIdPrefix.Length + 1 + DriverIdHexLength] == '_');
///
/// lmxopcua#849 review: a driver NAME that may not be given to a credential-bearing driver — one whose environment
/// form () is DRV or starts with an id form DRV_<12 HEX>.
/// Such a name would collide with the system-generated id convention every driver's own references are
/// recommended to use.
///
/// The proposed name.
/// Whether the name is reserved.
public static bool IsReservedInstanceName(string? name)
{
var env = NormalizeEnvironmentIdentifier(name);
return env == DriverIdPrefix
|| IsIdShaped(new InstanceReference("", CredentialReferenceKind.Environment, env));
}
private static bool StartsWithIdForm(string part, char separator, bool ignoreCase)
{
var length = DriverIdPrefix.Length + 1 + DriverIdHexLength;
if (part.Length < length
|| !part.StartsWith(DriverIdPrefix, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)
|| part[DriverIdPrefix.Length] != separator)
return false;
for (var i = DriverIdPrefix.Length + 1; i < length; i++)
{
var c = part[i];
if (!(char.IsAsciiDigit(c) || c is >= 'A' and <= 'F' || (ignoreCase && c is >= 'a' and <= 'f'))) return false;
}
return true;
}
private static bool Matches(InstanceReference reference, string? identifier)
{
if (string.IsNullOrEmpty(identifier)) return false;
if (reference.Kind == CredentialReferenceKind.Secret)
return string.Equals(reference.Part, identifier, StringComparison.OrdinalIgnoreCase);
var normalized = NormalizeEnvironmentIdentifier(identifier);
return normalized.Length > 0
&& (string.Equals(reference.Part, normalized, StringComparison.Ordinal)
|| reference.Part.StartsWith(normalized + "_", StringComparison.Ordinal));
}
///
/// True when the config carries at least one in-scope secret: or env: reference — i.e. the
/// cross-instance rule () has something to check, so a seam must load
/// the instance list. Lets seams skip the ConfigDb read otherwise.
///
/// The owning driver's type.
/// The config JSON.
/// Whether any instance reference is present.
public static bool HasInstanceSegments(string? driverType, string? json) =>
CollectInstanceReferences(driverType, json).Count > 0;
///
/// lmxopcua#835/#849: inside one namespace, a reference that names (see / ) a DIFFERENT
/// existing instance of the same driver type — by its or its
/// — is refused: otherwise a Designer could create (or Test Connect /
/// browse) a driver that points at their own endpoint with secret:galaxy/<other-instance>/apikey (or
/// env:OTOPCUA_GALAXY_<OTHER_INSTANCE>_KEY) and capture that instance's key. Shared names that name no
/// other instance (secret:galaxy/gw/apikey, env:GALAXY_MXGW_API_KEY) stay valid, as does a reference
/// naming the instance itself.
///
///
/// A match against ANOTHER instance wins over a match against the owner — names are not unique, and renaming
/// one's own driver after a victim's must not unlock the victim's secret.
/// is null for a driver that does not exist yet (every listed instance is then "another").
///
/// The owning driver's type.
/// The DriverConfig / DeviceConfig / merged config JSON.
/// The driver the config belongs to; null when it is being created.
/// The known driver instances (any type; the owner may be included).
/// The problems; empty when acceptable, unreadable, or the type has no rules.
public static IReadOnlyList DescribeOtherInstanceProblems(
string? driverType, string? json, string? ownDriverInstanceId, IEnumerable instances)
{
ArgumentNullException.ThrowIfNull(instances);
var problems = new List();
if (!TryGet(driverType, out var rules)) return problems;
var references = CollectInstanceReferences(driverType, json);
if (references.Count == 0) return problems;
var others = instances
.Where(i => string.Equals(i.DriverType, rules.DriverType, StringComparison.OrdinalIgnoreCase)
&& !string.Equals(i.DriverInstanceId, ownDriverInstanceId, StringComparison.Ordinal))
.ToList();
foreach (var reference in references)
{
var other = others.FirstOrDefault(o => ReferenceNamesId(reference, o.DriverInstanceId) || ReferenceNamesName(reference, o.Name));
if (other is null) continue;
problems.Add(reference.Kind == CredentialReferenceKind.Secret
? $"{reference.FieldPath} names a secret under '{reference.Part}/', which is another {rules.Scope.Label} driver "
+ $"instance ('{other.Name}', {other.DriverInstanceId}) — a driver may reference only its own secrets "
+ $"(secret:{rules.Scope.SecretNamespaces[0]}/…) or a shared name that is no other "
+ "instance's id or name (lmxopcua#835)."
: $"{reference.FieldPath} names an environment variable of another {rules.Scope.Label} driver instance "
+ $"('{other.Name}', {other.DriverInstanceId}) — a driver may reference only its own variables "
+ $"(env:{rules.Scope.EnvVariablePrefixes[0]}_…, the id upper-cased with every other "
+ "character as '_') or a shared name that starts with no other instance's id or name (lmxopcua#849).");
}
return problems;
}
///
/// Both rules at once — (namespace, literals, path fields) followed
/// by — as every seam that knows the owner and the instance list applies them.
///
/// The owning driver's type.
/// The config JSON.
/// The owning driver; null when it is being created.
/// The known driver instances.
/// The problems.
public static IReadOnlyList DescribeProblems(
string? driverType, string? json, string? ownDriverInstanceId, IEnumerable instances) =>
[.. DescribeProblems(driverType, json), .. DescribeOtherInstanceProblems(driverType, json, ownDriverInstanceId, instances)];
///
/// True when the config carries at least one in-scope credential REFERENCE (secret: or env:) — the
/// Test Connect / browse audit trigger (#835 review I-1).
///
/// The driver type.
/// The config JSON.
/// Whether a reference that would be resolved is present.
public static bool HasCredentialReferences(string? driverType, string? json)
{
if (!TryGet(driverType, out var rules) || string.IsNullOrWhiteSpace(json)) return false;
var found = false;
WithDocument(json, root => Visit(root, "", rules, 0, (_, value, field, _) =>
{
if (field is null || value.ValueKind != JsonValueKind.String) return;
if (CredentialReferences.Parse(value.GetString(), rules.Scope, out _) is CredentialReferenceKind.Secret or CredentialReferenceKind.Environment)
found = true;
}));
return found;
}
///
/// The endpoint values (see ) of a config — every string / number
/// under an endpoint key at any depth (arrays flattened), trimmed. Empty for an unreadable config or a type without
/// rules.
///
/// The driver type.
/// The config JSON.
/// The values, in document order.
public static IReadOnlyList EndpointValues(string? driverType, string? json)
{
var values = new List();
if (!TryGet(driverType, out var rules) || rules.EndpointFieldList.Count == 0 || string.IsNullOrWhiteSpace(json)) return values;
WithDocument(json, root => CollectEndpoints(root, rules, values, 0, false));
return values;
}
///
/// #835 review I-1: whether every endpoint value of (a Test Connect / browse config,
/// possibly carrying UNSAVED edits) is one the driver already stores (its DriverConfig or any of its DeviceConfigs).
/// If not, the caller must not treat the stored driver as the config's owner: its own secrets would otherwise be sent
/// to an endpoint nobody saved. A type without endpoint fields never matches (conservative).
///
/// The driver type.
/// The config about to be probed / browsed.
/// The owner's stored DriverConfig + DeviceConfigs.
/// Whether the submitted endpoints are all stored ones.
public static bool EndpointsMatchStored(string? driverType, string? submittedJson, IEnumerable storedJsons)
{
ArgumentNullException.ThrowIfNull(storedJsons);
if (!TryGet(driverType, out var rules) || rules.EndpointFieldList.Count == 0) return false;
var allowed = new HashSet(storedJsons.SelectMany(s => EndpointValues(driverType, s)), StringComparer.OrdinalIgnoreCase);
return EndpointValues(driverType, submittedJson).All(allowed.Contains);
}
private static void CollectEndpoints(JsonElement element, DriverCredentialRules rules, List values, int depth, bool under)
{
if (depth > 32) return;
switch (element.ValueKind)
{
case JsonValueKind.Array:
foreach (var item in element.EnumerateArray()) CollectEndpoints(item, rules, values, depth + 1, under);
return;
case JsonValueKind.Object:
foreach (var p in element.EnumerateObject())
{
var isEndpoint = rules.EndpointFieldList.Any(f => string.Equals(f, p.Name, StringComparison.OrdinalIgnoreCase));
CollectEndpoints(p.Value, rules, values, depth + 1, isEndpoint);
}
return;
case JsonValueKind.String when under:
if (element.GetString() is { } s && s.Trim().Length > 0) values.Add(s.Trim());
return;
case JsonValueKind.Number when under:
values.Add(element.GetRawText());
return;
}
}
private static void WithDocument(string json, Action use)
{
JsonDocument doc;
try
{
doc = JsonDocument.Parse(json, new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true });
}
catch (JsonException)
{
return;
}
using (doc) use(doc.RootElement);
}
///
/// Every in-scope instance reference of a config (lmxopcua#835 secret: segments + #849 env: parts), at
/// any depth. Empty for an unreadable config or a type without rules.
///
/// The owning driver's type.
/// The config JSON.
/// The references, in document order.
public static IReadOnlyList CollectInstanceReferences(string? driverType, string? json)
{
var found = new List();
if (!TryGet(driverType, out var rules) || string.IsNullOrWhiteSpace(json)) return found;
// Unreadable JSON is reported by DescribeProblems.
WithDocument(json, root => Visit(root, "", rules, 0, (fieldPath, value, field, _) =>
{
if (field is null || value.ValueKind != JsonValueKind.String) return;
var text = value.GetString();
if (InstanceSegment(text, rules.Scope) is { Length: > 0 } segment)
found.Add(new(fieldPath, CredentialReferenceKind.Secret, segment));
else if (EnvironmentInstancePart(text, rules.Scope) is { Length: > 0 } part)
found.Add(new(fieldPath, CredentialReferenceKind.Environment, part));
}));
return found;
}
}
/// The instance-identifying part of one in-scope credential reference (lmxopcua#835 / #849).
/// Where it sits in the config (never the value).
/// or .
///
/// The secret: instance segment () or the env: remainder
/// after the prefix ().
///
public readonly record struct InstanceReference(string FieldPath, CredentialReferenceKind Kind, string Part);