fix(grpc-data): A2b security review — outcome-unknown after dispatch, per-principal registry cap, audit category + sanitising, monotonic activation sequence, bounded Lock wait, consumer cancel = OutcomeUnknown
This commit is contained in:
@@ -21,6 +21,10 @@ public sealed class DataConnectionOptions
|
||||
public long MaxTransportBytes { get; set; } = 64 * 1024 * 1024;
|
||||
public long MaxPendingBytes { get; set; } = 1024 * 1024;
|
||||
public TimeSpan MaxSessionLifetime { get; set; } = TimeSpan.FromHours(1);
|
||||
/// <summary>A2b: remote condition-method operations the origin remembers at once for duplicate protection (all principals).</summary>
|
||||
public int MaxConditionMethodOperations { get; set; } = ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.LocalDataServices.DefaultConditionMethodMaxOperations;
|
||||
/// <summary>A2b security review: the same, per principal (≤ <see cref="MaxConditionMethodOperations"/>).</summary>
|
||||
public int MaxConditionMethodOperationsPerPrincipal { get; set; } = ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.LocalDataServices.DefaultConditionMethodMaxOperationsPerPrincipal;
|
||||
public ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.DataResourceLimits Hub { get; set; } = new();
|
||||
public TimeSpan UnaryTimeout { get; set; } = TimeSpan.FromSeconds(30);
|
||||
public TimeSpan StreamCommandTimeout { get; set; } = TimeSpan.FromSeconds(5);
|
||||
|
||||
@@ -36,6 +36,9 @@ public sealed class DataConnectionOptionsValidator(IHostEnvironment environment)
|
||||
|| options.Hub is null || options.BundleRefreshInterval < TimeSpan.FromMilliseconds(100)
|
||||
|| options.BundleRefreshInterval > TimeSpan.FromMinutes(1))
|
||||
errors.Add("Data-plane retained work and refresh limits are invalid.");
|
||||
if (options.MaxConditionMethodOperations is < 1 or > 65_536 || options.MaxConditionMethodOperationsPerPrincipal < 1
|
||||
|| options.MaxConditionMethodOperationsPerPrincipal > options.MaxConditionMethodOperations)
|
||||
errors.Add("Condition-method operation limits must be 1..65536, with the per-principal limit no larger than the total.");
|
||||
if (options.UnaryTimeout <= TimeSpan.Zero || options.UnaryTimeout > TimeSpan.FromMinutes(5)
|
||||
|| options.StreamCommandTimeout <= TimeSpan.Zero || options.StreamCommandTimeout > TimeSpan.FromMinutes(1))
|
||||
errors.Add("Unary and stream-command timeouts must be finite and within supported limits.");
|
||||
|
||||
@@ -39,6 +39,7 @@ public static class DataConnectionRegistration
|
||||
services.TryAddSingleton<TimeProvider>(TimeProvider.System);
|
||||
services.TryAddSingleton<DataWriteDispatchFence>();
|
||||
services.TryAddSingleton<DataConnectionWarmRoleView>();
|
||||
AddDataConnectionAuditLog(services);
|
||||
services.AddSingleton(sp =>
|
||||
{
|
||||
var role = sp.GetRequiredService<IClusterRoleInfo>();
|
||||
@@ -176,12 +177,15 @@ public static class DataConnectionRegistration
|
||||
sp.GetRequiredService<TimeProvider>(), sp.GetRequiredService<DataWriteRuntime>(), host,
|
||||
sp.GetRequiredService<SubscriptionAcquisitionCapacity>(), new(4096, options.Hub.MaxTrackedSources,
|
||||
options.MaxStreams, Math.Min(options.MaxStreams, options.MaxStreamsPerPrincipal), options.MaxTransportBytes,
|
||||
128, 64, options.MaxPendingBytes, options.MaxSessionLifetime, TimeSpan.FromSeconds(5)),
|
||||
128, 64, options.MaxPendingBytes, options.MaxSessionLifetime, TimeSpan.FromSeconds(5),
|
||||
options.MaxConditionMethodOperations, options.MaxConditionMethodOperationsPerPrincipal),
|
||||
// H2: remote history over the node manager's history port, resolved once the SDK server is up.
|
||||
new DeferredOriginHistoryPort(sp.GetRequiredService<DeferredAddressSpaceSink>()), LoggerFor<LocalDataServices>(sp),
|
||||
sp.GetRequiredService<DataConnectionHistoryDiagnostics>(),
|
||||
// A2: root-scoped condition items over the A1 hub and the node manager's snapshot port.
|
||||
sp.GetService<ConditionStateHub>(), new DeferredOriginConditionSource(sp.GetRequiredService<DeferredAddressSpaceSink>()));
|
||||
sp.GetService<ConditionStateHub>(), new DeferredOriginConditionSource(sp.GetRequiredService<DeferredAddressSpaceSink>()),
|
||||
// A2b security review: the audit trail on its OWN category from the host's logger factory.
|
||||
sp.GetRequiredService<IDataConnectionAuditLog>());
|
||||
});
|
||||
services.AddSingleton<IDataConnectionFactory>(sp => new DeferredFactory(() => sp.GetRequiredService<LocalDataRuntimeComposition>().Services));
|
||||
services.AddSingleton<DataConnectionSecretChangeHandler>();
|
||||
@@ -276,6 +280,15 @@ public static class DataConnectionRegistration
|
||||
Microsoft.Extensions.Logging.LoggerExtensions.LogInformation(logger, "{Reason}", keys.UnavailableReason);
|
||||
return keys;
|
||||
}
|
||||
/// <summary>
|
||||
/// A2b security review: registers the data-connection audit log — a logger of
|
||||
/// <see cref="LoggerDataConnectionAuditLog.Category"/> created from the host's REAL <c>ILoggerFactory</c> (no factory ⇒ no
|
||||
/// output), so operators can route the audit trail by category. A test or host may register its own first.
|
||||
/// </summary>
|
||||
internal static void AddDataConnectionAuditLog(IServiceCollection services) =>
|
||||
services.TryAddSingleton<IDataConnectionAuditLog>(sp =>
|
||||
LoggerDataConnectionAuditLog.Create(sp.GetService<Microsoft.Extensions.Logging.ILoggerFactory>()));
|
||||
|
||||
private static Microsoft.Extensions.Logging.ILogger LoggerFor<T>(IServiceProvider sp) =>
|
||||
(Microsoft.Extensions.Logging.ILogger?)sp.GetService<Microsoft.Extensions.Logging.ILoggerFactory>()?.CreateLogger<T>()
|
||||
?? Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance;
|
||||
|
||||
@@ -36,5 +36,11 @@ public sealed class DeferredOriginConditionSource(DeferredAddressSpaceSink defer
|
||||
/// <inheritdoc />
|
||||
public OriginConditionMethodOutcome TryExecuteConditionMethod(OriginConditionMethodCall call) =>
|
||||
deferred.GetCapability<IOriginConditionSource>() is { } inner ? inner.TryExecuteConditionMethod(call)
|
||||
: throw new InvalidOperationException("The OPC UA server is not running.");
|
||||
: throw new OriginConditionSourceUnavailableException();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A2b security review: the ONE exception a condition method port throws that proves nothing was dispatched — the OPC
|
||||
/// UA server (and so the node manager) is not running. Any other exception from the port means the outcome is unknown.
|
||||
/// </summary>
|
||||
public sealed class OriginConditionSourceUnavailableException() : InvalidOperationException("The OPC UA server is not running.");
|
||||
|
||||
@@ -52,47 +52,69 @@ public sealed partial class OtOpcUaNodeManager
|
||||
ArgumentNullException.ThrowIfNull(call);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(call.ConditionId);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(call.Principal);
|
||||
lock (Lock)
|
||||
// Security review: a remote caller never waits on Lock without bound (a long rebuild or a stalled holder would
|
||||
// otherwise pin one gRPC worker per call). Not acquired ⇒ refused before ANY state change.
|
||||
var lockTaken = false;
|
||||
try
|
||||
{
|
||||
var key = MapKey(call.Realm, call.ConditionId);
|
||||
if (!_alarmConditions.TryGetValue(key, out var alarm))
|
||||
return Refused(false, StatusCodes.BadNodeIdUnknown, "The condition is not materialised.");
|
||||
var native = _nativeAlarmNodeIds.Contains(key);
|
||||
|
||||
if (_standby.RefusesMutations)
|
||||
return RefusedBy(native, WarmStandbyState.StandbyRefusal($"call {call.Method}"));
|
||||
if (NativeAlarmAckPrimaryGate is { } primary && !primary())
|
||||
return Refused(native, StatusCodes.BadInvalidState, "This server is not the redundancy Primary.");
|
||||
|
||||
MethodState? method = call.Method switch
|
||||
{
|
||||
"Acknowledge" => alarm.Acknowledge,
|
||||
"AddComment" => alarm.AddComment,
|
||||
"Confirm" when !native => alarm.Confirm,
|
||||
_ => null,
|
||||
};
|
||||
if (method is null) return Refused(native, StatusCodes.BadNotSupported, "The condition does not support this method.");
|
||||
|
||||
// T3: the marker moves only on a new occurrence; an unchanged re-projection keeps the caller's EventIds valid.
|
||||
var current = _activation.TryGetValue(key, out var entry) ? entry.Sequence : 0UL;
|
||||
if (!string.Equals(call.ExpectedActivation.Incarnation, ConditionIncarnation, StringComparison.Ordinal)
|
||||
|| call.ExpectedActivation.Sequence != current)
|
||||
return Refused(native, StatusCodes.BadEventIdUnknown, "The condition has a newer occurrence.");
|
||||
|
||||
var identity = new RoleCarryingUserIdentity(new UserNameIdentityToken { UserName = call.Principal }, [],
|
||||
principal: call.Principal, apiKeyId: call.ApiKeyId);
|
||||
var context = new RemoteConditionMethodContext(Server, alarm, identity);
|
||||
var eventId = alarm.EventId?.Value ?? default;
|
||||
var comment = call.Comment is null ? default : new LocalizedText(call.Comment);
|
||||
var result = method switch
|
||||
{
|
||||
AddCommentMethodState { OnCall: { } onCall } m => onCall(context, m, alarm.NodeId, eventId, comment),
|
||||
_ => new ServiceResult(StatusCodes.BadNotSupported),
|
||||
};
|
||||
return ServiceResult.IsGood(result)
|
||||
? new OriginConditionMethodOutcome(true, native, StatusCodes.Good.Code, null)
|
||||
: RefusedBy(native, result);
|
||||
Monitor.TryEnter(Lock, ConditionMethodLockTimeout, ref lockTaken);
|
||||
if (!lockTaken)
|
||||
return Refused(false, StatusCodes.BadTimeout, "The node manager is busy; the condition method was not applied.");
|
||||
return TryExecuteConditionMethodLocked(call);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (lockTaken) Monitor.Exit(Lock);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// How long a remote condition method waits for the node manager's <c>Lock</c> before it is refused
|
||||
/// (<c>BadTimeout</c>, nothing applied). Default 5 s — the consumer's default <c>ConditionMethodTimeoutMilliseconds</c>,
|
||||
/// after which the caller has given up anyway.
|
||||
/// </summary>
|
||||
internal TimeSpan ConditionMethodLockTimeout { get; set; } = TimeSpan.FromSeconds(5);
|
||||
|
||||
private OriginConditionMethodOutcome TryExecuteConditionMethodLocked(OriginConditionMethodCall call)
|
||||
{
|
||||
var key = MapKey(call.Realm, call.ConditionId);
|
||||
if (!_alarmConditions.TryGetValue(key, out var alarm))
|
||||
return Refused(false, StatusCodes.BadNodeIdUnknown, "The condition is not materialised.");
|
||||
var native = _nativeAlarmNodeIds.Contains(key);
|
||||
|
||||
if (_standby.RefusesMutations)
|
||||
return RefusedBy(native, WarmStandbyState.StandbyRefusal($"call {call.Method}"));
|
||||
if (NativeAlarmAckPrimaryGate is { } primary && !primary())
|
||||
return Refused(native, StatusCodes.BadInvalidState, "This server is not the redundancy Primary.");
|
||||
|
||||
MethodState? method = call.Method switch
|
||||
{
|
||||
"Acknowledge" => alarm.Acknowledge,
|
||||
"AddComment" => alarm.AddComment,
|
||||
"Confirm" when !native => alarm.Confirm,
|
||||
_ => null,
|
||||
};
|
||||
if (method is null) return Refused(native, StatusCodes.BadNotSupported, "The condition does not support this method.");
|
||||
|
||||
// T3: the marker moves only on a new occurrence; an unchanged re-projection keeps the caller's EventIds valid.
|
||||
var current = _activation.TryGetValue(key, out var entry) ? entry.Sequence : 0UL;
|
||||
if (!string.Equals(call.ExpectedActivation.Incarnation, ConditionIncarnation, StringComparison.Ordinal)
|
||||
|| call.ExpectedActivation.Sequence != current)
|
||||
return Refused(native, StatusCodes.BadEventIdUnknown, "The condition has a newer occurrence.");
|
||||
|
||||
var identity = new RoleCarryingUserIdentity(new UserNameIdentityToken { UserName = call.Principal }, [],
|
||||
principal: call.Principal, apiKeyId: call.ApiKeyId);
|
||||
var context = new RemoteConditionMethodContext(Server, alarm, identity);
|
||||
var eventId = alarm.EventId?.Value ?? default;
|
||||
var comment = call.Comment is null ? default : new LocalizedText(call.Comment);
|
||||
var result = method switch
|
||||
{
|
||||
AddCommentMethodState { OnCall: { } onCall } m => onCall(context, m, alarm.NodeId, eventId, comment),
|
||||
_ => new ServiceResult(StatusCodes.BadNotSupported),
|
||||
};
|
||||
return ServiceResult.IsGood(result)
|
||||
? new OriginConditionMethodOutcome(true, native, StatusCodes.Good.Code, null)
|
||||
: RefusedBy(native, result);
|
||||
}
|
||||
|
||||
private static OriginConditionMethodOutcome RefusedBy(bool native, ServiceResult result) =>
|
||||
|
||||
@@ -24,6 +24,7 @@ public sealed partial class OtOpcUaNodeManager
|
||||
/// last compared against. Mutable, only touched under <c>Lock</c>.</summary>
|
||||
private sealed class ActivationEntry
|
||||
{
|
||||
/// <summary>Drawn from the node manager's <see cref="_activationSequenceSource"/>, never per condition object.</summary>
|
||||
public ulong Sequence;
|
||||
public bool Active;
|
||||
public bool Acked = true;
|
||||
@@ -33,6 +34,11 @@ public sealed partial class OtOpcUaNodeManager
|
||||
private IConditionStateSink? _conditionStateSink;
|
||||
private readonly HashSet<RealmKey> _conditionStateKnown = new();
|
||||
private readonly Dictionary<RealmKey, ActivationEntry> _activation = new();
|
||||
// A2b security review: ONE monotonic sequence for the node-manager lifetime (the lifetime of ConditionIncarnation).
|
||||
// Every fresh activation entry and every bump draws the next value, so a condition removed and re-created under the
|
||||
// same id never re-issues a marker its previous incarnation carried — a stale ack bound to the old condition can
|
||||
// never match the new one. Only touched under Lock.
|
||||
private ulong _activationSequenceSource;
|
||||
// Rebuild memory for SCRIPTED conditions (native ones ride NativeConditionCarryOver): their marker basis survives
|
||||
// the clear-and-re-materialise so the engine's re-assert of an unchanged active alarm is not a new occurrence.
|
||||
private readonly Dictionary<RealmKey, ActivationEntry> _rebuildScriptedActivation = new();
|
||||
@@ -222,7 +228,7 @@ public sealed partial class OtOpcUaNodeManager
|
||||
{
|
||||
_conditionStateKnown.Remove(key);
|
||||
_rebuildPendingRemoval.Remove(key);
|
||||
_activation[key] = !isNative && _rebuildScriptedActivation.Remove(key, out var kept) ? kept : new ActivationEntry();
|
||||
_activation[key] = !isNative && _rebuildScriptedActivation.Remove(key, out var kept) ? kept : NewActivationEntry();
|
||||
}
|
||||
|
||||
/// <summary>Under <c>Lock</c>, after registration and any carry-over restore: raise the condition's first record.</summary>
|
||||
@@ -329,15 +335,18 @@ public sealed partial class OtOpcUaNodeManager
|
||||
/// <summary>T3: bump on an Active false→true edge or ANY Acked true→false edge; never otherwise.</summary>
|
||||
private ActivationEntry AdvanceActivation(RealmKey key, AlarmConditionState condition)
|
||||
{
|
||||
if (!_activation.TryGetValue(key, out var e)) _activation[key] = e = new ActivationEntry();
|
||||
if (!_activation.TryGetValue(key, out var e)) _activation[key] = e = NewActivationEntry();
|
||||
var active = condition.ActiveState?.Id?.Value ?? false;
|
||||
var acked = condition.AckedState?.Id?.Value ?? true;
|
||||
if ((active && !e.Active) || (e.Acked && !acked)) e.Sequence++;
|
||||
if ((active && !e.Active) || (e.Acked && !acked)) e.Sequence = ++_activationSequenceSource;
|
||||
e.Active = active;
|
||||
e.Acked = acked;
|
||||
return e;
|
||||
}
|
||||
|
||||
/// <summary>Under <c>Lock</c>: a fresh entry whose marker no earlier condition (incl. one under the same id) carried.</summary>
|
||||
private ActivationEntry NewActivationEntry() => new() { Sequence = ++_activationSequenceSource };
|
||||
|
||||
private ConditionStateRecord BuildConditionRecord(
|
||||
RealmKey key, AlarmConditionState c, long version, bool removed, ActivationEntry? entry = null)
|
||||
{
|
||||
|
||||
+5
-2
@@ -85,8 +85,11 @@ public sealed partial class GrpcDataConnection : IDataConditionMethodService
|
||||
catch (Exception ex) when (ex is RpcException or HttpRequestException or OperationCanceledException or InvalidOperationException
|
||||
or ArgumentException or IOException)
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested && ex is OperationCanceledException) throw;
|
||||
return new(DataWriteState.OutcomeUnknown, BadCommunicationError, "OutcomeUnknown: the transport failed after the request was sent.");
|
||||
// Security review: a CALLER cancel after the request was handed to the transport is OutcomeUnknown too —
|
||||
// the origin may already have applied it, so it must never read as a clean failure (or be retried).
|
||||
return new(DataWriteState.OutcomeUnknown, BadCommunicationError, cancellationToken.IsCancellationRequested
|
||||
? "OutcomeUnknown: the call was cancelled after the request was sent."
|
||||
: "OutcomeUnknown: the transport failed after the request was sent.");
|
||||
}
|
||||
}
|
||||
return new(DataWriteState.RejectedBeforeDispatch, unsupported ? BadNotSupportedMethod : BadNoCommunication,
|
||||
|
||||
+11
-2
@@ -5,9 +5,13 @@ using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
|
||||
namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
|
||||
|
||||
/// <summary>Bounds shared physical demand and downstream subscription resources for one process.</summary>
|
||||
/// <param name="MaxConditionMethodOperations">A2b: condition-method operations the origin remembers at once (all principals).</param>
|
||||
/// <param name="MaxConditionMethodOperationsPerPrincipal">A2b security review: the same, per principal.</param>
|
||||
public sealed record LocalDataRuntimeLimits(int MaxDrivers, int MaxInterests, int MaxOperations,
|
||||
int MaxOperationsPerPrincipal, long MaxTransportBytes, int MaxCommands, int MaxPendingFrames,
|
||||
long MaxPendingBytes, TimeSpan MaxSessionLifetime, TimeSpan DriverAskTimeout);
|
||||
long MaxPendingBytes, TimeSpan MaxSessionLifetime, TimeSpan DriverAskTimeout,
|
||||
int MaxConditionMethodOperations = LocalDataServices.DefaultConditionMethodMaxOperations,
|
||||
int MaxConditionMethodOperationsPerPrincipal = LocalDataServices.DefaultConditionMethodMaxOperationsPerPrincipal);
|
||||
|
||||
/// <summary>Owns the local caller-bound services and the one shared physical-demand bridge.</summary>
|
||||
public sealed class LocalDataRuntimeComposition : IDisposable
|
||||
@@ -20,7 +24,8 @@ public sealed class LocalDataRuntimeComposition : IDisposable
|
||||
IActorRef host, SubscriptionAcquisitionCapacity acquisitionCapacity, LocalDataRuntimeLimits limits,
|
||||
ZB.MOM.WW.OtOpcUa.OpcUaServer.IOriginHistoryPort? history = null, Microsoft.Extensions.Logging.ILogger? logger = null,
|
||||
DataConnectionHistoryDiagnostics? historyDiagnostics = null,
|
||||
ConditionStateHub? conditionHub = null, ZB.MOM.WW.OtOpcUa.OpcUaServer.IOriginConditionSource? conditionSource = null)
|
||||
ConditionStateHub? conditionHub = null, ZB.MOM.WW.OtOpcUa.OpcUaServer.IOriginConditionSource? conditionSource = null,
|
||||
IDataConnectionAuditLog? audit = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(catalog); ArgumentNullException.ThrowIfNull(hub);
|
||||
ArgumentNullException.ThrowIfNull(policy); ArgumentNullException.ThrowIfNull(capabilities);
|
||||
@@ -44,6 +49,10 @@ public sealed class LocalDataRuntimeComposition : IDisposable
|
||||
Logger = logger ?? Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance, HistoryDiagnostics = historyDiagnostics,
|
||||
// A2: condition streams over the A1 hub and the node manager's snapshot port; keys from the coordinator.
|
||||
ConditionHub = conditionHub, ConditionSource = conditionSource, ConditionKeysSource = () => catalog.ConditionKeys,
|
||||
// A2b security review: the audit trail on its own logger category (the Host passes it), never the services' logger.
|
||||
Audit = audit ?? new LoggerDataConnectionAuditLog(logger ?? Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance),
|
||||
ConditionMethodMaxOperations = limits.MaxConditionMethodOperations,
|
||||
ConditionMethodMaxOperationsPerPrincipal = limits.MaxConditionMethodOperationsPerPrincipal,
|
||||
};
|
||||
Services = services;
|
||||
}
|
||||
|
||||
+186
-55
@@ -24,19 +24,34 @@ public interface IDataConnectionAuditLog
|
||||
void RecordConditionMethod(DataConditionMethodAuditEntry entry);
|
||||
}
|
||||
|
||||
/// <summary>The default audit log: structured entries on a dedicated logger category.</summary>
|
||||
/// <summary>
|
||||
/// The default audit log: structured entries on the dedicated <see cref="Category"/> logger, so operators can route the
|
||||
/// audit trail to its own sink. Every caller-supplied string is passed through
|
||||
/// <see cref="LocalDataServices.SanitizeAuditText(string?, int)"/> again here (defence in depth: an
|
||||
/// <see cref="IDataConnectionAuditLog"/> entry built elsewhere cannot inject CR/LF or control characters into log text).
|
||||
/// </summary>
|
||||
public sealed class LoggerDataConnectionAuditLog(ILogger logger) : IDataConnectionAuditLog
|
||||
{
|
||||
/// <summary>The logger category operators route to the audit sink.</summary>
|
||||
public const string Category = "ZB.MOM.WW.OtOpcUa.DataConnections.Audit";
|
||||
|
||||
/// <summary>The audit log over a logger of <see cref="Category"/> from <paramref name="factory"/> (null ⇒ no output).</summary>
|
||||
/// <param name="factory">The host's logger factory.</param>
|
||||
/// <returns>The audit log.</returns>
|
||||
public static LoggerDataConnectionAuditLog Create(ILoggerFactory? factory) =>
|
||||
new((ILogger?)factory?.CreateLogger(Category) ?? Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance);
|
||||
|
||||
/// <inheritdoc />
|
||||
public void RecordConditionMethod(DataConditionMethodAuditEntry entry) =>
|
||||
public void RecordConditionMethod(DataConditionMethodAuditEntry entry)
|
||||
{
|
||||
static string Clean(string? text) => LocalDataServices.SanitizeAuditText(text, LocalDataServices.MaxAuditFieldLength) ?? "-";
|
||||
var address = entry.Placement.Address;
|
||||
logger.LogInformation(
|
||||
"Data-connection condition method {Method} by {Principal} (key {ApiKeyId}) on {PlacementRealm}:{PlacementNamespace}:{Placement} op {OperationId}: {State} 0x{StatusCode:X8}{Joined}; on behalf of {OnBehalfOf}",
|
||||
entry.Method, entry.Principal, entry.ApiKeyId ?? "-", entry.Placement.Realm, entry.Placement.Address.NamespaceUri,
|
||||
entry.Placement.Address.Identifier, entry.OperationId, entry.State, entry.StatusCode, entry.Joined ? " (joined)" : "",
|
||||
entry.OnBehalfOf ?? "-");
|
||||
entry.Method, Clean(entry.Principal), Clean(entry.ApiKeyId), entry.Placement.Realm, Clean(address.NamespaceUri),
|
||||
Clean(address.Identifier), Clean(entry.OperationId), entry.State, entry.StatusCode, entry.Joined ? " (joined)" : "",
|
||||
Clean(entry.OnBehalfOf));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A2b: the origin side of <c>CallConditionMethod</c> (plan §5.6 "Origin", §6).</summary>
|
||||
@@ -46,27 +61,50 @@ public sealed partial class LocalDataServices
|
||||
BadTimeout = 0x800A0000u, BadUserAccessDenied = 0x801F0000u, BadNodeIdUnknown = 0x80340000u,
|
||||
BadInvalidArgument = 0x80AB0000u;
|
||||
|
||||
/// <summary>The most characters of one caller-supplied audit field other than <c>on_behalf_of</c>.</summary>
|
||||
public const int MaxAuditFieldLength = 512;
|
||||
|
||||
/// <summary>Default <see cref="ConditionMethodMaxOperations"/>.</summary>
|
||||
public const int DefaultConditionMethodMaxOperations = 4096;
|
||||
|
||||
/// <summary>Default <see cref="ConditionMethodMaxOperationsPerPrincipal"/>.</summary>
|
||||
public const int DefaultConditionMethodMaxOperationsPerPrincipal = 256;
|
||||
|
||||
private readonly object _methodRegistryGate = new();
|
||||
private WriteOperationRegistry? _methodRegistry;
|
||||
private IDataConnectionAuditLog? _audit;
|
||||
|
||||
/// <summary>A2b: the data-connection audit log (default: <see cref="LoggerDataConnectionAuditLog"/> over <see cref="Logger"/>).</summary>
|
||||
/// <summary>
|
||||
/// A2b: the data-connection audit log. The Host passes <see cref="LoggerDataConnectionAuditLog.Create"/> over its
|
||||
/// logger factory (the dedicated audit category); the fallback writes to <see cref="Logger"/>.
|
||||
/// </summary>
|
||||
public IDataConnectionAuditLog Audit { get => _audit ??= new LoggerDataConnectionAuditLog(Logger); init => _audit = value; }
|
||||
|
||||
/// <summary>A2b: how long a completed operation id is remembered (a duplicate within it joins the stored outcome).</summary>
|
||||
public TimeSpan ConditionMethodRetention { get; init; } = TimeSpan.FromMinutes(5);
|
||||
|
||||
/// <summary>A2b: the most condition-method operations the origin remembers at once (all principals).</summary>
|
||||
public int ConditionMethodMaxOperations { get; init; } = DefaultConditionMethodMaxOperations;
|
||||
|
||||
/// <summary>
|
||||
/// A2b security review: the most condition-method operations ONE principal may hold in the registry at once, so a
|
||||
/// single peer cannot exhaust <see cref="ConditionMethodMaxOperations"/> for every other peer. Refusals before
|
||||
/// dispatch hold no entry.
|
||||
/// </summary>
|
||||
public int ConditionMethodMaxOperationsPerPrincipal { get; init; } = DefaultConditionMethodMaxOperationsPerPrincipal;
|
||||
|
||||
/// <summary>Whether this origin serves remote condition methods: the condition port is up (same as streaming).</summary>
|
||||
internal bool ConditionMethodsServable => ConditionsServable;
|
||||
|
||||
/// <summary>The duplicate-protection registry of the current serving incarnation (a new incarnation starts empty).</summary>
|
||||
private WriteOperationRegistry MethodRegistry(string incarnation)
|
||||
internal WriteOperationRegistry MethodRegistry(string incarnation)
|
||||
{
|
||||
lock (_methodRegistryGate)
|
||||
{
|
||||
if (_methodRegistry is null || _methodRegistryIncarnation != incarnation)
|
||||
{
|
||||
_methodRegistry = new WriteOperationRegistry(incarnation, 4096, 8L * 1024 * 1024, ConditionMethodRetention, Clock);
|
||||
_methodRegistry = new WriteOperationRegistry(incarnation, ConditionMethodMaxOperations, 8L * 1024 * 1024,
|
||||
ConditionMethodRetention, Clock, ConditionMethodMaxOperationsPerPrincipal);
|
||||
_methodRegistryIncarnation = incarnation;
|
||||
}
|
||||
return _methodRegistry;
|
||||
@@ -81,8 +119,18 @@ public sealed partial class LocalDataServices
|
||||
/// (else <c>BadNodeIdUnknown</c> — existence is not disclosed); the origin ACL on the placement's subject
|
||||
/// (<c>BadUserAccessDenied</c>); native Confirm (<c>BadNotSupported</c>); the Galaxy service-ack opt-in
|
||||
/// (<c>BadUserAccessDenied</c>); then the operation registry (a duplicate id joins) and the node manager (Warm
|
||||
/// Standby, Primary, activation marker, native preflight). Never retried.
|
||||
/// Standby, Primary, activation marker, native preflight). Never retried. Every call is audited, whatever its end.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <b>Time of check vs time of use (security review, documented).</b> Authorization (export grant, origin ACL,
|
||||
/// Galaxy opt-in, caller usability) is decided here against the catalog/authority captured at the start of the call,
|
||||
/// and the node manager applies the method afterwards under its own <c>Lock</c>. A deploy, key revocation or ACL change
|
||||
/// that lands between the two is not re-checked: the window is one synchronous hop (no I/O, no await between the ACL
|
||||
/// check and the dispatch other than the registry claim), the same bound a local OPC UA client's call has (its role
|
||||
/// is read before the SDK applies), and a revocation stops every later call. Serving-identity changes ARE caught at
|
||||
/// apply time — the node manager re-checks Primary and Warm Standby under <c>Lock</c>, and the activation marker
|
||||
/// refuses a condition re-created by a rebuild.
|
||||
/// </remarks>
|
||||
internal async Task<DataConditionMethodResult> CallConditionMethodAsync(DataAuthenticatedContext context, DataTarget target,
|
||||
DataConditionMethodRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
@@ -90,20 +138,36 @@ public sealed partial class LocalDataServices
|
||||
request.Validate();
|
||||
target.Validate();
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var onBehalfOf = SanitizeAuditText(request.OnBehalfOf);
|
||||
var catalog = _catalog();
|
||||
var serving = catalog?.Serving;
|
||||
var (result, joined) = await DecideAsync().ConfigureAwait(false);
|
||||
result = result with { Serving = serving };
|
||||
Audit.RecordConditionMethod(new(Clock.GetUtcNow(), context.PrincipalId, context.ApiKeyId, request.Placement, request.OperationId,
|
||||
request.Method, result.State, result.StatusCode, joined, onBehalfOf));
|
||||
OtOpcUaTelemetry.DataConnConditionMethods.Add(1, new KeyValuePair<string, object?>("method", request.Method.ToString()),
|
||||
new KeyValuePair<string, object?>("outcome", result.State.ToString()));
|
||||
return result;
|
||||
DataConditionMethodResult? result = null;
|
||||
var joined = false;
|
||||
try
|
||||
{
|
||||
(result, joined) = await DecideAsync().ConfigureAwait(false);
|
||||
result = result with { Serving = serving };
|
||||
return result;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Security review: ALWAYS audited — a decided outcome, or (an exception escaped) OutcomeUnknown.
|
||||
var state = result?.State ?? DataWriteState.OutcomeUnknown;
|
||||
var status = result?.StatusCode ?? BadInternalError;
|
||||
try
|
||||
{
|
||||
Audit.RecordConditionMethod(AuditEntry(context, request, state, status, joined));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.LogError(ex, "The data-connection audit log failed to record a condition method call");
|
||||
}
|
||||
OtOpcUaTelemetry.DataConnConditionMethods.Add(1, new KeyValuePair<string, object?>("method", request.Method.ToString()),
|
||||
new KeyValuePair<string, object?>("outcome", state.ToString()));
|
||||
}
|
||||
|
||||
async Task<(DataConditionMethodResult, bool)> DecideAsync()
|
||||
{
|
||||
if (!ConditionMethodsServable) return (Reject(BadNotSupported, "Condition methods are not served."), false);
|
||||
if (!ConditionMethodsServable || ConditionSource is null) return (Reject(BadNotSupported, "Condition methods are not served."), false);
|
||||
if (catalog is null || !Ready(catalog) || context.AuthorityEpoch != catalog.AuthorityEpoch || !RoleAllows(target, catalog.Serving))
|
||||
return (Reject(BadNoCommunication, "Condition methods unavailable."), false);
|
||||
// §5.6: remote condition methods are Primary-only for both kinds (the capability bits are stripped off-Primary too).
|
||||
@@ -121,13 +185,15 @@ public sealed partial class LocalDataServices
|
||||
var acl = operation == DataOperations.AlarmConfirm ? OpcUaOperation.AlarmConfirm : OpcUaOperation.AlarmAcknowledge;
|
||||
if (!_policy.AuthorizeLocal(Caller(context), acl, placement.Scope))
|
||||
return (Reject(BadUserAccessDenied, "Denied by the origin ACL."), false);
|
||||
if (placement.SourceKind == ConditionSourceKind.Native && (request.Method & DataConditionMethodSets.Native) == 0)
|
||||
var native = placement.SourceKind == ConditionSourceKind.Native;
|
||||
if (native && (request.Method & DataConditionMethodSets.Native) == 0)
|
||||
return (Reject(BadNotSupported, "A native condition supports Acknowledge and AddComment only."), false);
|
||||
if (placement.IsGalaxy && !catalog.AllowsGalaxyServiceAck(context.PrincipalId, placement))
|
||||
return (Reject(BadUserAccessDenied, "Galaxy service acknowledge is not enabled on this export."), false);
|
||||
|
||||
var claim = MethodRegistry(catalog.Serving.Incarnation).Claim(context.PrincipalId, request.OperationId,
|
||||
request.ExpectedServingIncarnation, SemanticHash(request));
|
||||
// Everything above refused without touching the registry, so a refusal holds no capacity.
|
||||
var registry = MethodRegistry(catalog.Serving.Incarnation);
|
||||
var claim = registry.Claim(context.PrincipalId, request.OperationId, request.ExpectedServingIncarnation, SemanticHash(request));
|
||||
switch (claim.Kind)
|
||||
{
|
||||
case WriteClaimKind.Stale: return (Reject(BadInvalidState, "Serving incarnation changed."), false);
|
||||
@@ -143,33 +209,91 @@ public sealed partial class LocalDataServices
|
||||
}
|
||||
|
||||
var owner = claim.Claim!;
|
||||
OriginConditionMethodOutcome verdict;
|
||||
DataWriteOutcome? outcome = null;
|
||||
try
|
||||
{
|
||||
verdict = ConditionSource!.TryExecuteConditionMethod(new(placement.Condition.Realm, placement.Condition.ConditionId,
|
||||
DataConditionMethodSets.Part9Name(request.Method), request.Comment,
|
||||
new ConditionActivationMarker(request.ExpectedActivation.Incarnation, request.ExpectedActivation.Sequence),
|
||||
context.PrincipalId, context.ApiKeyId));
|
||||
outcome = Dispatch();
|
||||
return (FromOutcome(outcome), false);
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
finally
|
||||
{
|
||||
verdict = new(false, placement.SourceKind == ConditionSourceKind.Native, BadNoCommunication, ex.Message);
|
||||
// Security review: the claim is ALWAYS finished. An exception that escaped after the node manager may have
|
||||
// applied the call is OutcomeUnknown (joiners get the same); a refusal releases its entry at once.
|
||||
if (outcome is null)
|
||||
{
|
||||
owner.TryMarkDispatched();
|
||||
outcome = new(DataWriteState.OutcomeUnknown, BadInternalError, "OutcomeUnknown: the origin failed while applying the call.");
|
||||
owner.Complete(outcome);
|
||||
}
|
||||
owner.PhysicalFinished();
|
||||
if (outcome.State == DataWriteState.RejectedBeforeDispatch)
|
||||
registry.ReleaseUndispatched(context.PrincipalId, request.OperationId, owner);
|
||||
}
|
||||
DataWriteOutcome outcome;
|
||||
if (verdict.Applied)
|
||||
|
||||
DataWriteOutcome Dispatch()
|
||||
{
|
||||
owner.TryMarkDispatched();
|
||||
outcome = verdict.Native
|
||||
? new(DataWriteState.AcceptedUnconfirmed, verdict.StatusCode, "AcceptedUnconfirmed: routed to the driver; its confirmation or revert arrives on the condition stream.")
|
||||
: new(DataWriteState.DriverConfirmedSuccess, verdict.StatusCode, null);
|
||||
OriginConditionMethodOutcome verdict;
|
||||
try
|
||||
{
|
||||
verdict = ConditionSource.TryExecuteConditionMethod(new(placement.Condition.Realm, placement.Condition.ConditionId,
|
||||
DataConditionMethodSets.Part9Name(request.Method), request.Comment,
|
||||
new ConditionActivationMarker(request.ExpectedActivation.Incarnation, request.ExpectedActivation.Sequence),
|
||||
context.PrincipalId, context.ApiKeyId));
|
||||
}
|
||||
catch (OriginConditionSourceUnavailableException ex)
|
||||
{
|
||||
// The ONE exception that proves nothing was dispatched: the node manager is not running.
|
||||
verdict = new(false, native, BadNoCommunication, ex.Message);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
// Anything else may have been thrown after the node manager applied the call: the outcome is unknown.
|
||||
Logger.LogWarning(ex, "A remote condition method failed inside the node manager; answering OutcomeUnknown");
|
||||
owner.TryMarkDispatched();
|
||||
var unknown = new DataWriteOutcome(DataWriteState.OutcomeUnknown, BadInternalError,
|
||||
"OutcomeUnknown: the origin failed while applying the call.");
|
||||
owner.Complete(unknown);
|
||||
return unknown;
|
||||
}
|
||||
DataWriteOutcome decided;
|
||||
if (verdict.Applied)
|
||||
{
|
||||
owner.TryMarkDispatched();
|
||||
decided = !verdict.Native
|
||||
? new(DataWriteState.DriverConfirmedSuccess, verdict.StatusCode, null)
|
||||
: request.Method == DataConditionMethods.Acknowledge
|
||||
? new(DataWriteState.AcceptedUnconfirmed, verdict.StatusCode,
|
||||
"AcceptedUnconfirmed: routed to the driver; its confirmation or revert arrives on the condition stream.")
|
||||
: new(DataWriteState.AcceptedUnconfirmed, verdict.StatusCode,
|
||||
"AcceptedUnconfirmed: the comment was applied at the origin (not sent to the driver); it arrives on the condition stream.");
|
||||
}
|
||||
else decided = new(DataWriteState.RejectedBeforeDispatch, verdict.StatusCode, verdict.Diagnostic);
|
||||
owner.Complete(decided);
|
||||
return decided;
|
||||
}
|
||||
else outcome = new(DataWriteState.RejectedBeforeDispatch, verdict.StatusCode, verdict.Diagnostic);
|
||||
owner.Complete(outcome);
|
||||
owner.PhysicalFinished();
|
||||
return (FromOutcome(outcome), false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The audit entry with every caller-supplied string sanitised (security review: log injection).</summary>
|
||||
private DataConditionMethodAuditEntry AuditEntry(DataAuthenticatedContext context, DataConditionMethodRequest request,
|
||||
DataWriteState state, uint status, bool joined)
|
||||
{
|
||||
static string Field(string text) => SanitizeAuditText(text, MaxAuditFieldLength) ?? string.Empty;
|
||||
var p = request.Placement;
|
||||
var a = p.Address;
|
||||
var placement = p with
|
||||
{
|
||||
Address = a with
|
||||
{
|
||||
OriginClusterId = Field(a.OriginClusterId), NamespaceUri = Field(a.NamespaceUri),
|
||||
IdentifierKind = Field(a.IdentifierKind), Identifier = Field(a.Identifier),
|
||||
},
|
||||
MappingId = p.MappingId is null ? null : Field(p.MappingId), Subject = Field(p.Subject),
|
||||
};
|
||||
return new(Clock.GetUtcNow(), Field(context.PrincipalId), context.ApiKeyId is null ? null : Field(context.ApiKeyId), placement,
|
||||
Field(request.OperationId), request.Method, state, status, joined, SanitizeAuditText(request.OnBehalfOf));
|
||||
}
|
||||
|
||||
private static DataConditionMethodResult Reject(uint status, string diagnostic) =>
|
||||
new(DataWriteState.RejectedBeforeDispatch, status, diagnostic);
|
||||
|
||||
@@ -187,37 +311,44 @@ public sealed partial class LocalDataServices
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// §6: the peer's <c>on_behalf_of</c> as the audit log may record it — control (Cc), format (Cf), line/paragraph
|
||||
/// separator and unpaired surrogate characters removed, then capped at
|
||||
/// <see cref="DataConditionMethodRequest.MaxOnBehalfOfLength"/> characters without splitting a surrogate pair.
|
||||
/// Null/empty-after-sanitising ⇒ null.
|
||||
/// §6: the peer's <c>on_behalf_of</c> as the audit log may record it — see <see cref="SanitizeAuditText(string?, int)"/>,
|
||||
/// capped at <see cref="DataConditionMethodRequest.MaxOnBehalfOfLength"/> characters.
|
||||
/// </summary>
|
||||
public static string? SanitizeAuditText(string? text)
|
||||
public static string? SanitizeAuditText(string? text) => SanitizeAuditText(text, DataConditionMethodRequest.MaxOnBehalfOfLength);
|
||||
|
||||
/// <summary>
|
||||
/// Caller-supplied text as the audit log may record it: control (Cc), format (Cf), private-use (Co), unassigned (Cn),
|
||||
/// line/paragraph separator and unpaired surrogate characters removed (in BMP and supplementary planes alike), then
|
||||
/// capped at <paramref name="maxLength"/> UTF-16 units without splitting a surrogate pair — the result is always
|
||||
/// well-formed UTF-16. Null/empty-after-sanitising ⇒ null.
|
||||
/// </summary>
|
||||
/// <param name="text">The untrusted text.</param>
|
||||
/// <param name="maxLength">The most UTF-16 units kept.</param>
|
||||
/// <returns>The sanitised text, or null.</returns>
|
||||
public static string? SanitizeAuditText(string? text, int maxLength)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text)) return null;
|
||||
var builder = new StringBuilder(Math.Min(text.Length, DataConditionMethodRequest.MaxOnBehalfOfLength));
|
||||
for (var i = 0; i < text.Length && builder.Length < DataConditionMethodRequest.MaxOnBehalfOfLength; i++)
|
||||
if (string.IsNullOrEmpty(text) || maxLength <= 0) return null;
|
||||
var builder = new StringBuilder(Math.Min(text.Length, maxLength));
|
||||
for (var i = 0; i < text.Length && builder.Length < maxLength; i++)
|
||||
{
|
||||
var c = text[i];
|
||||
if (char.IsHighSurrogate(c))
|
||||
{
|
||||
if (i + 1 < text.Length && char.IsLowSurrogate(text[i + 1]))
|
||||
{
|
||||
var category = CharUnicodeInfo.GetUnicodeCategory(text, i);
|
||||
if (category != UnicodeCategory.Format && builder.Length + 2 <= DataConditionMethodRequest.MaxOnBehalfOfLength)
|
||||
if (!Dropped(CharUnicodeInfo.GetUnicodeCategory(text, i)) && builder.Length + 2 <= maxLength)
|
||||
builder.Append(c).Append(text[i + 1]);
|
||||
i++;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (char.IsLowSurrogate(c)) continue;
|
||||
switch (CharUnicodeInfo.GetUnicodeCategory(c))
|
||||
{
|
||||
case UnicodeCategory.Control or UnicodeCategory.Format or UnicodeCategory.LineSeparator
|
||||
or UnicodeCategory.ParagraphSeparator or UnicodeCategory.OtherNotAssigned: continue;
|
||||
default: builder.Append(c); break;
|
||||
}
|
||||
if (char.IsLowSurrogate(c) || Dropped(CharUnicodeInfo.GetUnicodeCategory(c))) continue;
|
||||
builder.Append(c);
|
||||
}
|
||||
return builder.Length == 0 ? null : builder.ToString();
|
||||
|
||||
static bool Dropped(UnicodeCategory category) => category is UnicodeCategory.Control or UnicodeCategory.Format
|
||||
or UnicodeCategory.LineSeparator or UnicodeCategory.ParagraphSeparator or UnicodeCategory.OtherNotAssigned
|
||||
or UnicodeCategory.PrivateUse or UnicodeCategory.Surrogate;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,21 +11,31 @@ public sealed class WriteOperationRegistry
|
||||
{
|
||||
private readonly object _gate = new();
|
||||
private readonly Dictionary<(string Principal, string Operation), Entry> _entries = new(new KeyComparer());
|
||||
// Retained entries per principal (case-insensitive like the key), so one principal cannot exhaust the global table.
|
||||
private readonly Dictionary<string, int> _perPrincipal = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly string _incarnation;
|
||||
private readonly int _maxEntries;
|
||||
private readonly int _maxEntriesPerPrincipal;
|
||||
private readonly long _maxBytes;
|
||||
private readonly TimeSpan _retention;
|
||||
private readonly TimeProvider _clock;
|
||||
private long _retainedBytes;
|
||||
|
||||
/// <param name="maxEntriesPerPrincipal">
|
||||
/// A2b security review: the most entries one principal may hold at once (null ⇒ <paramref name="maxEntries"/>, i.e.
|
||||
/// only the global cap). Past it that principal's claims answer <see cref="WriteClaimKind.Capacity"/> while other
|
||||
/// principals are still admitted.
|
||||
/// </param>
|
||||
public WriteOperationRegistry(string servingIncarnation, int maxEntries, long maxRetainedBytes,
|
||||
TimeSpan retention, TimeProvider? clock = null)
|
||||
TimeSpan retention, TimeProvider? clock = null, int? maxEntriesPerPrincipal = null)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(servingIncarnation);
|
||||
if (maxEntries <= 0 || maxRetainedBytes <= 0 || retention <= TimeSpan.Zero)
|
||||
throw new ArgumentOutOfRangeException(nameof(maxEntries));
|
||||
if (maxEntriesPerPrincipal is <= 0) throw new ArgumentOutOfRangeException(nameof(maxEntriesPerPrincipal));
|
||||
_incarnation = servingIncarnation;
|
||||
_maxEntries = maxEntries;
|
||||
_maxEntriesPerPrincipal = Math.Min(maxEntriesPerPrincipal ?? maxEntries, maxEntries);
|
||||
_maxBytes = maxRetainedBytes;
|
||||
_retention = retention;
|
||||
_clock = clock ?? TimeProvider.System;
|
||||
@@ -47,23 +57,57 @@ public sealed class WriteOperationRegistry
|
||||
if (_entries.TryGetValue(key, out var existing))
|
||||
return existing.Hash.AsSpan().SequenceEqual(semanticHash.Span)
|
||||
? new(WriteClaimKind.Existing, existing.Claim) : new(WriteClaimKind.Conflict);
|
||||
if (_entries.Count >= _maxEntries || bytes > _maxBytes - _retainedBytes)
|
||||
_perPrincipal.TryGetValue(principal, out var held);
|
||||
if (_entries.Count >= _maxEntries || held >= _maxEntriesPerPrincipal || bytes > _maxBytes - _retainedBytes)
|
||||
return new(WriteClaimKind.Capacity);
|
||||
var claim = new WriteClaim(_clock);
|
||||
_entries.Add(key, new Entry(semanticHash.ToArray(), claim, bytes));
|
||||
_perPrincipal[principal] = held + 1;
|
||||
_retainedBytes += bytes;
|
||||
return new(WriteClaimKind.Owner, claim);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A2b security review: forgets an entry whose operation was refused BEFORE dispatch (nothing applied), so a refusal
|
||||
/// retains no capacity. Only removes <paramref name="claim"/> itself, and only once it has completed undispatched;
|
||||
/// a joiner already waiting on it still receives its outcome. A later call with the same id is a fresh owner.
|
||||
/// </summary>
|
||||
/// <returns>True when the entry was removed.</returns>
|
||||
public bool ReleaseUndispatched(string principal, string operationId, WriteClaim claim)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(claim);
|
||||
if (!claim.IsCompletedUndispatched) return false;
|
||||
lock (_gate)
|
||||
{
|
||||
var key = (principal, operationId);
|
||||
if (!_entries.TryGetValue(key, out var entry) || !ReferenceEquals(entry.Claim, claim)) return false;
|
||||
Remove(key, entry);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Test seam: the entries currently retained (all principals).</summary>
|
||||
internal int CountForTests { get { lock (_gate) return _entries.Count; } }
|
||||
|
||||
private void Remove((string Principal, string Operation) key, Entry entry)
|
||||
{
|
||||
_entries.Remove(key);
|
||||
_retainedBytes -= entry.Bytes;
|
||||
if (_perPrincipal.TryGetValue(key.Principal, out var held))
|
||||
{
|
||||
if (held <= 1) _perPrincipal.Remove(key.Principal);
|
||||
else _perPrincipal[key.Principal] = held - 1;
|
||||
}
|
||||
}
|
||||
|
||||
private void Prune()
|
||||
{
|
||||
var now = _clock.GetTimestamp();
|
||||
foreach (var pair in _entries.ToArray())
|
||||
{
|
||||
if (!pair.Value.Claim.CanRetire(now, _retention)) continue;
|
||||
_entries.Remove(pair.Key);
|
||||
_retainedBytes -= pair.Value.Bytes;
|
||||
Remove(pair.Key, pair.Value);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,6 +140,8 @@ public sealed class WriteClaim
|
||||
public Task<DataWriteOutcome> Completion => _completion.Task;
|
||||
public bool IsDispatched => Volatile.Read(ref _state) is 1 or 3 or 5;
|
||||
public DataWriteOutcome? CurrentOutcome => Volatile.Read(ref _outcome);
|
||||
/// <summary>Completed as rejected before dispatch (state 4): nothing was applied.</summary>
|
||||
public bool IsCompletedUndispatched => Volatile.Read(ref _state) == 4;
|
||||
|
||||
public bool TryMarkDispatched() => Interlocked.CompareExchange(ref _state, 1, 0) == 0;
|
||||
|
||||
|
||||
+47
@@ -19,6 +19,7 @@ using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.FileProviders;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
|
||||
@@ -273,6 +274,52 @@ public sealed class GrpcDataRuntimeRegistrationTests
|
||||
lease.Dispose();
|
||||
}
|
||||
|
||||
[Fact, Trait("Phase", "A2")]
|
||||
public async Task The_registered_audit_log_writes_on_its_own_category_from_the_real_logger_factory()
|
||||
{
|
||||
// A2b security review: the audit log is the DI-registered one (category ZB.MOM.WW.OtOpcUa.DataConnections.Audit
|
||||
// from the host's ILoggerFactory) and the live LocalDataServices records through IT — never a NullLogger fallback.
|
||||
var system = ActorSystem.Create("grpc-audit-" + Guid.NewGuid().ToString("N"));
|
||||
try
|
||||
{
|
||||
var registry = new ActorRegistry();
|
||||
var capture = new CapturingLoggerProvider();
|
||||
var services = RegisteredOriginServices(registry);
|
||||
services.AddLogging(logging => logging.AddProvider(capture));
|
||||
await using var provider = services.BuildServiceProvider();
|
||||
registry.Register<DriverHostActorKey>(system.ActorOf(Props.Create(() => new LocalActor())));
|
||||
|
||||
var audit = provider.GetRequiredService<IDataConnectionAuditLog>();
|
||||
provider.GetRequiredService<LocalDataRuntimeComposition>().Services.Audit.ShouldBeSameAs(audit);
|
||||
var placement = new DataView(new("cluster", "https://zb.com/otopcua/raw", "string", "Plant/x\r\nforged"), DataRealm.Raw, null, 0, "Plant/x");
|
||||
audit.RecordConditionMethod(new(DateTimeOffset.UtcNow, "peer", "key", placement, "op-1", DataConditionMethods.Acknowledge,
|
||||
DataWriteState.DriverConfirmedSuccess, 0, false, "operator"));
|
||||
|
||||
var line = capture.Entries.Where(e => e.Category == LoggerDataConnectionAuditLog.Category).ShouldHaveSingleItem();
|
||||
line.Message.ShouldContain("op op-1");
|
||||
line.Message.ShouldContain("Plant/xforged"); // defence in depth: CR/LF stripped by the logger too
|
||||
}
|
||||
finally { await system.Terminate(); }
|
||||
}
|
||||
|
||||
private sealed class CapturingLoggerProvider : Microsoft.Extensions.Logging.ILoggerProvider
|
||||
{
|
||||
public List<(string Category, string Message)> Entries { get; } = [];
|
||||
public Microsoft.Extensions.Logging.ILogger CreateLogger(string categoryName) => new Logger(this, categoryName);
|
||||
public void Dispose() { }
|
||||
|
||||
private sealed class Logger(CapturingLoggerProvider owner, string category) : Microsoft.Extensions.Logging.ILogger
|
||||
{
|
||||
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
|
||||
public bool IsEnabled(Microsoft.Extensions.Logging.LogLevel logLevel) => true;
|
||||
public void Log<TState>(Microsoft.Extensions.Logging.LogLevel logLevel, Microsoft.Extensions.Logging.EventId eventId, TState state,
|
||||
Exception? exception, Func<TState, Exception?, string> formatter)
|
||||
{
|
||||
lock (owner.Entries) owner.Entries.Add((category, formatter(state, exception)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static ServiceCollection RegisteredOriginServices(ActorRegistry registry, bool warm = false)
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
|
||||
@@ -232,6 +232,102 @@ public sealed class ConditionMethodNodeManagerTests : IDisposable
|
||||
await host.DisposeAsync();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- security review (A2b)
|
||||
|
||||
[Fact]
|
||||
public async Task AddComment_is_refused_off_Primary_for_a_native_and_a_scripted_condition()
|
||||
{
|
||||
var (host, nm, sink) = await BootAsync();
|
||||
Materialise(nm);
|
||||
var commands = new List<AlarmCommand>();
|
||||
nm.AlarmCommandRouter = commands.Add;
|
||||
nm.WriteAlarmCondition(Native, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw);
|
||||
nm.WriteAlarmCondition(Scripted, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Uns);
|
||||
var before = sink.Records.Count;
|
||||
|
||||
nm.NativeAlarmAckPrimaryGate = () => false; // this node is the Secondary
|
||||
foreach (var (id, realm) in new[] { (Native, AddressSpaceRealm.Raw), (Scripted, AddressSpaceRealm.Uns) })
|
||||
nm.TryExecuteConditionMethod(Call(nm, id, realm, "AddComment", "from the standby"))
|
||||
.ShouldSatisfyAllConditions(o => o.Applied.ShouldBeFalse(), o => o.StatusCode.ShouldBe(StatusCodes.BadInvalidState.Code));
|
||||
|
||||
commands.ShouldBeEmpty();
|
||||
sink.Records.Count.ShouldBe(before);
|
||||
nm.TryGetAlarmCondition(Native, AddressSpaceRealm.Raw)!.Comment?.Value.Text.ShouldNotBe("from the standby");
|
||||
nm.TryGetAlarmCondition(Scripted, AddressSpaceRealm.Uns)!.Comment?.Value.Text.ShouldNotBe("from the standby");
|
||||
await host.DisposeAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_scripted_AddComment_is_refused_on_a_Warm_Standby()
|
||||
{
|
||||
var (host, warm, sink) = await BootAsync(warm: true);
|
||||
Materialise(warm);
|
||||
var commands = new List<AlarmCommand>();
|
||||
warm.AlarmCommandRouter = commands.Add;
|
||||
warm.WriteAlarmCondition(Scripted, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Uns);
|
||||
var before = sink.Records.Count;
|
||||
|
||||
warm.TryExecuteConditionMethod(Call(warm, Scripted, AddressSpaceRealm.Uns, "AddComment", "standby note"))
|
||||
.ShouldSatisfyAllConditions(o => o.Applied.ShouldBeFalse(), o => o.StatusCode.ShouldBe(StatusCodes.BadInvalidState.Code));
|
||||
commands.ShouldBeEmpty();
|
||||
sink.Records.Count.ShouldBe(before);
|
||||
await host.DisposeAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_condition_removed_and_re_created_never_accepts_a_marker_of_its_previous_incarnation()
|
||||
{
|
||||
var (host, nm, _) = await BootAsync();
|
||||
Materialise(nm);
|
||||
var routed = new List<NativeAlarmAck>();
|
||||
nm.NativeAlarmAckRouter = routed.Add;
|
||||
nm.WriteAlarmCondition(Native, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw);
|
||||
var stale = nm.GetActivationMarker(Native, AddressSpaceRealm.Raw)!.Value;
|
||||
|
||||
nm.RemoveAlarmConditionNode(Native, AddressSpaceRealm.Raw).ShouldBeTrue();
|
||||
nm.MaterialiseAlarmCondition(Native, Device, "TankHi", "OffNormalAlarm", 700, AddressSpaceRealm.Raw, isNative: true);
|
||||
nm.CompleteAddressSpaceApply();
|
||||
nm.WriteAlarmCondition(Native, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw); // same shape, new occurrence
|
||||
|
||||
var fresh = nm.GetActivationMarker(Native, AddressSpaceRealm.Raw)!.Value;
|
||||
fresh.Incarnation.ShouldBe(stale.Incarnation); // same node-manager lifetime ...
|
||||
fresh.Sequence.ShouldBeGreaterThan(stale.Sequence); // ... so only the monotonic sequence tells them apart
|
||||
nm.TryExecuteConditionMethod(Call(nm, Native, AddressSpaceRealm.Raw, "Acknowledge", marker: stale))
|
||||
.ShouldSatisfyAllConditions(o => o.Applied.ShouldBeFalse(), o => o.StatusCode.ShouldBe(BadEventIdUnknown));
|
||||
routed.ShouldBeEmpty();
|
||||
nm.TryGetAlarmCondition(Native, AddressSpaceRealm.Raw)!.AckedState!.Id!.Value.ShouldBeFalse();
|
||||
await host.DisposeAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_remote_call_waits_a_bounded_time_for_the_Lock_and_is_refused_unapplied()
|
||||
{
|
||||
var (host, nm, sink) = await BootAsync();
|
||||
Materialise(nm);
|
||||
nm.AlarmCommandRouter = _ => { };
|
||||
nm.WriteAlarmCondition(Scripted, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Uns);
|
||||
var call = Call(nm, Scripted, AddressSpaceRealm.Uns, "Acknowledge");
|
||||
var before = sink.Records.Count;
|
||||
nm.ConditionMethodLockTimeout = TimeSpan.FromMilliseconds(100);
|
||||
using var held = new ManualResetEventSlim();
|
||||
using var release = new ManualResetEventSlim();
|
||||
var holder = Task.Factory.StartNew(() => { lock (nm.Lock) { held.Set(); release.Wait(TimeSpan.FromSeconds(30)); } },
|
||||
Ct, TaskCreationOptions.LongRunning, TaskScheduler.Default);
|
||||
held.Wait(Ct);
|
||||
|
||||
var started = System.Diagnostics.Stopwatch.StartNew();
|
||||
var outcome = nm.TryExecuteConditionMethod(call);
|
||||
started.Stop();
|
||||
release.Set();
|
||||
await holder;
|
||||
|
||||
outcome.ShouldSatisfyAllConditions(o => o.Applied.ShouldBeFalse(), o => o.StatusCode.ShouldBe(StatusCodes.BadTimeout.Code));
|
||||
started.Elapsed.ShouldBeLessThan(TimeSpan.FromSeconds(5));
|
||||
sink.Records.Count.ShouldBe(before);
|
||||
nm.TryExecuteConditionMethod(call).Applied.ShouldBeTrue(); // the Lock free again: served
|
||||
await host.DisposeAsync();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- helpers
|
||||
|
||||
private static Func<int> CountEvents(AlarmConditionState alarm)
|
||||
|
||||
@@ -254,16 +254,18 @@ public sealed class ConditionStateNodeManagerTests : IDisposable
|
||||
var (host, nm, _) = await BootAsync();
|
||||
MaterialiseAll(nm);
|
||||
ulong Seq() => nm.GetActivationMarker(Native, AddressSpaceRealm.Raw)!.Value.Sequence;
|
||||
Seq().ShouldBe(0ul);
|
||||
// The sequence is node-manager-wide (security review): it MOVES (strictly up) on a new occurrence, by any amount.
|
||||
var initial = Seq();
|
||||
nm.WriteAlarmCondition(Native, State(true, false), DateTime.UtcNow, AddressSpaceRealm.Raw);
|
||||
Seq().ShouldBe(1ul);
|
||||
var raised = Seq();
|
||||
raised.ShouldBeGreaterThan(initial);
|
||||
nm.WriteAlarmCondition(Native, State(true, false, message: "changed"), DateTime.UtcNow, AddressSpaceRealm.Raw);
|
||||
nm.WriteAlarmCondition(Native, State(true, false, message: "changed"), DateTime.UtcNow, AddressSpaceRealm.Raw);
|
||||
Seq().ShouldBe(1ul); // message-only change and same-state re-projection
|
||||
Seq().ShouldBe(raised); // message-only change and same-state re-projection
|
||||
nm.WriteAlarmCondition(Native, State(false, true), DateTime.UtcNow, AddressSpaceRealm.Raw);
|
||||
Seq().ShouldBe(1ul);
|
||||
Seq().ShouldBe(raised);
|
||||
nm.WriteAlarmCondition(Native, State(false, false), DateTime.UtcNow, AddressSpaceRealm.Raw); // InactiveUnacknowledged
|
||||
Seq().ShouldBe(2ul);
|
||||
Seq().ShouldBeGreaterThan(raised);
|
||||
await host.DisposeAsync();
|
||||
}
|
||||
|
||||
|
||||
+19
@@ -80,6 +80,23 @@ public sealed class GrpcDataConditionMethodClientTests
|
||||
a.MethodCalls.ShouldBe(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_caller_cancel_after_the_request_was_sent_is_OutcomeUnknown_not_a_clean_failure()
|
||||
{
|
||||
var a = new Endpoint("a") { Hang = true };
|
||||
await using var connection = Connect([a]);
|
||||
using var cts = CancellationTokenSource.CreateLinkedTokenSource(Ct);
|
||||
|
||||
var call = connection.CallConditionMethodAsync(Request(), cts.Token);
|
||||
while (Volatile.Read(ref a.MethodCalls) == 0) await Task.Delay(10, Ct); // the request reached the origin
|
||||
await cts.CancelAsync();
|
||||
var result = await call;
|
||||
|
||||
result.State.ShouldBe(DataWriteState.OutcomeUnknown);
|
||||
result.StatusCode.ShouldBe(0x80050000u);
|
||||
a.MethodCalls.ShouldBe(1);
|
||||
}
|
||||
|
||||
private static GrpcDataConnection Connect(Endpoint[] endpoints, TimeSpan? methodTimeout = null)
|
||||
{
|
||||
var manager = new DataConnectionManager("consumer", 1);
|
||||
@@ -97,6 +114,7 @@ public sealed class GrpcDataConditionMethodClientTests
|
||||
public string Role { get; init; } = "Primary";
|
||||
public uint Methods { get; init; } = 7;
|
||||
public bool Drop { get; init; }
|
||||
public bool Hang { get; init; }
|
||||
public Grpc.Core.StatusCode? Fail { get; init; }
|
||||
public int MethodCalls;
|
||||
public W.ConditionMethodRequest? LastRequest { get; private set; }
|
||||
@@ -124,6 +142,7 @@ public sealed class GrpcDataConditionMethodClientTests
|
||||
var bytes = await request.Content!.ReadAsByteArrayAsync(token);
|
||||
LastRequest = W.ConditionMethodRequest.Parser.ParseFrom(bytes.AsSpan(5).ToArray());
|
||||
if (Drop) throw new HttpRequestException("connection reset after the request was sent");
|
||||
if (Hang) await Task.Delay(Timeout.Infinite, token);
|
||||
if (Fail is { } fail) return Status(fail);
|
||||
message = DataConditionProtoMapper.EncodeMethodResponse(new(DataWriteState.AcceptedUnconfirmed, 0, "AcceptedUnconfirmed", Serving));
|
||||
}
|
||||
|
||||
+137
-2
@@ -35,8 +35,13 @@ public sealed class GrpcDataConditionMethodTests
|
||||
string op = "op-1", string? comment = "ack", string incarnation = "serving-1", TimeSpan? budget = null, string? onBehalfOf = null) =>
|
||||
new(op, placement, method, Marker, comment, incarnation, budget ?? TimeSpan.FromSeconds(5), onBehalfOf);
|
||||
|
||||
private static Task<DataConditionMethodResult> CallAsync(ConditionFixture f, DataConditionMethodRequest request) =>
|
||||
((IDataConditionMethodService)f.Services.Create(f.Context, f.Target)).CallConditionMethodAsync(request, Ct);
|
||||
private static Task<DataConditionMethodResult> CallAsync(ConditionFixture f, DataConditionMethodRequest request,
|
||||
DataAuthenticatedContext? context = null) =>
|
||||
((IDataConditionMethodService)f.Services.Create(context ?? f.Context, f.Target)).CallConditionMethodAsync(request, Ct);
|
||||
|
||||
private const uint BadTooManyOperations = 0x80100000u, BadNoCommunication = 0x80310000u, BadInternalError = 0x80020000u;
|
||||
|
||||
private static int Retained(ConditionFixture f) => f.Services.MethodRegistry(f.Serving.Incarnation).CountForTests;
|
||||
|
||||
private static NodeAcl Acl(NodeAclScopeKind kind, string? scopeId, NodePermissions permissions, string id = "grant") =>
|
||||
new() { NodeAclId = id, ClusterId = "cluster", Principal = "peer", ScopeKind = kind, ScopeId = scopeId, PermissionFlags = permissions };
|
||||
@@ -226,4 +231,134 @@ public sealed class GrpcDataConditionMethodTests
|
||||
var snapshot = await stream.ReadSnapshotAsync();
|
||||
snapshot.Records.ShouldHaveSingleItem().Info.ShouldNotBeNull().SupportedMethods.ShouldBe(expected);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ security review (A2b)
|
||||
|
||||
[Fact]
|
||||
public async Task Principal_B_reusing_principal_As_operation_id_never_joins_As_operation()
|
||||
{
|
||||
using var f = new ConditionFixture(1, extraOperations: Methods, secondPrincipal: true,
|
||||
acls: [Acl(NodeAclScopeKind.Cluster, null, NodePermissions.Operator)]);
|
||||
var calls = 0;
|
||||
f.Source.Execute = _ => Interlocked.Increment(ref calls) == 1
|
||||
? new(true, true, 0, null) : new(false, true, BadInvalidState, "B's own verdict");
|
||||
|
||||
var a = await CallAsync(f, Request(RawPlacement(0), op: "shared-op"));
|
||||
var b = await CallAsync(f, Request(RawPlacement(0), op: "shared-op"), f.Context2);
|
||||
// Same id, a DIFFERENT call from B: still B's own operation, never A's conflict either.
|
||||
var b2 = await CallAsync(f, Request(RawPlacement(0), op: "shared-op", comment: "other"), f.Context2);
|
||||
|
||||
a.State.ShouldBe(DataWriteState.AcceptedUnconfirmed);
|
||||
b.ShouldSatisfyAllConditions(r => r.State.ShouldBe(DataWriteState.RejectedBeforeDispatch), r => r.StatusCode.ShouldBe(BadInvalidState));
|
||||
b2.StatusCode.ShouldBe(BadInvalidState); // executed, not BadInvalidArgument (A's hash)
|
||||
f.Source.MethodCalls.Select(c => c.Principal).ShouldBe(["peer", "peer2", "peer2"]);
|
||||
f.AuditLog.Entries.Select(e => (e.Principal, e.Joined)).ShouldBe([("peer", false), ("peer2", false), ("peer2", false)]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task An_exception_after_dispatch_answers_OutcomeUnknown_finishes_the_claim_and_is_audited()
|
||||
{
|
||||
using var f = new ConditionFixture(1, extraOperations: Methods, acls: [Acl(NodeAclScopeKind.Cluster, null, NodePermissions.Operator)]);
|
||||
// The node manager may have applied the call before this throws: it is not "nothing applied".
|
||||
f.Source.Execute = _ => throw new InvalidOperationException("thrown after the SDK applied the ack");
|
||||
|
||||
var first = await CallAsync(f, Request(RawPlacement(0)));
|
||||
var duplicate = await CallAsync(f, Request(RawPlacement(0), budget: TimeSpan.FromMilliseconds(50)));
|
||||
|
||||
first.ShouldSatisfyAllConditions(r => r.State.ShouldBe(DataWriteState.OutcomeUnknown), r => r.StatusCode.ShouldBe(BadInternalError));
|
||||
// The claim was finished with the same outcome (a joiner gets it at once, never "still running"); never re-executed.
|
||||
duplicate.ShouldBe(first);
|
||||
f.Source.MethodCalls.Count.ShouldBe(1);
|
||||
f.AuditLog.Entries.Select(e => (e.State, e.Joined)).ShouldBe([(DataWriteState.OutcomeUnknown, false), (DataWriteState.OutcomeUnknown, true)]);
|
||||
Retained(f).ShouldBe(1); // kept: a retry must join, not apply twice
|
||||
|
||||
// Any other exception type too (it used to escape: no audit, a claim left pending forever).
|
||||
f.Source.Execute = _ => throw new NullReferenceException("boom");
|
||||
(await CallAsync(f, Request(RawPlacement(0), op: "op-2"))).State.ShouldBe(DataWriteState.OutcomeUnknown);
|
||||
f.AuditLog.Entries.Last().ShouldSatisfyAllConditions(e => e.OperationId.ShouldBe("op-2"), e => e.State.ShouldBe(DataWriteState.OutcomeUnknown));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_node_manager_that_is_not_running_is_nothing_applied_and_retains_no_entry()
|
||||
{
|
||||
using var f = new ConditionFixture(1, extraOperations: Methods, acls: [Acl(NodeAclScopeKind.Cluster, null, NodePermissions.Operator)]);
|
||||
f.Source.Execute = _ => throw new OriginConditionSourceUnavailableException();
|
||||
|
||||
var refused = await CallAsync(f, Request(RawPlacement(0)));
|
||||
|
||||
refused.ShouldSatisfyAllConditions(r => r.State.ShouldBe(DataWriteState.RejectedBeforeDispatch), r => r.StatusCode.ShouldBe(BadNoCommunication));
|
||||
Retained(f).ShouldBe(0);
|
||||
f.Source.Execute = _ => new(true, true, 0, null);
|
||||
(await CallAsync(f, Request(RawPlacement(0)))).State.ShouldBe(DataWriteState.AcceptedUnconfirmed); // a fresh owner, not a join
|
||||
f.Source.MethodCalls.Count.ShouldBe(2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task One_principal_cannot_exhaust_the_registry_for_another()
|
||||
{
|
||||
using var f = new ConditionFixture(1, extraOperations: Methods, secondPrincipal: true, methodMaxOperations: 10, methodMaxPerPrincipal: 2,
|
||||
acls: [Acl(NodeAclScopeKind.Cluster, null, NodePermissions.Operator)]);
|
||||
|
||||
(await CallAsync(f, Request(RawPlacement(0), op: "a1"))).State.ShouldBe(DataWriteState.AcceptedUnconfirmed);
|
||||
(await CallAsync(f, Request(RawPlacement(0), op: "a2"))).State.ShouldBe(DataWriteState.AcceptedUnconfirmed);
|
||||
(await CallAsync(f, Request(RawPlacement(0), op: "a3"))).StatusCode.ShouldBe(BadTooManyOperations);
|
||||
(await CallAsync(f, Request(RawPlacement(0), op: "b1"), f.Context2)).State.ShouldBe(DataWriteState.AcceptedUnconfirmed);
|
||||
f.Source.MethodCalls.Count.ShouldBe(3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_global_registry_cap_holds_across_principals()
|
||||
{
|
||||
using var f = new ConditionFixture(1, extraOperations: Methods, secondPrincipal: true, methodMaxOperations: 2, methodMaxPerPrincipal: 2,
|
||||
acls: [Acl(NodeAclScopeKind.Cluster, null, NodePermissions.Operator)]);
|
||||
|
||||
(await CallAsync(f, Request(RawPlacement(0), op: "a1"))).State.ShouldBe(DataWriteState.AcceptedUnconfirmed);
|
||||
(await CallAsync(f, Request(RawPlacement(0), op: "b1"), f.Context2)).State.ShouldBe(DataWriteState.AcceptedUnconfirmed);
|
||||
(await CallAsync(f, Request(RawPlacement(0), op: "b2"), f.Context2)).StatusCode.ShouldBe(BadTooManyOperations);
|
||||
f.Source.MethodCalls.Count.ShouldBe(2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Refusals_retain_no_registry_capacity()
|
||||
{
|
||||
using var f = new ConditionFixture(1, extraOperations: Methods, methodMaxOperations: 10, methodMaxPerPrincipal: 1,
|
||||
acls: [Acl(NodeAclScopeKind.Cluster, null, NodePermissions.Operator)]);
|
||||
// Refused by the facade (unknown placement, native Confirm) and by the node manager (marker mismatch): nothing retained.
|
||||
(await CallAsync(f, Request(RawPlacement(9), op: "r1"))).StatusCode.ShouldBe(BadNodeIdUnknown);
|
||||
(await CallAsync(f, Request(RawPlacement(0), DataConditionMethods.Confirm, op: "r2"))).StatusCode.ShouldBe(BadNotSupported);
|
||||
f.Source.Execute = _ => new(false, true, BadEventIdUnknown, "newer occurrence");
|
||||
for (var i = 0; i < 5; i++)
|
||||
(await CallAsync(f, Request(RawPlacement(0), op: "nm" + i))).StatusCode.ShouldBe(BadEventIdUnknown);
|
||||
Retained(f).ShouldBe(0);
|
||||
|
||||
f.Source.Execute = _ => new(true, true, 0, null);
|
||||
(await CallAsync(f, Request(RawPlacement(0), op: "ok"))).State.ShouldBe(DataWriteState.AcceptedUnconfirmed);
|
||||
Retained(f).ShouldBe(1);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Every_caller_supplied_audit_string_is_sanitised()
|
||||
{
|
||||
using var f = new ConditionFixture(1, extraOperations: Methods, acls: [Acl(NodeAclScopeKind.Cluster, null, NodePermissions.Operator)]);
|
||||
var hostile = new DataView(new("cluster\r\n", "https://zb.com/otopcua/raw\u0007", "string\u2028", "Plant/x\r\n2026 FAKE AUDIT LINE"),
|
||||
DataRealm.Raw, null, 0, "Plant/x\u0000y");
|
||||
|
||||
await CallAsync(f, Request(hostile, op: "op\r\n-forged"));
|
||||
|
||||
var entry = f.AuditLog.Entries.ShouldHaveSingleItem();
|
||||
entry.OperationId.ShouldBe("op-forged");
|
||||
var a = entry.Placement.Address;
|
||||
new[] { a.OriginClusterId, a.NamespaceUri, a.IdentifierKind, a.Identifier, entry.Placement.Subject, entry.OperationId }
|
||||
.ShouldAllBe(text => text.All(c => !char.IsControl(c) && c != '\u2028'));
|
||||
a.Identifier.ShouldBe("Plant/x2026 FAKE AUDIT LINE");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SanitizeAuditText_drops_private_use_and_lone_surrogates_and_stays_well_formed()
|
||||
{
|
||||
var text = "a\uE000b" + "\U000F0000" + "c" + '\uDC00' + "d" + '\uD83D';
|
||||
var clean = LocalDataServices.SanitizeAuditText(text).ShouldNotBeNull();
|
||||
clean.ShouldBe("abcd");
|
||||
System.Text.Encoding.UTF8.GetString(new System.Text.UTF8Encoding(false, true).GetBytes(clean)).ShouldBe(clean);
|
||||
}
|
||||
}
|
||||
|
||||
+31
-8
@@ -511,6 +511,8 @@ internal sealed class ConditionFixture : IDisposable
|
||||
internal readonly RecordingAuditLog AuditLog = new();
|
||||
internal readonly LocalDataServices Services;
|
||||
internal readonly DataAuthenticatedContext Context;
|
||||
/// <summary>A second principal (<c>peer2</c>, same grants and ACLs), only with <c>secondPrincipal: true</c>.</summary>
|
||||
internal readonly DataAuthenticatedContext? Context2;
|
||||
internal readonly DataTarget Target;
|
||||
internal readonly DataView Root = new(new("cluster", "https://zb.com/otopcua/raw", "string", "Plant"), DataRealm.Raw, null, 0, "Plant");
|
||||
internal readonly DataView UnsRoot = new(new("cluster", "https://zb.com/otopcua/uns", "string", "Area"), DataRealm.Uns, null, 0, "Area");
|
||||
@@ -525,6 +527,7 @@ internal sealed class ConditionFixture : IDisposable
|
||||
private readonly DataOperations _extra;
|
||||
private readonly string? _driverType;
|
||||
private readonly bool _galaxyAck;
|
||||
private readonly bool _second;
|
||||
private volatile LocalExportCatalog _catalog;
|
||||
internal volatile bool HoldTicks;
|
||||
private readonly List<ConditionStream> _streams = [];
|
||||
@@ -535,8 +538,9 @@ internal sealed class ConditionFixture : IDisposable
|
||||
Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>? scopePaths = null, string? driverType = null, bool galaxyAck = false,
|
||||
long maxPendingBytes = 200_000, int maxMessageBytes = 1_000_000, long? principalSnapshotBytes = null,
|
||||
int maxConditionItems = SubscriptionSessionLimits.DefaultMaxConditionItems, string? unsDisplayName = null,
|
||||
byte[]? artifact = null)
|
||||
byte[]? artifact = null, bool secondPrincipal = false, int? methodMaxOperations = null, int? methodMaxPerPrincipal = null)
|
||||
{
|
||||
_second = secondPrincipal;
|
||||
_uns = unsPrincipal; _maxConditions = maxConditions; _grant = grantAlarmSubscribe; _unsName = unsDisplayName;
|
||||
_extra = extraOperations; _driverType = driverType; _galaxyAck = galaxyAck;
|
||||
Serving = new ServingIdentity("node-a", "serving-1", role, 1, 1);
|
||||
@@ -552,9 +556,17 @@ internal sealed class ConditionFixture : IDisposable
|
||||
Coordinator = new LocalCatalogCoordinator(Activation, Authority, () => Serving with { CatalogEpoch = 0, AuthorityEpoch = 0 });
|
||||
Publish(artifact);
|
||||
}
|
||||
else Authority.Apply("cluster", "first", [key],
|
||||
acls ?? [new NodeAcl { NodeAclId = "grant", ClusterId = "cluster", Principal = "peer", ScopeKind = NodeAclScopeKind.Cluster,
|
||||
PermissionFlags = NodePermissions.ReadOnly }], scopePaths ?? new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>());
|
||||
var key2 = new ApiKey { ApiKeyId = "peer2-key", Name = "peer2-key", Principal = "peer2", SecretHash = "hash2", Enabled = true };
|
||||
if (artifact is null)
|
||||
{
|
||||
IReadOnlyList<NodeAcl> grants = acls ?? [new NodeAcl { NodeAclId = "grant", ClusterId = "cluster", Principal = "peer",
|
||||
ScopeKind = NodeAclScopeKind.Cluster, PermissionFlags = NodePermissions.ReadOnly }];
|
||||
if (secondPrincipal)
|
||||
grants = [.. grants, .. grants.Select(a => new NodeAcl { NodeAclId = a.NodeAclId + "-2", ClusterId = a.ClusterId,
|
||||
Principal = "peer2", ScopeKind = a.ScopeKind, ScopeId = a.ScopeId, PermissionFlags = a.PermissionFlags })];
|
||||
Authority.Apply("cluster", "first", secondPrincipal ? [key, key2] : [key], grants,
|
||||
scopePaths ?? new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>());
|
||||
}
|
||||
if (artifact is null)
|
||||
{
|
||||
var epoch = Activation.Begin("first");
|
||||
@@ -562,6 +574,9 @@ internal sealed class ConditionFixture : IDisposable
|
||||
Activation.Complete(epoch, true);
|
||||
}
|
||||
Context = new("peer", key.ApiKeyId, DataCallerIdentity.CredentialVersionFor(key), Clock.GetUtcNow().AddMinutes(10), Authority.Current.GenerationId);
|
||||
if (secondPrincipal)
|
||||
Context2 = new("peer2", key2.ApiKeyId, DataCallerIdentity.CredentialVersionFor(key2), Clock.GetUtcNow().AddMinutes(10),
|
||||
Authority.Current.GenerationId);
|
||||
Target = new(DataTargetMode.Node, "cluster", "node-a");
|
||||
for (var i = 0; i < conditions; i++) { _listed.Add(i); Source.Add(i); }
|
||||
_catalog = Compile(_grant);
|
||||
@@ -579,7 +594,11 @@ internal sealed class ConditionFixture : IDisposable
|
||||
new TriePermissionEvaluator(Authority.Tries, Clock), Clock), capabilities, Clock,
|
||||
targetSubscriptions: (context, target) => new LocalSubscriptionService(services!, context, target, new DeferredSubscriptionDemand(),
|
||||
sessionLimits, capacity))
|
||||
{ ConditionHub = Hub, ConditionSource = Source, ConditionKeysSource = () => Keys, Audit = AuditLog };
|
||||
{
|
||||
ConditionHub = Hub, ConditionSource = Source, ConditionKeysSource = () => Keys, Audit = AuditLog,
|
||||
ConditionMethodMaxOperations = methodMaxOperations ?? LocalDataServices.DefaultConditionMethodMaxOperations,
|
||||
ConditionMethodMaxOperationsPerPrincipal = methodMaxPerPrincipal ?? LocalDataServices.DefaultConditionMethodMaxOperationsPerPrincipal,
|
||||
};
|
||||
Services = services;
|
||||
}
|
||||
|
||||
@@ -629,10 +648,14 @@ internal sealed class ConditionFixture : IDisposable
|
||||
}
|
||||
var operations = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Subscribe
|
||||
| (grant ? DataOperations.AlarmSubscribe | _extra : DataOperations.None);
|
||||
DataExport Export(string id, string principal) => new()
|
||||
{
|
||||
DataExportId = id, ClusterId = "cluster", Enabled = true, Realm = _uns ? DataRealm.Uns : DataRealm.Raw,
|
||||
RootKind = _uns ? "UnsArea" : "RawFolder", RootEntityId = _uns ? "area" : "folder", PrincipalId = principal,
|
||||
AllowedOperations = operations, MaxConditions = _maxConditions, AllowGalaxyServiceAck = _galaxyAck,
|
||||
};
|
||||
return new LocalExportCatalog("cluster", Serving, Activation.CaptureAuthority(), nodes,
|
||||
[new() { DataExportId = "export", ClusterId = "cluster", Enabled = true, Realm = _uns ? DataRealm.Uns : DataRealm.Raw,
|
||||
RootKind = _uns ? "UnsArea" : "RawFolder", RootEntityId = _uns ? "area" : "folder", PrincipalId = "peer",
|
||||
AllowedOperations = operations, MaxConditions = _maxConditions, AllowGalaxyServiceAck = _galaxyAck }], conditionPlacements: placements);
|
||||
_second ? [Export("export", "peer"), Export("export-2", "peer2")] : [Export("export", "peer")], conditionPlacements: placements);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+17
@@ -93,4 +93,21 @@ public sealed class GrpcDataWriteRegistryTests
|
||||
claim.CurrentOutcome.ShouldBe(Success);
|
||||
claim.LateRefine(new(DataWriteState.RejectedBeforeDispatch, 0, null)).ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void A2b_the_per_principal_cap_refuses_one_principal_and_admits_another_and_release_frees_the_slot()
|
||||
{
|
||||
var registry = new WriteOperationRegistry("inc-1", 10, 4096, TimeSpan.FromSeconds(10), maxEntriesPerPrincipal: 2);
|
||||
registry.Claim("A", "1", "inc-1", Hash).Kind.ShouldBe(WriteClaimKind.Owner);
|
||||
var second = registry.Claim("a", "2", "inc-1", Hash).Claim!; // principal keys are case-insensitive
|
||||
registry.Claim("A", "3", "inc-1", Hash).Kind.ShouldBe(WriteClaimKind.Capacity);
|
||||
registry.Claim("B", "1", "inc-1", Hash).Kind.ShouldBe(WriteClaimKind.Owner); // B is not A's operation
|
||||
|
||||
// Only a claim that completed UNDISPATCHED can be released; a pending/dispatched one cannot.
|
||||
registry.ReleaseUndispatched("a", "2", second).ShouldBeFalse();
|
||||
second.Complete(new(DataWriteState.RejectedBeforeDispatch, 0, null)).ShouldBeTrue();
|
||||
registry.ReleaseUndispatched("a", "2", second).ShouldBeTrue();
|
||||
registry.CountForTests.ShouldBe(2);
|
||||
registry.Claim("A", "3", "inc-1", Hash).Kind.ShouldBe(WriteClaimKind.Owner);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user