feat(alarms): structural degraded-status signal for truncated alarm snapshots
The truncation-cliff fix made alarm transitions truncation-safe but silent:
when GetXmlCurrentAlarms2 returns exactly maxAlmCnt records the worker
suppresses absence-implies-Clear inference and says so only in a rate-limited
stderr warning. No client and no operator could tell a complete active set
from a capped one.
Two additive proto3 booleans carry the verdict out:
- QueryActiveAlarmsReplyPayload.snapshot_truncated = 2 (worker IPC reply)
- ActiveAlarmSnapshot.from_truncated_snapshot = 16 (per record)
The per-record field is not an aesthetic choice. QueryActiveAlarms returns a
bare `stream ActiveAlarmSnapshot` with no envelope, header, or trailer, so a
per-record boolean is the only carrier that stays wire-compatible; an envelope
message would change every existing client's stream element type. The reply
payload states it too because a prefix filter can leave zero records and a
truncated fetch with nothing to report still has to say so. The flag means
"this set may be incomplete", never "this record is unreliable" — it is
independent of the subtag-fallback `degraded` field.
Detection is deliberately UNCHANGED: IsTruncatedFetch remains
`fetchedRecordCount >= maxAlarmsPerFetch`. The live probe (docs/AlarmProbeFindings.md,
ce5d8ae) could not verify whether ALARM_RECORDS/@COUNT reports the total active
count or only the records in the reply, so @COUNT is not parsed for detection;
switching to it stays blocked on probe evidence. The probe's comment
annotations in WnWrapAlarmConsumer.cs are preserved.
Reset semantics: not latched. WnWrapAlarmConsumer.FoldFetch replaces the
verdict on every poll under the same lock as the snapshot merge, so the first
sub-cap fetch clears it; GatewayAlarmMonitor.ClearCache drops it with the cache
generation it describes. A caveat that never turns off is one operators learn
to ignore.
Flow: WnWrapAlarmConsumer.LastSnapshotTruncated -> AlarmDispatcher (stamps every
record) / IAlarmCommandHandler (payload) -> MxAccessCommandExecutor reply ->
GatewayAlarmMonitor._snapshotTruncated -> IGatewayAlarmService.SnapshotTruncated
-> DashboardAlarmQueryResult -> AlarmsPage warning banner (render-side only; the
poll loop and DisposeAsync drain are untouched). The public QueryActiveAlarms
RPC forwards worker snapshots unmodified, so the per-record flag needed no
mapper change — a test pins that.
Parity: this describes OUR fetch mechanics — additive gateway metadata — not
MXAccess provider behavior. No event is synthesized and no MXAccess-observable
semantics change, so it is not a parity deviation.
Tests: worker LastSnapshotTruncated set/reset/consecutive-burst (windev-run);
gateway end-to-end truncated reply -> monitor -> public stream, with the
complete-reply control as the load-bearing assertion; AlarmsPage banner
present/absent. Docs: gateway.md alarm surface, docs/DesignDecisions.md entry.
This commit is contained in:
@@ -2,14 +2,16 @@ using System.Security.Claims;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text.Json;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
using Microsoft.Extensions.Options;
|
||||
using ZB.MOM.WW.MxGateway.Server.Configuration;
|
||||
|
||||
namespace ZB.MOM.WW.MxGateway.Server.Dashboard;
|
||||
|
||||
/// <summary>
|
||||
/// Mints and validates short-lived bearer tokens for SignalR hub connections.
|
||||
/// The token is a data-protected JSON payload containing the user's name and
|
||||
/// role claims. Validity is enforced by the data-protection time-limited
|
||||
/// protector; no separate signing keys are configured.
|
||||
/// The token is a data-protected JSON payload containing the user's name, role
|
||||
/// claims, and granted dashboard visibility tags. Validity is enforced by the
|
||||
/// data-protection time-limited protector; no separate signing keys are configured.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This service is registered as a singleton in
|
||||
@@ -32,24 +34,33 @@ public sealed class HubTokenService
|
||||
// Hub bearer tokens are single-purpose, data-protection-encrypted, and NOT server-side
|
||||
// revocable. A short lifetime bounds the exposure window of a token captured from a proxy
|
||||
// or log after logout (the cookie is cleared on logout, but outstanding tokens are not), and
|
||||
// bounds how long a stale role set survives a role change. Five minutes is transparent to
|
||||
// clients that re-fetch from /hubs/token on every (re)connect, which is what a remote hub
|
||||
// consumer is expected to do; see docs/GatewayDashboardDesign.md. Heavier jti-denylist
|
||||
// revocation is deliberately deferred until per-session hub ACLs land, when tokens gain
|
||||
// session binding.
|
||||
// bounds how long a stale role set survives a role change. It now bounds a stale *tag* grant
|
||||
// the same way (SEC-25): the token carries the tags resolved from the caller's LDAP groups at
|
||||
// mint time, so revoking a GroupToTag entry takes effect for token-authenticated hub
|
||||
// connections within one lifetime — the natural place the deferred "tokens gain session
|
||||
// binding" note landed. Five minutes is transparent to clients that re-fetch from /hubs/token
|
||||
// on every (re)connect, which is what a remote hub consumer is expected to do; see
|
||||
// docs/GatewayDashboardDesign.md. Heavier jti-denylist revocation stays deferred.
|
||||
internal static readonly TimeSpan TokenLifetime = TimeSpan.FromMinutes(5);
|
||||
|
||||
private readonly ITimeLimitedDataProtector _protector;
|
||||
private readonly IOptions<GatewayOptions> _options;
|
||||
|
||||
/// <summary>Initializes a new instance of the HubTokenService with a data protection provider.</summary>
|
||||
/// <param name="dataProtection">The data protection provider for token encryption.</param>
|
||||
public HubTokenService(IDataProtectionProvider dataProtection)
|
||||
/// <param name="options">
|
||||
/// Gateway options supplying <c>MxGateway:Dashboard:GroupToTag</c>, the map used to resolve the
|
||||
/// caller's granted visibility tags at mint time.
|
||||
/// </param>
|
||||
public HubTokenService(IDataProtectionProvider dataProtection, IOptions<GatewayOptions> options)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(dataProtection);
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
_protector = dataProtection.CreateProtector(ProtectorPurpose).ToTimeLimitedDataProtector();
|
||||
_options = options;
|
||||
}
|
||||
|
||||
/// <summary>Issues a bearer token carrying the user's identity and roles.</summary>
|
||||
/// <summary>Issues a bearer token carrying the user's identity, roles, and granted tags.</summary>
|
||||
/// <param name="user">The claims principal representing the user.</param>
|
||||
/// <returns>The data-protected bearer token string.</returns>
|
||||
public string Issue(ClaimsPrincipal user) => Issue(user, TokenLifetime);
|
||||
@@ -65,10 +76,20 @@ public sealed class HubTokenService
|
||||
internal string Issue(ClaimsPrincipal user, TimeSpan lifetime)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(user);
|
||||
|
||||
// Resolved from the caller's LDAP-group claims rather than copied from any tag claims the
|
||||
// principal already carries: re-resolving is what makes the 5-minute lifetime an actual
|
||||
// staleness bound on the grant. Tags are stamped for every caller — an Administrator
|
||||
// bypasses the ACL, so theirs are simply moot rather than a special case here.
|
||||
IReadOnlySet<string> grantedTags = DashboardGroupTagMapping.MapGroupsToTags(
|
||||
user.FindAll(DashboardAuthenticationDefaults.LdapGroupClaimType).Select(c => c.Value),
|
||||
_options.Value.Dashboard.GroupToTag);
|
||||
|
||||
HubTokenPayload payload = new(
|
||||
user.Identity?.Name,
|
||||
user.FindFirstValue(ClaimTypes.NameIdentifier),
|
||||
[.. user.FindAll(ClaimTypes.Role).Select(c => c.Value)]);
|
||||
[.. user.FindAll(ClaimTypes.Role).Select(c => c.Value)],
|
||||
[.. grantedTags]);
|
||||
return _protector.Protect(JsonSerializer.Serialize(payload), lifetime);
|
||||
}
|
||||
|
||||
@@ -107,6 +128,12 @@ public sealed class HubTokenService
|
||||
}
|
||||
|
||||
claims.AddRange((payload.Roles ?? []).Select(r => new Claim(ClaimTypes.Role, r)));
|
||||
// Rehydrated alongside the roles so the reconstructed principal is what
|
||||
// IDashboardSessionAcl reads on the hub path — a token minted before the tag field
|
||||
// existed (or by a caller with no grant) simply yields an empty grant, which denies.
|
||||
claims.AddRange((payload.Tags ?? []).Select(t => new Claim(
|
||||
DashboardAuthenticationDefaults.DashboardTagClaimType,
|
||||
t)));
|
||||
|
||||
ClaimsIdentity identity = new(
|
||||
claims,
|
||||
@@ -121,5 +148,5 @@ public sealed class HubTokenService
|
||||
}
|
||||
}
|
||||
|
||||
private sealed record HubTokenPayload(string? Name, string? NameIdentifier, string[]? Roles);
|
||||
private sealed record HubTokenPayload(string? Name, string? NameIdentifier, string[]? Roles, string[]? Tags);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user