diff --git a/docs/adr/evidence/target-identity.md b/docs/adr/evidence/target-identity.md index b3728e970d..178e0a7a91 100644 --- a/docs/adr/evidence/target-identity.md +++ b/docs/adr/evidence/target-identity.md @@ -51,18 +51,24 @@ bundle) does not declare its format today. universal-binary slice. It is `null` when nothing is selected. - `url`: the URL with userinfo removed and its `origin`. Userinfo is a transport credential and is never part of an identity. - - `process`: `pid`, `start_time` (nullable when the platform does not report - it), and `executable_sha256` (nullable when the executable could not be - read stably). A PID alone does not identify a process after exit or reuse - (see the `src/process/` identity primitives). A record whose start time is - unknown says so, rather than claiming an identity it does not have. - - `session`: the session `kind` (for example `gdb`, `rizin`, - `browser-scenario`), the session `id` REA minted, and the `target` the - session was opened on (a `TargetIdentity`, possibly `unknown`). + - `process`: `pid`, `start_time` (the platform start identity the + `src/process/` identity primitives read for that PID), and + `executable_sha256` (nullable when the executable could not be read + stably). A PID alone does not identify a process after exit or reuse, so + the start time is required: a producer that did not read it names an + `unknown` (`not-observed`) target rather than claiming an identity it + does not have. + - `session`: the `session_kind` (`rizin`, `gdb`; later kinds such as + `browser-scenario` are added when a producer needs them), the session + `id` REA minted, and the `target` the session was opened on: the launch + file hashed when the session started, or `unknown`. Later debugger + commands do not rebind the session. - `unknown`: a `reason` from a closed set: `derived-from-linked-evidence` (comparisons and workflows; their sources - are already committed through `evidence_links`), `not-observed`, and - `unsupported-subject`. + are already committed through `evidence_links`), `not-observed`, + `unsupported-subject`, and `withheld-by-caller` (REA observed the + identity and the caller chose not to record it, for example process + capture PID normalization). Display facts (`name`, `local_path`) stay beside the identity and are not committed, as today. diff --git a/docs/guides/runtime/process-capture.md b/docs/guides/runtime/process-capture.md index 8dde4ededf..ed10c87301 100644 --- a/docs/guides/runtime/process-capture.md +++ b/docs/guides/runtime/process-capture.md @@ -130,6 +130,20 @@ Captures are local Evidence files; keep their source artifacts and invocation context available when interpreting a difference. +The capture's Evidence subject names the launched root process: +`{ "kind": "process", "pid", "start_time", "executable_sha256" }`, where +`start_time` is the platform start identity REA read for that PID at launch, +bound to the capture's run token, and `executable_sha256` is `null` unless the +executable's path metadata stayed stable across spawn. `manifest.root_process` +records the same observation. A PID alone does not identify a process, so when +the start identity could not be read the subject is +`{ "kind": "unknown", "reason": "not-observed" }` and `root_process` keeps the +reason. When PID normalization is selected (the default), REA honours it: the +raw PID and start identity are not recorded, `root_process` is +`{ "state": "withheld-by-caller" }`, and the subject is +`{ "kind": "unknown", "reason": "withheld-by-caller" }`. A planned scenario +(`dry_run`) launches nothing and stays `not-observed`. + ## Hash a report independently of terminal output Select the producer's report directory and give `file_bytes` enough room for diff --git a/docs/reference/mcp-contracts.md b/docs/reference/mcp-contracts.md index 2625aa4759..838ea2fe8a 100644 --- a/docs/reference/mcp-contracts.md +++ b/docs/reference/mcp-contracts.md @@ -1032,12 +1032,25 @@ facts outside the ID. The subject has no separate `digest`, `format` or `architecture` members; read them from `subject.identity`. A live browser page observation names the page's reported URL, `{ "kind": "url", "url": …, "origin": … }`, with userinfo removed and `origin` -`null` for an opaque origin; its `name` and `local_path` are `null`. Every +`null` for an opaque origin; its `name` and `local_path` are `null`. A process +capture names its launched root, +`{ "kind": "process", "pid": …, "start_time": …, "executable_sha256": … }`, +where `start_time` is the platform start identity read for that PID at launch +and `executable_sha256` is `null` when the executable was not stable across +spawn; its `name` and `local_path` are `null`. A Rizin or GDB debugger +command names its session, +`{ "kind": "session", "session_kind": …, "id": …, "target": … }`, where `id` +is the session ID REA minted and `target` is the launch file hashed when the +session started (validated like a file subject), or an `unknown` target when +REA did not observe one (always for GDB, whose session launches no file); +later debugger commands do not rebind it. Every record has a subject: one whose target REA did not identify names `{ "kind": "unknown", "reason": … }`, where the reason is `derived-from-linked-evidence` (comparisons and workflows, whose sources are -committed through `evidence_links`), `not-observed` or `unsupported-subject`, -and its `name` and `local_path` are `null`. Retention has no +committed through `evidence_links`), `not-observed`, `unsupported-subject`, or +`withheld-by-caller` (REA observed the target and the caller chose not to +record its identity, as with process capture PID normalization), and its +`name` and `local_path` are `null`. Retention has no automatic persistence or silent eviction. `binary_session.investigation` reports record/revision/head counts, estimated retained representation bytes and the fixed allowance derived from initial V8 diff --git a/docs/reverse-engineering-tools.md b/docs/reverse-engineering-tools.md index 10a5be9e8d..bb9a0c7c9d 100644 --- a/docs/reverse-engineering-tools.md +++ b/docs/reverse-engineering-tools.md @@ -49,7 +49,7 @@ Captured stdout and stderr share `max_output_bytes` (CLI: `--max-output-bytes`), ## GDB -Persistent GDB sessions, including the MCP workflow and one-shot `rea debug-with-gdb` CLI, are available only on Linux. REA verifies a live inferior's output descriptors through `/proc` before detaching it; it does not claim equivalent descriptor verification on macOS. Windows is also unsupported because owned Job Object cleanup can terminate debugger inferiors. On supported Linux hosts, `start_gdb_session`, `gdb_console`, `gdb_session_status`, and `close_gdb_session` manage a persistent GDB/MI session in MCP. The one-shot CLI requires a caller-selected durable TTY: `rea debug-with-gdb --inferior-tty /dev/pts/7 'file ./program'`. The TTY must remain available after GDB exits so a detached inferior can continue writing. MCP starts GDB with `--nx --quiet --interpreter=mi3`, retries initialization with MI2 if MI3 initialization returns an error and cleanup succeeds, waits for its prompt, and disables auto-loading. Pass optional `inferior_tty` to select the terminal that future inferior runs use; REA configures it before the session becomes ready and checks the exact value with GDB/MI. `gdb_session_status` reports the selected path, whether REA still considers the configuration verified, and whether invalid UTF-8 has been observed in MI bytes (`mi_invalid_utf8`) or stderr (`stderr_invalid_utf8`). Commands that can change the inferior TTY or redirect a run revoke that verification permanently for the session, so close retains GDB ownership if a live inferior remains. The complete built-in inspections `show inferior-tty` and `help inferior-tty` preserve verification; compound commands still use the conservative mutation checks. Closing a session with one live inferior and a verified TTY automatically detaches the target, which can resume execution; MCP clients receive destructive-operation annotations for this behavior. The console remains unrestricted and can run shell commands, change target state, access files, and use network in the REA process user's security context. Raw MI records and console/target/log streams are returned with Evidence; command output is retained up to the configured budget (16 MiB by default) and explicitly marked when truncated. A single console, target or log record over the 16 MiB MI line limit is dropped and the command is marked truncated, while an oversized result or async record still stops the session. GDB startup waits 10000 ms with no runtime override. Each MI command defaults to 120000 ms; its deadline, command-output budget, session capacity and pending-command queue use the [shared debugger launch settings](#debugger-launch-settings). `command_timeout_ms` does not change a persistent debugger session. +Persistent GDB sessions, including the MCP workflow and one-shot `rea debug-with-gdb` CLI, are available only on Linux. REA verifies a live inferior's output descriptors through `/proc` before detaching it; it does not claim equivalent descriptor verification on macOS. Windows is also unsupported because owned Job Object cleanup can terminate debugger inferiors. On supported Linux hosts, `start_gdb_session`, `gdb_console`, `gdb_session_status`, and `close_gdb_session` manage a persistent GDB/MI session in MCP. The one-shot CLI requires a caller-selected durable TTY: `rea debug-with-gdb --inferior-tty /dev/pts/7 'file ./program'`. The TTY must remain available after GDB exits so a detached inferior can continue writing. MCP starts GDB with `--nx --quiet --interpreter=mi3`, retries initialization with MI2 if MI3 initialization returns an error and cleanup succeeds, waits for its prompt, and disables auto-loading. Pass optional `inferior_tty` to select the terminal that future inferior runs use; REA configures it before the session becomes ready and checks the exact value with GDB/MI. `gdb_session_status` reports the selected path, whether REA still considers the configuration verified, and whether invalid UTF-8 has been observed in MI bytes (`mi_invalid_utf8`) or stderr (`stderr_invalid_utf8`). Commands that can change the inferior TTY or redirect a run revoke that verification permanently for the session, so close retains GDB ownership if a live inferior remains. The complete built-in inspections `show inferior-tty` and `help inferior-tty` preserve verification; compound commands still use the conservative mutation checks. Closing a session with one live inferior and a verified TTY automatically detaches the target, which can resume execution; MCP clients receive destructive-operation annotations for this behavior. The console remains unrestricted and can run shell commands, change target state, access files, and use network in the REA process user's security context. Raw MI records and console/target/log streams are returned with Evidence. Its subject names the session, `{ "kind": "session", "session_kind": "gdb", "id": , "target": { "kind": "unknown", "reason": "not-observed" } }`: `start_gdb_session` launches no program file, and REA does not hash programs that console commands load or attach, so the target stays unknown; command output is retained up to the configured budget (16 MiB by default) and explicitly marked when truncated. A single console, target or log record over the 16 MiB MI line limit is dropped and the command is marked truncated, while an oversized result or async record still stops the session. GDB startup waits 10000 ms with no runtime override. Each MI command defaults to 120000 ms; its deadline, command-output budget, session capacity and pending-command queue use the [shared debugger launch settings](#debugger-launch-settings). `command_timeout_ms` does not change a persistent debugger session. A truncated GDB command capture includes `output_limits` with the exact causes and effective maxima: `command_bytes`, `command_records`, or `mi_line_bytes`. @@ -92,7 +92,7 @@ close_gdb_session {"session_id":"…"} `start_rizin_debug_session` and `rea debug-with-rizin` require an explicit `inferior_tty` on Linux. REA asks Rizin to launch the target with stdin, stdout and stderr routed to that caller-selected TTY and `dbg.exitkills=false`; the target can therefore continue running, reading input from the TTY and writing to it after REA closes the debugger. This is a visible target input and output effect, and the caller is responsible for selecting a suitable terminal that remains available. REA sends Rizin its commands on Rizin's own stdin, so a target left on that stream would read them. Before closing, REA serializes after the active command, parses the structured `olj` descriptor list, detaches only a unique `ptrace://` descriptor, confirms its absence, reads back `dbg.exitkills=false`, verifies `/proc//fd/1` and `/proc//fd/2` still identify the selected TTY by device and inode, and refuses to detach while `/proc//fd/0` is Rizin's command stream. A target may close or replace its own stdin. If a previously identified inferior exits after Rizin confirms detach, REA verifies that the original process has ended instead of requiring output descriptors from an exited process. Unresolved identity or ambiguous readback keeps the Rizin session owned for retry. After output limits or a failed command interval, cleanup first waits up to 1000 ms for a fresh private NUL-delimited marker, discarding earlier frames before obtaining that new inferior readback. Synchronization never reopens user command admission. A missing marker, unavailable transport, or unknown inferior identity retains the cleanup owner. Caller cancellation keeps its exact reason and typed cancellation outcome even when cleanup remains incomplete; a successful retry resolves that retained cleanup state. Cancellation during final cleanup retains the captured observation and cleanup owner. An already observed startup or protocol failure remains primary and retains a later cancellation as a secondary failure; recovering the transport does not erase that original diagnosis. Persistent Rizin debugger sessions are unavailable outside Linux because this verification depends on `/proc`. -Persistent command Evidence retains the caller-selected and resolved startup paths in `parameters.launch_provenance`. These paths describe launch provenance, not the current target after unrestricted commands. `rizin_debug_session_status.output_invalid_utf8` reports whether lossy frame decoding has been observed during the session. Command Evidence sets `output_invalid_utf8` only when loss was observed in frames collected for that command, including retained partial output; earlier startup or command frames do not mark later valid output as lossy. +Persistent command Evidence retains the caller-selected and resolved startup paths in `parameters.launch_provenance`. These paths describe launch provenance, not the current target after unrestricted commands. Command Evidence names the session as its subject, `{ "kind": "session", "session_kind": "rizin", "id": , "target": … }`, where `target` is the launch file REA hashed before Rizin started (`{ "kind": "file", "sha256", "format": "file", "architecture": null, "selection": null }`). Later debugger commands do not rebind it. If the launch file cannot be hashed (for example it does not exist or is not a regular file), the session still starts, `target` is `{ "kind": "unknown", "reason": "not-observed" }`, and a limitation records the reason; cancellation or a descriptor that cannot be closed during the hash fails the start. `rizin_debug_session_status.output_invalid_utf8` reports whether lossy frame decoding has been observed during the session. Command Evidence sets `output_invalid_utf8` only when loss was observed in frames collected for that command, including retained partial output; earlier startup or command frames do not mark later valid output as lossy. Session status retains up to 64 recent protocol frames. Each history entry keeps a complete-character UTF-8 prefix of at most 16 KiB, plus a truncation marker when needed; `recent_output_truncated` reports omitted history. This history budget also accounts for replacement characters from invalid UTF-8. It does not shorten command Evidence, whose output budget defaults to 16 MiB. Rizin debug startup waits 30000 ms with no runtime override. Each command frame defaults to 120000 ms; its deadline, command-output budget, session capacity and pending-command queue use the [shared debugger launch settings](#debugger-launch-settings). The 16777216-byte frame cap and 4096-frame command cap remain fixed. Evidence names the cap that stopped the command. The one-shot `command_timeout_ms` setting does not change a debug session. diff --git a/src/application/process/ProcessEvidence.ts b/src/application/process/ProcessEvidence.ts index dd26f19d10..294ed95de2 100644 --- a/src/application/process/ProcessEvidence.ts +++ b/src/application/process/ProcessEvidence.ts @@ -1,4 +1,8 @@ -import { unknownTarget } from "../../domain/targetIdentity.js"; +import { + unknownTarget, + type ProcessTargetIdentity, + type UnknownTargetIdentity, +} from "../../domain/targetIdentity.js"; import type { z } from "zod"; import { posix, win32 } from "node:path"; @@ -108,26 +112,57 @@ const processEvidenceParameters = ( normalization: scenario.normalization, }); +/** + * The captured root process as the Evidence subject: its PID, start identity + * and stable executable digest; withheld when the caller normalized PIDs; + * otherwise not observed. + */ +const processCaptureSubject = ( + manifest: ProcessCapture["manifest"], +): ProcessTargetIdentity | UnknownTargetIdentity => { + const root = manifest.root_process; + switch (root.state) { + case "observed": + return { + kind: "process", + pid: root.pid, + start_time: root.start_time, + executable_sha256: manifest.executable_sha256, + }; + case "withheld-by-caller": + return unknownTarget("withheld-by-caller"); + case "unknown": + return unknownTarget("not-observed"); + } +}; + /** Create one canonical observed process capture Evidence record. */ export const createProcessCaptureEvidence = ( scenario: ProcessScenario, capture: ProcessCapture, ) => { - return createEvidence(unknownTarget("not-observed"), PROCESS_PROVIDER, { - predicateType: PROCESS_CAPTURE_EVIDENCE.predicate, - operation: PROCESS_CAPTURE_EVIDENCE.operation, - parameters: processEvidenceParameters(scenario, capture.manifest.platform), - result: capture, - confidence: "observed", - authority: "controlled-replay", - environment: { - id: `${capture.manifest.platform}-${capture.manifest.architecture}`, - platform: capture.manifest.platform, - architecture: capture.manifest.architecture, - isolation: "process", + return createEvidence( + processCaptureSubject(capture.manifest), + PROCESS_PROVIDER, + { + predicateType: PROCESS_CAPTURE_EVIDENCE.predicate, + operation: PROCESS_CAPTURE_EVIDENCE.operation, + parameters: processEvidenceParameters( + scenario, + capture.manifest.platform, + ), + result: capture, + confidence: "observed", + authority: "controlled-replay", + environment: { + id: `${capture.manifest.platform}-${capture.manifest.architecture}`, + platform: capture.manifest.platform, + architecture: capture.manifest.architecture, + isolation: "process", + }, + limitations: capture.limitations, }, - limitations: capture.limitations, - }); + ); }; /** Create one canonical planned-scenario Evidence record without observing a process. */ diff --git a/src/domain/evidence.test.ts b/src/domain/evidence.test.ts index fc182de15f..30d0c7bd8c 100644 --- a/src/domain/evidence.test.ts +++ b/src/domain/evidence.test.ts @@ -19,6 +19,7 @@ import { rebindEvidenceToTargetPath, evidenceFileTarget, evidenceSubjectDisplay, + evidenceSubject, } from "./evidence.js"; import { MAX_JSON_DEPTH, @@ -1080,3 +1081,36 @@ it("retains safe auxiliary paths when the direct caller path is unavailable", () }), ).toThrow(); }); + +it("validates a debugger session subject's launch file with the file subject declaration", () => { + const session = { + kind: "session", + session_kind: "rizin", + id: "00000000-0000-4000-8000-000000000001", + target: { + kind: "file", + sha256: "a".repeat(64), + format: "file", + architecture: null, + selection: null, + }, + } as const; + + expect( + evidenceSubject(session), + "a session bound to its hashed launch file has no file display facts", + ).toEqual({ identity: session, name: null, local_path: null }); + expect( + () => + evidenceSubject({ + ...session, + target: { ...session.target, format: "not-a-format" }, + }), + "the nested launch file obeys the format-owned declaration", + ).toThrow(); + expect( + evidenceSubject({ ...session, target: unknownTarget("not-observed") }) + .identity, + "an unobserved launch target stays an explicit unknown", + ).toEqual({ ...session, target: unknownTarget("not-observed") }); +}); diff --git a/src/domain/evidence.ts b/src/domain/evidence.ts index d6b3aa19c8..063218a48d 100644 --- a/src/domain/evidence.ts +++ b/src/domain/evidence.ts @@ -16,6 +16,8 @@ import { binaryTargetIdentity, fileTargetSelectionSchema, nonFileTargetIdentitySchema, + sessionTargetIdentitySchema, + unknownTargetIdentitySchema, type NonFileTargetIdentity, sameTargetIdentity, type FileTargetIdentity, @@ -89,9 +91,16 @@ const fileSubjectSchema = z.strictObject({ name: z.string().min(1), local_path: nulFreeStringSchema, }); -/** A subject that names no file (a URL, or an unknown target) has no file display facts. */ +/** A debugger session whose launch file is validated like a file subject. */ +const sessionSubjectIdentitySchema = sessionTargetIdentitySchema.extend({ + target: z.union([subjectIdentitySchema, unknownTargetIdentitySchema]), +}); +/** A subject that names no file (a URL, process, session, or unknown target) has no file display facts. */ const nonFileSubjectSchema = z.strictObject({ - identity: nonFileTargetIdentitySchema, + identity: z.union([ + nonFileTargetIdentitySchema, + sessionSubjectIdentitySchema, + ]), name: z.null(), local_path: z.null(), }); diff --git a/src/domain/process/processCapture.comparison.test.ts b/src/domain/process/processCapture.comparison.test.ts index e7fa16c341..806c60b0ca 100644 --- a/src/domain/process/processCapture.comparison.test.ts +++ b/src/domain/process/processCapture.comparison.test.ts @@ -959,6 +959,10 @@ it("refuses mixed terminal observation versions even with PID and port rules dis scenario: committed, full_scenario_sha256: digestProcessCommitment(committed), normalization_sha256: digestProcessCommitment(scenario.normalization), + root_process: { + state: "unknown", + reason: "the fixture launched no process", + }, comparison_contract: contract, comparison_contract_sha256: digestProcessCommitment(contract), }, @@ -1004,6 +1008,10 @@ it("refuses mixed path normalization versions even with PID and port rules disab scenario: committed, full_scenario_sha256: digestProcessCommitment(committed), normalization_sha256: digestProcessCommitment(scenario.normalization), + root_process: { + state: "unknown", + reason: "the fixture launched no process", + }, comparison_contract: contract, comparison_contract_sha256: digestProcessCommitment(contract), }, diff --git a/src/domain/process/processCapture.ts b/src/domain/process/processCapture.ts index 93e0670f47..e5147fe396 100644 --- a/src/domain/process/processCapture.ts +++ b/src/domain/process/processCapture.ts @@ -212,6 +212,28 @@ export type VerifiedProcessSettlement = readonly cleanup_outcome: "cleaned" | "failed"; }; +/** The launched root process as the capture observed it. */ +export const processCaptureRootProcessSchema = z.discriminatedUnion("state", [ + z.strictObject({ + state: z.literal("observed"), + pid: z.int().positive(), + start_time: z.string().min(1), + }), + z.strictObject({ state: z.literal("withheld-by-caller") }), + z.strictObject({ state: z.literal("unknown"), reason: z.string().min(1) }), +]); + +/** The launched root process as the capture observed it. */ +export type ProcessCaptureRootProcess = + | { + readonly state: "observed"; + readonly pid: number; + /** Platform start identity from `src/process`; opaque. */ + readonly start_time: string; + } + | { readonly state: "withheld-by-caller" } + | { readonly state: "unknown"; readonly reason: string }; + /** * Process capture observation set. * @@ -239,6 +261,12 @@ export interface UnverifiedProcessCapture { readonly state: "path_metadata_unchanged" | "unknown"; readonly reason: string | null; }; + /** + * The launched root process: its PID and the start identity read for it + * by the `src/process` identity primitives, withheld when the caller + * selected PID normalization, or unknown with the reason. + */ + readonly root_process: ProcessCaptureRootProcess; readonly normalization_sha256: string; }; readonly normalization: z.infer; @@ -509,6 +537,7 @@ const processCaptureShapeSchema = z.strictObject({ state: z.enum(["path_metadata_unchanged", "unknown"]), reason: z.string().nullable(), }), + root_process: processCaptureRootProcessSchema, normalization_sha256: z.string().regex(/^[a-f0-9]{64}$/u), }), normalization: normalizationSchema, diff --git a/src/domain/process/processCapture.validation.test.ts b/src/domain/process/processCapture.validation.test.ts index 5a21323b1e..ae86af1edf 100644 --- a/src/domain/process/processCapture.validation.test.ts +++ b/src/domain/process/processCapture.validation.test.ts @@ -435,6 +435,41 @@ it("rejects altered v4 commitments and accepts canonical key reordering", () => ).toThrow("executable_identity"); }); +it("withholds the root process identity exactly when PID normalization is selected", () => { + const capture = emptyCapture(); + const observed = { + state: "observed", + pid: 4242, + start_time: "linux-starttime:1", + } as const; + const withPids = (pids: boolean, root_process: object) => + parseProcessCapture({ + ...capture, + normalization: { ...capture.normalization, pids }, + manifest: { + ...capture.manifest, + root_process, + normalization_sha256: digestProcessCommitment({ + ...capture.normalization, + pids, + }), + }, + }); + + expect( + () => withPids(true, observed), + "a normalized capture never commits the raw root PID", + ).toThrow("root_process"); + expect( + () => withPids(false, { state: "withheld-by-caller" }), + "an identity is withheld only by the caller's normalization", + ).toThrow("root_process"); + expect( + withPids(false, observed).manifest.root_process, + "an unnormalized capture keeps the observed root", + ).toEqual(observed); +}); + it("requires producer coverage accounting in every parsed capture", () => { const capture = emptyCapture(); const { truncation_details: _details, ...missingCoverage } = capture; diff --git a/src/domain/process/processCaptureExample.ts b/src/domain/process/processCaptureExample.ts index 0b01a0e03f..0b29243008 100644 --- a/src/domain/process/processCaptureExample.ts +++ b/src/domain/process/processCaptureExample.ts @@ -31,6 +31,7 @@ export const EMPTY_PROCESS_CAPTURE_EXAMPLE = { state: "path_metadata_unchanged", reason: null, }, + root_process: { state: "withheld-by-caller" }, normalization_sha256: digestProcessCommitment(normalization), }, normalization, diff --git a/src/domain/process/processCaptureValidation.ts b/src/domain/process/processCaptureValidation.ts index fe6d08f3bd..ce1ba8333d 100644 --- a/src/domain/process/processCaptureValidation.ts +++ b/src/domain/process/processCaptureValidation.ts @@ -46,6 +46,9 @@ const validateCommitments = ( : manifest.executable_sha256 === null && manifest.executable_identity.reason !== null, "manifest.executable_identity", "launch identity and executable digest do not agree"); + require((manifest.root_process.state === "withheld-by-caller") === + capture.normalization + .pids, "manifest.root_process", "root process identity must be withheld exactly when PID normalization is selected"); for (const [field, value] of [ ["full_scenario_sha256", manifest.scenario], ["comparison_contract_sha256", manifest.comparison_contract], diff --git a/src/domain/targetIdentity.ts b/src/domain/targetIdentity.ts index ab8e0dc665..9ae5e44a0d 100644 --- a/src/domain/targetIdentity.ts +++ b/src/domain/targetIdentity.ts @@ -65,12 +65,15 @@ export interface FileTargetIdentity { /** * Why an observation names no target: it derives from linked Evidence that * already commits to its sources, the producer did not observe the target's - * identity, or the target is not a kind REA can identify. + * identity, the target is not a kind REA can identify, or REA observed the + * identity and the caller chose not to record it (for example PID + * normalization). */ export const unknownTargetReasonSchema = z.enum([ "derived-from-linked-evidence", "not-observed", "unsupported-subject", + "withheld-by-caller", ]); /** A target whose identity is unknown, with the reason it is unknown. */ @@ -136,6 +139,53 @@ export interface UrlTargetIdentity { readonly origin: string | null; } +/** + * A live process named by its PID and the start identity the `src/process` + * identity primitives read for that PID. A PID alone does not identify a + * process after exit or reuse, so the start identity is required. The + * executable digest is null when the executable could not be read stably + * across launch. + */ +export const processTargetIdentitySchema = z.strictObject({ + kind: z.literal("process"), + pid: z.int().positive(), + start_time: z.string().min(1), + executable_sha256: digestSchema.nullable(), +}); + +/** A live process named by its PID and start identity. */ +export interface ProcessTargetIdentity { + readonly kind: "process"; + readonly pid: number; + /** Platform start identity from `src/process`; opaque, compared only for equality. */ + readonly start_time: string; + readonly executable_sha256: string | null; +} + +/** Debugger sessions REA mints and can bind to a launch target. */ +export const debuggerSessionKindSchema = z.enum(["rizin", "gdb"]); + +/** + * A debugger session REA minted, bound to the target it launched: the launch + * file hashed when the session started, or an explicit unknown when REA did + * not observe it (an attach, or a launch file that could not be hashed). + * Later debugger commands do not rebind the session. + */ +export const sessionTargetIdentitySchema = z.strictObject({ + kind: z.literal("session"), + session_kind: debuggerSessionKindSchema, + id: z.string().min(1), + target: z.union([fileTargetIdentitySchema, unknownTargetIdentitySchema]), +}); + +/** A debugger session REA minted, bound to the target it launched. */ +export interface SessionTargetIdentity { + readonly kind: "session"; + readonly session_kind: z.infer; + readonly id: string; + readonly target: FileTargetIdentity | UnknownTargetIdentity; +} + /** * What an observation or cache entry is about. Tagged by `kind`; see * docs/adr/evidence/target-identity.md for the kinds later slices add. @@ -143,15 +193,22 @@ export interface UrlTargetIdentity { export type TargetIdentity = | FileTargetIdentity | UrlTargetIdentity + | ProcessTargetIdentity + | SessionTargetIdentity | UnknownTargetIdentity; /** A target identity that names no file, and so has no file display facts. */ export type NonFileTargetIdentity = Exclude; -/** The identities a subject without file display facts can commit to. */ +/** + * The identities without a nested target that a subject without file display + * facts can commit to. A session identity nests its target, so a persistence + * format validates it with its own file declaration. + */ export const nonFileTargetIdentitySchema = z.union([ unknownTargetIdentitySchema, urlTargetIdentitySchema, + processTargetIdentitySchema, ]); /** The universal Mach-O slice a target selects, with its FAT CPU declaration when admitted. */ diff --git a/src/gdb/GdbSessionManager.ts b/src/gdb/GdbSessionManager.ts index 98662775a2..23e5eefbd2 100644 --- a/src/gdb/GdbSessionManager.ts +++ b/src/gdb/GdbSessionManager.ts @@ -1,4 +1,7 @@ -import { unknownTarget } from "../domain/targetIdentity.js"; +import { + unknownTarget, + type SessionTargetIdentity, +} from "../domain/targetIdentity.js"; import { gdbMiConstText, gdbMiResultHeader, @@ -346,6 +349,20 @@ interface GdbSession { recentRecordsTruncated: boolean; } +/** + * GDB command Evidence names the session REA minted. `start_gdb_session` + * launches no program file: programs are loaded or attached by console + * commands that REA does not hash, so the session target stays unknown. + */ +const gdbSessionSubject = ( + session: Pick, +): SessionTargetIdentity => ({ + kind: "session", + session_kind: "gdb", + id: session.id, + target: unknownTarget("not-observed"), +}); + const gdbCloseUnavailable = (): AnalysisInputError => unknownDebuggerSessionError(GDB_SESSION_TOOLS, "close_gdb_session"); @@ -841,7 +858,7 @@ export class GdbSessionManager { const startupEvidence = startupEvidencePayload === undefined ? undefined - : createEvidence(unknownTarget("not-observed"), session.provider, { + : createEvidence(gdbSessionSubject(session), session.provider, { predicateType: "rea.debugger.startup-observation", operation: "start_gdb_session", parameters: { @@ -1056,7 +1073,7 @@ export class GdbSessionManager { accepted.value, ); const evidence = createEvidence( - unknownTarget("not-observed"), + gdbSessionSubject(session), session.provider, { predicateType: "rea.debugger.console-observation", @@ -1130,7 +1147,7 @@ export class GdbSessionManager { command, }; const evidence = createEvidence( - unknownTarget("not-observed"), + gdbSessionSubject(session), session.provider, { predicateType: "rea.debugger.console-observation", @@ -1705,7 +1722,7 @@ export class GdbSessionManager { const partialObservation = partial === undefined ? undefined - : createEvidence(unknownTarget("not-observed"), session.provider, { + : createEvidence(gdbSessionSubject(session), session.provider, { predicateType: "rea.debugger.console-observation", operation: "gdb_console", parameters: { @@ -1953,7 +1970,7 @@ export class GdbSessionManager { }, ); const evidence = createEvidence( - unknownTarget("not-observed"), + gdbSessionSubject(session), session.provider, { predicateType: @@ -2049,7 +2066,7 @@ export class GdbSessionManager { completion_status: "unknown", }; const evidence = createEvidence( - unknownTarget("not-observed"), + gdbSessionSubject(session), session.provider, { predicateType: "rea.debugger.console-observation", diff --git a/src/process/capture/ProcessCaptureLifecycle.ts b/src/process/capture/ProcessCaptureLifecycle.ts index ff659dc32b..d4f7956115 100644 --- a/src/process/capture/ProcessCaptureLifecycle.ts +++ b/src/process/capture/ProcessCaptureLifecycle.ts @@ -90,6 +90,7 @@ import type { ProcessCaptureEventJournalEntry, RecordProcessCaptureEvent, TerminalFrame, + ProcessCaptureRootProcess, } from "../../domain/process/processCapture.js"; import { partialProcessCaptureObservationSchema } from "../../domain/process/processCapture.js"; import { errorMessage } from "../../kernel/errorMessage.js"; @@ -704,6 +705,7 @@ export const createRunManifest = async ( startedAt: Date, completedAt: Date, executable: LaunchedExecutableObservation, + rootProcess: ProcessCaptureRootProcess, host: { readonly platform: NodeJS.Platform; readonly architecture: NodeJS.Architecture; @@ -732,6 +734,7 @@ export const createRunManifest = async ( state: executable.state, reason: executable.reason, }, + root_process: rootProcess, normalization_sha256: digestProcessCommitment(scenario.normalization), }; }; diff --git a/src/process/capture/ProcessHarness.test.ts b/src/process/capture/ProcessHarness.test.ts index 0f06813d3f..10edeceb1d 100644 --- a/src/process/capture/ProcessHarness.test.ts +++ b/src/process/capture/ProcessHarness.test.ts @@ -1,10 +1,13 @@ import { createTestProcessCaptureResourceScope } from "../../../tests/fixtures/processCaptureResourceScope.js"; +import { failedInspectionDescriptor } from "../../../tests/fixtures/processInspectionCleanup.js"; import { assertProcessOwnershipInspectionActive } from "../ProcessInspectionCancellation.js"; import { expect, it, vi, onTestFinished } from "vitest"; import { processScenarioSchema } from "../../domain/process/processScenario.js"; import { AnalysisCapabilityUnavailableError } from "../../domain/analysisErrorCore.js"; import { captureProcessScenario, + capturedRootProcess, + retainRootIdentity, retainRootSignaller, } from "./ProcessHarness.js"; import { @@ -806,22 +809,23 @@ it("retains the root start identity once at launch and signals only with it", as identity: "id-launch", })); const signal = vi.fn(async () => "signaled" as const); - const signalRoot = retainRootSignaller(4242, 500, "captured-run", { - observe, + const signalRoot = retainRootSignaller( + 4242, + retainRootIdentity(4242, "captured-run", observe), signal, - }); + ); expect( observe, "the identity is read at launch, before any signal", ).toHaveBeenCalledTimes(1); expect( - await signalRoot("SIGTERM"), + await signalRoot.signal("SIGTERM"), "a matching identity is signalled", ).toEqual({ delivery: "signaled", }); - await signalRoot("SIGKILL"); + await signalRoot.signal("SIGKILL"); expect( observe, @@ -854,49 +858,103 @@ it.each([ "never signals without a retained identity: %s", async (_label, read, delivery) => { const signal = vi.fn(async () => "signaled" as const); - const signalRoot = retainRootSignaller(4242, 500, "captured-run", { - observe: read, + const signalRoot = retainRootSignaller( + 4242, + retainRootIdentity(4242, "captured-run", read), signal, - }); + ); expect( - await signalRoot("SIGTERM"), + await signalRoot.signal("SIGTERM"), "the delivery result is recorded", ).toEqual(delivery); expect(signal, "no identity means no signal at all").not.toHaveBeenCalled(); }, ); -it("does not read an identity when there is no finalization interval", async () => { - const observe = vi.fn(async () => undefined); - const signalRoot = retainRootSignaller(4242, 0, "captured-run", { - observe, - signal: vi.fn(async () => "signaled" as const), +it.each([ + [ + "a readable identity", + { state: "identity", identity: "id-launch" } as const, + false, + { state: "observed", pid: 4242, start_time: "id-launch" }, + ], + [ + "PID normalization", + { state: "identity", identity: "id-launch" } as const, + true, + { state: "withheld-by-caller" }, + ], + [ + "a vanished root", + { state: "gone" } as const, + false, + { + state: "unknown", + reason: "the root process exited before its start identity was read", + }, + ], + [ + "an unverified identity", + { state: "unverified", reason: "token mismatch" } as const, + false, + { state: "unknown", reason: "token mismatch" }, + ], +])( + "records the root process from the launch identity: %s", + (_label, identity, pidsNormalized, expected) => { + expect( + capturedRootProcess(4242, identity, pidsNormalized), + "a PID is recorded only with its start identity, and never when the caller normalized PIDs", + ).toEqual(expected); + }, +); + +it("keeps the inspection failure of a delivery that settles after the caller stopped waiting", async () => { + const file = await failedInspectionDescriptor(); + let rejectDelivery: (cause: unknown) => void = () => undefined; + const delivery = new Promise((_resolve, reject) => { + rejectDelivery = reject; }); + // The signaller awaits it; this only keeps the early rejection handled. + delivery.catch(() => undefined); + const signalRoot = retainRootSignaller( + 4242, + retainRootIdentity(4242, "captured-run", async () => ({ + state: "readable", + identity: "id-launch", + })), + () => delivery, + ); + + void signalRoot.signal("SIGTERM"); + const settled = signalRoot.settled(); + rejectDelivery(file.failure); expect( - observe, - "the zero-interval path never inspects the root", - ).not.toHaveBeenCalled(); + await settled, + "the late identity-check failure is handed to the run, not dropped", + ).toHaveLength(1); expect( - await signalRoot("SIGKILL"), - "an unretained identity stays unverified", - ).toEqual({ - delivery: "unverified", - reason: "root identity was not retained", - }); + await signalRoot.settled(), + "each failure is handed over once", + ).toEqual([]); }); it.each(["signaled", "gone", "identity-changed", "unverified"] as const)( "reports the identity-checked delivery result %s unchanged", async (delivery) => { - const signalRoot = retainRootSignaller(4242, 500, "captured-run", { - observe: async () => ({ state: "readable", identity: "id-launch" }), - signal: async () => delivery, - }); + const signalRoot = retainRootSignaller( + 4242, + retainRootIdentity(4242, "captured-run", async () => ({ + state: "readable", + identity: "id-launch", + })), + async () => delivery, + ); expect( - await signalRoot("SIGKILL"), + await signalRoot.signal("SIGKILL"), "the signaller result is not coerced", ).toEqual( delivery === "unverified" @@ -940,14 +998,15 @@ it("seeds a finalization observation only for a scenario with an interval", () = }); it("keeps a non-empty reason when the identity inspection fails without a message", async () => { - const signalRoot = retainRootSignaller(4242, 500, "captured-run", { - observe: async () => { + const signalRoot = retainRootSignaller( + 4242, + retainRootIdentity(4242, "captured-run", async () => { throw new Error(); - }, - signal: vi.fn(async () => "signaled" as const), - }); + }), + vi.fn(async () => "signaled" as const), + ); - const result = await signalRoot("SIGTERM"); + const result = await signalRoot.signal("SIGTERM"); expect(result.delivery, "the attempt is unverified").toBe("unverified"); expect( @@ -957,12 +1016,16 @@ it("keeps a non-empty reason when the identity inspection fails without a messag }); it("keeps a non-empty reason when the identity diagnostic is empty", async () => { - const signalRoot = retainRootSignaller(4242, 500, "captured-run", { - observe: async () => ({ state: "unavailable" as const, reason: "" }), - signal: vi.fn(async () => "signaled" as const), - }); + const signalRoot = retainRootSignaller( + 4242, + retainRootIdentity(4242, "captured-run", async () => ({ + state: "unavailable" as const, + reason: "", + })), + vi.fn(async () => "signaled" as const), + ); - const result = await signalRoot("SIGTERM"); + const result = await signalRoot.signal("SIGTERM"); expect( result.reason?.length, diff --git a/src/process/capture/ProcessHarness.ts b/src/process/capture/ProcessHarness.ts index 28bf7f50e3..c534a46497 100644 --- a/src/process/capture/ProcessHarness.ts +++ b/src/process/capture/ProcessHarness.ts @@ -28,8 +28,10 @@ import type { ProcessSample, RecordProcessCaptureEvent, TerminalFrame, + ProcessCaptureRootProcess, } from "../../domain/process/processCapture.js"; import { startProcessSampler } from "./ProcessSampling.js"; +import { AbortedWait, waitForAbortable } from "../AbortablePromise.js"; import { snapshotRoots, ProcessCaptureSnapshotFailure, @@ -104,79 +106,162 @@ interface StartedCaptureRuntime { readonly stopSampler: ReturnType; /** One ownership ledger shared by observations and final cleanup for this run. */ readonly ownershipEvidence: ProcessOwnershipEvidenceOwner; + /** The root's start identity, read once at launch. */ + readonly rootIdentity: Promise; /** Signals the captured root only while its launch-time start identity still matches. */ - readonly signalRoot: (signal: "SIGTERM" | "SIGKILL") => Promise<{ + readonly rootSignaller: RootSignaller; +} + +/** Identity-checked finalization signalling for one captured root. */ +export interface RootSignaller { + /** Deliver one signal; never rejects, so a failed delivery is recorded as unverified. */ + readonly signal: (signal: "SIGTERM" | "SIGKILL") => Promise<{ readonly delivery: "signaled" | "gone" | "identity-changed" | "unverified"; readonly reason?: string | undefined; }>; + /** + * Join every delivery, including one that outlasted the finalization + * grace, and hand over the inspection failures their identity checks left + * owned. Never rejects. + */ + readonly settled: () => Promise; } -/** Identity observation and signalling used for finalization signals; injectable for tests. */ +/** Root identity observation and finalization signalling; injectable for tests. */ export interface FinalizationHost { readonly observe: typeof observeProcessStartIdentity; readonly signal: typeof signalProcessWithStartIdentity; } -/** Bind the captured root's initial identity to its run token before retaining it. */ +/** + * The captured root's launch-time start identity, bound to its run token. A + * read that failed through the inspection owner keeps that owner's failure, + * including any descriptor whose close failed, for the capture to retain. + */ +export type RetainedRootIdentity = + | { readonly state: "identity"; readonly identity: string } + | { readonly state: "gone" } + | { + readonly state: "unverified"; + readonly reason: string; + readonly inspectionFailure?: ProcessCaptureInspectionFailure; + }; + +/** + * Read the captured root's start identity once at launch, bound to its run + * token. Finalization signals and the capture's root process fact both use + * this one observation; nothing re-reads it later. + */ +export const retainRootIdentity = ( + pid: number, + runId: string, + observe: FinalizationHost["observe"] = (rootPid) => + observeProcessStartIdentity(rootPid, undefined, runId), +): Promise => + observe(pid).then( + (observation) => + observation === undefined + ? ({ state: "gone" } as const) + : observation.state === "readable" + ? ({ state: "identity", identity: observation.identity } as const) + : ({ + state: "unverified", + reason: + observation.reason.trim() === "" + ? "start identity is unavailable without a diagnostic" + : observation.reason, + } as const), + (cause: unknown) => { + const [inspectionFailure] = captureInspectionFailures( + normalizeCaptureFailure(cause), + ); + return { + state: "unverified", + reason: describeUnverifiedCause( + cause, + "start identity inspection failed without a message", + ), + ...(inspectionFailure === undefined ? {} : { inspectionFailure }), + } as const; + }, + ); + +/** + * Signal the captured root only while its retained launch identity still + * matches. A delivery whose identity check fails through the inspection owner + * is recorded as unverified, and the signaller keeps that failure until + * `settled` hands it to the run, so its descriptors stay owned for cleanup. + */ export const retainRootSignaller = ( pid: number, - finalizationMs: number, - runId: string, - host: FinalizationHost = { - observe: (rootPid) => - observeProcessStartIdentity(rootPid, undefined, runId), - signal: signalProcessWithStartIdentity, - }, -): StartedCaptureRuntime["signalRoot"] => { - const retained = - finalizationMs > 0 - ? host.observe(pid).then( - (observation) => - observation === undefined - ? ({ state: "gone" } as const) - : observation.state === "readable" - ? ({ - state: "identity", - identity: observation.identity, - } as const) - : ({ - state: "unverified", - reason: - observation.reason.trim() === "" - ? "start identity is unavailable without a diagnostic" - : observation.reason, - } as const), - (cause: unknown) => - ({ - state: "unverified", - reason: describeUnverifiedCause( - cause, - "start identity inspection failed without a message", - ), - }) as const, - ) - : undefined; - return async (signal) => { + retained: Promise, + signalProcess: FinalizationHost["signal"] = signalProcessWithStartIdentity, +): RootSignaller => { + const deliveries = new Set>(); + const inspectionFailures: ProcessCaptureInspectionFailure[] = []; + const deliver: RootSignaller["signal"] = async (signal) => { const identity = await retained; - if (identity === undefined) - return { - delivery: "unverified", - reason: "root identity was not retained", - }; if (identity.state === "unverified") return { delivery: "unverified", reason: identity.reason }; if (identity.state === "gone") return { delivery: "gone" }; - const delivery = await host.signal(pid, identity.identity, signal); - return delivery === "unverified" - ? { - delivery, - reason: - "start identity could not be verified or the signal call failed", - } - : { delivery }; + try { + const delivery = await signalProcess(pid, identity.identity, signal); + return delivery === "unverified" + ? { + delivery, + reason: + "start identity could not be verified or the signal call failed", + } + : { delivery }; + } catch (cause: unknown) { + inspectionFailures.push( + ...captureInspectionFailures(normalizeCaptureFailure(cause)), + ); + return { + delivery: "unverified", + reason: describeUnverifiedCause( + cause, + "signal delivery failed without a message", + ), + }; + } + }; + return { + signal: (signal) => { + const delivery = deliver(signal); + deliveries.add(delivery); + void delivery.finally(() => deliveries.delete(delivery)); + return delivery; + }, + settled: async () => { + while (deliveries.size > 0) await Promise.allSettled(deliveries); + return inspectionFailures.splice(0); + }, }; }; +/** + * The capture's root process fact: the PID with its retained launch + * identity, withheld when the caller selected PID normalization, or unknown + * with the reason. A PID without its start identity is not an identity. + */ +export const capturedRootProcess = ( + pid: number, + identity: RetainedRootIdentity, + pidsNormalized: boolean, +): ProcessCaptureRootProcess => + pidsNormalized + ? { state: "withheld-by-caller" } + : identity.state === "identity" + ? { state: "observed", pid, start_time: identity.identity } + : { + state: "unknown", + reason: + identity.state === "gone" + ? "the root process exited before its start identity was read" + : identity.reason, + }; + const cleanupFailedStartup = async (options: { readonly cause: unknown; readonly timers: Set; @@ -291,6 +376,7 @@ const startCaptureRuntime = async ( | ReturnType | undefined; let stopSampler: ReturnType | undefined; + let rootIdentity: Promise | undefined; try { const privacy = createProcessSensitiveOutput(scenario); if (!privacy.ok) throw privacy.error; @@ -383,6 +469,11 @@ const startCaptureRuntime = async ( renderer, started, }); + rootIdentity = retainRootIdentity( + terminal.pid, + options.runId, + options.finalizationHost?.observe, + ); stopSampler = startProcessSampler({ rootPid: terminal.pid, runId: options.runId, @@ -403,11 +494,11 @@ const startCaptureRuntime = async ( lastOutput: () => lastOutput, terminalObservation, stopSampler, - signalRoot: retainRootSignaller( + rootIdentity, + rootSignaller: retainRootSignaller( terminal.pid, - scenario.finalization_ms, - options.runId, - options.finalizationHost, + rootIdentity, + options.finalizationHost?.signal, ), }; } catch (cause: unknown) { @@ -420,13 +511,19 @@ const startCaptureRuntime = async ( try { await stopSampler?.(); } catch (samplingCause: unknown) { - failure = retainSamplingFailure( + failure = retainSecondaryInspectionFailure( failure, samplingCause, options.resourceScope, options.inspectionFailures, ); } + failure = retainRootIdentityFailure( + failure, + await rootIdentity, + options.resourceScope, + options.inspectionFailures, + ); return cleanupFailedStartup({ cause: failure, timers: options.timers, @@ -462,8 +559,30 @@ const retainRunInspectionFailures = ( return failure; }; -/** A sampler's final rejection cannot skip cleanup or replace an earlier physical failure. */ -const retainSamplingFailure = ( +/** + * A failed launch identity read through the inspection owner fails the + * capture like a sampler read: its descriptors stay owned for cleanup. + */ +const retainRootIdentityFailure = ( + primary: unknown, + identity: RetainedRootIdentity | undefined, + resources: ProcessCaptureResourceScope, + inspections: Set, +): unknown => + identity?.state === "unverified" && identity.inspectionFailure !== undefined + ? retainSecondaryInspectionFailure( + primary, + identity.inspectionFailure, + resources, + inspections, + ) + : primary; + +/** + * A sampler's, identity read's or signal delivery's final rejection cannot + * skip cleanup or replace an earlier physical failure. + */ +const retainSecondaryInspectionFailure = ( primary: unknown, cause: unknown, resources: ProcessCaptureResourceScope, @@ -521,13 +640,31 @@ const finishProcessRun = async (options: { try { await options.stopSampler(); } catch (cause: unknown) { - executionFailure = retainSamplingFailure( + executionFailure = retainSecondaryInspectionFailure( executionFailure, cause, options.resourceScope, options.inspectionFailures, ); } + // Join the launch identity read on every exit; it never rejects and, like + // other cleanup reads, runs without the caller's signal so it can finish. + executionFailure = retainRootIdentityFailure( + executionFailure, + await options.runtime?.rootIdentity, + options.resourceScope, + options.inspectionFailures, + ); + // Join finalization deliveries the same way: an identity check that failed + // through the inspection owner fails the capture and keeps its descriptors. + for (const inspection of (await options.runtime?.rootSignaller.settled()) ?? + []) + executionFailure = retainSecondaryInspectionFailure( + executionFailure, + inspection, + options.resourceScope, + options.inspectionFailures, + ); const sampledProcessGroupIds = options.runtime === undefined ? undefined @@ -727,6 +864,14 @@ const completeCapture = async (options: { truncated: after.truncated, }, ]; + // The launch identity read keeps running unsignalled for finalization + // signals; only this wait observes cancellation. finishProcessRun joins it. + const rootIdentity = await waitForAbortable( + runtime.rootIdentity, + options.signal, + ); + if (rootIdentity instanceof AbortedWait) + throw processCaptureCancelled(rootIdentity.carried); let manifest: Awaited>; try { manifest = await createRunManifest( @@ -734,6 +879,11 @@ const completeCapture = async (options: { runtime.startedAt, new Date(), runtime.executableIdentity, + capturedRootProcess( + runtime.terminal.pid, + rootIdentity, + scenario.normalization.pids, + ), { platform: options.hostPlatform, architecture: HOST_PLATFORM.architecture, @@ -902,7 +1052,7 @@ const runProcessScenario = async ( started: runtime.started, lastOutput: runtime.lastOutput, signal, - signalTarget: runtime.signalRoot, + signalTarget: runtime.rootSignaller.signal, recordFinalization: (finalization) => { observations.finalization = { state: "available", value: finalization }; }, diff --git a/src/rizin/RizinDebugSessionManager.ts b/src/rizin/RizinDebugSessionManager.ts index abe357cba5..151b110c41 100644 --- a/src/rizin/RizinDebugSessionManager.ts +++ b/src/rizin/RizinDebugSessionManager.ts @@ -1,4 +1,12 @@ -import { unknownTarget } from "../domain/targetIdentity.js"; +import { + unknownTarget, + type FileTargetIdentity, + type UnknownTargetIdentity, +} from "../domain/targetIdentity.js"; +import { + hashStableFile, + stableFileHashCause, +} from "../filesystem/StableFileHash.js"; import { readRuntimeSetting } from "../config/runtimeAnalysisSettings.js"; import { RIZIN_DEBUGGER_PROVIDER_IDENTITY } from "./RizinDebuggerProviderIdentity.js"; import { persistentDebuggerHostSupported } from "../process/PersistentDebuggerHost.js"; @@ -95,6 +103,19 @@ interface RizinLaunchProvenance { readonly resolved_path: string; } +/** + * The session's launch file, hashed before Rizin started. A hash failure + * other than cleanup or cancellation leaves the target unknown, with the + * failure retained as a limitation. + */ +interface RizinLaunchTarget { + readonly identity: FileTargetIdentity | UnknownTargetIdentity; + readonly unobservedReason?: string; +} + +const RIZIN_SESSION_TARGET_LIMITATION = + "The session target is the launch file hashed at session start; later debugger commands do not rebind it."; + const RIZIN_LAUNCH_PROVENANCE_LIMITATION = "Launch provenance records the original and resolved startup paths; it does not establish the current target after unrestricted debugger commands."; @@ -104,6 +125,7 @@ interface RizinCommandEvidenceInput { readonly result: RizinDebugCommandResult; readonly inferiorTty: string; readonly launchProvenance: RizinLaunchProvenance; + readonly launchTarget: RizinLaunchTarget; readonly limitations: readonly string[]; } @@ -113,10 +135,16 @@ const createRizinCommandEvidence = ({ result, inferiorTty, launchProvenance, + launchTarget, limitations, }: RizinCommandEvidenceInput): Evidence => createEvidence( - unknownTarget("not-observed"), + { + kind: "session", + session_kind: "rizin", + id: sessionId, + target: launchTarget.identity, + }, RIZIN_DEBUGGER_PROVIDER_IDENTITY, { predicateType: "rea.debugger.command-observation", @@ -130,7 +158,12 @@ const createRizinCommandEvidence = ({ result: { ...result }, rawResult: { ...result }, limitations: [ - "The current debugger target identity is not established by the Rizin session identifier.", + RIZIN_SESSION_TARGET_LIMITATION, + ...(launchTarget.unobservedReason === undefined + ? [] + : [ + `The launch file could not be hashed at session start, so the session target is unknown: ${launchTarget.unobservedReason}`, + ]), ...limitations, ...(result.completion_status === "unknown" ? [ @@ -174,6 +207,7 @@ interface RizinCommandTimeoutEvidenceInput { readonly inferiorTty: string; readonly cleanupFailure: string | undefined; readonly launchProvenance: RizinLaunchProvenance; + readonly launchTarget: RizinLaunchTarget; readonly deadline: DebuggerAdmissionLimit; } @@ -189,6 +223,7 @@ const createRizinCommandTimeoutEvidence = ({ inferiorTty, cleanupFailure, launchProvenance, + launchTarget, deadline, }: RizinCommandTimeoutEvidenceInput): Evidence => createRizinCommandEvidence({ @@ -197,6 +232,7 @@ const createRizinCommandTimeoutEvidence = ({ result, inferiorTty, launchProvenance, + launchTarget, limitations: [ rizinCommandTimeoutLimitation(deadline), ...(result.output_invalid_utf8 @@ -229,6 +265,7 @@ interface RizinDebugSession { }>; readonly backend: string | null; readonly launchProvenance: RizinLaunchProvenance; + readonly launchTarget: RizinLaunchTarget; readonly inferiorTty: string; readonly inferiorTtyDevice: number; readonly inferiorTtyInode: number; @@ -292,7 +329,7 @@ class RizinFrameTimeoutError extends Error { /** Owns persistent Rizin debugger processes independently from BinarySession. */ export class RizinDebugSessionManager { readonly #sessions: OwnedDebuggerSessionRegistry; - readonly #ttyResources = new ArtifactResourceScope(); + readonly #startupResources = new ArtifactResourceScope(); readonly #environment: Readonly; #closingAll = false; readonly #command: string; @@ -372,6 +409,73 @@ export class RizinDebugSessionManager { return parsed.value; } + /** + * Hash the launch file before Rizin starts, so the session names the file + * it launched. Cleanup failure and cancellation fail the start; any other + * hash failure leaves the target unknown and keeps its reason. + */ + async #observeLaunchFile( + path: string, + signal: AbortSignal | undefined, + ): Promise> { + const operation = "start_rizin_debug_session"; + let lease: AnalysisCleanupLease | undefined; + try { + const { sha256 } = await hashStableFile(path, { + ...(signal === undefined ? {} : { signal }), + retainFailedClose: (owner) => { + lease = new AnalysisCleanupLease(() => owner.close(), [path]); + this.#startupResources.retain({ + kind: "lease", + resource: path, + lease, + }); + }, + }); + return ok({ + identity: { + kind: "file", + sha256, + format: "file", + architecture: null, + selection: null, + }, + }); + } catch (cause: unknown) { + const cancellation = regularFileCancellation(cause); + const cancelled = + cancellation === undefined + ? undefined + : cancelledBy(operation, carriedReason(cancellation.reason)); + const describe = (failure: unknown): string => + errorMessage(stableFileHashCause(failure)); + if (!(cause instanceof RegularFileCleanupFailure)) { + if (cancelled !== undefined) return err(cancelled); + return ok({ + identity: unknownTarget("not-observed"), + unobservedReason: describe(cause), + }); + } + // The close failure fails the start; a read failure beside it stays + // in the error, since the retained lease only retries the close. + const cleanup = new ProviderCleanupError( + "rizin", + [path], + cause.outcome.kind === "failed" && cancelled === undefined + ? { launch_file_hash_failure: describe(cause.outcome.cause) } + : {}, + { operation, cause: cause.cleanupCause }, + ); + const error = + cancelled === undefined + ? cleanup + : analysisErrorWithCleanupFailure(cancelled, cleanup, operation); + lease?.bindCleanupError(cleanup); + if (error !== cleanup) lease?.bindCleanupError(error); + return err(error); + } + } + async start( input: { readonly path: string; @@ -459,11 +563,11 @@ export class RizinDebugSessionManager { let ttyInode: number; let ttyLease: AnalysisCleanupLease | undefined; try { - await this.#ttyResources.retryCleanup(); + await this.#startupResources.retryCleanup(); } catch (cause: unknown) { const cleanup = new ProviderCleanupError( "rizin", - this.#ttyResources.cleanupResources, + this.#startupResources.cleanupResources, {}, { operation: "start_rizin_debug_session", cause }, ); @@ -483,7 +587,7 @@ export class RizinDebugSessionManager { ...(signal === undefined ? {} : { signal }), retainFailedClose: (owner) => { ttyLease = new AnalysisCleanupLease(() => owner.close(), [ttyPath]); - this.#ttyResources.retain({ + this.#startupResources.retain({ kind: "lease", resource: ttyPath, lease: ttyLease, @@ -560,6 +664,10 @@ export class RizinDebugSessionManager { caller_selected_path: input.path, resolved_path: resolvedPath, }; + const launchTarget = await this.#observeLaunchFile(resolvedPath, signal); + if (!launchTarget.ok) return launchTarget; + if (signal?.aborted) + return err(cancelledBy("start_rizin_debug_session", signal)); const arguments_ = [ "-N", "-0", @@ -609,6 +717,7 @@ export class RizinDebugSessionManager { id, launched, launchProvenance, + launchTarget: launchTarget.value, backend: input.backend ?? null, inferiorTty: ttyPath, inferiorTtyDevice: ttyDevice, @@ -936,6 +1045,7 @@ export class RizinDebugSessionManager { result, inferiorTty: session.inferiorTty, launchProvenance: session.launchProvenance, + launchTarget: session.launchTarget, limitations: [ "Rizin commands and debugger effects depend on the loaded IO plugin and target.", "Output contains all NUL frames through an explicit command-completion marker; backend output interleaved before that marker cannot be distinguished from command output.", @@ -983,6 +1093,7 @@ export class RizinDebugSessionManager { result: partialResult, inferiorTty: session.inferiorTty, launchProvenance: session.launchProvenance, + launchTarget: session.launchTarget, limitations, }); if (signal?.aborted || cause instanceof AnalysisCancelledError) { @@ -1062,6 +1173,7 @@ export class RizinDebugSessionManager { cleanupFailure: stopped.status === "incomplete" ? stopped.reason : undefined, launchProvenance: session.launchProvenance, + launchTarget: session.launchTarget, }); return this.#finalizeCommandObservation( session, @@ -1078,6 +1190,7 @@ export class RizinDebugSessionManager { result, inferiorTty: session.inferiorTty, launchProvenance: session.launchProvenance, + launchTarget: session.launchTarget, limitations: [ "Rizin exited before the command-completion marker; retained frame output is partial and command completion is unknown.", "The command is unrestricted and may access local files, the shell, network, or mutate the target.", @@ -1229,11 +1342,11 @@ export class RizinDebugSessionManager { async retryCleanupFailures(): Promise> { try { - await this.#ttyResources.retryCleanup(); + await this.#startupResources.retryCleanup(); } catch (cause: unknown) { const error = new ProviderCleanupError( "rizin", - this.#ttyResources.cleanupResources, + this.#startupResources.cleanupResources, {}, { operation: "start_rizin_debug_session", @@ -1253,7 +1366,7 @@ export class RizinDebugSessionManager { await this.#sessions.closeStarts(); const outcomes = await Promise.allSettled([ this.#sessions.closeAll(), - this.#ttyResources.close(), + this.#startupResources.close(), ]); const failures = outcomes.flatMap((outcome) => outcome.status === "rejected" ? [outcome.reason] : [], diff --git a/tests/boundary/process/ProcessEvidence.test.ts b/tests/boundary/process/ProcessEvidence.test.ts index 8ffec42355..6923af9dc0 100644 --- a/tests/boundary/process/ProcessEvidence.test.ts +++ b/tests/boundary/process/ProcessEvidence.test.ts @@ -82,6 +82,7 @@ const captureEvidenceForEnvironmentSecret = async (value: string) => { new Date(0), new Date(1), executableIdentity, + { state: "withheld-by-caller" }, ); const base = emptyUnverifiedProcessCapture(); const scenarioManifest = { diff --git a/tests/boundary/process/processCaptureLifecycle.test.ts b/tests/boundary/process/processCaptureLifecycle.test.ts index 3bce132e3f..1ec3b4b4c5 100644 --- a/tests/boundary/process/processCaptureLifecycle.test.ts +++ b/tests/boundary/process/processCaptureLifecycle.test.ts @@ -13,6 +13,7 @@ import { fileURLToPath } from "node:url"; import { promisify } from "node:util"; import { expect, onTestFinished, vi } from "vitest"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { failedInspectionDescriptor } from "../../fixtures/processInspectionCleanup.js"; import { itWithCaptureCapability } from "./processCaptureCapability.js"; import { @@ -971,6 +972,175 @@ itWithCaptureCapability( 15_000, ); +itWithCaptureCapability( + "joins the launch identity read before a cancelled capture returns", + async () => { + const controller = new AbortController(); + let readSettledAt: number | undefined; + const finalizationHost: FinalizationHost = { + observe: async () => { + // Cancel while the launch identity read is still pending, then let + // the read finish only afterwards. + controller.abort(); + await new Promise((resolve) => setTimeout(resolve, 300)); + readSettledAt = performance.now(); + return { state: "readable" as const, identity: "launch" }; + }, + signal: async () => "signaled" as const, + }; + const root = await createTestTempDirectory("rea-root-identity-join-"); + const result = await captureProcessScenario( + processScenarioSchema.parse({ + executable: process.execPath, + arguments: ["-e", "setTimeout(() => {}, 20000)"], + working_directory: root, + timeout_ms: 20_000, + idle_timeout_ms: 20_000, + }), + controller.signal, + process.platform, + process.env, + undefined, + undefined, + undefined, + undefined, + finalizationHost, + ); + const returnedAt = performance.now(); + + if (result.ok) throw new Error("expected cancellation"); + if (!(result.error instanceof ProcessCaptureError)) throw result.error; + if (result.error.cleanupIncomplete) + expectUnverifiedHostCleanup(result.error); + expect( + readSettledAt, + "the capture does not return while its identity read is still running", + ).toBeDefined(); + expect(readSettledAt!).toBeLessThanOrEqual(returnedAt); + }, + 15_000, +); + +itWithCaptureCapability( + "fails the capture and keeps the descriptor a failed launch identity read could not close", + async () => { + const root = await createTestTempDirectory("rea-root-identity-owner-"); + const file = await failedInspectionDescriptor(root); + const finalizationHost: FinalizationHost = { + observe: async () => { + throw file.failure; + }, + signal: async () => "signaled" as const, + }; + const resources = new ProcessCaptureResourceScope(); + // A failed assertion must still release the capture's retained resources. + onTestFinished(async () => { + file.allow(); + await resources.close(); + }); + const result = await captureProcessScenario( + processScenarioSchema.parse({ + executable: process.execPath, + arguments: ["-e", ""], + working_directory: root, + timeout_ms: 5_000, + idle_timeout_ms: 5_000, + }), + undefined, + process.platform, + process.env, + undefined, + undefined, + undefined, + resources, + finalizationHost, + ); + + if (result.ok) + throw new Error("expected the unclosed identity descriptor to fail"); + expect( + result.error.cleanupResources, + "the failure names the descriptor the identity read left open", + ).toContain(file.path); + expect(result.error.cleanupIncomplete).toBe(true); + expect(file.handle.fd, "the descriptor stays owned").not.toBe(-1); + file.allow(); + await resources.close(); + expect(file.handle.fd, "a cleanup retry closes it").toBe(-1); + expect(result.error.cleanupIncomplete).toBe(false); + }, +); + +itWithCaptureCapability( + "fails the capture and keeps the descriptor a finalization signal's identity check could not close", + async () => { + const root = await createTestTempDirectory("rea-signal-identity-owner-"); + const file = await failedInspectionDescriptor(root); + const finalizationHost: FinalizationHost = { + observe: async () => ({ state: "readable" as const, identity: "launch" }), + signal: async (pid, _identity, signal) => { + if (signal === "SIGTERM") throw file.failure; + process.kill(pid, signal); + return "signaled" as const; + }, + }; + const resources = new ProcessCaptureResourceScope(); + // A failed assertion must still release the capture's retained resources. + onTestFinished(async () => { + file.allow(); + await resources.close(); + }); + const result = await captureProcessScenario( + processScenarioSchema.parse({ + executable: process.execPath, + arguments: [finalizationFixture, "ignoring", root], + working_directory: root, + idle_timeout_ms: 10_000, + timeout_ms: 300, + finalization_ms: 300, + }), + undefined, + process.platform, + process.env, + undefined, + undefined, + undefined, + resources, + finalizationHost, + ); + + if (result.ok) + throw new Error("expected the unclosed signal descriptor to fail"); + if (!(result.error instanceof ProcessCaptureError)) throw result.error; + expect( + result.error.cleanupResources, + "the failure names the descriptor the signal's identity check left open", + ).toContain(file.path); + expect(result.error.cleanupIncomplete).toBe(true); + expect(file.handle.fd, "the descriptor stays owned").not.toBe(-1); + const partial = result.error.partialObservation; + if (partial === undefined || !("capture" in partial)) + throw new Error("expected the completed capture observations"); + expect( + partial.capture.exit.finalization, + "the failed delivery stays recorded as unverified", + ).toMatchObject({ + signals: [ + { + signal: "SIGTERM", + delivery: "unverified", + reason: file.failure.message, + }, + { signal: "SIGKILL", delivery: "signaled" }, + ], + }); + file.allow(); + await resources.close(); + expect(file.handle.fd, "a cleanup retry closes it").toBe(-1); + expect(result.error.cleanupIncomplete).toBe(false); + }, +); + itWithCaptureCapability( "keeps the attempts when the escalation cannot be delivered through the retained identity", async () => { diff --git a/tests/boundary/process/processDescendantPidAdapters.test.ts b/tests/boundary/process/processDescendantPidAdapters.test.ts index 8629e1d3ab..07abe48b41 100644 --- a/tests/boundary/process/processDescendantPidAdapters.test.ts +++ b/tests/boundary/process/processDescendantPidAdapters.test.ts @@ -100,6 +100,21 @@ itWithCaptureCapability.each([ const identity = identitySchema.parse( JSON.parse(await readFile(identityPath, "utf8")), ); + expect( + evidence.subject, + "the subject names the observed root by PID and start identity, and withholds both when the caller normalized PIDs", + ).toEqual({ + identity: pids + ? { kind: "unknown", reason: "withheld-by-caller" } + : { + kind: "process", + pid: identity.root_pid, + start_time: expect.stringMatching(/\S/u), + executable_sha256: capture.manifest.executable_sha256, + }, + name: null, + local_path: null, + }); const original = `root pid ${identity.root_pid}\r\nchild pid ${identity.child_pid}\r\ncount 9007199254740991\r\n`; const expected = pids ? "root pid \r\nchild pid \r\ncount 9007199254740991\r\n" diff --git a/tests/boundary/process/processHostIdentity.test.ts b/tests/boundary/process/processHostIdentity.test.ts index db84d1c392..fd7ba69a57 100644 --- a/tests/boundary/process/processHostIdentity.test.ts +++ b/tests/boundary/process/processHostIdentity.test.ts @@ -27,6 +27,7 @@ it("uses one selected host identity for manifest and settlement", async () => { new Date(0), new Date(1), observeLaunchedExecutable(scenario.executable, selectedExecutable), + { state: "withheld-by-caller" }, selectedHost, ); const settlement = await observeSettlement({ diff --git a/tests/boundary/providers/GdbSessionManagerCoverage.test.ts b/tests/boundary/providers/GdbSessionManagerCoverage.test.ts index 6e57a0b589..737b39f2ef 100644 --- a/tests/boundary/providers/GdbSessionManagerCoverage.test.ts +++ b/tests/boundary/providers/GdbSessionManagerCoverage.test.ts @@ -2459,6 +2459,13 @@ it("retains a multi-run console command through its completion query before disp expect(result.value.evidence.normalized_result).toMatchObject({ console: result.value.result.console, }); + // The session launches no file, so its target stays unknown. + expect(result.value.evidence.subject.identity).toEqual({ + kind: "session", + session_kind: "gdb", + id: started.value.session_id, + target: { kind: "unknown", reason: "not-observed" }, + }); const next = await follower; if (!next.ok) throw next.error; expect(next.value.result.console).toBe('~"REA_NEXT_COMMAND\\n"'); diff --git a/tests/boundary/providers/GdbSessionReviewRegressions.test.ts b/tests/boundary/providers/GdbSessionReviewRegressions.test.ts index 4327cadb7c..dc4173c330 100644 --- a/tests/boundary/providers/GdbSessionReviewRegressions.test.ts +++ b/tests/boundary/providers/GdbSessionReviewRegressions.test.ts @@ -1166,6 +1166,14 @@ process.stdin.on("data", (chunk) => { }, }); expect(exited.error.partialObservation).toMatchObject({ + subject: { + identity: { + kind: "session", + session_kind: "gdb", + id: started.value.session_id, + target: { kind: "unknown", reason: "not-observed" }, + }, + }, parameters: { command: "second command", session_id: started.value.session_id, diff --git a/tests/boundary/providers/RizinDebugSessionCoverage.part3.test.ts b/tests/boundary/providers/RizinDebugSessionCoverage.part3.test.ts index e81cf65202..d8eecb2290 100644 --- a/tests/boundary/providers/RizinDebugSessionCoverage.part3.test.ts +++ b/tests/boundary/providers/RizinDebugSessionCoverage.part3.test.ts @@ -1,4 +1,9 @@ +import { createHash } from "node:crypto"; +import { writeFileSync } from "node:fs"; +import { writeFile } from "node:fs/promises"; +import { join } from "node:path"; import { afterEach, expect, it, vi } from "vitest"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { withVerifierCleanup } from "../../../scripts/lib/verifier-cleanup.mjs"; import { phaseGate } from "../../support/lifecycleHarness.js"; import { AnalysisCancelledError } from "../../../src/domain/analysisErrorCore.js"; @@ -40,7 +45,10 @@ it.skipIf(process.platform === "win32")( }, }); expect(result.value.evidence.limitations).toEqual([ - expect.stringMatching(/target identity.*not established/iu), + expect.stringMatching( + /session target is the launch file.*do not rebind/iu, + ), + expect.stringMatching(/launch file could not be hashed.*unknown/iu), expect.stringMatching( /timed out.*10 ms.*REA_DEBUGGER_COMMAND_DEADLINE_MS.*partial.*completion is unknown/iu, ), @@ -323,7 +331,10 @@ it.skipIf(process.platform === "win32")( }); expect(result.value.evidence.raw_result).toEqual(result.value.result); expect(result.value.evidence.limitations).toEqual([ - expect.stringMatching(/target identity.*not established/iu), + expect.stringMatching( + /session target is the launch file.*do not rebind/iu, + ), + expect.stringMatching(/launch file could not be hashed.*unknown/iu), expect.stringMatching( /Rizin exited.*output is partial.*completion is unknown/iu, ), @@ -716,3 +727,77 @@ it.skipIf(process.platform === "win32").each([false, true])( } }, ); + +it.skipIf(process.platform === "win32")( + "binds command Evidence to the session and the launch file hashed before Rizin starts", + async () => { + const directory = await createTestTempDirectory("rea-rizin-launch-"); + const launchFile = join(directory, "target.bin"); + await writeFile(launchFile, "launch bytes"); + const missing = join(directory, "missing.bin"); + for (const path of [launchFile, missing]) { + const injected = createInjectedProcess({ + // Rewriting the file after the hash must not rebind the session. + beforeSpawnReturns: () => { + if (path === launchFile) writeFileSync(launchFile, "after spawn"); + }, + onWrite: (text, control) => { + const marker = /!echo (.+)\n/u.exec(text)?.[1]; + if (marker !== undefined) + setImmediate(() => { + control.output(Buffer.from([0])); + control.output(Buffer.from(`${marker}\0`)); + }); + }, + }); + const manager = createManager( + { REA_RIZIN_COMMAND: "injected-rizin" }, + { spawnProcess: injected.spawnProcess }, + ); + const started = await manager.start({ + path, + inferior_tty: await rizinTestInferiorTty(), + }); + if (!started.ok) throw started.error; + const first = await manager.execute(started.value.session_id, "dr"); + if (!first.ok) throw first.error; + await writeFile(launchFile, "between commands"); + const result = await manager.execute(started.value.session_id, "dr"); + if (!result.ok) throw result.error; + expect( + result.value.evidence.subject, + "later commands keep the subject bound at start", + ).toEqual(first.value.evidence.subject); + expect( + result.value.evidence.subject, + "the subject is the minted session bound to its launch file, or an explicit unknown when the file could not be hashed", + ).toEqual({ + identity: { + kind: "session", + session_kind: "rizin", + id: started.value.session_id, + target: + path === launchFile + ? { + kind: "file", + sha256: createHash("sha256") + .update("launch bytes") + .digest("hex"), + format: "file", + architecture: null, + selection: null, + } + : { kind: "unknown", reason: "not-observed" }, + }, + name: null, + local_path: null, + }); + expect( + result.value.evidence.limitations.some((limitation) => + /launch file could not be hashed/iu.test(limitation), + ), + "only an unhashable launch file records the hash failure", + ).toBe(path === missing); + } + }, +); diff --git a/tests/boundary/providers/RizinTtyCleanup.test.ts b/tests/boundary/providers/RizinTtyCleanup.test.ts index bd59fff2fc..29909184e7 100644 --- a/tests/boundary/providers/RizinTtyCleanup.test.ts +++ b/tests/boundary/providers/RizinTtyCleanup.test.ts @@ -1,7 +1,9 @@ import { isatty } from "node:tty"; import { open } from "node:fs/promises"; +import { join } from "node:path"; import { expect, it, onTestFinished, vi } from "vitest"; import { createInjectedProcess } from "./RizinDebugSessionCoverage.fixtures.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { RizinDebugSessionManager } from "../../../src/rizin/RizinDebugSessionManager.js"; vi.mock("node:tty", async (importOriginal) => { @@ -237,3 +239,72 @@ it.skipIf(process.platform === "win32")( expect(second.error.cleanupIncomplete).toBe(false); }, ); + +it.skipIf(process.platform === "win32")( + "keeps the launch file read failure when its descriptor close also fails", + async () => { + const actual = + await vi.importActual( + "node:fs/promises", + ); + vi.mocked(isatty).mockReturnValue(true); + // Registered first, so its removal runs after the descriptor release. + const directory = await createTestTempDirectory("rea-rizin-launch-close-"); + const launchFile = join(directory, "target.bin"); + await actual.writeFile(launchFile, "launch bytes"); + let allowClose = false; + let closeCalls = 0; + let releaseFixture: (() => Promise) | undefined; + vi.mocked(open).mockImplementation(async (...args) => { + const handle = await actual.open(...args); + if (args[0] !== launchFile) return handle; + const close = handle.close.bind(handle); + releaseFixture = close; + vi.spyOn(handle, "read").mockRejectedValue( + new Error("launch file read refused"), + ); + vi.spyOn(handle, "close").mockImplementation(async () => { + closeCalls++; + if (!allowClose) throw new Error("launch file close refused"); + await close(); + }); + return handle; + }); + onTestFinished(async () => { + await releaseFixture?.().catch(() => undefined); + vi.restoreAllMocks(); + }); + let spawned = false; + const manager = new RizinDebugSessionManager( + {}, + { + platform: "linux", + spawnProcess: () => { + spawned = true; + throw new Error("must not spawn after a failed close"); + }, + }, + ); + const result = await manager.start({ + path: launchFile, + inferior_tty: "/dev/null", + }); + if (result.ok) throw new Error("expected the failed close to fail start"); + expect(spawned, "a retained descriptor fails the start").toBe(false); + expect(result.error.cleanupIncomplete).toBe(true); + expect(result.error.cleanupResources).toContain(launchFile); + expect( + result.error.diagnostics, + "the read failure is kept beside the close failure", + ).toMatchObject({ + launch_file_hash_failure: expect.stringContaining( + "launch file read refused", + ), + }); + allowClose = true; + expect((await manager.retryCleanupFailures()).ok).toBe(true); + expect(closeCalls).toBe(2); + expect(result.error.cleanupIncomplete).toBe(false); + await manager.closeAll(); + }, +);