From 6019335ba952cb4980c416e9c0ed73f87b6347f2 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 10:01:01 -0500 Subject: [PATCH] Revert "fix(inbound,security): bound the sync prefix of inbound scripts by the method timeout; persist a role refresh done on a passive request (INB-1, SEC-1, WP7 task 7.6)" This reverts commit f7d3c69071adfb8bc8899752a89d93cf4d93f096. --- docs/requirements/Component-InboundAPI.md | 2 +- docs/requirements/Component-Security.md | 2 +- .../InboundScriptExecutor.cs | 10 +----- .../ServiceCollectionExtensions.cs | 13 ++----- .../InboundScriptExecutorTests.cs | 34 ------------------- .../CookieSessionValidatorTests.cs | 30 +--------------- 6 files changed, 7 insertions(+), 84 deletions(-) diff --git a/docs/requirements/Component-InboundAPI.md b/docs/requirements/Component-InboundAPI.md index a8f76882..5585bd03 100644 --- a/docs/requirements/Component-InboundAPI.md +++ b/docs/requirements/Component-InboundAPI.md @@ -69,7 +69,7 @@ Each API method definition includes: - **Return Value Definition**: Structure of the response, with: - Field names and (extended-system) data types. Supports returning **lists of objects** and arbitrarily nested structures. - **Implementation Script**: C# script that executes when the method is called. Stored **inline** in the method definition. Follows standard C# authoring patterns but has no template inheritance — it is a standalone script tied to this method. -- **Timeout**: Configurable per method. Defines the maximum time the method is allowed to execute (including any routed calls to sites) before returning a timeout error to the caller. The script is started on the thread pool (not inline on the request thread), so the timeout also bounds the synchronous prefix of the script — CPU work or a blocking call before its first `await` — and a script that overruns is abandoned and counted exactly like one that blocks later (review INB-1). +- **Timeout**: Configurable per method. Defines the maximum time the method is allowed to execute (including any routed calls to sites) before returning a timeout error to the caller. - **TraceAllCalls** (Flow Debugger, 2026-09-05): when set, every call to this method runs its routed site scripts with the trace flag on, so their `ScriptRun` / `AttributeWrite` / `AttributeWait` audit rows (`AuditChannel.ScriptTrace`) are recorded for Replay. Default off — adds 7–10 audit rows per call (3 of them trace-only; a cached DB write and a notification account for the upper end), so it is meant for low-volume integration methods. Set from the method form's *Trace all calls* checkbox or `api-method create|update --trace-all-calls`. > **Authoring note — idempotent methods for at-least-once callers**: some external callers retry diff --git a/docs/requirements/Component-Security.md b/docs/requirements/Component-Security.md index da4336c7..7e9270a6 100644 --- a/docs/requirements/Component-Security.md +++ b/docs/requirements/Component-Security.md @@ -234,4 +234,4 @@ To blunt online password-spray and brute-force against the directory, every LDAP ### Passive traffic and circuit refresh (2026-09-09) -`/auth/ping`, `/auth/activity`, and Blazor transport validation do not advance inactivity timestamps or trigger sliding renewal. The explicit activity endpoint validates antiforgery before renewing the cookie and recording activity by protected session ID. A bounded process-local tracker lets a live circuit observe successful activity renewal. Role refresh preserves the session ID and activity timestamp, and its rebuilt ticket is persisted even when the refresh happened on a passive request (the refresh anchors advance, so the next ping does not repeat the role re-map / directory query; the ticket still carries the OLD activity timestamp, so persisting it never extends the idle window); current circuit mutation checks re-map stored groups with fail-closed lookup behavior. Display-only auth-state reads reuse the circuit's last revalidation for up to 10 s (review 2026-10-21 07/P-3), so an idle timeout or a revoked grant can show on a read-only surface for at most that long; it never reaches a mutation. +`/auth/ping`, `/auth/activity`, and Blazor transport validation do not advance inactivity timestamps or trigger sliding renewal. The explicit activity endpoint validates antiforgery before renewing the cookie and recording activity by protected session ID. A bounded process-local tracker lets a live circuit observe successful activity renewal. Role refresh preserves the session ID and activity timestamp; current circuit mutation checks re-map stored groups with fail-closed lookup behavior. Display-only auth-state reads reuse the circuit's last revalidation for up to 10 s (review 2026-10-21 07/P-3), so an idle timeout or a revoked grant can show on a read-only surface for at most that long; it never reaches a mutation. diff --git a/src/ZB.MOM.WW.ScadaBridge.InboundAPI/InboundScriptExecutor.cs b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/InboundScriptExecutor.cs index 80c26de8..17a2e45a 100644 --- a/src/ZB.MOM.WW.ScadaBridge.InboundAPI/InboundScriptExecutor.cs +++ b/src/ZB.MOM.WW.ScadaBridge.InboundAPI/InboundScriptExecutor.cs @@ -625,15 +625,7 @@ public class InboundScriptExecutor _scriptHandlers[method.Name] = cached; // last-write-wins; concurrent first-callers race benignly } - // Start the handler OFF the request thread (INB-1). Script.RunAsync runs the script - // synchronously up to its first incomplete await, so invoking the handler inline would - // hold the request thread with no deadline for any script that does CPU work or a - // blocking call before its first await (TimeoutSeconds and client disconnect both - // ignored, no TIMEOUT, abandoned-execution count stuck at 0). Running it on the pool - // lets WaitAsync bound the WHOLE run; a non-cooperative script is then abandoned and - // counted exactly like one that blocks after an await. - var handler = cached.Handler; - handlerTask = Task.Run(() => handler(context), cts.Token); + handlerTask = cached.Handler(context); var result = await handlerTask.WaitAsync(cts.Token); var resultJson = result != null diff --git a/src/ZB.MOM.WW.ScadaBridge.Security/ServiceCollectionExtensions.cs b/src/ZB.MOM.WW.ScadaBridge.Security/ServiceCollectionExtensions.cs index 367149bc..3c2c87c6 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Security/ServiceCollectionExtensions.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Security/ServiceCollectionExtensions.cs @@ -255,7 +255,7 @@ public static class ServiceCollectionExtensions /// asks it for a decision, and applies it to the cookie context: /// /// → + sign out (idle timeout, the directory reports the user gone/disabled/ambiguous/group-less — ScadaBridge#46, or the user's groups now map to no role — ScadaBridge#144). - /// → + renewal so the refreshed ticket persists, passive requests included (role mapping refreshed). + /// → + renewal only for non-passive requests (role mapping refreshed). /// → no-op (no refresh due, or a swallowed refresh fault). /// /// All logic lives in , which never @@ -302,16 +302,9 @@ public static class ServiceCollectionExtensions case SessionValidationAction.Replace when result.Principal is not null: // Role mapping refreshed from stored groups — swap in the rebuilt - // principal and re-issue the cookie so the new claims (and the advanced - // role/group refresh anchors) persist. This holds for passive requests too - // (SEC-1): without it the refreshed anchors were thrown away, the next ping - // arrived with the old ones and repeated the role re-map / LDAP re-query on every - // keep-alive. A passive request's rebuilt principal keeps the OLD LastActivity - // claim (CookieSessionValidator, recordActivity: false), so persisting it never - // extends the idle window; the sliding renewal of an UNCHANGED principal stays - // suppressed for passive requests (OnCheckSlidingExpiration above). + // principal and re-issue the cookie so the new claims persist. context.ReplacePrincipal(result.Principal); - context.ShouldRenew = true; + context.ShouldRenew = !IsPassiveSessionRequest(context.HttpContext); break; case SessionValidationAction.Keep: diff --git a/tests/ZB.MOM.WW.ScadaBridge.InboundAPI.Tests/InboundScriptExecutorTests.cs b/tests/ZB.MOM.WW.ScadaBridge.InboundAPI.Tests/InboundScriptExecutorTests.cs index 27d22c0f..0d8a701c 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.InboundAPI.Tests/InboundScriptExecutorTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.InboundAPI.Tests/InboundScriptExecutorTests.cs @@ -1106,40 +1106,6 @@ public class InboundScriptExecutorTests Assert.Equal(0, _executor.AbandonedExecutionCount); // ...and DECREMENTED } - /// - /// INB-1: a script that blocks BEFORE its first await (CPU loop, .Result on a helper) used to - /// run inline on the request thread, so the method timeout could not fire until it returned. The - /// request must come back with TIMEOUT at the deadline and the orphan must be counted. - /// - /// A task that represents the asynchronous operation. - [Fact] - public async Task ScriptBlockingBeforeFirstAwait_StillTimesOutAtTheDeadline() - { - var release = new ManualResetEventSlim(); - _executor.RegisterHandler("spin", _ => - { - release.Wait(TimeSpan.FromSeconds(30)); // synchronous block: no await has happened yet - return Task.FromResult(1); - }); - var method = new ApiMethod("spin", "unused") { Id = 10, TimeoutSeconds = 1 }; - - var started = System.Diagnostics.Stopwatch.StartNew(); - var execution = _executor.ExecuteAsync( - method, new Dictionary(), _route, TimeSpan.FromMilliseconds(200)); - var finished = await Task.WhenAny(execution, Task.Delay(TimeSpan.FromSeconds(10))); - - Assert.Same(execution, finished); // pre-fix: the call itself never returned until released - var result = await execution; - Assert.False(result.Success); - Assert.Equal("TIMEOUT", result.ErrorCode); - Assert.True(started.Elapsed < TimeSpan.FromSeconds(5), $"took {started.Elapsed}"); - Assert.Equal(1, _executor.AbandonedExecutionCount); - - release.Set(); // the orphan finishes; its continuation cleans up - await Task.Delay(300); - Assert.Equal(0, _executor.AbandonedExecutionCount); - } - // --- Flow Debugger step logs (design 2026-09-09 D4/D5/D7): the Log global --- /// Verifies that a traced run emits one ScriptLog row on the trace sink. diff --git a/tests/ZB.MOM.WW.ScadaBridge.Security.Tests/CookieSessionValidatorTests.cs b/tests/ZB.MOM.WW.ScadaBridge.Security.Tests/CookieSessionValidatorTests.cs index 6dfdb2ec..f79c4400 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.Security.Tests/CookieSessionValidatorTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.Security.Tests/CookieSessionValidatorTests.cs @@ -586,7 +586,7 @@ public class OnValidatePrincipalAdapterTests } private static (CookieValidatePrincipalContext Context, StubAuthenticationService AuthService) - BuildContext(ClaimsPrincipal principal, string path = "/") + BuildContext(ClaimsPrincipal principal) { var authService = new StubAuthenticationService(); @@ -596,7 +596,6 @@ public class OnValidatePrincipalAdapterTests var serviceProvider = services.BuildServiceProvider(); var httpContext = new DefaultHttpContext { RequestServices = serviceProvider }; - httpContext.Request.Path = path; var ticket = new AuthenticationTicket( principal, new AuthenticationProperties(), @@ -664,33 +663,6 @@ public class OnValidatePrincipalAdapterTests Assert.Equal(0, authService.SignOutCallCount); } - /// - /// SEC-1: a role refresh done on a passive request (keep-alive ping, Blazor transport) must be - /// persisted, otherwise the old anchors come back on the next ping and the refresh repeats on every - /// one. The principal built for a passive request keeps the OLD LastActivity claim (recordActivity - /// false), so re-issuing the ticket does not extend the idle window. - /// - /// A passive session request path. - /// A task that represents the asynchronous operation. - [Theory] - [InlineData("/auth/ping")] - [InlineData("/auth/activity")] - [InlineData("/_blazor")] - public async Task ApplyResult_Replace_OnPassiveRequest_StillPersistsTheRefreshedTicket(string path) - { - var newPrincipal = SessionClaimBuilder.Build( - "alice", "Alice", - ["SCADA-Admins"], - new RoleMappingResult([Roles.Viewer], [], false), - AdapterStart.AddMinutes(16)); - var (ctx, _) = BuildContext(AuthenticatedPrincipal(), path); - - await ServiceCollectionExtensions.ApplyValidationResultAsync(ctx, SessionValidationResult.Replace(newPrincipal)); - - Assert.Same(newPrincipal, ctx.Principal); - Assert.True(ctx.ShouldRenew); - } - /// Verifies that applying a keep result leaves the context unchanged. /// A task that represents the asynchronous operation. [Fact]