feat(security): per-client pre-auth API-key miss budget; widen IOpcUaUserAuthenticator with the remote endpoint (lmxopcua#751)

The #733 miss budget (MissBurst / MissRefillPerSecond) was process-wide, because
the impersonation seam did not carry the client's address, so one noisy client
could drain it for everybody while the known-id set was unavailable.

- IOpcUaUserAuthenticator gains AuthenticateUserNameAsync(username, password,
  IPEndPoint? remoteEndpoint, ct) (default: ignore it and delegate); the server
  calls it. IApiKeyStore gains the matching FindAsync(..., IPAddress?, ...).
- The SDK (1.5.378) exposes no client address publicly. SecureChannelRemoteEndpoint
  reads it from the TCP listener's private channel map by reflection (through the
  protected TransportListeners, exposed by OtOpcUaSdkServer), keyed by the
  session's secure channel id. Fail-soft: null => process-wide accounting only.
- BoundedApiKeyStore charges a miss to the client's own bucket (keyed by IP
  address) and then to the process-wide one, which stays as the backstop. A
  refusal by either takes from neither; a hit refunds both. New options
  Security:ApiKeys:MissBurstPerEndpoint (10) / MissRefillPerSecondPerEndpoint (2),
  0 disables; telemetry outcome endpoint_miss_budget. At most 4096 addresses are
  tracked; idle buckets are pruned and an address beyond the cap is charged
  process-wide only.

Tests: BoundedApiKeyStorePerEndpointTests (noisy client vs quiet one, process-wide
backstop, refund + refill, off switch, authenticator forwards the address) and
over the wire ApiKeyMissBudgetPerEndpointTests (activation hands the authenticator
the loopback endpoint; real authenticator + bounded store refuse a client's 3rd
and 4th unknown key without a store read). Each new behaviour test fails with its
fix mutated out. Host.Tests 224/0, OpcUaServer.Tests 1019/1 (the one failure is the
wall-clock NodeManagerLockTimeBenchmarkTests under suite load; passes alone).
Docs: security.md.

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
This commit is contained in:
Joseph Doherty
2026-11-09 13:46:24 -05:00
parent f54922f94c
commit d59e76dd9d
11 changed files with 698 additions and 35 deletions
@@ -69,8 +69,14 @@ public sealed class ApiKeyOpcUaUserAuthenticator : IOpcUaUserAuthenticator
}
/// <inheritdoc />
public Task<OpcUaUserAuthResult> AuthenticateUserNameAsync(string username, string password, CancellationToken ct) =>
AuthenticateUserNameAsync(username, password, remoteEndpoint: null, ct);
/// <inheritdoc />
// The client's address rides into the store so BoundedApiKeyStore can charge a miss to that client's own
// budget before the process-wide one (lmxopcua#751).
public async Task<OpcUaUserAuthResult> AuthenticateUserNameAsync(
string username, string password, CancellationToken ct)
string username, string password, System.Net.IPEndPoint? remoteEndpoint, CancellationToken ct)
{
var opts = _options.Value;
@@ -95,7 +101,7 @@ public sealed class ApiKeyOpcUaUserAuthenticator : IOpcUaUserAuthenticator
ApiKeyLookup? lookup;
try
{
lookup = await _store.FindAsync(apiKeyId, now, ct).ConfigureAwait(false);
lookup = await _store.FindAsync(apiKeyId, now, remoteEndpoint?.Address, ct).ConfigureAwait(false);
}
catch (Exception ex)
{
@@ -18,9 +18,11 @@ namespace ZB.MOM.WW.OtOpcUa.Host.OpcUa;
/// set is unavailable.
/// </para>
/// <para>
/// The budget is process-wide, not per remote endpoint: the OPC UA SDK's impersonation callback
/// (the <c>IOpcUaUserAuthenticator</c> seam) does not carry the client's address. Per-endpoint
/// accounting needs that seam widened in the OpcUaServer project — a follow-up, not this lane.
/// Since lmxopcua#751 the miss budget is also kept <b>per client IP address</b>
/// (<see cref="MissBurstPerEndpoint"/> / <see cref="MissRefillPerSecondPerEndpoint"/>): a miss is charged
/// to the client's own bucket first and then to the process-wide one, which stays as the backstop. One
/// noisy client therefore exhausts its own budget long before it can drain the process-wide one for
/// everybody. A client whose address cannot be resolved is charged to the process-wide bucket only.
/// </para>
/// </remarks>
public sealed class ApiKeyStoreGuardOptions
@@ -44,6 +46,17 @@ public sealed class ApiKeyStoreGuardOptions
/// <summary>How many miss tokens are restored per second, up to <see cref="MissBurst"/>.</summary>
public double MissRefillPerSecond { get; set; } = 20;
/// <summary>
/// How many store misses ONE client IP address may burst before its further lookups for unknown ids are
/// refused without a store read (lmxopcua#751). Deliberately a tenth of <see cref="MissBurst"/>: a
/// legitimate client presents a known key, which is never charged, so only a misconfigured or hostile
/// client spends from it. <c>0</c> disables per-client accounting (process-wide only).
/// </summary>
public int MissBurstPerEndpoint { get; set; } = 10;
/// <summary>How many per-client miss tokens are restored per second, up to <see cref="MissBurstPerEndpoint"/>.</summary>
public double MissRefillPerSecondPerEndpoint { get; set; } = 2;
/// <summary>Binds the section, with defaults for anything absent.</summary>
/// <param name="configuration">The app configuration; null yields the defaults.</param>
/// <returns>The bound options.</returns>
@@ -84,6 +84,32 @@ public sealed class BoundedApiKeyStore : IApiKeyStore
private double _missTokens;
private DateTimeOffset _missRefilledUtc;
/// <summary>
/// How many client addresses the per-endpoint miss budget tracks at once (lmxopcua#751). When full, idle
/// (refilled) buckets are pruned; if every tracked client is still active, a new address is charged to the
/// process-wide bucket only — never a fresh, full per-client budget.
/// </summary>
public const int MaxTrackedEndpoints = 4096;
// lmxopcua#751 — the per-client miss buckets, keyed by IP address (not port: one client can open many
// connections). Guarded by _bucketGate, like the process-wide bucket they sit in front of.
private readonly Dictionary<System.Net.IPAddress, EndpointBucket> _endpointBuckets = new();
/// <summary>One client's miss bucket.</summary>
private sealed class EndpointBucket
{
public double Tokens;
public DateTimeOffset RefilledUtc;
}
/// <summary>Which budget refused a lookup.</summary>
private enum MissBudget
{
Granted,
EndpointExhausted,
ProcessExhausted,
}
/// <summary>Initializes a new instance of the <see cref="BoundedApiKeyStore"/> class.</summary>
/// <param name="inner">The store being bounded.</param>
/// <param name="options">The <c>Security:ApiKeys</c> options carrying the deadline and TTL.</param>
@@ -136,7 +162,12 @@ public sealed class BoundedApiKeyStore : IApiKeyStore
// that has expired by the clock in the meantime. The TTL therefore bounds how stale an
// Enabled revocation may be, and nothing else.
/// <inheritdoc />
public async Task<ApiKeyLookup?> FindAsync(string apiKeyId, DateTime utcNow, CancellationToken ct)
public Task<ApiKeyLookup?> FindAsync(string apiKeyId, DateTime utcNow, CancellationToken ct) =>
FindAsync(apiKeyId, utcNow, remoteAddress: null, ct);
/// <inheritdoc />
public async Task<ApiKeyLookup?> FindAsync(
string apiKeyId, DateTime utcNow, System.Net.IPAddress? remoteAddress, CancellationToken ct)
{
var ttl = Ttl;
if (ttl > TimeSpan.Zero
@@ -159,18 +190,31 @@ public sealed class BoundedApiKeyStore : IApiKeyStore
}
// R03:3.3, guard 2 — a lookup that will reach the store needs a miss token unless the id is known
// to exist (a known id is a real key being verified, never a guess).
if (known is null && !TryTakeMissToken())
// to exist (a known id is a real key being verified, never a guess). lmxopcua#751: the client's own
// bucket is charged first, so one noisy client cannot drain the process-wide budget for everyone.
if (known is null)
{
OtOpcUaTelemetry.ApiKeyStoreBounded.Add(1, new KeyValuePair<string, object?>("outcome", "miss_budget"));
throw new InvalidOperationException(
"ApiKeyStore: the unknown-key miss budget is exhausted (Security:ApiKeys:MissBurst / "
+ "MissRefillPerSecond); refusing this lookup without a store read.");
switch (TryTakeMissToken(remoteAddress))
{
case MissBudget.EndpointExhausted:
OtOpcUaTelemetry.ApiKeyStoreBounded.Add(
1, new KeyValuePair<string, object?>("outcome", "endpoint_miss_budget"));
throw new InvalidOperationException(
"ApiKeyStore: this client's unknown-key miss budget is exhausted (Security:ApiKeys:"
+ "MissBurstPerEndpoint / MissRefillPerSecondPerEndpoint); refusing this lookup without a "
+ "store read.");
case MissBudget.ProcessExhausted:
OtOpcUaTelemetry.ApiKeyStoreBounded.Add(
1, new KeyValuePair<string, object?>("outcome", "miss_budget"));
throw new InvalidOperationException(
"ApiKeyStore: the unknown-key miss budget is exhausted (Security:ApiKeys:MissBurst / "
+ "MissRefillPerSecond); refusing this lookup without a store read.");
}
}
var fresh = await BoundAsync(token => _inner.FindAsync(apiKeyId, utcNow, token), ct)
.ConfigureAwait(false);
if (fresh is not null && known is null) RefundMissToken();
if (fresh is not null && known is null) RefundMissToken(remoteAddress);
if (ttl > TimeSpan.Zero) Store(_keys, apiKeyId, fresh);
return fresh;
}
@@ -219,32 +263,99 @@ public sealed class BoundedApiKeyStore : IApiKeyStore
}
}
/// <summary>Takes one miss token, refilling by elapsed time first; always succeeds when the budget is disabled.</summary>
/// <returns><see langword="false"/> when the budget is exhausted.</returns>
private bool TryTakeMissToken()
/// <summary>
/// Takes one miss token from <paramref name="remoteAddress"/>'s bucket (when known and per-client accounting
/// is on) AND from the process-wide bucket, refilling both by elapsed time first. All or nothing: a refusal
/// by either takes from neither. A disabled budget always grants.
/// </summary>
/// <param name="remoteAddress">The client's IP address; null charges the process-wide bucket only.</param>
/// <returns>Which budget, if any, refused the lookup.</returns>
private MissBudget TryTakeMissToken(System.Net.IPAddress? remoteAddress)
{
var burst = _guard.MissBurst;
if (burst <= 0) return true;
var endpointBurst = _guard.MissBurstPerEndpoint;
if (burst <= 0 && (endpointBurst <= 0 || remoteAddress is null)) return MissBudget.Granted;
lock (_bucketGate)
{
var now = _time.GetUtcNow();
var elapsed = (now - _missRefilledUtc).TotalSeconds;
if (elapsed > 0)
if (burst > 0)
{
_missTokens = Math.Min(burst, _missTokens + elapsed * Math.Max(0, _guard.MissRefillPerSecond));
_missRefilledUtc = now;
var elapsed = (now - _missRefilledUtc).TotalSeconds;
if (elapsed > 0)
{
_missTokens = Math.Min(burst, _missTokens + elapsed * Math.Max(0, _guard.MissRefillPerSecond));
_missRefilledUtc = now;
}
}
if (_missTokens < 1) return false;
_missTokens -= 1;
return true;
var endpoint = endpointBurst > 0 && remoteAddress is not null ? EndpointBucketFor(remoteAddress, now) : null;
if (endpoint is not null && endpoint.Tokens < 1) return MissBudget.EndpointExhausted;
if (burst > 0 && _missTokens < 1) return MissBudget.ProcessExhausted;
if (endpoint is not null) endpoint.Tokens -= 1;
if (burst > 0) _missTokens -= 1;
return MissBudget.Granted;
}
}
/// <summary>A lookup that reached the store and HIT was not a miss: its token goes back.</summary>
private void RefundMissToken()
/// <summary>
/// The refilled bucket for <paramref name="address"/>, created full on first sight; null when the table is
/// at <see cref="MaxTrackedEndpoints"/> even after pruning idle buckets. Caller holds <c>_bucketGate</c>.
/// </summary>
/// <param name="address">The client's IP address.</param>
/// <param name="now">The current time.</param>
/// <returns>The bucket, or null when no slot is free.</returns>
private EndpointBucket? EndpointBucketFor(System.Net.IPAddress address, DateTimeOffset now)
{
if (_guard.MissBurst <= 0) return;
lock (_bucketGate) _missTokens = Math.Min(_guard.MissBurst, _missTokens + 1);
var burst = _guard.MissBurstPerEndpoint;
if (_endpointBuckets.TryGetValue(address, out var bucket))
{
Refill(bucket, now);
return bucket;
}
if (_endpointBuckets.Count >= MaxTrackedEndpoints)
{
// An idle bucket (refilled to full) carries no history worth keeping — dropping it is the same as
// re-creating it full later. A bucket still below full is a client being throttled; never reset it.
foreach (var (key, candidate) in _endpointBuckets.ToList())
{
Refill(candidate, now);
if (candidate.Tokens >= burst) _endpointBuckets.Remove(key);
}
if (_endpointBuckets.Count >= MaxTrackedEndpoints) return null;
}
bucket = new EndpointBucket { Tokens = burst, RefilledUtc = now };
_endpointBuckets[address] = bucket;
return bucket;
}
/// <summary>Refills a per-client bucket by elapsed time. Caller holds <c>_bucketGate</c>.</summary>
private void Refill(EndpointBucket bucket, DateTimeOffset now)
{
var elapsed = (now - bucket.RefilledUtc).TotalSeconds;
if (elapsed <= 0) return;
bucket.Tokens = Math.Min(
_guard.MissBurstPerEndpoint,
bucket.Tokens + elapsed * Math.Max(0, _guard.MissRefillPerSecondPerEndpoint));
bucket.RefilledUtc = now;
}
/// <summary>A lookup that reached the store and HIT was not a miss: its tokens go back.</summary>
/// <param name="remoteAddress">The client the token was charged to, or null.</param>
private void RefundMissToken(System.Net.IPAddress? remoteAddress)
{
lock (_bucketGate)
{
if (_guard.MissBurst > 0) _missTokens = Math.Min(_guard.MissBurst, _missTokens + 1);
if (_guard.MissBurstPerEndpoint > 0 && remoteAddress is not null
&& _endpointBuckets.TryGetValue(remoteAddress, out var bucket))
{
bucket.Tokens = Math.Min(_guard.MissBurstPerEndpoint, bucket.Tokens + 1);
}
}
}
// Keyed by principal — the anonymous activation path, which runs on every unauthenticated connect.
@@ -27,6 +27,20 @@ public interface IApiKeyStore
/// <returns>The key and its principal's grants, or null when no usable key matches.</returns>
Task<ApiKeyLookup?> FindAsync(string apiKeyId, DateTime utcNow, CancellationToken ct);
/// <summary>
/// <see cref="FindAsync(string, DateTime, CancellationToken)"/> on behalf of the client at
/// <paramref name="remoteAddress"/> (lmxopcua#751), so a decorator can account pre-authentication misses
/// per client. The default ignores the address; only <see cref="BoundedApiKeyStore"/> uses it.
/// </summary>
/// <param name="apiKeyId">The public key id parsed from the presented credential.</param>
/// <param name="utcNow">Current UTC time, for the expiry check.</param>
/// <param name="remoteAddress">The activating client's IP address; null when unknown.</param>
/// <param name="ct">The cancellation token.</param>
/// <returns>The key and its principal's grants, or null when no usable key matches.</returns>
Task<ApiKeyLookup?> FindAsync(
string apiKeyId, DateTime utcNow, System.Net.IPAddress? remoteAddress, CancellationToken ct) =>
FindAsync(apiKeyId, utcNow, ct);
/// <summary>
/// Returns the ACL grants naming a principal, with no key involved. Used for the
/// <c>anonymous</c> principal, which has grants but obviously no credential.