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 commit is contained in:
@@ -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.
|
||||
- **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).
|
||||
- **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
|
||||
|
||||
@@ -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; 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, 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.
|
||||
|
||||
@@ -625,7 +625,15 @@ public class InboundScriptExecutor
|
||||
_scriptHandlers[method.Name] = cached; // last-write-wins; concurrent first-callers race benignly
|
||||
}
|
||||
|
||||
handlerTask = cached.Handler(context);
|
||||
// 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);
|
||||
var result = await handlerTask.WaitAsync(cts.Token);
|
||||
|
||||
var resultJson = result != null
|
||||
|
||||
@@ -255,7 +255,7 @@ public static class ServiceCollectionExtensions
|
||||
/// asks it for a decision, and applies it to the cookie context:
|
||||
/// <list type="bullet">
|
||||
/// <item><see cref="SessionValidationAction.Reject"/> → <see cref="CookieValidatePrincipalContext.RejectPrincipal"/> + 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).</item>
|
||||
/// <item><see cref="SessionValidationAction.Replace"/> → <see cref="CookieValidatePrincipalContext.ReplacePrincipal"/> + renewal only for non-passive requests (role mapping refreshed).</item>
|
||||
/// <item><see cref="SessionValidationAction.Replace"/> → <see cref="CookieValidatePrincipalContext.ReplacePrincipal"/> + renewal so the refreshed ticket persists, passive requests included (role mapping refreshed).</item>
|
||||
/// <item><see cref="SessionValidationAction.Keep"/> → no-op (no refresh due, or a swallowed refresh fault).</item>
|
||||
/// </list>
|
||||
/// All logic lives in <see cref="CookieSessionValidator.ValidateAsync"/>, which never
|
||||
@@ -302,9 +302,16 @@ 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 persist.
|
||||
// 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).
|
||||
context.ReplacePrincipal(result.Principal);
|
||||
context.ShouldRenew = !IsPassiveSessionRequest(context.HttpContext);
|
||||
context.ShouldRenew = true;
|
||||
break;
|
||||
|
||||
case SessionValidationAction.Keep:
|
||||
|
||||
@@ -1106,6 +1106,40 @@ public class InboundScriptExecutorTests
|
||||
Assert.Equal(0, _executor.AbandonedExecutionCount); // ...and DECREMENTED
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// INB-1: a script that blocks BEFORE its first await (CPU loop, <c>.Result</c> 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.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[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<object?>(1);
|
||||
});
|
||||
var method = new ApiMethod("spin", "unused") { Id = 10, TimeoutSeconds = 1 };
|
||||
|
||||
var started = System.Diagnostics.Stopwatch.StartNew();
|
||||
var execution = _executor.ExecuteAsync(
|
||||
method, new Dictionary<string, object?>(), _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 ---
|
||||
|
||||
/// <summary>Verifies that a traced run emits one ScriptLog row on the trace sink.</summary>
|
||||
|
||||
@@ -586,7 +586,7 @@ public class OnValidatePrincipalAdapterTests
|
||||
}
|
||||
|
||||
private static (CookieValidatePrincipalContext Context, StubAuthenticationService AuthService)
|
||||
BuildContext(ClaimsPrincipal principal)
|
||||
BuildContext(ClaimsPrincipal principal, string path = "/")
|
||||
{
|
||||
var authService = new StubAuthenticationService();
|
||||
|
||||
@@ -596,6 +596,7 @@ public class OnValidatePrincipalAdapterTests
|
||||
var serviceProvider = services.BuildServiceProvider();
|
||||
|
||||
var httpContext = new DefaultHttpContext { RequestServices = serviceProvider };
|
||||
httpContext.Request.Path = path;
|
||||
var ticket = new AuthenticationTicket(
|
||||
principal,
|
||||
new AuthenticationProperties(),
|
||||
@@ -663,6 +664,33 @@ public class OnValidatePrincipalAdapterTests
|
||||
Assert.Equal(0, authService.SignOutCallCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="path">A passive session request path.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[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);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that applying a keep result leaves the context unchanged.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
|
||||
Reference in New Issue
Block a user