Skip to content

fix(runtime): guard and attribute remote destructive closes - #8888

Closed
bbingz wants to merge 6 commits into
stablyai:mainfrom
bbingz:fix/session-close-kill-attribution
Closed

bbingz wants to merge 6 commits into
stablyai:mainfrom
bbingz:fix/session-close-kill-attribution

Conversation

@bbingz

@bbingz bbingz commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Refs #8871. This is the host-side defense-in-depth companion to #8872.

  • soft-deny session.tabs.close, terminal.close, and terminal.closeTab when a paired desktop/runtime client omits explicit close intent; the RPC succeeds but no host tab or PTY is destroyed
  • validate the intent source and target, deduplicate request ids across reconnects, rate-limit destructive actions per paired device, and reject lifecycle/mirror-only sources
  • permit client-created-rollback only for a terminal created by the same connection within a short ownership window
  • preserve legacy mobile, local CLI, automation, SSH, and in-process close behavior
  • retain recent subscription evidence and persist allowed/blocked close decisions with device, connection, target, source, and reason
  • include the requesting local daemon-control client id in session-killed logs
  • never log the paired device bearer token

Screenshots

No visual change.

Testing

  • pnpm lint — exact changed-file oxlint and repository pre-commit lint/React Doctor checks pass; max-lines ratchet passes; remaining full verify chain deferred to CI
  • pnpm typecheck — node, CLI, and web tsconfigs pass
  • pnpm test — focused RPC/runtime/daemon/CLI suites pass (7 files / 112 tests); final policy, attribution, and daemon rerun passes (3 files / 42 tests)
  • pnpm build — not run locally; deferred to CI
  • Added or updated high-quality tests that would catch regressions

The failing-first tests proved that a legacy runtime client still invoked all three destructive methods before this patch. Coverage now includes explicit user closes, target mismatch, schema rejection, duplicate ids across reconnects, same-connection rollback ownership, forged rollback, per-device rate limiting, recent-attach evidence, lifecycle-only intent, mobile compatibility, attribution success/failure, token exclusion, and daemon requester logging.

AI Review Report

The review traced the destructive call chain from authenticated WebSocket context through dispatcher schemas, runtime tab/terminal handlers, PTY controller shutdown, and daemon logging. It rejected the initial attribution-only design because it diagnosed the next incident but did not stop it. It also rejected using client wall-clock age as an authorization gate: macOS, Linux, Windows, WSL, and SSH hosts can have clock skew, so replay protection uses device-scoped request-id dedupe instead.

The final policy is default-deny only for paired desktop/runtime clients. Mobile and in-process callers retain the established contract. The client-created rollback exception is connection-scoped and consumed once. Bulk closes have a high enough rate ceiling for normal UI use, while repeated destructive RPCs remain bounded.

Cross-platform review found no shortcut, label, shell, path-separator, Git, or platform-specific API changes. The policy and intent are transport-neutral JSON and apply equally to macOS, Linux, Windows, WSL, and SSH-backed runtime hosts.

Security Audit

Close intent is not an authentication credential and does not elevate a client; the existing paired-device scope remains the trust boundary. The intent only distinguishes an explicit destructive action from lifecycle/reconciliation noise. Untrusted fields are bounded and parsed with Zod, targets must match the RPC, duplicate ids are suppressed per device, and rollback ownership is tied to the creating connection.

RpcContext.clientId contains the E2EE bearer token and is never read by the attribution path. Only the non-sensitive deviceId is persisted, with a regression test searching the complete serialized trace. The daemon-side client id names a local control connection, not a paired-device credential. No command execution, filesystem path, dependency, secret, or auth mechanism changed.

Notes

Older runtime clients will receive a successful no-op for destructive close requests until upgraded to a client that sends intent (#8872). This intentionally favors preserving host processes over honoring ambiguous legacy close requests. Mobile and local CLI behavior is unchanged.

ELI5

Remote clients could close host tabs or terminals without clear user intent, which is dangerous. Destructive closes now require validated intent, rate limits, and source checks on the host.

@coderabbitai

coderabbitai Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 5a99f6e3-4d7c-4fcf-9e6e-35c48e76269a

📥 Commits

Reviewing files that changed from the base of the PR and between d01308b3a73ca5d557d25d49cd10abb7a70a970c and b13235211c8df37c612215a46c76ba8d0c70c189.

📒 Files selected for processing (2)
  • src/main/runtime/rpc/methods/terminal.ts
  • src/main/runtime/rpc/terminal-multiplex.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/runtime/rpc/terminal-multiplex.test.ts
  • src/main/runtime/rpc/methods/terminal.ts

📝 Walkthrough

Walkthrough

Adds runtime close intent schemas, an in-memory authorization policy, decision-based terminal and session-tab teardown, attachment and creation tracking, and persisted close attribution spans. RPC dispatch now forwards device identity and the shared policy to handlers. Tests cover allowed and blocked closes, malformed or mismatched intents, replay detection, rollback ownership, rate limiting, lifecycle sources, tracing outcomes, token redaction, and local identity fallbacks. Daemon session-killed logs now include the requesting control client identifier.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 11.76% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed It clearly summarizes the main change: guarding and attributing destructive runtime closes.
Description check ✅ Passed All required template sections are present and substantively filled, including testing, review, security, and notes.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@AmethystLiang
AmethystLiang requested a review from Jinwoo-H July 15, 2026 16:47
@bbingz
bbingz force-pushed the fix/session-close-kill-attribution branch from 774cd39 to 811c765 Compare July 16, 2026 14:47
@bbingz bbingz changed the title fix(runtime): record client identity on session.tabs.close and daemon kills fix(runtime): guard and attribute remote destructive closes Jul 16, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 93b0880d-936a-4472-8bb6-1b8f6e3a019b

📥 Commits

Reviewing files that changed from the base of the PR and between 774cd39fb608ae5fbce71f4c4951be8b66721d5b and 811c765b4b7c1caa463435997125aa23184f2126.

📒 Files selected for processing (13)
  • src/main/daemon/daemon-server.test.ts
  • src/main/daemon/daemon-server.ts
  • src/main/runtime/rpc/core.ts
  • src/main/runtime/rpc/dispatcher.ts
  • src/main/runtime/rpc/methods/session-tabs-schemas.ts
  • src/main/runtime/rpc/methods/session-tabs.ts
  • src/main/runtime/rpc/methods/terminal.ts
  • src/main/runtime/rpc/runtime-close-attribution.ts
  • src/main/runtime/rpc/runtime-close-intent-schema.ts
  • src/main/runtime/rpc/runtime-close-policy.ts
  • src/main/runtime/rpc/runtime-terminal-close-policy.test.ts
  • src/main/runtime/rpc/session-close-attribution.test.ts
  • src/main/runtime/runtime-rpc.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/main/daemon/daemon-server.test.ts
  • src/main/runtime/runtime-rpc.ts
  • src/main/runtime/rpc/core.ts

@bbingz

bbingz commented Jul 16, 2026

Copy link
Copy Markdown
Contributor Author

Follow-up d01308b3a addresses all three actionable review findings:

  • records worktrees first observed through later session.tabs.subscribeAll updates
  • records terminal attachment evidence only after a usable live stream is established, with negative abort/scrollback-only coverage and positive multiplex coverage
  • replaces global live-entry eviction with actor-partitioned TTL maps that fail closed at per-actor capacity without weakening another device's replay or rollback protection

Verification after the follow-up: 10 related test files / 161 tests passed; full node/CLI/web typecheck passed; exact changed-file oxlint passed; max-lines ratchet passed; git diff --check passed.

The remaining CodeRabbit docstring-coverage item is a non-blocking style warning rather than a functional finding. I kept the repository convention of a concise Why: comment on the non-obvious actor-capacity boundary instead of adding boilerplate docstrings to private/internal helpers.

@bbingz

bbingz commented Jul 22, 2026

Copy link
Copy Markdown
Contributor Author

@Jinwoo-H Rebased onto current origin/main and force-pushed (fix/session-close-kill-attribution → 5a32f0e378). Companion to #8872.

Conflict resolution notes:

  • Kept main's pairedDeviceId navigation identity while also wiring the PR's non-sensitive deviceId for close/kill attribution spans (same value on the WebSocket path; never logs the bearer clientId).
  • Adopted the PR close-intent policy (RuntimeClosePolicy + blocked decisions + deferred attachment recording after successful subscribe) on top of main's newer RPC structure (dedupeTerminalCreate, focus navigation, multiplex subscribe flow).

@bbingz

bbingz commented Jul 22, 2026

Copy link
Copy Markdown
Contributor Author

@Jinwoo-H Rebased onto current main (head 5a32f0e378) as the host-side companion to mergeable #8872. Close-intent policy + attribution preserved on main’s current RPC/pairedDeviceId shape.

Ready for re-review alongside #8872.

@AmethystLiang AmethystLiang added the orca-remote-server Remote Orca Server / orca serve / paired remote runtime label Jul 22, 2026
@AmethystLiang

Copy link
Copy Markdown
Contributor

Associating this PR with related issue(s): #8871

@AmethystLiang

Copy link
Copy Markdown
Contributor

Related to #9952 (sessions vanishing over remote Orca link).

@AmethystLiang

Copy link
Copy Markdown
Contributor

Associating this PR with related issue(s): #8871

@bbingz

bbingz commented Jul 23, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto current origin/main (7a422712b1).

Integration notes (vs pre-rebase shape):

  • main now splits session.tabs.close / session.tabs.closeLifecycle with missing-intent refuse for unattributed in-process callers
  • this PR's RuntimeClosePolicy + attribution now lives in session-tab-close-methods.ts (user close path) and terminal close/closeTab, without collapsing the lifecycle method
  • CloseTab accepts both reason: 'user' and optional closeIntent
  • focused RPC policy/attribution/session-tabs tests: 56/56 green

ahead=4 behind=0.

@bbingz

bbingz commented Jul 23, 2026

Copy link
Copy Markdown
Contributor Author

Coordination note (close / kill cluster)

Related open PRs share the destructive-close surface. Do not add a third confirm modal here.

PR Layer
#10013 Attribution + orphan-sweep confirm gate
#8467 Resource Manager idle-shell review before unbound cleanup
#8888 (this) Protocol soft-deny / rate-limit / audit for unattributed session.tabs.close / terminal close — policy only
#9752 Windows Job Objects after authorized kill
#8872 Closed — tab closeLifecycle superseded by #9804/#9687

This PR should remain host-side policy (soft-deny + rate limit + durable allow/block audit), not a second Resource Manager confirm UX.

Restacked onto latest main when clean; residual unique vs main is the RuntimeClosePolicy / soft-deny layer (not on main’s #9804 liveness path).

@bbingz
bbingz force-pushed the fix/session-close-kill-attribution branch from f41134e to c23c384 Compare July 23, 2026 03:26
bbingz added a commit to bbingz/orca that referenced this pull request Jul 23, 2026
… split

Keep main's close/closeLifecycle method split and missing-intent refuse
gate while applying stablyai#8888's RuntimeClosePolicy + attribution to user
closes and terminal close/closeTab. Update tests for reason:user wiring,
runtime soft-deny, and dedupeTerminalCreate create stubs.
@bbingz
bbingz force-pushed the fix/session-close-kill-attribution branch from c23c384 to f55c031 Compare July 23, 2026 07:06
@bbingz

bbingz commented Jul 23, 2026

Copy link
Copy Markdown
Contributor Author

Re-restack note

Rebased onto latest main after DIRTY (main advanced). Conflicts resolved:

  • Kept main’s multiplex flow-control stream limits + round-robin
  • Kept close-policy soft-deny / attribution
  • recordAttachedTarget stays after stream is live (preserve-evidence commit), not at subscribe start

Coordination unchanged: policy layer only — no third confirm modal vs #10013/#8467.

Ready for upstream review; community author cannot merge.

@nwparker nwparker added the bug Something isn't working label Jul 27, 2026
@bbingz
bbingz force-pushed the fix/session-close-kill-attribution branch from f55c031 to a6e4cd1 Compare July 28, 2026 01:23
@bbingz
bbingz force-pushed the fix/session-close-kill-attribution branch from a6e4cd1 to 87a1a84 Compare July 28, 2026 01:46
bbingz added a commit to bbingz/orca that referenced this pull request Jul 28, 2026
… split

Keep main's close/closeLifecycle method split and missing-intent refuse
gate while applying stablyai#8888's RuntimeClosePolicy + attribution to user
closes and terminal close/closeTab. Update tests for reason:user wiring,
runtime soft-deny, and dedupeTerminalCreate create stubs.
bbingz added 5 commits July 30, 2026 10:03
… split

Keep main's close/closeLifecycle method split and missing-intent refuse
gate while applying stablyai#8888's RuntimeClosePolicy + attribution to user
closes and terminal close/closeTab. Update tests for reason:user wiring,
runtime soft-deny, and dedupeTerminalCreate create stubs.
@bbingz
bbingz force-pushed the fix/session-close-kill-attribution branch from 87a1a84 to 5ddee4f Compare July 30, 2026 02:06
@greptile-apps

greptile-apps Bot commented Jul 30, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR adds host-side defense-in-depth against remote destructive closes on session.tabs.close, terminal.close, and terminal.closeTab. Paired desktop/runtime clients now require a validated RuntimeCloseIntent or the RPC succeeds but the PTY is not destroyed (soft-deny). Attribution spans capture device, connection, target, and decision for every close attempt without exposing the bearer token.

  • Introduces RuntimeClosePolicy — a per-dispatcher singleton that deduplicates request IDs per device, rate-limits destructive closes, and grants a connection-scoped rollback token only for terminals the same connection created within a 30-second window.
  • Updates all client-side close sites (web-runtime-session, remote-runtime-pty-transport, retire-unowned-background-terminal, terminals.ts) to mint and attach structured closeIntent objects so previously-unguarded closes now carry verifiable intent through the upgraded host.
  • Preserves legacy mobile, in-process, local CLI, and SSH close behavior; older runtime clients receive a successful no-op envelope until upgraded.

Confidence Score: 5/5

The close-intent policy is sound and all destructive code paths are covered. The change is safe to merge.

The policy logic is correct across all client kinds: runtime clients require validated intent, mobile and in-process callers retain their established contracts, and rollback tokens are correctly scoped to the creating connection and consumed on first use. All call sites that invoke retireProvider now pass an owner; the type-level optional is defensive API flexibility rather than a live gap. The widening of RuntimeMobileSessionTabCloseResult.closed from literal true to boolean is handled consistently on both the host and all client-side resync paths. The two observations flagged are a documentation nuance and a minor requestId retention asymmetry — neither affects correctness or security.

Files Needing Attention: No files require special attention before merging. The schema file would benefit from inline comments clarifying which fields are required per target kind, but this is cosmetic.

Important Files Changed

Filename Overview
src/main/runtime/rpc/runtime-close-policy.ts New core policy class — deduplication, rate limiting, rollback ownership, and attachment evidence all work correctly; minor inconsistency with requestId not being released on userInitiated=false mismatch unlike the rate-limit path.
src/main/runtime/rpc/runtime-close-intent-schema.ts New Zod schema for close intent; hostTabId and ptyOrHandle are marked optional but policy silently rejects their absence as a target mismatch rather than a schema validation error.
src/main/runtime/rpc/methods/session-tab-close-methods.ts Rewrites session.tabs.close to route through RuntimeClosePolicy for runtime clients; in-process refusal and legacy-mobile paths preserved correctly; attribution spans are consistent.
src/main/runtime/rpc/methods/terminal.ts Adds closeIntent gating to terminal.close and terminal.closeTab; terminal.create and agent-session creates now record rollback ownership; multiplex/subscribe attach-target recording is gated behind the live-stream check.
src/main/runtime/rpc/runtime-close-attribution.ts New attribution helper wrapping withSpan; correctly emits deviceId (not clientId/bearer token), target kind, decision, and intent source for every close attempt.
src/renderer/src/runtime/web-runtime-session.ts Mints user-tab-close and user-pane-close intents for all runtime close calls; adds owningWorktreeId lookup guard and resync-on-denial flow for both session-tab and terminal closes.
src/renderer/src/lib/retire-unowned-background-terminal.ts Adds mintClientCreatedRollbackIntent and passes it to all retireProvider callers; owner is now required at all call sites; soft-denial is surfaced as a warning.
src/shared/runtime-types.ts Widens RuntimeMobileSessionTabCloseResult.closed from literal true to boolean and adds blockedReason; adds blockedReason to RuntimeTerminalClose for soft-denial signaling.

Sequence Diagram

sequenceDiagram
    participant C as Runtime Client
    participant D as RpcDispatcher
    participant P as RuntimeClosePolicy
    participant R as OrcaRuntimeService

    C->>D: session.tabs.close / terminal.close / terminal.closeTab
    note over D: Attach runtimeClosePolicy from dispatcher
    D->>P: evaluate(ctx, target, closeIntent?)
    alt "clientKind !== runtime"
        P-->>D: "allowed=true, reason=legacy-client"
    else no closeIntent
        P-->>D: "allowed=false, reason=close_intent_required"
    else target mismatch
        P-->>D: "allowed=false, reason=close_intent_mismatch"
    else duplicate requestId
        P-->>D: "allowed=false, reason=close_intent_duplicate"
    else "user source + userInitiated=true"
        P->>P: consumeRateSlot(deviceActor)
        alt rate limit hit
            P-->>D: "allowed=false, reason=close_rate_limited"
        else
            P-->>D: "allowed=true, reason=explicit-user"
        end
    else client-created-rollback + terminal kind
        P->>P: check createdTerminalHandles[connectionActor]
        alt owned + within TTL
            P-->>D: "allowed=true, reason=owned-rollback"
        else
            P-->>D: "allowed=false, reason=close_rollback_not_owned"
        end
    else lifecycle or mirror source
        P-->>D: "allowed=false, reason=close_source_not_allowed"
    end
    D->>D: recordRuntimeCloseAttribution(span)
    alt decision.allowed
        D->>R: closeMobileSessionTab / closeTerminal
        R-->>D: "ptyKilled=true"
    else
        D-->>C: "ptyKilled=false, blockedReason"
    end
    C-->>C: "if ptyKilled !== true, warn and resync snapshot"
Loading

Reviews (2): Last reviewed commit: "fix(runtime): tighten close policy state" | Re-trigger Greptile

@nwparker nwparker added the pending_repro Repro attempted; still pending conclusive reproduction label Aug 3, 2026
@nwparker

nwparker commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

Closing as already fixed on main

Thanks for this, @bbingz — and sorry it sat so long. The incident it targets (#8871) has since been fixed on main, so there's no longer a bug here for this PR to land against. #8871 was closed on the same basis.

Verified on current main (not just read — the suites were run):

  1. Renderer leg. closeTerminalTab now early-returns for the mirror echo before any host call — src/renderer/src/components/terminal/terminal-tab-actions.ts:103-107:

    if (options?.reason === 'pty-exit') {
      // Why: stream exit is not host-tab closure; the HUB snapshot decides whether reconnect restores or removes this tab.
      return
    }

    This landed in fix(runtime): route HUB-owned SSH worktrees through owning runtime #9994 (41751dd90d). The regression test your issue asked for already exists verbatim as "does not convert a paired terminal exit into host close intent" (terminal-tab-actions.test.ts:342), asserting closeWebRuntimeSessionTab is not called for { reason: 'pty-exit' }.

  2. Host leg. session.tabs.close refuses unattributed closes from intent-capable runtime clients, and lifecycle echoes were split onto a separate session.tabs.closeLifecycle that refuses on stale publication epoch, stale terminal incarnation, unknown liveness, and any non-user reason whose parent tab still has a live PTY (orca-runtime.ts:7501-7556). Landed across fix(terminal): prevent reconnect from killing live daemon sessions #9804 (f9f3cd2fbe) and fix(terminals): negotiate explicit close intent for paired runtimes #10129 (24706ccff0).

  3. Both suites green on main:

    npx vitest run --config config/vitest.config.ts \
      src/renderer/src/components/terminal/terminal-tab-actions.test.ts \
      src/main/runtime/rpc/methods/session-tabs.test.ts
    
    Test Files  2 passed (2)
         Tests  54 passed (54)
    

    I tried to construct a failing variant against main and could not: with the early return there is no input for which a reason: 'pty-exit' close reaches the wire.

Why closing rather than rebasing: the branch is CONFLICTING/DIRTY, and its base predates both the clientNavigationId attribution and the SESSION_TAB_CLOSE_INTENT_RUNTIME_CAPABILITY gate. Merging as-is would revert the negotiated-capability approach that shipped — main deliberately gates on negotiated capability specifically so mixed-version pairings don't regress into silent no-op closes.

One part of this is still genuinely missing, and it'd be welcome as its own PR

Your daemon-side attribution is not covered by any of the above. main still logs the kill without a requester — src/main/daemon/daemon-server.ts:934-937:

this.log.log('session-killed', {
  sessionId: request.payload.sessionId,
  immediate: request.payload.immediate === true
})

So incident forensics still can't attribute a kill to the client that asked for it. Two things from this PR would stand on their own as a small, focused change:

  • the session-killed requester-clientId attribution and its test, and
  • the separate non-sensitive deviceId on RpcContext, keeping the E2EE bearer-token clientId out of traces — that's a real improvement independent of the close-policy work, and the test that scans the serialized trace for the token is a nice touch.

You also correctly observed that terminal.close / terminal.closeTab have no attribution span at all. Also still true.

A small PR with just those pieces on top of current main would very likely go in. Thanks again for the thorough investigation — the diagnosis in #8871 was right, it just got fixed from a different direction while this sat.

@nwparker nwparker closed this Aug 3, 2026
@nwparker nwparker removed the pending_repro Repro attempted; still pending conclusive reproduction label Aug 3, 2026
@bbingz

bbingz commented Aug 6, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed verification. The two pieces you called out landed as #12238 (merged 2026-08-04, 79d3c847b):

  • Daemon kill attribution: session-killed and session-kill-failed now carry the requesting control clientId, and the success event is emitted only after the kill completes — src/main/daemon/daemon-server.ts:938-953.
  • terminal.close / terminal.closeTab and the session-tab close spans now carry runtime, paired-device, request, target, decision and outcome identities, with the E2EE bearer clientId kept out of the serialized trace (the trace-scan test guards that).

Nothing else from this branch is outstanding — the negotiated-capability close policy on main stays as shipped.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working orca-remote-server Remote Orca Server / orca serve / paired remote runtime

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants