Files
mxaccessgw/code-reviews/2026-12-02-perf-bugs/server-security-config-alarms.md
T

26 KiB
Raw Blame History

Server Security / Configuration / Alarms — Bug and Performance Review

  • Scope: src/ZB.MOM.WW.MxGateway.Server/Security/, .../Configuration/, .../Alarms/ at HEAD 54367e74.
  • Method: read-only code reading; no tests were run and no source was modified. Paths below are relative to src/ZB.MOM.WW.MxGateway.Server/ unless stated.
  • Confidence: Confirmed = the defect follows directly from the cited code. Plausible = the code permits it but it depends on timing or on behaviour outside this scope (stated per finding).
ID Severity Category Confidence Title
SEC-001 High Bug Confirmed gRPC failure-limiter partition includes the client's ephemeral port, so the per-peer layer resets on every new connection
SEC-002 High Bug Confirmed Aggregate throttle runs ahead of the verification cache, so an unauthenticated sprayer can deny a key to its legitimate holder
SEC-003 Medium Bug Confirmed Every successful RPC wipes the key's cross-peer aggregate, so an actively used key is never aggregate-throttled
SEC-004 Medium Bug Confirmed Revoking/deleting a key does not end its already-open server streams
SEC-005 High Bug Confirmed Alarm monitor restart drops the cache without telling feed subscribers; alarms cleared during the gap stay active forever downstream
SEC-006 Medium Bug Plausible Reconcile applies an older worker snapshot over newer live transitions (phantom Clear / phantom Raise for one reconcile interval)
SEC-007 Medium Bug Plausible An Acknowledge for an alarm not in the cache (ack after return-to-normal) is inserted as a phantom ActiveAcked alarm
SEC-008 Medium Performance Confirmed Watch-list refresh runs an uncached Galaxy SQL query and rebuilds a full fingerprint every reconcile interval, and inline in the event loop on failover
SEC-009 Low Bug Confirmed Reconcile repair misses a same-state re-raise and silently ignores a non-OK reconcile reply
SEC-010 Low Performance Confirmed Monitor restart uses a fixed 5 s backoff and launches a new worker process on every attempt
SEC-011 Low Bug Confirmed Options validation gaps: Alarms:ReconcileIntervalSeconds unvalidated; Events:ReplayRetentionSeconds has no upper bound
SEC-012 Low Performance Confirmed Auth hot path allocates ~8 objects and hashes the token on every RPC even on a cache hit
SEC-013 Low Bug Plausible Constraint JSON missing a list member deserializes to null lists (NRE per RPC, or a null browse scope)
SEC-014 Low Performance Confirmed Audit retention sweep is a non-sargable full scan in the auth SQLite file and blocks host startup

SEC-001 — Failure-limiter partition includes the ephemeral source port

  • Severity: High · Category: Bug (security) · Confidence: Confirmed
  • Location: Security/Authorization/GatewayGrpcAuthorizationInterceptor.cs:174-179; Security/Authorization/ApiKeyFailureLimiter.cs:148-159, 404-409; contrast Security/Authorization/MetricsAuthorization.cs:66-68.

Description. ResolveThrottlePartition passes context.Peer straight into ApiKeyThrottlePartition. In Grpc.AspNetCore that string is ipv4:<address>:<port> (the repo's own test fixtures use ipv4:127.0.0.1:5000), and the port is the client's ephemeral source port. The limiter uses the string verbatim as the partition key and as the _peerKeyIds key. The "address that produced the failures" is therefore really "the TCP connection that produced them". The /metrics handler does it correctly with Connection.RemoteIpAddress (no port), so the two auth surfaces disagree.

Failure scenario. An attacker sends 9 bad secrets for mxgw_operator01_*, closes the channel, opens a new one (new source port) and repeats. No (peer, key id) partition ever reaches ApiKeyFailureLimit (10). The per-address cap of 32 key-id partitions (MaxKeyIdPartitionsPerPeer) is equally per-connection. Junk-shaped tokens land on the peer-only fallback partition, which is also fresh per connection, so junk spraying is never throttled at all (no key id means no aggregate either). Each connection also mints a tracked partition, pushing the map to its cap and forcing the O(n) EvictIfOverCapacity scan on every recorded failure.

Suggested fix. Derive the partition from the remote IP only (context.GetHttpContext().Connection.RemoteIpAddress, or strip the trailing :port from Peer, handling the bracketed ipv6:[..]:port form). Share one helper with MetricsAuthenticationHandler.

Test idea. Interceptor test: 9 failures from ipv4:203.0.113.7:40001, then 9 from ipv4:203.0.113.7:40002; assert the 11th failure overall is ResourceExhausted. Today it is Unauthenticated.


SEC-002 — Aggregate throttle can deny a key to its legitimate holder

  • Severity: High · Category: Bug (availability) · Confidence: Confirmed
  • Location: Security/Authorization/GatewayGrpcAuthorizationInterceptor.cs:125-143; Security/Authorization/ApiKeyFailureLimiter.cs:161-206, 307-325.

Description. failureLimiter.Check runs before apiKeyVerifier.VerifyAsync, so it also runs before CachingApiKeyVerifier's cache lookup. Once a key id's cross-peer aggregate is over ApiKeyFailureAggregateLimit (30 per 60 s), every request presenting that key id from any peer — including the legitimate holder, whose verification is already cached — is refused unless it wins the single probe slot per ApiKeyFailureProbeIntervalSeconds (5 s). The slot goes to whichever request arrives first, and a failed probe re-arms it (RecordInto, lines 319-323). Key ids are not secret (docs/Authorization.md line 99 says so).

Failure scenario. An attacker who knows key id otopcua sends bad secrets from three or more connections (see SEC-001; three source IPs also work). Thirty failures trip the aggregate. The attacker keeps sending at a high rate; the legitimate client at 50 RPC/s wins the 5-second probe only in proportion to its share of arrivals. When it does win, Reset clears the aggregate, and the attacker re-trips it within milliseconds. The legitimate client sees ResourceExhausted on nearly every call for as long as the spray continues. The class remark that the limiter "can never deny a key to the holder of the correct secret" does not hold.

Suggested fix. Let proven-good traffic bypass the valve: consult the verification cache before the limiter (a cache hit costs no store read, which is the only thing the limiter protects), and/or exempt a remote IP that has a recent successful verification for that key id from the aggregate layer. Keep the limiter in front of cache misses only.

Test idea. Prime a successful verification from HolderPeer; record 30 failures for the same key id from other peers; assert the holder's next call (inside the cache TTL and inside the probe interval) succeeds. Today it throws ResourceExhausted.


SEC-003 — A successful RPC wipes the key's cross-peer aggregate

  • Severity: Medium · Category: Bug (security) · Confidence: Confirmed
  • Location: Security/Authorization/GatewayGrpcAuthorizationInterceptor.cs:157; Security/Authorization/ApiKeyFailureLimiter.cs:275-281.

Description. Reset runs on every successful authentication, cache hits included, and unconditionally does _aggregates.TryRemove(partition.KeyId). For a key in steady use the aggregate is deleted many times per second, so it never accumulates.

Failure scenario. otopcua is polled at 20 RPC/s by its real client. A source-rotating sprayer (or a single host, given SEC-001) guesses secrets for the same key id. Each legitimate call deletes the aggregate before it reaches 30. The sprayer is bounded by neither layer, and every guess costs a SQLite read plus the peppered hash (failures are never cached). The aggregate layer only works for idle keys.

Suggested fix. On success, clear only the caller's own (peer, key id) partition. Leave the aggregate to decay by window, combined with the SEC-002 bypass so the holder is not penalised.

Test idea. Interleave one success per failure for the same key id from distinct peers; assert the aggregate still trips after 30 failures.


SEC-004 — Revoke/delete does not end already-open streams

  • Severity: Medium · Category: Bug (security) · Confidence: Confirmed
  • Location: Security/Authorization/GatewayGrpcAuthorizationInterceptor.cs:45-60; Security/Authentication/CachingApiKeyVerifier.cs:313-341; call site Dashboard/DashboardApiKeyManagementService.cs:105-109.

Description. A server-streaming call is authenticated once, at open. Revoke/rotate/delete only evicts the verification cache. Nothing links an open StreamEvents, StreamAlarms or WatchDeployEvents call to its key id, and no code under Sessions/, Grpc/ or Alarms/ reacts to revocation.

Failure scenario. A key is leaked and an admin revokes it on the dashboard. The holder's open StreamAlarms stream (session-less, no lease) keeps delivering the galaxy-wide alarm feed, and an open StreamEvents keeps delivering tag values, until the client disconnects or the gateway restarts. New calls fail as expected, which makes the revoke look complete.

Suggested fix. Keep a per-key-id registry of CancellationTokenSources for open streaming calls (registered in ServerStreamingServerHandler) and cancel them from Invalidate(keyId). Optionally close sessions owned by the key.

Test idea. Open a streaming call through the interceptor with key K, call Invalidate("K"), assert the call's token is cancelled / the stream ends with Unauthenticated.


SEC-005 — Monitor restart silently drops the cache; subscribers keep stale alarms

  • Severity: High · Category: Bug · Confidence: Confirmed
  • Location: Alarms/GatewayAlarmMonitor.cs:330-342 (finally → ClearCache), 1007-1020, 237-245, 884-937.

Description. StreamAsync subscribers deliberately outlive the monitor's worker session. When a lifecycle ends (worker crash, lease overflow, command failure) ClearCache empties _alarms with no Clear broadcast. After the restart the first ApplyReconcile diffs the new snapshot against the empty cache, so it emits only Raise repairs. An alarm that cleared while the monitor was down is in neither set and gets no Clear. Separately, the lifecycle start re-baselines _providerMode/_providerDegraded/_providerReason (lines 237-245) without BroadcastToAll.

Failure scenario. OtOpcUa holds a StreamAlarms stream. Alarm Galaxy!Area.Tank01.HiHi is active. The worker faults; the monitor restarts after 5 s plus worker startup. The alarm returns to normal during that gap. The new reconcile does not contain it, the cache is already empty, and no Clear is ever sent. OtOpcUa shows the alarm active until its own stream reconnects, which may be never. Likewise a subscriber that last saw Subtag / degraded keeps showing degraded after the restart lands back on the alarm manager, because Auto mode raises no mode-change event at start.

Suggested fix. Keep the previous generation for diffing instead of clearing it (hide it from CurrentAlarms while not Monitoring), so the first reconcile of the new lifecycle emits the missing Clears. Alternatively broadcast Clear for every cached alarm in ClearCache. Broadcast the provider status after the re-baseline.

Test idea. Fake session manager: reconcile returns {A, B}; attach a subscriber; end the event stream to force a restart; second lifecycle's reconcile returns {A}. Assert the subscriber receives Clear for B. Second test: assert a ProviderStatus frame after a restart from Subtag.


SEC-006 — Reconcile overwrites newer live state with an older snapshot

  • Severity: Medium · Category: Bug · Confidence: Plausible (ordering race between two independent async paths; not reproduced)
  • Location: Alarms/GatewayAlarmMonitor.cs:413-467 (reconcile loop task), 293-311 (live loop), 884-947.

Description. ReconcileLoopAsync runs concurrently with the live await foreach. ApplyReconcile replaces the cache with the worker's snapshot unconditionally. The snapshot reply and a later live transition travel different gateway paths (command-reply continuation versus pump → lease channel → loop). Nothing orders them, and ApplyReconcile compares no timestamp or sequence against the cached entry. The existing dedup only handles the reverse order (repair first, live duplicate second).

Failure scenario. The worker builds a snapshot without alarm X at t1 and raises X at t2. The live Raise is applied first (cache has X, feed sends Raise). The t1 snapshot is applied next: X is absent, so the monitor broadcasts a synthetic Clear and removes X. Subscribers and QueryActiveAlarms show a genuinely active alarm as cleared until the next pass (30 s by default). The mirror case — a snapshot containing X applied after the live Clear — re-raises a cleared alarm for one interval.

Suggested fix. In ApplyReconcile, skip any entry whose cached LastTransitionTimestamp is newer than the snapshot's, and skip a synthetic Clear for an entry inserted by a live transition after the reconcile command was issued (stamp entries with a monotonic apply counter captured before InvokeAsync). Or run the reconcile on the event loop.

Test idea. Drive ApplyTransition(Raise X, ts=t2) then ApplyReconcile with a snapshot lacking X captured "before"; assert no Clear is broadcast and X stays cached.


SEC-007 — Acknowledge for an uncached alarm creates a phantom active alarm

  • Severity: Medium · Category: Bug · Confidence: Plausible (depends on the worker emitting the transition; Worker/MxAccess/AlarmRecordTransitionMapper.cs:88 maps UnackRtn → AckRtn to Acknowledge)
  • Location: Alarms/GatewayAlarmMonitor.cs:493-506, 1284-1301.

Description. The non-Clear branch of ApplyTransition always does _alarms[reference] = SnapshotFromTransition(transition), and SnapshotFromTransition maps Acknowledge to ActiveAcked without checking that the alarm is cached as active.

Failure scenario. An alarm raises and returns to normal unacknowledged: Clear removes it from the cache. An operator then acknowledges the returned alarm; the worker emits Acknowledge. The monitor inserts it as ActiveAcked. QueryActiveAlarms, new StreamAlarms snapshots and the dashboard list an inactive alarm as active until the next reconcile, which then broadcasts a second, synthetic Clear. The same happens for any Unspecified/Retrigger kind, which fall through as Active.

Suggested fix. For Acknowledge, update the cache only when the reference is already present; still broadcast the transition. Ignore transition kinds other than Raise/Acknowledge/Clear for cache purposes.

Test idea. ApplyTransition(Raise), ApplyTransition(Clear), ApplyTransition(Acknowledge); assert CurrentAlarms is empty.


SEC-008 — Watch-list refresh: uncached SQL and full fingerprint every interval

  • Severity: Medium · Category: Performance · Confidence: Confirmed
  • Location: Alarms/GatewayAlarmMonitor.cs:413-426, 558-562, 611-655, 692-725; Alarms/AlarmWatchListResolver.cs:59-141; library ZB.MOM.WW.GalaxyRepository/GalaxyRepository.cs:118-133 (new SqlConnection + query per call, no cache).

Description. With the defaults (Fallback:Mode=Auto, Discovery:UseGalaxyRepository=true) CanUseSubtagFallback is true, so every reconcile tick (30 s default, 5 s minimum):

  1. runs the Galaxy alarm-attribute SQL query;
  2. allocates one AlarmSubtagTarget plus four to six interpolated strings per alarm attribute;
  3. builds, sorts and joins the canonical fingerprint string over every target.

The acknowledged fingerprint (one string covering the whole watch-list) is also retained for the process lifetime. For a galaxy with tens of thousands of alarm attributes that is several MB of large-object-heap garbage per tick, plus a steady load on the Galaxy SQL Server, to detect a change that only happens on deploy.

ReconcileAsync waits behind the refresh in the same pass, so a slow or hung Galaxy SQL stretches the reconcile cadence by the connect/command timeout. On a failover to Subtag the refresh is awaited inline in the event-consumer loop (line 560), stalling transition processing for the same duration at the moment the feed is degraded.

Suggested fix. Gate re-resolution on the deploy signal the gateway already tracks (last deploy time / hierarchy cache generation), or on a much longer interval. Store a SHA-256 of the fingerprint instead of the string. Run ReconcileAsync regardless of refresh latency (separate timers, or reconcile first). Bound the failover-edge refresh with a short timeout.

Test idea. Counting fake resolver: advance N reconcile ticks with an unchanged deploy time and assert ResolveAsync ran once. Resolver that delays 30 s: assert QueryActiveAlarms is still issued on schedule.


SEC-009 — Reconcile misses a same-state re-raise; non-OK reconcile is silent

  • Severity: Low · Category: Bug · Confidence: Confirmed
  • Location: Alarms/GatewayAlarmMonitor.cs:916-936, 457-460, 273-276.

Description. (a) The repair delta compares CurrentState only. An alarm that cleared and re-raised between passes with both transitions missed, and is unacknowledged both times, has the same state and a new OriginalRaiseTimestamp; no Raise repair is emitted. The cache is updated, so QueryActiveAlarms and the live feed disagree on the instance. Severity and priority changes are dropped the same way. (b) ReconcileAsync returns without logging or setting _lastError when the worker replies non-OK. If that happens on the initial reconcile, the monitor still enters Monitoring with an empty cache.

Failure scenario. After a lease overflow window a consumer holds raise time T0 for an alarm whose current instance was raised at T1, and its "time in alarm" is wrong until the next real transition. A worker that rejects QueryActiveAlarms yields a healthy-looking monitor with zero alarms.

Suggested fix. Also treat a differing OriginalRaiseTimestamp as a Raise repair. Log a warning and surface _lastError on a non-OK reconcile; fail the lifecycle if the initial reconcile is non-OK.

Test idea. Two ApplyReconcile calls with the same reference and state but different OriginalRaiseTimestamp; assert a Raise is broadcast.


SEC-010 — Fixed 5 s restart backoff launches a worker process per attempt

  • Severity: Low · Category: Performance · Confidence: Confirmed
  • Location: Alarms/GatewayAlarmMonitor.cs:24, 171-198, 251-256, 398-405.

Description. Any lifecycle failure restarts after a constant RestartBackoff. Each attempt calls OpenSessionAsync, which launches a new x86 worker with COM initialisation, before SubscribeAlarms can fail. A permanent failure (invalid subscription expression, alarm manager not installed, worker rejecting the command) therefore cycles a worker process roughly every 7 s indefinitely, and logs a warning with a stack trace each time.

Failure scenario. On a host under endpoint security that makes process launch expensive (the vd03 CPU investigation in perf.md), a misconfigured Alarms:SubscriptionExpression produces continuous process churn and log growth, and holds one of MaxSessions slots intermittently.

Suggested fix. Exponential backoff with a cap (for example 5 s → 5 min), reset after a lifecycle reaches Monitoring. Demote repeats of the same error to one summary line.

Test idea. Fake session manager whose InvokeAsync always rejects SubscribeAlarms; with a fake clock assert the gap between OpenSessionAsync calls grows.


SEC-011 — Options validation gaps

  • Severity: Low · Category: Bug · Confidence: Confirmed (missing checks); the downstream throws follow from PeriodicTimer / TimeSpan argument limits
  • Location: Configuration/GatewayOptionsValidator.cs:581-630 (no ReconcileIntervalSeconds check), 465-467; Alarms/GatewayAlarmMonitor.cs:415-439; Sessions/SessionEventDistributor.cs:303.

Description.

  • Alarms:ReconcileIntervalSeconds is never validated. Zero or negative values are silently clamped to 5. A value above about 4,294,967 s exceeds PeriodicTimer's maximum period and throws ArgumentOutOfRangeException inside ReconcileLoopAsync, whose outer try catches only OperationCanceledException. The loop task faults unobserved (it is awaited only in a finally with an empty catch), so reconciliation never runs and nothing is logged.
  • Events:ReplayRetentionSeconds (a double) is only checked >= 0. Infinity or anything above about 9.2e11 passes startup validation and then throws OverflowException from TimeSpan.FromSeconds when the first event distributor is built, so every StreamEvents fails at runtime rather than at startup.

Failure scenario. An operator sets ReconcileIntervalSeconds to a huge number meaning "effectively off". The monitor reports Monitoring, but missed transitions are never repaired and the watch-list is never refreshed.

Suggested fix. Validate ReconcileIntervalSeconds to a sane range (for example 5–86,400) and ReplayRetentionSeconds to finite and at most a day or so. Catch and log non-cancellation exceptions in ReconcileLoopAsync.

Test idea. Validator tests for both bounds; a monitor test asserting a faulted reconcile loop is logged.


SEC-012 — Per-RPC allocations and hashing on the auth cache-hit path

  • Severity: Low · Category: Performance · Confidence: Confirmed
  • Location: Security/Authorization/GatewayGrpcAuthorizationInterceptor.cs:125-159, 238; Security/Authorization/ApiKeyFailureLimiter.cs:305, 418; Security/Authentication/CachingApiKeyVerifier.cs:426-448; Security/Authentication/GatewayApiKeyIdentityMapper.cs:110-117.

Description. A fully cached, successful RPC still performs:

  • TryResolveKeyId: a new key-id string;
  • Composite(peer, keyId): a new concatenated string for a dictionary lookup that normally misses;
  • TryComputeCacheKey: token.ToString(), a UTF-8 byte array, a SHA-256 over the token, a 64-character hex string, and a prefix concatenation;
  • ToGatewayIdentity: a new ApiKeyIdentity record;
  • Reset: two TryRemove calls.

That is about eight allocations (roughly 0.7 KB) plus a hash per call. It is small per call but sits on every unary RPC of the bulk-read path.

Suggested fix. Hash straight from the header span into a stack buffer and key the cache on a struct (or use an alternate span lookup). Cache the mapped gateway ApiKeyIdentity alongside the verification instead of re-mapping. Skip Composite when _partitions is empty. Skip Reset when Check found no tracked state.

Test idea. BenchmarkDotNet or an allocation assertion (GC.GetAllocatedBytesForCurrentThread) around UnaryServerHandler with a warm cache.


SEC-013 — Partial constraint JSON yields null lists

  • Severity: Low · Category: Bug · Confidence: Plausible (needs a blob not written by ApiKeyConstraintSerializer.Serialize, e.g. a hand-edited row or one written by another tool)
  • Location: Security/Authentication/ApiKeyConstraintSerializer.cs:30-38; Security/Authentication/ApiKeyConstraints.cs:3-11, 62-84; Security/Authorization/GatewayBrowseScopeProvider.cs:41-44.

Description. ApiKeyConstraints is a positional record of non-nullable lists, but JsonSerializer.Deserialize leaves any constructor parameter that is absent from the JSON as null. Only DashboardTags normalizes null. HasReadConstraints, HasWriteConstraints and IsEmpty then dereference null. GatewayBrowseScopeProvider returns BrowseSubtrees as-is, and its return type is nullable in the library contract, so a missing browse_subtrees yields null rather than an empty list; how the library treats null was not verified here.

Failure scenario. A row whose constraints are {"read_subtrees":["Area1*"]} authenticates, then every constrained command throws NullReferenceException (surfacing as an internal error) when ReadTagGlobs.Count is evaluated.

Suggested fix. Normalize every list to Array.Empty<string>() after deserialization (or in the record's init accessors) and add a round-trip test for a sparse blob.

Test idea. Deserialize("{\"read_subtrees\":[\"A*\"]}"); assert every list is non-null and HasWriteConstraints does not throw.


SEC-014 — Audit retention sweep is a full scan in the auth database

  • Severity: Low · Category: Performance · Confidence: Confirmed
  • Location: Security/Audit/SqliteCanonicalAuditStore.cs:43-57, 158-176; Security/Audit/AuditDrainService.cs:43-60.

Description. DELETE FROM audit_event WHERE datetime(occurred_at_utc) < datetime($cutoff) wraps the column in a function, and the table has no index on occurred_at_utc. The primary key is a random GUID stored as text. Each sweep (hourly, and once in StartAsync before the host continues starting) scans the whole table and holds SQLite's single write lock for the duration, in the same file the API-key store reads and the last_used write uses.

Failure scenario. A deployment with a constraint-denied-heavy client accumulates millions of audit rows over the 90-day retention. Startup blocks on the scan, and an hourly write-lock pause delays MarkUsed and admin writes.

Suggested fix. The stored value is already a fixed-width ISO-8601 UTC string, so compare it directly (occurred_at_utc < $cutoff) and add an index on occurred_at_utc. Delete in bounded chunks. Run the startup sweep from the background loop instead of StartAsync.

Test idea. EXPLAIN QUERY PLAN assertion that the delete uses the index; a startup test with a slow sink asserting StartAsync does not await the sweep.