fix(flow-debugger): refuse method-entry Live runs for site-scoped users (#55)

Owner decision (b), 2026-11-09. An inbound API method has no site
affinity, so the F2 route-time scope only bounded routed SITE traffic;
the method's central-side effects (Database.*, ExternalSystem,
notifications) still ran for a scoped Deployer. FlowDebugRunner now
refuses FlowDebugRunMethodCommand for a site-scoped caller (site ids,
not Administrator) before the script executes, audits the refusal as a
failed InboundRequest under the operator's name, and raises
SiteScopeViolationException -> ManagementUnauthorized, so the Central
UI and the CLI (same /management command) share the gate.

The page disables the "Inbound API method" entry for scoped Deployers
with the reason (tooltip + inline note), starts them on script entry,
and ignores ?methodId= / a stored method choice. Replay and the
instance-scoped script / value-change Live runs are unchanged. The
route-time scope is kept as defence in depth.

Tests: scoped refused (in- and out-of-scope routing; script never runs,
refusal audited), unscoped/Administrator allowed, scoped Replay allowed,
scoped in-scope value-change Live still runs; bUnit for the disabled
entry, the drill-in, and the unscoped control. Mutation-proven (gate
and UI flag reverted -> 4 red).

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
This commit is contained in:
Joseph Doherty
2026-11-09 22:22:44 -05:00
parent 4624c8db28
commit 63ec45e2e3
11 changed files with 198 additions and 25 deletions
@@ -575,37 +575,74 @@ public class FlowDebugRunnerTests
return sites;
}
/// <summary>Verifies that a site-scoped deployer routing to another site is unauthorized and the inbound row is still written.</summary>
// --- Gitea #55 (owner decision (b)): a site-scoped operator may not Live-run a method at all ---
//
// F2's route-time scope only bounds routed SITE traffic; a method's central-side effects
// (Database.*, ExternalSystem, notifications) have no site to scope against. So a scoped
// operator is refused before the script executes — whether or not it would route in scope.
/// <summary>Verifies that a site-scoped deployer is refused a method Live run, nothing executes, and the refusal is audited.</summary>
/// <param name="routesTo">The site the method would route to — in or out of the operator's scope.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task RunMethod_ScopedDeployer_RouteToOtherSite_IsUnauthorized_AndInboundRowIsWritten()
[Theory]
[InlineData("site-a")] // within scope (id 1 → site-a): still refused, the central effects are unscoped
[InlineData("site-b")] // outside scope
public async Task RunMethod_ScopedDeployer_IsRefused_BeforeTheScriptRuns_AndTheRefusalIsAudited(string routesTo)
{
WireRoutedMethod(11, "inst", "site-b");
WireRoutedMethod(11, "inst", routesTo);
var ran = false;
_executor.RegisterHandler("M", _ => { ran = true; return Task.FromResult<object?>(1); });
var scoped = new AuthenticatedUser("ops", "Ops", new[] { "Deployer" }, new[] { "1" });
await Assert.ThrowsAsync<SiteScopeViolationException>(() => Runner().RunMethodAsync(
var ex = await Assert.ThrowsAsync<SiteScopeViolationException>(() => Runner().RunMethodAsync(
_services.BuildServiceProvider(), new FlowDebugRunMethodCommand(11, null), scoped, CancellationToken.None));
// The site was never contacted...
Assert.Equal(FlowDebugRunner.MethodLiveRefusedMessage(scoped), ex.Message);
Assert.Contains("Replay", ex.Message);
Assert.False(ran, "the method script must not execute for a site-scoped operator");
await _router.DidNotReceiveWithAnyArgs().RouteToCallAsync(default!, default!, default);
// ...but the denied attempt IS recorded against the operator's name.
Assert.Contains(_central, e => e.AsRow().Kind == AuditKind.InboundRequest && e.Actor == "ops");
// The refused attempt IS recorded against the operator's name.
var row = Assert.Single(_central, e => e.AsRow().Kind == AuditKind.InboundRequest);
Assert.Equal("ops", row.Actor);
Assert.Equal(AuditStatus.Failed, row.AsRow().Status);
}
/// <summary>Verifies that a site-scoped deployer routing within its scope runs the method.</summary>
/// <summary>Verifies that a site-scoped deployer can still Replay a method execution.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task RunMethod_ScopedDeployer_RouteWithinScope_Runs()
public async Task Replay_ScopedDeployer_IsAllowed()
{
// The same scoped user, routing to a site their numeric id DOES resolve to.
WireRoutedMethod(12, "inst", "site-a");
var repo = Substitute.For<IAuditLogRepository>();
var root = Guid.NewGuid();
var rows = new[]
{
ScadaBridgeAuditEventFactory.Create(AuditChannel.ApiInbound, AuditKind.InboundRequest, AuditStatus.Delivered, executionId: root),
};
repo.GetTraceEventsAsync(root, Arg.Any<CancellationToken>(), Arg.Is<IReadOnlyList<string>>(s => s.SequenceEqual(new[] { "1" })))
.Returns(new ZB.MOM.WW.ScadaBridge.Commons.Types.Audit.TraceEventBatch(root, rows, false));
_services.AddSingleton(repo);
var scoped = new AuthenticatedUser("ops", "Ops", new[] { "Deployer" }, new[] { "1" });
var result = await Runner().RunMethodAsync(
_services.BuildServiceProvider(), new FlowDebugRunMethodCommand(12, null), scoped, CancellationToken.None);
var result = await Runner().ReplayAsync(_services.BuildServiceProvider(), new FlowDebugReplayCommand(root), CancellationToken.None, scoped);
Assert.True(result.Completed, result.Error);
await _router.ReceivedWithAnyArgs(1).RouteToCallAsync(default!, default!, default);
Assert.Equal(rows, result.Events);
}
/// <summary>Verifies that a site-scoped deployer's value-change Live run on a permitted instance still runs (instance-scoped entry is unchanged by #55).</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task RunValueChange_ScopedDeployer_InScopeSite_StillRuns()
{
var (_, _, puller) = WireValueChange();
puller.PullAsync(default!, default!, default, default, default, default).ReturnsForAnyArgs(Array.Empty<AuditEvent>());
var scoped = new AuthenticatedUser("ops", "Ops", new[] { "Deployer" }, new[] { "2" }); // instance 5 lives on site 2
var result = await Runner().RunValueChangeAsync(_services.BuildServiceProvider(),
new FlowDebugRunValueChangeCommand(5, "Status", "Running", WaitSeconds: 3), scoped, CancellationToken.None);
await _router.ReceivedWithAnyArgs(1).RouteToSetAttributesAsync(default!, default!, default);
Assert.Equal(FlowDebugRunner.NoTriggerCode, result.ErrorCode); // ran to the poll, not refused
}
/// <summary>Verifies that an administrator is never restricted by site scope.</summary>