fix(security): #835/#836 review — unsaved endpoints never borrow the owner's secrets; audit credential use; path rule follows AuthType

I-1: Test Connect / browse configs may carry unsaved edits (the device modal merges
the stored DriverConfig with the typed device config). The server
(DriverInstanceIdentities.EffectiveOwnerAsync, used by AdminOperationsActor and
BrowserSessionService) honours the named owner only when every endpoint value
(new DriverCredentialRules.EndpointFields: Galaxy Endpoint, OpcUaClient
EndpointUrl/EndpointUrls/DiscoveryUrl, Heidenhain Host/Port) is one that driver
stores; otherwise the owner is null and its instance-named secrets are refused.
Every Test Connect / browse whose config carries an in-scope secret:/env: reference
is recorded (CredentialUseAudit: IAuditWriter event category CredentialUse + a
structured Information line: user, driver, endpoint hosts, outcome).

L-1: the UserCertificatePath rule is skipped only in an object that explicitly sets
AuthType to non-Certificate (string or ordinal); the deploy gate also checks the
runtime-merged driver+device config so the switch cannot be split from the path; the
form no longer persists the hidden field.
L-2: a ConfigDb fault in the browse check is a refusal; RawBrowseModal catches open
failures into its error message.
L-4: a relative UserCertificateDirectory resolves against AppContext.BaseDirectory.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Joseph Doherty
2026-11-11 04:12:40 -05:00
parent 87416a230f
commit 271b96a644
18 changed files with 753 additions and 25 deletions
@@ -53,7 +53,7 @@ public static class CredentialReferenceDeployChecks
.ToList();
foreach (var driver in draft.DriverInstances)
{
if (!DriverCredentialPolicy.TryGet(driver.DriverType, out _)) continue;
if (!DriverCredentialPolicy.TryGet(driver.DriverType, out var rules)) continue;
var devices = draft.Devices
.Where(d => string.Equals(d.DriverInstanceId, driver.DriverInstanceId, StringComparison.Ordinal))
.ToList();
@@ -74,10 +74,32 @@ public static class CredentialReferenceDeployChecks
foreach (var problem in DriverCredentialPolicy.DescribeProblems(driver.DriverType, driver.DriverConfig))
errors.Add(new(Code, $"{driver.DriverType} driver '{driver.Name}': {problem}{MigrationHint}", driver.DriverInstanceId));
var reported = new HashSet<string>(StringComparer.Ordinal);
foreach (var problem in DriverCredentialPolicy.DescribeProblems(driver.DriverType, driver.DriverConfig))
reported.Add(problem);
foreach (var device in devices)
{
foreach (var problem in DriverCredentialPolicy.DescribeProblems(driver.DriverType, device.DeviceConfig))
{
reported.Add(problem);
errors.Add(new(Code, $"{driver.DriverType} device '{device.Name}': {problem}{MigrationHint}", device.DeviceId));
}
}
// #836 review L-1: a path field is exempt only in an object that explicitly switches it off (OpcUaClient
// AuthType ≠ Certificate), and the switch and the path may sit in different configs (driver vs device). Check
// the config exactly as the runtime merges it, so a split can never deploy a path the driver will load.
if (rules.PathFieldList.Count > 0)
{
var merged = DriverDeviceConfigMerger.Merge(
driver.DriverConfig,
devices.Select(d => new DriverDeviceConfigMerger.DeviceRow(d.Name, d.DeviceConfig)).ToList(),
[]);
foreach (var problem in DriverCredentialPolicy.DescribeProblems(driver.DriverType, merged))
{
if (reported.Add(problem))
errors.Add(new(Code, $"{driver.DriverType} driver '{driver.Name}' (merged with its devices): {problem}{MigrationHint}", driver.DriverInstanceId));
}
}
}
@@ -28,6 +28,64 @@ public static class DriverInstanceIdentities
.ToList();
}
/// <summary>
/// #835 review I-1: the owner a Test Connect / browse config may claim. The caller names a driver, but the config can
/// carry UNSAVED edits (the device modal merges the stored DriverConfig with the typed device config), so a Designer
/// could type their own host as the endpoint of a victim's device and Test Connect it with the victim's own
/// <c>secret:galaxy/&lt;victim-id&gt;/…</c>. The claim is honoured only when the driver exists, has the same type, and every
/// endpoint value of the config is one it already STORES (DriverConfig or any DeviceConfig) — otherwise the owner is
/// null, i.e. the strict "new driver" treatment (no instance-named secrets at all).
/// </summary>
/// <param name="db">The config DB.</param>
/// <param name="driverType">The driver type of the request.</param>
/// <param name="configJson">The config about to be probed / browsed.</param>
/// <param name="claimedOwner">The driver the caller says the config belongs to.</param>
/// <param name="ct">Cancellation.</param>
/// <returns>The owner to use, or null.</returns>
public static async Task<string?> EffectiveOwnerAsync(
OtOpcUaConfigDbContext db, string? driverType, string? configJson, string? claimedOwner, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(db);
if (string.IsNullOrEmpty(claimedOwner) || driverType is null) return null;
var driver = await db.DriverInstances.AsNoTracking()
.Where(d => d.DriverInstanceId == claimedOwner)
.Select(d => new { d.DriverType, d.DriverConfig })
.FirstOrDefaultAsync(ct).ConfigureAwait(false);
if (driver is null || !string.Equals(driver.DriverType, driverType, StringComparison.OrdinalIgnoreCase)) return null;
var deviceConfigs = await db.Devices.AsNoTracking()
.Where(d => d.DriverInstanceId == claimedOwner)
.Select(d => d.DeviceConfig)
.ToListAsync(ct).ConfigureAwait(false);
return DriverCredentialPolicy.EndpointsMatchStored(driverType, configJson, [driver.DriverConfig, .. deviceConfigs])
? claimedOwner
: null;
}
/// <summary>
/// The cross-instance problems of a Test Connect / browse config: <see cref="EffectiveOwnerAsync"/> first (an
/// unsaved endpoint does not get the owner's own secrets), then <see cref="DescribeOtherInstanceProblemsAsync"/>.
/// </summary>
/// <param name="db">The config DB.</param>
/// <param name="driverType">The driver type.</param>
/// <param name="configJson">The config.</param>
/// <param name="claimedOwner">The driver the caller names.</param>
/// <param name="ct">Cancellation.</param>
/// <returns>The problems.</returns>
public static async Task<IReadOnlyList<string>> DescribeProbeProblemsAsync(
OtOpcUaConfigDbContext db, string? driverType, string? configJson, string? claimedOwner, CancellationToken ct)
{
if (driverType is null || !DriverCredentialPolicy.HasInstanceSegments(driverType, configJson)) return [];
var owner = await EffectiveOwnerAsync(db, driverType, configJson, claimedOwner, ct).ConfigureAwait(false);
var problems = await DescribeOtherInstanceProblemsAsync(db, driverType, configJson, owner, ct).ConfigureAwait(false);
if (problems.Count == 0 || owner is not null || string.IsNullOrEmpty(claimedOwner)) return problems;
return
[
.. problems,
$"(The endpoint differs from what driver {claimedOwner} has saved, so its own secrets are not sent to it from an "
+ "unsaved form — save the change first; lmxopcua#835.)",
];
}
/// <summary>
/// The cross-instance problems of <paramref name="configJson"/> — reading the ConfigDb only when the config carries
/// an in-scope <c>secret:</c> reference at all.
@@ -8,7 +8,38 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions;
/// </summary>
/// <param name="Name">The JSON property name (matched case-insensitively, as the driver binds it).</param>
/// <param name="DirectoryDescription">How the operator configures the directory (for messages).</param>
public sealed record CredentialPathField(string Name, string DirectoryDescription);
/// <param name="ActiveWhenKey">
/// Optional sibling key that switches the field on (OpcUaClient <c>AuthType</c>): the field is checked UNLESS the same
/// JSON object sets this key to something other than <paramref name="ActiveWhenValue"/> /
/// <paramref name="ActiveWhenOrdinal"/>. An absent key keeps the field checked (conservative — the driver's merge may
/// supply the switch from another config), so only an EXPLICITLY inactive object is exempt.
/// </param>
/// <param name="ActiveWhenValue">The string value of <paramref name="ActiveWhenKey"/> that activates the field.</param>
/// <param name="ActiveWhenOrdinal">The numeric (enum ordinal) value that activates the field.</param>
public sealed record CredentialPathField(
string Name, string DirectoryDescription, string? ActiveWhenKey = null, string? ActiveWhenValue = null, int? ActiveWhenOrdinal = null)
{
/// <summary>Whether the field is in force in <paramref name="owner"/> (the JSON object holding it).</summary>
/// <param name="owner">The object.</param>
/// <returns>False only when the object explicitly switches the field off.</returns>
public bool IsActiveIn(System.Text.Json.JsonElement owner)
{
if (ActiveWhenKey is null || owner.ValueKind != System.Text.Json.JsonValueKind.Object) return true;
foreach (var p in owner.EnumerateObject())
{
if (!string.Equals(p.Name, ActiveWhenKey, StringComparison.OrdinalIgnoreCase)) continue;
return p.Value.ValueKind switch
{
System.Text.Json.JsonValueKind.Null => true,
System.Text.Json.JsonValueKind.String => string.Equals(p.Value.GetString(), ActiveWhenValue, StringComparison.OrdinalIgnoreCase),
System.Text.Json.JsonValueKind.Number => !p.Value.TryGetInt32(out var n) || n == ActiveWhenOrdinal,
_ => true,
};
}
return true;
}
}
/// <summary>
/// The one rule for <see cref="CredentialPathField"/> values (lmxopcua#836): authored as a RELATIVE path inside a
@@ -12,11 +12,19 @@ public sealed record CredentialField(string Name, CredentialLiteralPolicy Litera
/// <param name="Scope">The namespace its references are confined to.</param>
/// <param name="Fields">The credential fields its DriverConfig/DeviceConfig may carry.</param>
/// <param name="PathFields">Fields naming a node-local key-material file, confined to a node directory (lmxopcua#836).</param>
/// <param name="EndpointFields">
/// 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).
/// </param>
public sealed record DriverCredentialRules(
string DriverType, CredentialScope Scope, IReadOnlyList<CredentialField> Fields, IReadOnlyList<CredentialPathField>? PathFields = null)
string DriverType, CredentialScope Scope, IReadOnlyList<CredentialField> Fields, IReadOnlyList<CredentialPathField>? PathFields = null,
IReadOnlyList<string>? EndpointFields = null)
{
/// <summary>The path fields (never null).</summary>
public IReadOnlyList<CredentialPathField> PathFieldList => PathFields ?? [];
/// <summary>The endpoint fields (never null).</summary>
public IReadOnlyList<string> EndpointFieldList => EndpointFields ?? [];
}
/// <summary>The identity of one driver instance, as the cross-instance rule (lmxopcua#835) matches it.</summary>
@@ -57,7 +65,8 @@ public static class DriverCredentialPolicy
/// <summary>OpcUaClient <c>UserCertificatePath</c>: a relative path inside the node's user-certificate directory (#836).</summary>
public static readonly CredentialPathField OpcUaClientUserCertificatePathField = new(
"UserCertificatePath",
OpcUaClientUserCertificateDirectoryKey + ", default <LocalAppData>/OtOpcUa/pki/user-certificates");
OpcUaClientUserCertificateDirectoryKey + ", default <LocalAppData>/OtOpcUa/pki/user-certificates",
ActiveWhenKey: "AuthType", ActiveWhenValue: "Certificate", ActiveWhenOrdinal: 2);
/// <summary>Galaxy <c>Gateway.ApiKeySecretRef</c> (literal accepted for back-compat, with a warning at resolve).</summary>
public static readonly CredentialField GalaxyApiKeyField = new("ApiKeySecretRef", CredentialLiteralPolicy.Allowed);
@@ -73,13 +82,14 @@ public static class DriverCredentialPolicy
new("InspectPassword", CredentialLiteralPolicy.Refused),
new("DncPassword", CredentialLiteralPolicy.Refused),
new("DataPassword", CredentialLiteralPolicy.Refused),
]),
[DriverTypeNames.Galaxy] = new(DriverTypeNames.Galaxy, GalaxyScope, [GalaxyApiKeyField, GalaxyAckPasswordField]),
], 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]),
], [OpcUaClientUserCertificatePathField], ["EndpointUrl", "EndpointUrls", "DiscoveryUrl"]),
};
/// <summary>The rules for a driver type, if it resolves credential references.</summary>
@@ -187,6 +197,9 @@ public static class DriverCredentialPolicy
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);
}
}
@@ -290,6 +303,100 @@ public static class DriverCredentialPolicy
string? driverType, string? json, string? ownDriverInstanceId, IEnumerable<DriverInstanceIdentity> instances) =>
[.. DescribeProblems(driverType, json), .. DescribeOtherInstanceProblems(driverType, json, ownDriverInstanceId, instances)];
/// <summary>
/// True when the config carries at least one in-scope credential REFERENCE (<c>secret:</c> or <c>env:</c>) — the
/// Test Connect / browse audit trigger (#835 review I-1).
/// </summary>
/// <param name="driverType">The driver type.</param>
/// <param name="json">The config JSON.</param>
/// <returns>Whether a reference that would be resolved is present.</returns>
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;
}
/// <summary>
/// The endpoint values (see <see cref="DriverCredentialRules.EndpointFields"/>) 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.
/// </summary>
/// <param name="driverType">The driver type.</param>
/// <param name="json">The config JSON.</param>
/// <returns>The values, in document order.</returns>
public static IReadOnlyList<string> EndpointValues(string? driverType, string? json)
{
var values = new List<string>();
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;
}
/// <summary>
/// #835 review I-1: whether every endpoint value of <paramref name="submittedJson"/> (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).
/// </summary>
/// <param name="driverType">The driver type.</param>
/// <param name="submittedJson">The config about to be probed / browsed.</param>
/// <param name="storedJsons">The owner's stored DriverConfig + DeviceConfigs.</param>
/// <returns>Whether the submitted endpoints are all stored ones.</returns>
public static bool EndpointsMatchStored(string? driverType, string? submittedJson, IEnumerable<string?> storedJsons)
{
ArgumentNullException.ThrowIfNull(storedJsons);
if (!TryGet(driverType, out var rules) || rules.EndpointFieldList.Count == 0) return false;
var allowed = new HashSet<string>(storedJsons.SelectMany(s => EndpointValues(driverType, s)), StringComparer.OrdinalIgnoreCase);
return EndpointValues(driverType, submittedJson).All(allowed.Contains);
}
private static void CollectEndpoints(JsonElement element, DriverCredentialRules rules, List<string> 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<JsonElement> use)
{
JsonDocument doc;
try
{
doc = JsonDocument.Parse(json, new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true });
}
catch (JsonException)
{
return;
}
using (doc) use(doc.RootElement);
}
private static List<(string FieldPath, string Segment)> CollectSegments(string? driverType, string? json)
{
var found = new List<(string, string)>();