Compare commits

..
Author SHA1 Message Date
N0zoM1z0 34661d816c fix(hopper): distinguish runtime processes from argument text
Parse procfs argument boundaries rather than searching rendered ps command text. Keep executable identity checks and deferred permission failures, eliminate the extra ps process, and put shared process observations in the serial process-boundary lane.
2026-10-13 06:52:50 +00:00
Rudy Mizrahi Celekli e74e4e951b fix(screenshot): reject invalid PNG header dimensions (#2472) 2026-10-13 15:50:44 +09:00
chAngEandchAngE 68ecf3df8c fix(browser): exclude sensitive binary lengths from historical captures (#2477)
Co-authored-by: chAngE <172472630+chAng-L19@users.noreply.github.com>
2026-10-13 14:49:47 +08:00
Stefano RizzelloandClaude Opus 5 ab62ee9dcf fix(windows): preserve caller affinity only within one processor group (#2202)
* fix(windows): preserve caller affinity only within one processor group

`spawnProcess` read the caller's affinity mask and applied it to the
suspended child unconditionally. A mask names processors relative to one
processor group, and Windows assigns each new process to a group of its
own choosing, so on hosts with more than 64 logical processors the child
is often placed in another group. `SetProcessAffinityMask` then rejects
the mask with ERROR_INVALID_PARAMETER (87) and the spawn fails, making
every owned provider process start intermittently on such hosts.

Affinity is a nicety, not an authority or isolation control, so it is now
applied only when the caller and the suspended child both occupy the same
single processor group. A child placed in another group keeps that group's
default affinity and the spawn proceeds. Job Object membership,
kill-on-owner-close policy, owner normalization and priority preservation
are unchanged, and the mask failure remains fatal within a shared group,
where it is not expected.

Single-group hosts, including every host with 64 or fewer logical
processors, are unaffected: `GetProcessGroupAffinity` reports one group
for both processes and the same mask is applied as before.

The optional process-boundary fixture gains an `affinity` observation,
and the native verification lane asserts that an owned spawn succeeds and
that the child's mask matches the caller's whenever both share a single
group.

Fixes #2181

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(windows): refuse to widen a pinned caller's affinity across groups

Addresses review feedback on the first commit.

An unconstrained caller loses nothing when Windows places an owned child
in another processor group, so that spawn proceeds with the group's
default. A caller deliberately pinned to fewer processors than its group
holds is a different case: silently accepting the default would hand the
provider tree the whole group, which `docs/installation.md` tells
operators to rely on affinity to prevent. Such a spawn now fails naming
the constraint instead. `GetProcessAffinityMask` already reports the
group's active set, which distinguishes the two without another query.

Selecting the caller's group at creation through
PROC_THREAD_ATTRIBUTE_GROUP_AFFINITY was tried first and rejected:
`CreateProcessW` fails with ERROR_INVALID_PARAMETER on a host with a
single processor group, both alongside PROC_THREAD_ATTRIBUTE_JOB_LIST and
on its own, so it cannot carry the ordinary path.

The boundary fixture's affinity observation now reports a process id's
own mask rather than its own, because a separate probe process is
assigned its own group and cannot stand in for the process that spawns
the child. Masks and the group's active set cross as fixed-width
hexadecimal strings: a mask can set bits above the safe-integer range,
where `JSON.parse` would round two different masks to one value.

The verification lane asserts the mask is inherited exactly when caller
and child share a group, and otherwise that the caller was unconstrained.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* docs(windows): record what owned-process affinity does not preserve

A mask covering its group's whole active set does not distinguish a
caller the system placed in that group from one that selected the group
deliberately, so an owned child can still be placed elsewhere with its
processor count bounded and its group placement lost. Treating that case
as constrained instead is not available: on a multi-group host an
ordinary process is assigned a group by the system and its mask is that
group's active set, so refusing it would fail every owned spawn there.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-10-13 14:49:34 +08:00
吴佳浩Albenand吴佳浩 2c6a4fac4f fix(process): accept a trace identifier the comparison result can represent (#2488)
The trace specification owns the declared identifier vocabulary and the
comparison result echoes those identifiers verbatim into raw_trace[].event_id,
matched_variant and diagnostic event_ids. The result module restated the shared
IDENTIFIER_PATTERN by hand with a 64-character cap, so a specification with a
longer identifier validated and then its own comparison result failed to parse:
compareProcessTraces threw a raw ZodError at the caller instead of returning a
comparison.

Export the identifier schema from the specification as the single owner and
reuse it in the evaluation module, removing the capped copy. IDENTIFIER_PATTERN
has no length bound and every other consumer uses it unbounded, so the
duplicate was the outlier. Removing the bound rather than adding one keeps the
advertised trace_spec input contract unchanged; identifiers of 64 characters or
fewer behave exactly as before.

Verified with 48 process tests, 24 boundary CLI/MCP trace tests, check:fast and
verify:test-discovery on macOS arm64. The regression test failed with the
ZodError before the change and passes after it.

Co-authored-by: 吴佳浩 <wujiahao@supremind.com>
2026-10-13 14:48:26 +08:00
Mykola Dementiev c6acd19b6d fix(ida): stop the private input of a universal Mach-O at the end of the selected slice (#2291)
* test(ida): expect the private input of a universal Mach-O to end at the selected slice

Cover a universal file larger than one read chunk with another slice after the selected one, for both a middle slice and the first slice.

* fix(ida): stop the private input of a universal Mach-O at the end of the selected slice

A read chunk that starts after the slice produced a negative end offset, and Buffer.subarray counts a negative bound from the end, so the head of the following slice was written to the private input and its digest.
2026-10-13 14:48:17 +08:00
AurantiumandAurantium-47 1a1b67c888 fix(javascript): preserve POSIX runtime path case on Windows (#2422)
Use POSIX path semantics for recorded POSIX roots when reconciling runtime Evidence on Windows. Preserve Windows mapping behavior and cover implicit and explicit file roots through the reconciliation service.

Assisted-by: OpenAI GPT-6 <noreply@openai.com>

Co-authored-by: Aurantium-47 <280805072+Aurantium-47@users.noreply.github.com>
2026-10-13 14:46:28 +08:00
Rohit Ghumare 12303812a8 fix(evidence): admit bundle imports across session transitions (#2303) 2026-10-13 14:45:03 +08:00
Kaoru0822andClaude Opus 5.5 f6556ad2bc fix(pcap): order evidence ties by code point instead of host locale (#2509)
The pcap summary sorted equal-count endpoints and protocol stacks with
String#localeCompare, and Flutter build inspection sorted APK ABI
directory names the same way. localeCompare follows the host's ICU
locale, so the same capture produced differently ordered Evidence on
different hosts: under da_DK "aarp" sorts after "zz", under lt_LT
"syslog" sorts before "ssdp", and every locale puts "fe80::1" before
"fe80:1::1". Use the repository's compareUnicodeCodePoints, as the
other Evidence producers already do.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 14:44:09 +08:00
吴佳浩Albenand吴佳浩 d73ed6fce2 fix(domain): preserve retryable capability failures through redaction (#2494)
redactExplicitFailure rebuilds each typed failure field by field so explicit
literals are removed while the projected code stays the same. The rebuild for
AnalysisCapabilityUnavailableError carried providerId, operation, reason and
userMessage but not retryable, and the constructor defaults that field to false.
Redacting a transient capability failure therefore made it permanent and changed
the remediation shown to the caller.

Pass the field through with the same conditional-spread shape used for
userMessage. The constructor recomputes retryable from cleanupIncomplete, and
cleanup is already part of the reconstructed context, so a value that was true
before redaction stays true and a false value stays absent.

Verified with 66 error projection, access-denied, redaction and capture-failure
tests, check:fast and verify:test-discovery on macOS arm64. The regression test
failed with "expected false to be true" before the change.

Co-authored-by: 吴佳浩 <wujiahao@supremind.com>
2026-10-13 14:43:10 +08:00
Vinícius Andrade 60f771a11e fix(apple): limit already-loaded reuse to rpath dependencies (#2292)
* fix(apple): limit already-loaded reuse to rpath dependencies

dyld reuses an already-loaded image by install name only for @rpath/
dependencies (Loader.cpp:802-816) and evaluates other dependency forms
against their expanded path for each loader. When multiple images in
different directories depend on @loader_path/ libraries sharing an
install name, checking loaded images before candidate expansion caused
subsequent loaders to bind to the first loaded image's copy or appear
resolved when their own copy was absent.

Limit byInstallName registration and lookup to install names that start
with @rpath/, leaving caller-relative and literal dependencies to expand
and evaluate their own candidate paths.

Signed-off-by: Vinícius DS Andrade <95101505+viniciusdsandrade@users.noreply.github.com>

* test(apple): verify loader_path dependencies across isolated directories

Assert that multiple images depending on @loader_path/ libraries with
the same install name do not reuse already-loaded images across loaders.
When the second loader's helper is absent, its candidate path is absent
and dyld reports required-load-unresolved; when both helpers exist, each
loader resolves to its own directory.

Signed-off-by: Vinícius DS Andrade <95101505+viniciusdsandrade@users.noreply.github.com>

---------

Signed-off-by: Vinícius DS Andrade <95101505+viniciusdsandrade@users.noreply.github.com>
2026-10-13 14:40:43 +08:00
The one -Niu 650237efb0 fix(setup): pin Hopper's macOS publisher identity before install (#2481)
The macOS installer accepted any bundle that passed `codesign --verify`
and whose `Info.plist` said `com.cryptic-apps.hopper-web-4`. An ad-hoc
signed bundle with that identifier satisfies both, so a substituted DMG
could be copied to ~/Applications and launched.

Verify a pinned code requirement instead, covering the sealed bundle
identifier and the signing team together, and report a distinct
`publisher_verification_failed` code so a vendor key change is not
confused with a corrupt package.
2026-10-13 14:40:04 +08:00
吴佳浩Albenand吴佳浩 7017c4d68c fix(artifacts): read every ZIP package family extraction is asked to open (#2493)
extract_artifact carried its own copy of the ZIP package format list with five
of the eight members the domain owner declares, and used it both as the guard
that refuses a format without an extraction reader and as the selector for the
reader itself. A .hap, .hsp or App Pack target was therefore refused with
"Artifact format has no extraction reader" even though the next branch builds a
ZipArtifactReader for exactly those formats, while inventory_artifact classifies
the same path through the owner and reads it.

Import isZipPackageFormat from the domain owner and delete the duplicate list
and its predicate, removing the second representation instead of reconciling it.
The reader branch now narrows to ZipPackageFormat, which is what the
ZipArtifactReader constructor already requires.

Verified with 41 boundary extraction, ZIP integrity and detection tests,
check:fast and verify:test-discovery on macOS arm64. Reverting only the source
change fails exactly the three added families and leaves the zip control green.

Co-authored-by: 吴佳浩 <wujiahao@supremind.com>
2026-10-13 14:39:29 +08:00
YsopwnableandLuis Taffelli 141d2095f5 test(hopper): repair Linux demo setup and native verification (#2638)
* fix(verification): align Linux Hopper setup lane with current contracts

* fix(verification): retain orphan checks on clean Linux runners

* fix(verification): detect Hopper through alternate launcher paths

* fix(verification): report identified Hopper leaks before proc errors

* fix(verification): distinguish Hopper string recognition from byte fidelity

* fix(verification): report full literal decoding coverage explicitly

---------

Co-authored-by: Luis Taffelli <86675342+LuisTaffelli@users.noreply.github.com>
2026-10-13 14:39:18 +08:00
58 changed files with 1779 additions and 742 deletions
+1 -1
View File
@@ -93,7 +93,7 @@ def project_record(state, secrets):
safe_bytes, credential_url = transport_value(value, path, transport_url)
content_base64 = base64.b64encode(value).decode("ascii")
digest = hashlib.sha256(value).hexdigest()
hidden = any(secret in value or secret in safe_bytes for secret in byte_secrets) or any(secret in content_base64 or secret in digest for secret in secrets)
hidden = any(secret in value or secret in safe_bytes for secret in byte_secrets) or any(secret in content_base64 or secret in digest or secret in str(len(value)) for secret in secrets)
safe_text = None
try:
safe_text = safe_bytes.decode("utf-8", errors="strict")
+1 -1
View File
@@ -174,7 +174,7 @@ Resolution follows dyld:
- `@rpath` tries each `LC_RPATH` of the loading image first, then those of the
image that loaded it, up to the process root.
- Dependencies load dependents-first in load-command order, and each image
loads once per process. A later request whose install name matches an
loads once per process. A later @rpath request whose install name matches an
already loaded image reuses it.
- Symlinks such as `Versions/Current` are followed inside the analyzed root.
An escape through `..` or an absolute link is `escapes-target`.
+31 -2
View File
@@ -298,13 +298,42 @@ subsequent wire recovery and clean shutdown. Caller timeout does not interrupt
Hopper's synchronous native operation. Socket boundary tests deterministically
cover active and queued expiry, late replies and timer cleanup.
The Linux demo lane remains a separate `verify:hopper:linux` command. Its
lifecycle checks attempt competing CLI launches for the active target and a
The Linux demo lane remains a separate `verify:hopper:linux` command. Hopper
6.4.2's ELF loader did not recognize the original 4,119-byte literal or three
non-ASCII byte strings in the measured fixtures. The lane retains complete raw
byte checks for those literals through source-owned symbols. Recognition of the
original full-length literal is bound to its exact source address; its decoded
object coverage remains explicitly unverified on Linux even when recognized.
Absent non-ASCII recognition also reports decoded-object coverage as unverified.
Recognized non-ASCII and control-text objects must still match their source
bytes, encoding, filters and searches.
A separate 548-byte ASCII literal requires native fragmentation, shortened
provider display, complete decoded fragments and dossier provenance on Linux;
the macOS lane retains the original full-length recognition requirement. These
are observed fixture/build capabilities, not universal Hopper length limits.
Its lifecycle checks attempt competing CLI launches for the active target and a
different target, requiring rejection before either can change the owning
MCP session's documents or procedures. Lease boundary tests also preserve
unresponsive or malformed live endpoints while allowing confirmed stale
sockets to recover.
`verify:setup:linux` exercises installation on a clean supported Linux runner as
root. Use a disposable VM: this lane installs Hopper and its Linux runtime
dependencies through the system package manager. Set `REA_VERIFY_SERVER_COMMAND`
to the CLI entrypoint being verified. The command builds and checks source-owned
ELF fixtures before testing the read-only Hopper setup plan, approved
installation, scoped doctor, real CLI/MCP analysis, rejection of a modified
launcher, idempotent setup without requesting a reinstall, and owned child
cleanup. Before installation and after teardown, a clean-runner process scan
also rejects surviving Hopper demo helpers or Xvfb groups, including orphans
whose launcher exited. This scan observes processes without signaling them.
Hopper detection compares executable file identity through `/proc`, covering
alternate or configured launcher paths even after an invoked symlink is removed.
The dedicated runner must have no unrelated Hopper/Xvfb sessions. It requires
the repository's pinned development toolchain and an
existing host C compiler, `file`, `nm`, and `strings`. Use `verify:hopper:linux`
instead when Hopper is already installed.
`verify:hopper:fat` is a separate macOS lane requiring installed Hopper and the
existing Xcode clang/lipo toolchain. It compiles arm64/x86-64 thin executables and
one- and two-slice FAT32 containers, verifies exact/interior address mappings
+6 -2
View File
@@ -153,8 +153,12 @@ the private runtime, isolating Ghidra preferences, logs, and caches.
Process creation assigns a suspended child atomically to an owned Job Object.
Membership and kill-on-owner-close policy are verified before resume.
Breakaway is disabled. Only the child's default file owner is normalized;
the caller token stays unchanged. Caller CPU affinity and priority are
preserved. Close, cancellation, timeout, startup failure, and provider failure
the caller token stays unchanged. Caller priority is preserved, and caller CPU
affinity whenever the caller and the child share a processor group. A child that
Windows places in another group keeps that group's default when the caller asked
for no bound of its own; a caller pinned to fewer processors than its group
holds is refused there rather than widened.
Close, cancellation, timeout, startup failure, and provider failure
terminate the job and verify all members have settled before runtime cleanup.
Cleanup removes admitted objects by handle and unlinks reparse entries without
following their targets. Abrupt owner death kills the job but can leave
@@ -19,10 +19,6 @@ Follow-up: [SQLite existing-control measurements](sqlite-existing-controls.md)
tests QGIS's shipped GeoPackage through the existing column selection, preserving
full selected-table schema and typed cells before considering another API.
Follow-up: [small real PCAP recordings](pcap-small-captures.md) compares existing
complete delivery with summary/pages. Preserve the negative SDK/model input
results: compact captures do not justify another production mechanism.
Follow-up: [native PE/DOS entry views and real model verification](native-entry-views.md)
records the post-merge native continuation, including a small-function case where
four selected replies cost more bytes than the complete dossier.
@@ -178,7 +178,7 @@ def main():
'inspect_android_package', 'search_android_classes',
'inspect_android_class', 'inspect_android_method',
'inspect_firmware_regions', 'inspect_managed_artifact',
'inspect_sqlite_database', 'inspect_pcap_capture',
'inspect_sqlite_database',
'inspect_managed_members', 'inspect_managed_native_boundaries',
'inspect_artifact', 'inspect_wasm_artifact',
'inspect_evm_interface', 'get_evidence_bundle', 'export_evidence_bundle',
@@ -70,32 +70,6 @@ for (const [side, answer] of [
value: answer.evidence_ids,
});
}
// PCAP delivery observations preserve each actual receipt's identity, limitations
// and view coverage. Summary/page scopes differ from complete source scope;
// retain them as run-specific facts rather than equating page exhaustion with
// capture coverage. The common capture facts and URI prefix still must match.
if (
["wireshark-http.cap", "wireshark-http_redirects.pcapng"].includes(
left.artifact,
)
) {
for (const [side, answer] of [
["left", a],
["right", b],
]) {
if (
!Array.isArray(answer.delivery_observations) ||
!answer.delivery_observations.length
)
throw new Error("Missing original PCAP delivery observations");
runSpecific.push({
side,
path: ["delivery_observations"],
value: answer.delivery_observations,
});
delete answer.delivery_observations;
}
}
// Binwalk assigns a new opaque region UUID in each invocation. Preserve both
// original lookup values in this report; compare the observed region facts
// separately. The product and original replies retain those IDs unchanged.
@@ -263,34 +263,6 @@
"url": "https://raw.githubusercontent.com/qgis/QGIS/e1223b8e9e71fc50ee995ed556f711c54ccc101b/resources/data/world_map.gpkg",
"derivation": "unmodified official resource file; streaming Git blob and SHA-256 verification"
}
},
{
"id": "wireshark-http.cap",
"file": "http.cap",
"bytes": 25803,
"sha256": "25a72bdf10339f2c29916920c8b9501d294923108de8f29b19aba7cc001ab60d",
"provenance": {
"project": "Wireshark public sample captures",
"source_page": "https://wiki.wireshark.org/SampleCaptures",
"url": "https://wiki.wireshark.org/uploads/27707187aeb30df68e70c8fb9d614981/http.cap",
"resolved_url": "https://gitlab.com/wireshark/wireshark/-/wikis/uploads/27707187aeb30df68e70c8fb9d614981/http.cap",
"upstream_expected_digest": null,
"derivation": "Unmodified capture published by official Wireshark wiki. Local digest pins downloaded bytes; no independently published upstream digest is claimed."
}
},
{
"id": "wireshark-http_redirects.pcapng",
"file": "http_redirects.pcapng",
"bytes": 47804,
"sha256": "ff432a6b71d06cd20720f7763e584014edd0a43c3b55981c682d1b7640207abc",
"provenance": {
"project": "Wireshark public sample captures",
"source_page": "https://wiki.wireshark.org/SampleCaptures",
"url": "https://wiki.wireshark.org/uploads/__moin_import__/attachments/SampleCaptures/http_redirects.pcapng",
"resolved_url": "https://gitlab.com/wireshark/wireshark/-/wikis/uploads/__moin_import__/attachments/SampleCaptures/http_redirects.pcapng",
"upstream_expected_digest": null,
"derivation": "Unmodified capture published by official Wireshark wiki. Local digest pins downloaded bytes; no independently published upstream digest is claimed."
}
}
]
}
-108
View File
@@ -523,115 +523,7 @@ const inspectEvmTarget = async () => {
};
};
const pcapObservation = (evidence) => {
const value = normalized(evidence);
return {
evidence_id: evidence.evidence_id,
limitations: evidence.limitations,
...Object.fromEntries(
[
"kind",
"view",
"parent_evidence_id",
"coverage",
"limitations",
"unknowns",
]
.filter((key) => Object.hasOwn(value, key) && key !== "limitations")
.map((key) => [key, value[key]]),
),
...(Object.hasOwn(value, "limitations")
? { normalized_limitations: value.limitations }
: {}),
};
};
const inspectPcapTarget = async () => {
const input = {
path: values.path,
...(values.delivery === "summary" ? { detail: "summary" } : {}),
};
const definition = catalogDefinitions.get("inspect_pcap_capture");
const ajv = new Ajv2020({ strict: false, validateFormats: false });
if (
!definition ||
!ajv.validateSchema(definition.inputSchema) ||
!ajv.validate(definition.inputSchema, input)
)
throw new Error("Selected PCAP request is not advertised by this runtime");
const inspected = await call("inspect_pcap_capture", input);
const n = normalized(inspected);
const observations = [pcapObservation(inspected)];
let capture, uris;
if (values.delivery === "summary") {
if (n.kind !== "summary" || n.parent_operation !== "inspect_pcap_capture")
throw new Error("Runtime returned no requested PCAP summary");
capture = n.summary;
const selected = await call("inspect_analysis_view", {
source: { kind: "retained-evidence", evidence_id: n.parent_evidence_id },
view: { kind: "pcap", facet: "http-uris", offset: 0, limit: 2 },
});
const page = normalized(selected);
if (
page.parent_evidence_id !== n.parent_evidence_id ||
page.parent_operation !== "inspect_pcap_capture" ||
page.kind !== "pcap" ||
page.page.facet !== "http-uris" ||
page.source_coverage !== capture.coverage ||
page.coverage.total !== capture.retained_counts.http_request_uris ||
page.coverage.examined !== page.page.items.length ||
page.artifact.path !== capture.target.path ||
page.artifact.sha256 !== capture.target.sha256
)
throw new Error(
"PCAP page identity, scope or coverage differs from its parent",
);
uris = page.page.items;
observations.push(pcapObservation(selected));
} else {
const {
endpoints,
dns_queries,
tls_sni_values,
protocol_distribution,
http_request_uris,
unattributed_dns_addresses,
diagnostics,
...metadata
} = n;
capture = {
...metadata,
retained_counts: {
endpoints: endpoints.length,
dns_queries: dns_queries.length,
tls_sni_values: tls_sni_values.length,
protocol_distribution: protocol_distribution.length,
http_request_uris: http_request_uris.length,
unattributed_dns_addresses: unattributed_dns_addresses.length,
},
diagnostics_code_units:
diagnostics === undefined
? null
: {
tshark: diagnostics.tshark_stderr.length,
capinfos: diagnostics.capinfos_stderr.length,
},
};
uris = http_request_uris.slice(0, 2);
}
if (uris.length !== Math.min(2, capture.retained_counts.http_request_uris))
throw new Error("Runtime did not return the requested retained URI prefix");
return {
artifact_sha256: targetSha(inspected),
capture,
http_request_uris_first2: uris,
delivery_observations: observations,
evidence_ids: observations.map((item) => item.evidence_id),
};
};
const workflows = {
"wireshark-http.cap": inspectPcapTarget,
"wireshark-http_redirects.pcapng": inspectPcapTarget,
"qgis-world-map.gpkg": async () => {
const columns = ["fid", "NAME", "ISO_A3"];
const input = {
@@ -1,153 +0,0 @@
# Small real PCAP recordings: keep complete delivery
Continues [#2016](https://github.com/morluto/rea/issues/2016) after the QGIS
SQLite round. Measured main is pinned to
`3ae826ceba6f25b08bce50bcb51001209bc16b57`, with 23 intervening commits.
These include bounded PCAP summaries/pages, authenticated artifact subjects,
unknown-snapshot reuse and shared transcript grading. This round measures existing
PCAP delivery choices; it adds no production, API, default, cache or skill change.
## Corpus and question
Use two unmodified recordings published on the official
[Wireshark sample-capture page](https://wiki.wireshark.org/SampleCaptures):
| Recording | Bytes | SHA-256 |
| --------------------------------------- | -----: | ------------------------------------------------------------------ |
| HTTP request/response, `http.cap` | 25,803 | `25a72bdf10339f2c29916920c8b9501d294923108de8f29b19aba7cc001ab60d` |
| HTTP redirects, `http_redirects.pcapng` | 47,804 | `ff432a6b71d06cd20720f7763e584014edd0a43c3b55981c682d1b7640207abc` |
`corpus.json` preserves original/resolved URLs. Local digests pin downloaded
bytes; no independently published upstream digest or immutable source commit is
claimed. These are upstream saved application-protocol recordings, not generated
REA fixtures. Recorded clients and current deployments are unknown. No new
traffic is captured and no recorded target/URL is executed or fetched.
The question asks for complete returned identity/client/scalar metadata, every
observed count and source coverage, six retained inventory counts, explicit nulls,
diagnostic UTF-16 lengths, and the first two retained HTTP URIs in original order.
Preserve each used receipt's limitations and identity. Summary/page scope and
unknowns remain distinct from source coverage; exhaustion does not establish
network completeness. Other inventory lists and diagnostic text are unrequested.
Compare default `{path}` with existing `{path, detail: "summary"}` plus a retained
`http-uris` page, offset 0, limit 2. Ordinary selected-field
`inspect_packet_capture` remains a separate boundary, not a substitute claim
about complete inventories. `questions/pcap-http.txt` contains the fixed question.
## SDK measurements
Frozen dist/bridge file-table SHA-256:
`db050545e94dc305a48042e06df96ac6c64b21ee6c5c4707c787d5e46df79e47`.
Linux x64, Node 24.18.0, SDK client/server 2.3.1, installed Wireshark 4.0.17.
Explicit commands are `/usr/bin/tshark`, `/usr/bin/capinfos`, `/usr/bin/prlimit`;
private receipts retain executable hashes. Each workflow starts a fresh server
and uses actual named advertised definitions/schema validation. Host page caches
are not flushed. Both tools read the owned snapshot.
Eight trials run complete/summary/summary/complete per recording. Both pairs
match selected capture facts, URI prefixes, settings and original source bytes.
Each delivery's exact limitations, identities and coverage remain separately
recorded, rather than equating source coverage with page exhaustion.
| Trial | Reply bytes | SDK seconds | Payload CPU seconds | Kernel peak bytes |
| -------------------- | ----------: | ----------: | ------------------: | ----------------: |
| HTTP complete-1 | 7,601 | 4.349 | 5.336 | 611,778,560 |
| HTTP summary-1 | 17,540 | 4.972 | 5.973 | 601,661,440 |
| HTTP summary-2 | 17,540 | 5.101 | 6.092 | 611,438,592 |
| HTTP complete-2 | 7,601 | 4.463 | 5.503 | 617,148,416 |
| Redirects complete-1 | 7,535 | 4.670 | 5.641 | 610,627,584 |
| Redirects summary-1 | 17,240 | 5.099 | 6.104 | 615,522,304 |
| Redirects summary-2 | 17,240 | 5.060 | 6.056 | 610,385,920 |
| Redirects complete-2 | 7,535 | 4.466 | 5.458 | 608,141,312 |
Bytes are compact client-result JSON summed over one complete or two summary/page
calls, not model tokens or raw wire bytes. Summary/page expands replies to more
than twice the complete result on both recordings. All four SDK pairs are slower
and use more payload CPU; memory differences are small/inconsistent. CPU includes
driver/catalog work outside the SDK workflow timer.
Reproduce with `measure.mjs --artifact wireshark-http.cap` or
`wireshark-http_redirects.pcapng`, pinned path/runtime/revision, explicit provider
JSON, `--schemas selected`, and `--delivery complete|summary`. Use `compare.mjs`
on completed output directories. Original replies, catalogs, comparison receipts
and exact measured driver source stay private.
## Actual model tasks
Four actual Codex CLI 0.161.0 tasks use requested `gpt-5.6-terra` high, the same
redirects question/runtime/artifact/provider settings, direct mode, two exact
enabled tools and equal context/discovery capture flags. The requested alias is
not verified server-resolved model identity. Equal cohort instructions select
complete or summary plus one URI page. The experiment driver applies its existing
private per-tool approval policy to `inspect_pcap_capture`; global configuration
and REA authority are unchanged.
| Trial | Input | Cached | Uncached | Output | CLI wall seconds | MCP calls | Facts |
| ---------- | -----: | -----: | -------: | -----: | ---------------: | --------: | ----- |
| complete-1 | 38,947 | 9,984 | 28,963 | 2,119 | 69.469 | 1 | pass |
| summary-1 | 58,779 | 38,144 | 20,635 | 3,241 | 141.304 | 2 | pass |
| summary-2 | 58,584 | 38,144 | 20,440 | 4,261 | 50.916 | 2 | pass |
| complete-2 | 38,917 | 23,040 | 15,877 | 2,813 | 106.896 | 1 | pass |
Summary/page total input **increases 50.92% / 50.54%** and output increases
52.95% / 51.48%. Uncached input is mixed: 28.75% lower / 28.74% higher. Time is
mixed: 103.41% slower / 52.37% faster. No cause is inferred for caching or timing
variation. Cached input is included in total; each CLI reports one final aggregate
usage. Output includes 1,149 / 1,162 / 2,196 / 1,837 reasoning tokens.
All calls succeed without extras/retries. Events contain only the selected MCP
tools and agent messages. All source-digest and private-profile cleanup checks
pass. Model payload CPU seconds/kernel peaks: 7.818/791,060,480;
9.793/752,705,536; 7.685/757,891,072; 7.999/750,993,408. These do not establish
a general CPU/memory gain.
The first summary initially fails the grader because it uses explicit equivalent
labels and a URI object retaining page/source coverage. Its facts are correct.
The grading boundary accepts these known forms while checking exact types,
null presence, original limitations and extra scopes against actual receipts.
Conflicting duplicates and unsupported claims remain failures. Each cited
receipt's own ID must be reported; its parent lookup ID is checked separately.
Original answers/reviews/grader source remain intact. No model is rerun. A grader
review pause separates the pairs; it is not task time or a cold-cache claim.
## Verification and decision
An independent stdlib raw PCAP/PCAPNG/Ethernet/IP/TCP/complete-HTTP-header parser
agrees on 43/271 packets, per-packet endpoint counts, first URI prefixes and 2/23
distinct HTTP URIs. It invokes no Wireshark. DNS associations, protocol-stack
dissection, nullable timestamps and live-network semantics are not independently
validated.
Both real CLI complete results match full MCP normalized results, subjects,
parameters, IDs and limitations. Portable CLI summary/URI views match MCP retained
normalized facts and subjects; source forms/caller parameters remain distinct.
Source bytes stay unchanged. Twelve context/grading regressions pass. Five real-answer
mutations—omitted null, false page exhaustion, contradictory source scope,
unsupported absence claim and non-string receipt identity—fail correctly.
Malformed identities produce failed facts rather than crashing the grader.
JS syntax, Python compilation and
relevant standard lint pass.
**Decision: keep existing complete defaults; add no production optimization.**
For these compact recordings and this question, summary/page costs more total
input in both real-model pairs. No stable speed or CPU/memory benefit justifies
another API, automatic delivery switch, cache or plugin layer. Existing pages
remain available; their benefit needs evidence for the actual question/inventory.
Large captures, other protocols, Windows/macOS/Bun Wireshark and other model
workloads remain unverified here.
Heavy work stays serial with one CPU, 3 GiB early stop/4 GiB hard memory and no
swap. Build kernel peak: 2,575,732,736 bytes. Payload cleanup and zero phase limit
events are verified; missing terminal whole-scope counters remain unknown, so
strict whole-resource grades stay false. No raw capture, trace, credential,
runtime or result JSON is committed. No unrelated REA product bug is identified
or fixed, and no release is performed.
Review follow-up binds the cited URI page to its exact requested facet/range,
reported values and the summary retained parent. Small synthetic trial receipts
exercise the entire grading entrypoint, including faithful but wrong-page/range/
parent citations, missing nulls, false scope and malformed identities. These are
grader regressions, not real-provider evidence. All four stored actual model
answers still pass; no model reruns are required. Transcript readers close their
owned file handles after grading.
@@ -1 +0,0 @@
Statically inspect the supplied saved Wireshark capture at {{artifact_path}} using only registered REA inspect_pcap_capture and inspect_analysis_view. Report its original client/target identity and every returned scalar metadata/count/coverage field exactly, preserving explicit nulls. Include retained_counts for endpoints, dns_queries, tls_sni_values, protocol_distribution, http_request_uris and unattributed_dns_addresses; derive array lengths only when reading complete Evidence. Include diagnostics_code_units as exact UTF-16 lengths of retained capinfos/tshark stderr, or null if diagnostics are unrecorded. In capture, omit inventory arrays and diagnostic text; do not omit their observed counts or change source coverage. Report the first two retained HTTP URIs in original order, or all if fewer; do not request other inventory pages. Report delivery_observations in dependency order for the Evidence used: evidence_id, outer limitations, and each present normalized kind, view, parent_evidence_id, coverage, unknowns and normalized_limitations. Preserve presence, explicit nulls, scalar types and original limitation order. Distinguish source coverage from URI-page exhaustion. Final JSON fields: artifact_sha256, capture, http_request_uris_first2, delivery_observations, evidence_ids. Include only actual response IDs. Saved packet/URI observations do not establish current deployment, process identity, missing traffic, decrypted payloads or current DNS resolution. Do not use shell, host file tools, network, other agents, traffic acquisition or execute recorded targets. Stop once these selected facts are supported.
+19 -120
View File
@@ -67,28 +67,9 @@ def scope_with_verified_counts(value, expected_scope, returned_counts):
return scope, checks
def pcap_observation_fields(value):
"""Equivalent explicit labels are accepted; conflicting duplicates remain failures."""
if not isinstance(value, dict):
return value
result = dict(value)
for label, canonical in {
'outer_limitations': 'limitations', 'normalized_kind': 'kind',
'normalized_view': 'view', 'normalized_parent_evidence_id': 'parent_evidence_id',
'normalized_coverage': 'coverage', 'normalized_unknowns': 'unknowns',
'normalized_source_coverage': 'source_coverage',
}.items():
if label not in result:
continue
if canonical in result and json.dumps(result[label], sort_keys=True) != json.dumps(result[canonical], sort_keys=True):
return {**result, 'conflicting_fields': [label, canonical]}
result[canonical] = result.pop(label)
return result
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--domain', choices=['wasm', 'evm', 'android', 'flutter-aot', 'sqlite', 'pcap', 'managed', 'managed-nonempty', 'firmware', 'inventory', 'javascript', 'native', 'browser'], required=True)
parser.add_argument('--domain', choices=['wasm', 'evm', 'android', 'flutter-aot', 'sqlite', 'managed', 'managed-nonempty', 'firmware', 'inventory', 'javascript', 'native', 'browser'], required=True)
parser.add_argument('--trial', type=Path, required=True)
parser.add_argument('--reference', type=Path)
parser.add_argument('--resource-log', type=Path, required=True)
@@ -103,25 +84,24 @@ def main():
observed_ids = set()
producer_results = {}
tool_errors = []
with (args.trial / 'events.jsonl').open() as event_lines:
for line in event_lines:
event = json.loads(line)
item = event.get('item', {})
if event.get('type') != 'item.completed' or item.get('type') != 'mcp_tool_call':
continue
result = item.get('result') or {}
parsed = decode(result)
if item['status'] == 'completed':
# Only response text contributes observed IDs, never model arguments.
for text in strings(result):
observed_ids.update(re.findall(r'ev_[a-f0-9]{64}', text))
if parsed is not None:
producer_results.setdefault(item['tool'], []).append(parsed)
else:
tool_errors.append({'tool': item['tool'], 'arguments': item['arguments'], 'response': parsed if parsed is not None else result})
if parsed is not None and parsed.get('error', {}).get('code') == 'resource_constraint':
reference_value = parsed['error'].get('details', {}).get('reported_limits', {}).get('evidence_reference')
observed_ids.update(evidence_ids(reference_value))
for line in (args.trial / 'events.jsonl').open():
event = json.loads(line)
item = event.get('item', {})
if event.get('type') != 'item.completed' or item.get('type') != 'mcp_tool_call':
continue
result = item.get('result') or {}
parsed = decode(result)
if item['status'] == 'completed':
# Only response text contributes observed IDs, never model arguments.
for text in strings(result):
observed_ids.update(re.findall(r'ev_[a-f0-9]{64}', text))
if parsed is not None:
producer_results.setdefault(item['tool'], []).append(parsed)
else:
tool_errors.append({'tool': item['tool'], 'arguments': item['arguments'], 'response': parsed if parsed is not None else result})
if parsed is not None and parsed.get('error', {}).get('code') == 'resource_constraint':
reference_value = parsed['error'].get('details', {}).get('reported_limits', {}).get('evidence_reference')
observed_ids.update(evidence_ids(reference_value))
reported_ids = evidence_ids(answer.get('evidence_ids'))
checks = {
'reported_evidence_ids_observed_in_responses': bool(reported_ids) and reported_ids <= observed_ids,
@@ -158,87 +138,6 @@ def main():
# Missing is not SQL/JSON null; booleans are not numeric counters.
check(key, (key in answer, json.dumps(answer.get(key), sort_keys=True)),
(True, json.dumps(reference[key], sort_keys=True)))
elif domain == 'pcap':
check('capture', ('capture' in answer, json.dumps(answer.get('capture'), sort_keys=True)),
(True, json.dumps(reference['capture'], sort_keys=True)))
prefix = answer.get('http_request_uris_first2')
records = {value['evidence_id']: value for values in producer_results.values()
for value in values if isinstance(value, dict) and 'evidence_id' in value}
if isinstance(prefix, dict):
checks['pcap_prefix_fields_supported'] = set(prefix) <= {'items', 'coverage', 'source_coverage'} and 'items' in prefix
if 'source_coverage' in prefix:
check('pcap_prefix_source_coverage', prefix['source_coverage'], reference['capture']['coverage'])
if 'coverage' in prefix:
page_coverages = [value['normalized_result']['coverage'] for value in records.values()
if value['normalized_result'].get('kind') == 'pcap'
and value['normalized_result']['page'].get('facet') == 'http-uris'
and value['normalized_result']['page'].get('items') == prefix.get('items')]
checks['pcap_prefix_coverage_observed'] = any(json.dumps(prefix['coverage'], sort_keys=True) == json.dumps(value, sort_keys=True) for value in page_coverages)
prefix = prefix.get('items')
check('http_request_uris_first2', ('http_request_uris_first2' in answer, json.dumps(prefix, sort_keys=True)),
(True, json.dumps(reference['http_request_uris_first2'], sort_keys=True)))
observations = answer.get('delivery_observations')
canonical_observations = [pcap_observation_fields(value) for value in observations] if isinstance(observations, list) else observations
expected_observations = []
if isinstance(canonical_observations, list):
for observation in canonical_observations:
identity = observation.get('evidence_id') if isinstance(observation, dict) else None
record = records.get(identity) if isinstance(identity, str) else None
if record is None:
expected_observations.append(None)
continue
value = record['normalized_result']
expected = {'evidence_id': record['evidence_id'], 'limitations': record['limitations']}
for key in ['kind', 'view', 'parent_evidence_id', 'coverage', 'unknowns']:
if key in value:
expected[key] = value[key]
if 'limitations' in value:
expected['normalized_limitations'] = value['limitations']
if 'source_coverage' in observation and 'source_coverage' in value:
expected['source_coverage'] = value['source_coverage']
expected_observations.append(expected)
checks['pcap_delivery_observations_nonempty'] = isinstance(observations, list) and bool(observations)
check('pcap_original_delivery_observations', json.dumps(canonical_observations, sort_keys=True),
json.dumps(expected_observations, sort_keys=True))
if isinstance(canonical_observations, list) and all(isinstance(x, dict) for x in canonical_observations):
check('pcap_requested_delivery_chain', [x.get('kind', 'complete') for x in canonical_observations],
[x.get('kind', 'complete') for x in reference['delivery_observations']])
check('pcap_requested_views', [x.get('view') for x in canonical_observations],
[x.get('view') for x in reference['delivery_observations']])
identities = [x.get('evidence_id') for x in canonical_observations]
checks['pcap_observations_have_reported_ids'] = all(isinstance(value, str) for value in identities) and set(identities) <= reported_ids
cited = [records.get(identity) if isinstance(identity, str) else None for identity in identities]
checks['pcap_cited_source_supports_uri_prefix'] = False
if all(isinstance(record, dict) for record in cited):
if len(cited) == 1:
source = cited[0]['normalized_result']
checks['pcap_cited_source_supports_uri_prefix'] = (
source.get('target') == reference['capture']['target']
and isinstance(source.get('http_request_uris'), list)
and json.dumps(source['http_request_uris'][:2], sort_keys=True) == json.dumps(prefix, sort_keys=True)
)
elif len(cited) == 2:
source, page = [record['normalized_result'] for record in cited]
capture = source.get('summary', {})
selected_page = page.get('page', {})
checks['pcap_cited_source_supports_uri_prefix'] = (
source.get('kind') == 'summary'
and source.get('parent_operation') == 'inspect_pcap_capture'
and capture == reference['capture']
and isinstance(source.get('parent_evidence_id'), str)
and page.get('parent_evidence_id') == source['parent_evidence_id']
and page.get('parent_operation') == 'inspect_pcap_capture'
and page.get('view') == {'kind': 'pcap', 'facet': 'http-uris', 'offset': 0, 'limit': 2}
and selected_page.get('facet') == 'http-uris'
and json.dumps(selected_page.get('items'), sort_keys=True) == json.dumps(prefix, sort_keys=True)
and page.get('source_coverage') == capture.get('coverage')
and page.get('artifact') == {key: capture['target'][key] for key in ['path', 'sha256']}
)
else:
checks['pcap_requested_delivery_chain'] = False
checks['pcap_observations_have_reported_ids'] = False
checks['pcap_requested_views'] = False
checks['pcap_cited_source_supports_uri_prefix'] = False
elif domain == 'flutter-aot':
for key in ['target', 'abi', 'libapp', 'string_pool', 'coverage', 'limitations']:
check(key, answer.get(key), reference[key])
@@ -1,7 +1,6 @@
"""Distinct capture/cleanup failures; simulated CLI is not real-model evidence."""
import importlib.util
import copy
import io
import json
import os
@@ -39,140 +38,6 @@ class ManagedCoverageTests(unittest.TestCase):
self.assertNotEqual(scope, expected)
class PcapCoverageTests(unittest.TestCase):
def test_explicit_labels_preserve_original_nulls_and_source_scope(self):
canonical = runpy.run_path(str(Path(__file__).with_name('review-model.py')))['pcap_observation_fields']
original = {'outer_limitations': [], 'normalized_kind': 'pcap',
'normalized_coverage': {'examined': 2, 'total': 23, 'next_offset': 2, 'exhausted': False},
'normalized_source_coverage': 'partial', 'normalized_parent_evidence_id': None}
result = canonical(original)
self.assertEqual(result['limitations'], [])
self.assertEqual(result['source_coverage'], 'partial')
self.assertEqual(result['coverage']['total'], 23)
self.assertIsNone(result['parent_evidence_id'])
self.assertIn('outer_limitations', original)
self.assertNotIn('parent_evidence_id', canonical({}))
def test_conflicting_duplicates_and_json_type_substitutions_stay_failures(self):
canonical = runpy.run_path(str(Path(__file__).with_name('review-model.py')))['pcap_observation_fields']
for wrong in ['partial', None]:
result = canonical({'normalized_source_coverage': 'complete', 'source_coverage': wrong})
self.assertIn('conflicting_fields', result)
self.assertEqual(result['normalized_source_coverage'], 'complete')
self.assertEqual(result['source_coverage'], wrong)
result = canonical({'normalized_coverage': {'examined': 1}, 'coverage': {'examined': True}})
self.assertIn('conflicting_fields', result)
self.assertEqual(canonical({'outer_limitations': [], 'limitations': []}), {'limitations': []})
def test_unsupported_claims_are_retained_for_exact_producer_checking(self):
canonical = runpy.run_path(str(Path(__file__).with_name('review-model.py')))['pcap_observation_fields']
original = {'normalized_kind': 'pcap', 'unrecorded_traffic_absent': True}
self.assertIn('unrecorded_traffic_absent', canonical(original))
self.assertIsNone(canonical(None))
class PcapGraderWorkflowTests(unittest.TestCase):
"""Synthetic receipts test the grader boundary, not Wireshark or real models."""
def fixture(self):
parent, summary_id, page_id = ['ev_' + value * 64 for value in ['a', 'b', 'c']]
capture = {'target': {'path': '/fixture/http.pcapng', 'sha256': 'd' * 64},
'capture_start': None, 'coverage': 'complete',
'retained_counts': {'http_request_uris': 3}}
prefix = ['http://example.test/one', 'http://example.test/two']
coverage = {'status': 'page', 'examined': 2, 'total': 3, 'next_offset': 2, 'exhausted': False}
summary = {'evidence_id': summary_id, 'limitations': ['source', 'view'],
'normalized_result': {'kind': 'summary', 'view': {'kind': 'summary'},
'parent_operation': 'inspect_pcap_capture', 'parent_evidence_id': parent,
'summary': capture, 'coverage': {'status': 'complete-within-view', 'examined': 1, 'total': 1, 'next_offset': None, 'exhausted': True},
'limitations': ['source', 'view'], 'unknowns': ['unrecorded traffic']}}
page = {'evidence_id': page_id, 'limitations': ['source', 'view'],
'normalized_result': {'kind': 'pcap',
'view': {'kind': 'pcap', 'facet': 'http-uris', 'offset': 0, 'limit': 2},
'parent_operation': 'inspect_pcap_capture', 'parent_evidence_id': parent,
'page': {'facet': 'http-uris', 'items': prefix}, 'coverage': coverage,
'source_coverage': 'complete', 'artifact': capture['target'],
'limitations': ['source', 'view'], 'unknowns': ['unrecorded traffic']}}
observations = [self.observation(value) for value in [summary, page]]
reference = {'artifact_sha256': 'd' * 64, 'capture': capture,
'http_request_uris_first2': prefix, 'delivery_observations': observations}
answer = copy.deepcopy({**reference, 'http_request_uris_first2': {
'items': prefix, 'coverage': coverage, 'source_coverage': 'complete'},
'evidence_ids': [summary_id, page_id]})
return answer, [summary, page], copy.deepcopy(reference)
def observation(self, record):
value = record['normalized_result']
return {'evidence_id': record['evidence_id'], 'limitations': record['limitations'],
'kind': value['kind'], 'view': value['view'],
'parent_evidence_id': value['parent_evidence_id'], 'coverage': value['coverage'],
'unknowns': value['unknowns'], 'normalized_limitations': value['limitations']}
def grade(self, answer, records, reference):
review = runpy.run_path(str(Path(__file__).with_name('review-model.py')))
with tempfile.TemporaryDirectory() as directory:
root = Path(directory);trial = root / 'trial';trial.mkdir()
for name, value in [('summary.json', {'completed_mcp_calls': []}),
('trial-settings.json', {}), ('cleanup.json', {'profile_removed': True})]:
(trial / name).write_text(json.dumps(value))
(trial / 'answer.txt').write_text(json.dumps(answer))
events = [{'type': 'item.completed', 'item': {'type': 'mcp_tool_call',
'tool': 'inspect_pcap_capture' if value['normalized_result']['kind'] == 'summary' else 'inspect_analysis_view',
'status': 'completed', 'result': {'structuredContent': value}}} for value in records]
(trial / 'events.jsonl').write_text(''.join(json.dumps(value) + '\n' for value in events))
source = root / 'reference';source.mkdir();(source / 'answer.json').write_text(json.dumps(reference))
resource = root / 'resource.log'
resource.write_text(json.dumps({'resource_scope': 'simulated-grader-only', 'abort': None,
'resource_counters_verified': False, 'resource_events_final': None}) + '\n')
output = root / 'review.json'
argv = ['review-model.py', '--domain', 'pcap', '--trial', str(trial), '--reference', str(source),
'--resource-log', str(resource), '--output', str(output)]
with patch.object(sys, 'argv', argv), patch('sys.stdout', io.StringIO()), self.assertRaises(SystemExit) as stopped:
review['main']()
self.assertEqual(stopped.exception.code, 1) # Unknown resource counters stay false.
return json.loads(output.read_text())
def test_complete_grader_accepts_supported_receipts_and_equivalent_labels(self):
answer, records, reference = self.fixture()
self.assertTrue(self.grade(answer, records, reference)['all_factual_checks_pass'])
for observation in answer['delivery_observations']:
observation['outer_limitations'] = observation.pop('limitations')
observation['normalized_coverage'] = observation.pop('coverage')
self.assertTrue(self.grade(answer, records, reference)['all_factual_checks_pass'])
def test_complete_grader_rejects_missing_nulls_bad_scope_and_malformed_identity(self):
mutations = [lambda x: x['capture'].pop('capture_start'),
lambda x: x['http_request_uris_first2']['coverage'].__setitem__('exhausted', True),
lambda x: x['delivery_observations'][-1].__setitem__('evidence_id', {'unexpected': 'value'}),
lambda x: x['delivery_observations'][-1].__setitem__('unrecorded_traffic_absent', True)]
for mutate in mutations:
with self.subTest(mutation=mutate):
answer, records, reference = self.fixture();mutate(answer)
self.assertFalse(self.grade(answer, records, reference)['all_factual_checks_pass'])
def test_faithful_wrong_receipts_do_not_support_the_reported_uri_prefix(self):
for wrong in ['facet', 'range', 'parent']:
with self.subTest(wrong=wrong):
answer, records, reference = self.fixture()
page = copy.deepcopy(records[-1]);page['evidence_id'] = 'ev_' + 'e' * 64
value = page['normalized_result']
if wrong == 'facet':
value['view']['facet'] = 'endpoints'
value['page'] = {'facet': 'endpoints', 'items': [{'address': '127.0.0.1'}]}
elif wrong == 'range':
value['view']['offset'] = 1
value['page']['items'] = ['http://example.test/two', 'http://example.test/three']
else:
value['parent_evidence_id'] = 'ev_' + 'f' * 64
records.append(page)
answer['delivery_observations'][-1] = self.observation(page)
answer['evidence_ids'][-1] = page['evidence_id']
report = self.grade(answer, records, reference)
self.assertTrue(report['factual_checks']['pcap_original_delivery_observations'])
self.assertFalse(report['factual_checks']['pcap_cited_source_supports_uri_prefix'])
self.assertFalse(report['all_factual_checks_pass'])
class ContextCaptureTests(unittest.TestCase):
def test_filters_ambient_account_and_nested_usage_state(self):
with tempfile.TemporaryDirectory() as directory:
+16 -4
View File
@@ -69,10 +69,22 @@ without this lane reports Windows native controls as unavailable.
limits only for its JavaScript helpers when running on Bun, which ignores
their V8 heap flags; Node.js launches are unchanged.
- Only the suspended child's default file owner is normalized. Caller token
privileges and ownership remain unchanged. Caller CPU affinity and process
priority are preserved in the child. Environment names are sorted and
deduplicated using Windows ordinal comparison, preserving their native Unicode
semantics and caller-selected values.
privileges and ownership remain unchanged. Caller process priority is
preserved in the child, and caller CPU affinity whenever both occupy the same
processor group. Windows chooses a new process's group itself and rejects a
mask belonging to another group, so a child placed elsewhere keeps that
group's default when the caller asked for no bound of its own. A caller
deliberately pinned to fewer processors than its group holds is a constraint
such a child cannot express, and is refused rather than widened to that
group's default. A mask covering its group's whole active set does not
distinguish a caller Windows placed in that group from one that selected the
group deliberately, so such a child can still be placed elsewhere: its
processor count stays bounded, its group placement is not preserved, and
neither that case nor the refusal above has a verification lane, because both
need a host whose processors span more than one group.
Environment names are sorted and deduplicated using Windows
ordinal comparison, preserving their native Unicode semantics and
caller-selected values.
- Cleanup walks locked directory objects, removes files by handle, and unlinks
reparse entries without traversing their targets. Failed removal retains the
root and ancestor leases for retry; a partially removed runtime accepts only
+29 -1
View File
@@ -68,6 +68,18 @@ static ULONGLONG jobMemoryLimit(napi_env env, napi_value value) {
return limit;
}
// An affinity mask is meaningful only inside one processor group, so only a
// process occupying exactly one group has a group a child can inherit. A
// process whose threads span groups, or whose membership cannot be read, has no
// single group.
static bool singleProcessorGroup(HANDLE process, USHORT& group) {
USHORT count = 1;
std::array<USHORT, 1> groups{};
if (!GetProcessGroupAffinity(process, &count, groups.data()) || count != 1) return false;
group = groups[0];
return true;
}
static void pipe(Handle& read, Handle& write, bool parentReads = true) {
SECURITY_ATTRIBUTES attributes{sizeof(SECURITY_ATTRIBUTES), nullptr, TRUE};
HANDLE rawRead, rawWrite;
@@ -168,11 +180,27 @@ std::unique_ptr<Process> spawnProcess(const std::wstring& command, const std::ws
TOKEN_OWNER owner{reinterpret_cast<TOKEN_USER*>(tokenUser.data())->User.Sid};
require(SetTokenInformation(token.get(), TokenOwner, &owner, sizeof(owner)),
"Set suspended process file owner failed", command);
// A mask names processors inside one processor group, and Windows assigns a
// new process to a group of its own choosing, so a mask belonging to another
// group is rejected (ERROR_INVALID_PARAMETER). An unconstrained caller, whose
// mask is its group's whole active set, asks for no bound the child's own
// group cannot give, so such a child keeps that group's default and the spawn
// proceeds. A narrower mask is a deliberate CPU constraint that a child in
// another group cannot express, and silently widening it would hand the
// provider tree the whole group, so that spawn fails naming the constraint.
DWORD_PTR affinity = 0, systemAffinity = 0;
require(GetProcessAffinityMask(GetCurrentProcess(), &affinity, &systemAffinity),
"Read caller process affinity failed", command);
if (affinity != 0)
USHORT callerGroup = 0, childGroup = 0;
const bool sharedGroup = singleProcessorGroup(GetCurrentProcess(), callerGroup) &&
singleProcessorGroup(result->process.get(), childGroup) &&
callerGroup == childGroup;
if (affinity != 0 && sharedGroup)
require(SetProcessAffinityMask(result->process.get(), affinity), "Preserve caller process affinity failed", command);
else
require(affinity == 0 || affinity == systemAffinity,
"Caller CPU affinity cannot bound an owned process in another processor group", command,
ERROR_INVALID_PARAMETER);
const DWORD priority = GetPriorityClass(GetCurrentProcess());
require(priority != 0 && SetPriorityClass(result->process.get(), priority),
"Preserve caller process priority failed", command);
+1 -1
View File
@@ -207,7 +207,7 @@
"fixtures:harmony": "node scripts/fixtures/harmony/fetch.mjs",
"verify:agent": "npm run build:cached && node scripts/verify-agent-experience.mjs",
"verify:hopper:linux": "npm run verify:fixtures && npm run build:cached && node scripts/verify-real-hopper-linux.mjs",
"verify:setup:linux": "npm run build:cached && node scripts/verify-linux-setup-e2e.mjs",
"verify:setup:linux": "npm run verify:fixtures && npm run build:cached && node scripts/verify-linux-setup-e2e.mjs",
"build:fixtures": "node scripts/build-conformance-fixtures.mjs",
"build:ghidra-windows-fixture": "node scripts/create-ghidra-windows-fixture.mjs",
"verify:fixtures": "npm run build:fixtures && node scripts/verify-conformance-fixtures.mjs",
@@ -45,6 +45,20 @@ class Generator:
assert "ows-secret" not in json.dumps(projected), projected
if isinstance(value, bytes):
assert projected["binary_fields"][-1]["state"] == "redacted", projected
body = b"A" * 12345
state = {"response": {"content": body}}
control = adapter.project_record(state, [])
field = control["binary_fields"][0]
assert field["state"] == "retained" and field["bytes"] == len(body), control
for literal in ["12345", "2345"]:
# Only the generated byte count matches this exclusion.
assert literal not in control["reported"]["response"]["content"]
assert literal not in field["content_base64"] and literal not in field["sha256"]
projected = adapter.project_record(state, [literal])
assert projected["reported"]["response"]["content"] is None, projected
assert projected["binary_fields"] == [{"pointer": "/response/content", "representation": "producer-bytes", "state": "redacted", "content_base64": None, "bytes": None, "sha256": None}], projected
assert {"pointer": "/response/content", "reason": "explicit-sensitive-value"} in projected["redactions"], projected
assert literal not in json.dumps(projected), projected
(root / "native-error-classifications.json").write_text(json.dumps({"passed": len(classifications) + 2}))
first = http.HTTPFlow(connection.Client(peername=("127.0.0.1", 1), sockname=("127.0.0.1", 2)), connection.Server(address=("example.test", 80)))
first.id = "original-producer-id"
@@ -0,0 +1,3 @@
export function assertCleanLinuxHopperRuntime(
launcherPaths?: readonly string[],
): Promise<void>;
@@ -0,0 +1,70 @@
import { readFile, readdir, stat } from "node:fs/promises";
import { basename } from "node:path";
/**
* Observe leftover demo processes on a dedicated clean Linux runner, including
* groups reparented after their launcher exits. This is not ownership proof and
* never authorizes signaling; unrelated runtime processes also block this lane.
*/
export const assertCleanLinuxHopperRuntime = async (
launcherPaths = [
"/opt/hopper/bin/Hopper",
...(process.env.HOPPER_LAUNCHER_PATH === undefined
? []
: [process.env.HOPPER_LAUNCHER_PATH]),
],
) => {
const launchers = [];
for (const path of launcherPaths) {
try {
launchers.push(await stat(path, { bigint: true }));
} catch (error) {
if (error?.code !== "ENOENT") throw error;
}
}
// /proc exposes the executed file even when argv[0] names a removed symlink.
// Compare file identity, not a display path or a process name.
let inspectionError;
for (const entry of await readdir("/proc", { withFileTypes: true })) {
if (!entry.isDirectory() || !/^\d+$/u.test(entry.name)) continue;
let retainedRuntime;
try {
// procfs preserves argument boundaries. A caller merely mentioning a
// runtime in its script text or other arguments is not that runtime.
const arguments_ = (
await readFile(`/proc/${entry.name}/cmdline`, "utf8")
).split("\0");
retainedRuntime =
arguments_[0] === "/opt/hopper/bin/Hopper" ||
basename(arguments_[0] ?? "") === "Xvfb" ||
(basename(arguments_[0] ?? "") === "python3" &&
basename(arguments_[1] ?? "") === "hopper-demo-x11.py");
if (!retainedRuntime && launchers.length > 0) {
const executable = await stat(`/proc/${entry.name}/exe`, {
bigint: true,
});
retainedRuntime = launchers.some(
({ dev, ino }) => dev === executable.dev && ino === executable.ino,
);
}
} catch (error) {
if (error?.code === "ENOENT" || error?.code === "ESRCH") continue;
// Other users' process facts may be unreadable. The setup lane launches
// providers as the caller; unreadable caller-owned processes fail closed.
if (error?.code === "EACCES") {
const owner = await stat(`/proc/${entry.name}`).catch((cause) => {
if (cause?.code === "ENOENT") return undefined;
throw cause;
});
if (owner === undefined || owner.uid !== process.getuid()) continue;
}
// Finish the inventory so an unrelated restricted process cannot mask a
// positively identified leak. Unknown caller processes still fail closed.
inspectionError ??= error;
continue;
}
if (retainedRuntime)
throw new Error("Clean Linux runner retained a Hopper demo process");
}
if (inspectionError !== undefined) throw inspectionError;
};
+31
View File
@@ -0,0 +1,31 @@
import type { z } from "zod";
import type { analysisStringSchema } from "../../src/domain/hopperValues.js";
type VerifierCall = (
name: string,
arguments_?: Record<string, unknown>,
) => Promise<unknown>;
interface StringExpectation {
readonly value: string;
readonly encoding: string;
readonly symbol?: string;
readonly recognitionOptional?: boolean;
}
/** Verify source bytes, observed decoding, address filters and literal searches. */
export function verifyHopperStringObjects(
call: VerifierCall,
expectations: readonly StringExpectation[],
inventory?: readonly z.output<typeof analysisStringSchema>[] | null,
): Promise<{
readonly sourceBytesVerified: true;
readonly recognition: readonly {
readonly value: string;
readonly address: string;
readonly state: "observed" | "not_observed";
readonly decodedObject: "verified" | "unverified";
}[];
readonly displayEscapesExcludedFromMatching: true;
}>;
+132 -28
View File
@@ -1,13 +1,16 @@
import assert from "node:assert/strict";
import { mcpTextValue } from "./mcp-verifier-results.mjs";
const fixtureSymbolPrefix = process.platform === "darwin" ? "_" : "";
/** Exercise literal/regex search, Unicode identities and cache invalidation in Hopper. */
export async function verifyHopperSearch(call, invalid, procedure) {
const address = procedure.address;
const original = await call("address_name", { address });
let stringCoverage;
try {
await verifySymbolNames(call, invalid, address);
await verifySearchModes(call, address);
stringCoverage = await verifySearchModes(call, address);
} finally {
await call("set_address_name", { address, name: original });
}
@@ -26,7 +29,7 @@ export async function verifyHopperSearch(call, invalid, procedure) {
symbolUtf16LimitValidatedBeforeMutation: true,
regexAndCaseModes: true,
annotationCacheInvalidation: true,
escapedUtf8AndByteStrings: true,
stringCoverage,
};
}
@@ -103,11 +106,26 @@ async function verifySearchModes(call, address) {
[{ address, value: "REA_Search_Upper" }],
);
const strings = await call("list_strings");
const long = "REA_LONG_LITERAL_" + "x".repeat(4096) + "needle";
const longItem = strings.find((item) =>
item.value.startsWith("REA_LONG_LITERAL_"),
const linux = process.platform === "linux";
const fullLiteral = "REA_LONG_LITERAL_" + "x".repeat(4096) + "needle";
// Recognition is a provider/loader capability, not an adapter guarantee.
// Always retain the original size in raw-byte coverage; Linux additionally
// requires an extent observed to produce native fragmented string objects.
const fullBytes = Buffer.from(fullLiteral + "\0");
const raw = await call("read_bytes", {
address: `${fixtureSymbolPrefix}rea_long_literal`,
length: fullBytes.length,
});
assert.equal(raw.complete, true);
assert.equal(raw.bytes_hex, fullBytes.toString("hex"));
const long = linux
? "REA_FRAGMENTED_LITERAL_" + "x".repeat(512) + "fragment_tail"
: fullLiteral;
const longItem = strings.find(
(item) => long.startsWith(item.value) && item.value.startsWith("REA_"),
);
assert.ok(longItem, "fixture omitted its real long literal");
if (!linux) assert.equal(longItem.address, raw.address);
assert.ok(long.startsWith(longItem.value));
assert.ok(longItem.provider_value.endsWith("…"));
assert.equal(longItem.string.termination, "missing");
@@ -158,7 +176,7 @@ async function verifySearchModes(call, address) {
}
assert.deepEqual(
await call("search_strings", {
pattern: "needle",
pattern: linux ? "fragment_tail" : "needle",
mode: "literal",
case_sensitive: true,
}),
@@ -176,36 +194,122 @@ async function verifySearchModes(call, address) {
}),
expected,
);
await verifyHopperStringObjects(call, [
{ value: "REA_UTF8_é_😀", encoding: "utf-8" },
{ value: 'REA_ESCAPED_"\\line\nend\t\r', encoding: "utf-8" },
{ value: "REA_LITERAL_BACKSLASH_\\n", encoding: "utf-8" },
{ value: "REA_LITERAL_…", encoding: "utf-8" },
{ value: "REA_LATIN1_ÿ", encoding: "latin-1" },
]);
const objects = await verifyHopperStringObjects(
call,
[
{
value: "REA_UTF8_é_😀",
encoding: "utf-8",
symbol: `${fixtureSymbolPrefix}rea_utf8_literal`,
recognitionOptional: linux,
},
{ value: 'REA_ESCAPED_"\\line\nend\t\r', encoding: "utf-8" },
{ value: "REA_LITERAL_BACKSLASH_\\n", encoding: "utf-8" },
{
value: "REA_LITERAL_…",
encoding: "utf-8",
symbol: `${fixtureSymbolPrefix}rea_ellipsis_literal`,
recognitionOptional: linux,
},
{
value: "REA_LATIN1_ÿ",
encoding: "latin-1",
symbol: `${fixtureSymbolPrefix}rea_latin1_literal`,
recognitionOptional: linux,
},
],
strings,
);
return {
fullLiteralSourceBytes: fullBytes.length,
fragmentedLiteralSourceBytes: Buffer.byteLength(long),
fullLiteralRecognition: {
address: raw.address,
state: strings.some((item) => item.address === raw.address)
? "observed"
: "not_observed",
// Linux validates the original through raw bytes; its required decoded
// fragment/dossier checks exercise the separate supported-size literal.
decodedObject: linux ? "unverified" : "verified",
},
...objects,
};
}
/** Compare native string identities and values with the source fixture's bytes. */
export async function verifyHopperStringObjects(call, expectations) {
const strings = await call("list_strings");
for (const { value, encoding } of expectations) {
const item = strings.find((candidate) => candidate.value === value);
assert.ok(
item,
`Hopper omitted the decoded string ${JSON.stringify(value)}`,
);
assert.equal(item.string.encoding, encoding);
assert.equal(item.string.encoding_status, "inferred");
assert.equal(item.string.termination, "present_or_not_required");
export async function verifyHopperStringObjects(
call,
expectations,
inventory = null,
) {
// Reuse only the caller's inventory for this unchanged document, never live
// state from an earlier session. Address-filter and search checks remain real.
const strings = inventory ?? (await call("list_strings"));
const recognition = [];
for (const {
value,
encoding,
symbol,
recognitionOptional = false,
} of expectations) {
const expectedBytes = Buffer.from(
value + "\0",
encoding.replaceAll("-", ""),
);
assert.equal(item.string.byte_length, expectedBytes.length);
const bytes = await call("read_bytes", {
let sourceBytes;
if (symbol !== undefined) {
const raw = await call("read_bytes", {
address: symbol,
length: expectedBytes.length,
});
sourceBytes = raw;
assert.equal(raw.complete, true);
assert.equal(raw.bytes_hex, expectedBytes.toString("hex"));
}
const item = strings.find((candidate) =>
sourceBytes === undefined
? candidate.value === value
: candidate.address === sourceBytes.address,
);
if (item === undefined && recognitionOptional) {
assert.ok(
symbol,
"optional recognition requires independent source-byte coverage",
);
recognition.push({
value,
address: sourceBytes.address,
state: "not_observed",
decodedObject: "unverified",
});
continue;
}
assert.ok(
item,
`Hopper omitted the decoded string ${JSON.stringify(value)}`,
);
assert.equal(
item.value,
value,
"native string decoding changed the source value",
);
recognition.push({
value,
address: item.address,
length: expectedBytes.length,
state: "observed",
decodedObject: "verified",
});
assert.equal(item.string.encoding, encoding);
assert.equal(item.string.encoding_status, "inferred");
assert.equal(item.string.termination, "present_or_not_required");
assert.equal(item.string.byte_length, expectedBytes.length);
const bytes =
sourceBytes ??
(await call("read_bytes", {
address: item.address,
length: expectedBytes.length,
}));
assert.equal(bytes.complete, true);
assert.equal(bytes.bytes_hex, expectedBytes.toString("hex"));
assert.deepEqual(await call("list_strings", { address: item.address }), [
item,
@@ -225,7 +329,7 @@ export async function verifyHopperStringObjects(call, expectations) {
);
return {
sourceBytesVerified: true,
inferredEncodingReported: true,
recognition,
displayEscapesExcludedFromMatching: true,
};
}
+30 -24
View File
@@ -12,6 +12,7 @@ import { tmpdir } from "node:os";
import { promisify } from "node:util";
import { completeVerifierRun, createVerifierRun } from "./lib/verifier-run.mjs";
import { assertCleanLinuxHopperRuntime } from "./lib/clean-linux-hopper-runtime.mjs";
const execFileAsync = promisify(execFile);
const verifierRun = createVerifierRun();
@@ -19,12 +20,12 @@ const command = process.env.REA_VERIFY_SERVER_COMMAND;
if (process.platform !== "linux" || process.getuid?.() !== 0)
throw new Error("Linux setup verification requires a root Linux runner");
if (!command) throw new Error("REA_VERIFY_SERVER_COMMAND is required");
await assertCleanLinuxHopperRuntime();
try {
await access("/opt/hopper/bin/Hopper");
throw new Error("Linux setup verification requires a clean runner");
} catch (error) {
if (error instanceof Error && error.message.includes("clean runner"))
throw error;
if (error?.code !== "ENOENT") throw error;
}
const runJson = async (args) => {
@@ -35,14 +36,25 @@ const runJson = async (args) => {
return JSON.parse(stdout);
};
const plan = await runJson(["setup", "--json"]);
if (plan.status !== "needs_confirmation")
throw new Error("setup did not produce a read-only confirmation plan");
const plan = await runJson([
"setup",
"--install-hopper",
"--dry-run",
"--json",
]);
if (
plan.status !== "planned" ||
!plan.plannedActions.some(({ kind }) => kind === "install_hopper") ||
plan.appliedActions.length !== 0
)
throw new Error("setup did not produce a read-only Hopper installation plan");
await access("/opt/hopper/bin/Hopper").then(
() => {
throw new Error("setup plan mutated the clean runner");
},
() => undefined,
(error) => {
if (error?.code !== "ENOENT") throw error;
},
);
const installed = await runJson([
@@ -58,7 +70,7 @@ if (
throw new Error(
`approved setup did not become ready: ${JSON.stringify(installed)}`,
);
const doctor = await runJson(["doctor", "--json"]);
const doctor = await runJson(["doctor", "--provider", "hopper", "--json"]);
if (doctor.healthy !== true)
throw new Error(`doctor is unhealthy: ${JSON.stringify(doctor)}`);
@@ -67,8 +79,6 @@ await execFileAsync(command, ["analyze", "/usr/bin/true"], {
timeout: 180_000,
maxBuffer: 10 * 1024 * 1024,
});
process.env.HOPPER_TARGET_PATH = "/usr/bin/true";
process.env.HOPPER_SECOND_TARGET_PATH = "/usr/bin/false";
process.env.REA_VERIFY_SERVER_ARGS_JSON = '["mcp"]';
await import("./verify-real-hopper-linux.mjs");
@@ -95,28 +105,24 @@ try {
await rm(modifiedDirectory, { recursive: true, force: true });
}
const repeated = await runJson([
"setup",
"--yes",
"--install-hopper",
"--json",
]);
const repeated = await runJson(["setup", "--yes", "--json"]);
if (
repeated.status !== "ready" ||
repeated.appliedActions.includes("installed_hopper")
repeated.plannedActions.length !== 0 ||
repeated.appliedActions.length !== 0
)
throw new Error("a second setup was not idempotent");
const { stdout: processes } = await execFileAsync("ps", [
"-ax",
"-o",
"command=",
]);
if (/\/opt\/hopper\/bin\/Hopper|\bXvfb\b|hopper-demo-x11\.py/u.test(processes))
throw new Error("Linux setup verification leaked a Hopper demo session");
await assertCleanLinuxHopperRuntime();
const completedVerifierRun = await completeVerifierRun(verifierRun);
if (
completedVerifierRun.process_lineage.status !== "verified" ||
completedVerifierRun.process_lineage.descendants.length !== 0
)
throw new Error("Linux setup verification did not prove owned child cleanup");
console.log(
JSON.stringify({
verifier_run: await completeVerifierRun(verifierRun),
verifier_run: completedVerifierRun,
status: "verified",
setup: true,
cli: true,
+4 -1
View File
@@ -11,7 +11,8 @@ createVerifierRun();
if (process.platform !== "linux")
throw new Error("Linux real-Hopper verification must run on Linux");
const launcher = process.env.HOPPER_LAUNCHER_PATH ?? "/opt/hopper/bin/Hopper";
const configuredLauncher = process.env.HOPPER_LAUNCHER_PATH;
const launcher = configuredLauncher ?? "/opt/hopper/bin/Hopper";
await access(launcher);
await access("/usr/bin/Xvfb");
await access("/usr/bin/xauth");
@@ -28,5 +29,7 @@ try {
process.env.HOPPER_LAUNCHER_PATH = alternateLauncher;
await import("./verify-real-hopper.mjs");
} finally {
if (configuredLauncher === undefined) delete process.env.HOPPER_LAUNCHER_PATH;
else process.env.HOPPER_LAUNCHER_PATH = configuredLauncher;
await rm(alternateDirectory, { recursive: true, force: true });
}
+36
View File
@@ -662,6 +662,42 @@ setInterval(()=>{},1000);\n`,
unicodeNamesPreserved: true,
});
report.processes.windowsEnvironmentSemantics = true;
// Observed through this process's own id: a separate probe process would
// get its own processor group, so it cannot stand in for the process that
// spawns the child.
const callerAffinity = JSON.parse(
execFileSync(boundaryFixture, ["affinity", String(process.pid)], {
encoding: "utf8",
}),
);
const affinityChild = native.call("process_spawn", [
boundaryFixture,
`${quote(boundaryFixture)} affinity`,
workspace,
environment,
]);
const observedAffinity = await wait(affinityChild);
native.call("process_close", [affinityChild.handle]);
assert.equal(observedAffinity.exitCode, 0);
const childAffinity = JSON.parse(observedAffinity.output);
// Masks cross as hexadecimal strings because a mask can exceed the
// safe-integer range. Sharing one processor group makes the caller's mask
// applicable, so it must be inherited exactly. Windows placing the child in
// another group is only permitted when the caller asked for no bound of its
// own, which its group's whole active set establishes; a narrower mask has
// to fail the spawn rather than widen to that group's default.
const sharedGroup =
callerAffinity.singleProcessorGroup &&
childAffinity.singleProcessorGroup &&
callerAffinity.processorGroup === childAffinity.processorGroup;
if (sharedGroup)
assert.equal(childAffinity.affinityMask, callerAffinity.affinityMask);
else assert.equal(callerAffinity.affinityMask, callerAffinity.systemMask);
report.processes.callerAffinityBoundsOwnedProcessOrRefusesToWiden = true;
report.callerAffinity = {
...callerAffinity,
sharedGroupWithChild: sharedGroup,
};
}
const ownerFixture = join(workspace, "owner.mjs");
const ownerPidFile = join(workspace, "crash-child.pid");
+23 -4
View File
@@ -2,12 +2,16 @@ import { createHash } from "node:crypto";
import { describe, expect, it } from "vitest";
import { installMacHopper, type MacHopperInstallHost } from "./MacHopper.js";
import {
installMacHopper,
type MacHopperBundleVerification,
type MacHopperInstallHost,
} from "./MacHopper.js";
class FakeMacHopperHost implements MacHopperInstallHost {
readonly archive = new TextEncoder().encode("hopper-dmg");
archiveOk = true;
valid = true;
verification: MacHopperBundleVerification = "verified";
existing = false;
mountSucceeds = true;
copySucceeds = true;
@@ -15,6 +19,7 @@ class FakeMacHopperHost implements MacHopperInstallHost {
badHash = false;
unmounts = 0;
cleanups = 0;
installs = 0;
opens = 0;
replaces = false;
@@ -47,7 +52,7 @@ class FakeMacHopperHost implements MacHopperInstallHost {
return Promise.resolve();
};
appBundle = () => Promise.resolve("/mounted/Hopper Disassembler.app");
validBundle = () => Promise.resolve(this.valid);
validBundle = () => Promise.resolve(this.verification);
destinationExists = () => Promise.resolve(this.existing);
installBundle = (
_source: string,
@@ -55,6 +60,7 @@ class FakeMacHopperHost implements MacHopperInstallHost {
_stage: string,
replaceExisting: boolean,
) => {
this.installs += 1;
this.replaces = replaceExisting;
return Promise.resolve(this.copySucceeds);
};
@@ -115,7 +121,7 @@ describe("macOS Hopper installation", () => {
it("cleans and detaches after bundle validation fails", async () => {
const host = new FakeMacHopperHost();
host.valid = false;
host.verification = "invalid_signature";
await expect(installMacHopper({}, host)).resolves.toEqual({
status: "failed",
reason: "bundle",
@@ -123,4 +129,17 @@ describe("macOS Hopper installation", () => {
expect(host.unmounts).toBe(1);
expect(host.cleanups).toBe(1);
});
it("reports a publisher mismatch without copying or launching the bundle", async () => {
const host = new FakeMacHopperHost();
host.verification = "unverified_publisher";
await expect(installMacHopper({}, host)).resolves.toEqual({
status: "failed",
reason: "publisher_verification_failed",
});
expect(host.installs).toBe(0);
expect(host.opens).toBe(0);
expect(host.unmounts).toBe(1);
expect(host.cleanups).toBe(1);
});
});
+52 -22
View File
@@ -24,7 +24,35 @@ const execFileAsync = promisify(execFile);
const RELEASES_URL =
"https://www.hopperapp.com/include/files-api.php?request=releases&public=true";
const DOWNLOAD_PREFIX = "https://www.hopperapp.com:443/downloader/public/";
const BUNDLE_IDENTIFIER = "com.cryptic-apps.hopper-web-4";
/**
* Apple publisher identity pinned for the official Hopper macOS bundle. The
* team identifier was captured from `Hopper-6.6.0-demo.dmg` at
* `https://www.hopperapp.com:443/downloader/public/Hopper-6.6.0-demo.dmg`
* (34846271 bytes, SHA-1 0be530f038249742590992199c7b042ea20ca955) with
* `codesign -dvvv`, which reported
* `Authority=Developer ID Application: Cryptic Apps (2AMA2753NF)`.
*/
export const HOPPER_PUBLISHER = Object.freeze({
bundleIdentifier: "com.cryptic-apps.hopper-web-4",
teamIdentifier: "2AMA2753NF",
});
/**
* Code requirement enforcing the bundle identifier and signing team together.
* The identifier is read from the sealed CodeDirectory, so it cannot be changed
* by editing `Info.plist` the way the previous string comparison could.
*/
const HOPPER_PUBLISHER_REQUIREMENT =
`= identifier "${HOPPER_PUBLISHER.bundleIdentifier}"` +
` and anchor apple generic` +
` and certificate leaf[subject.OU] = "${HOPPER_PUBLISHER.teamIdentifier}"`;
/** Outcome of reading a mounted bundle's signature and publisher identity. */
export type MacHopperBundleVerification =
| "verified"
| "invalid_signature"
| "unverified_publisher";
/** Stable network and command effects disclosed before macOS Hopper setup. */
export const macHopperInstallDisclosure = {
@@ -32,6 +60,7 @@ export const macHopperInstallDisclosure = {
commands: [
"hdiutil attach -readonly -nobrowse -mountpoint <private-mount> <verified-hopper.dmg>",
"codesign --verify --deep --strict <mounted-hopper.app>",
`codesign --verify --strict '-R${HOPPER_PUBLISHER_REQUIREMENT}' <mounted-hopper.app>`,
"ditto <mounted-hopper.app> <user-Applications-stage>",
"open <installed-hopper.app>",
] as const,
@@ -52,6 +81,7 @@ export type MacHopperInstallResult =
| "integrity"
| "mount"
| "bundle"
| "publisher_verification_failed"
| "destination_exists"
| "copy"
| "launcher_missing";
@@ -69,7 +99,7 @@ export interface MacHopperInstallHost {
mount(packagePath: string, mountPath: string): Promise<boolean>;
unmount(mountPath: string): Promise<void>;
appBundle(mountPath: string): Promise<string | undefined>;
validBundle(appPath: string): Promise<boolean>;
validBundle(appPath: string): Promise<MacHopperBundleVerification>;
destinationExists(path: string): Promise<boolean>;
installBundle(
source: string,
@@ -124,8 +154,12 @@ export const installMacHopper = async (
return { status: "failed", reason: "mount" };
mounted = true;
const source = await host.appBundle(mountPath);
if (source === undefined || !(await host.validBundle(source)))
if (source === undefined) return { status: "failed", reason: "bundle" };
const verification = await host.validBundle(source);
if (verification === "invalid_signature")
return { status: "failed", reason: "bundle" };
if (verification === "unverified_publisher")
return { status: "failed", reason: "publisher_verification_failed" };
const stage = `${destination}.rea-stage`;
if (
!(await host.installBundle(
@@ -222,25 +256,21 @@ export const systemMacHopperInstallHost = (
environment,
))
)
return false;
try {
const identifier = (
await execFileAsync(
"/usr/libexec/PlistBuddy",
[
"-c",
"Print :CFBundleIdentifier",
join(appPath, "Contents/Info.plist"),
],
{ env: environment },
)
).stdout.trim();
return identifier === BUNDLE_IDENTIFIER;
} catch (cause: unknown) {
// best-effort cleanup: optional bundle probing; unreadable means invalid.
void cause;
return false;
}
return "invalid_signature";
if (
!(await commandSucceeds(
"codesign",
[
"--verify",
"--strict",
`-R${HOPPER_PUBLISHER_REQUIREMENT}`,
appPath,
],
environment,
))
)
return "unverified_publisher";
return "verified";
},
async destinationExists(path) {
try {
@@ -0,0 +1,23 @@
import { describe, expect, it } from "vitest";
import { HOPPER_PUBLISHER } from "./MacHopper.js";
import { setupInstallFailure } from "./SetupInstallFailure.js";
describe("macOS Hopper setup failure projection", () => {
it("projects a publisher mismatch onto its own code and recovery", () => {
expect(setupInstallFailure("publisher_verification_failed")).toEqual({
status: "failed",
code: "publisher_verification_failed",
remediation: `The mounted Hopper application is not signed by the publisher REA pins (${HOPPER_PUBLISHER.bundleIdentifier}, Apple team ${HOPPER_PUBLISHER.teamIdentifier}); nothing was copied or launched. Install Hopper yourself and set HOPPER_LAUNCHER_PATH to its launcher, then rerun rea setup.`,
});
});
it("keeps a broken bundle distinct from a publisher mismatch", () => {
expect(setupInstallFailure("bundle")).toEqual({
status: "failed",
code: "bundle_invalid",
remediation:
"The mounted package did not contain the expected Hopper application bundle. Retry setup; if it repeats, update REA before installing.",
});
});
});
+10
View File
@@ -1,3 +1,5 @@
import { HOPPER_PUBLISHER } from "./MacHopper.js";
export type SetupFailureCode =
| "unsupported_host"
| "download_failed"
@@ -10,6 +12,7 @@ export type SetupFailureCode =
| "destination_exists"
| "mount_failed"
| "bundle_invalid"
| "publisher_verification_failed"
| "copy_failed"
| "skill_install_failed"
| "cleanup_failed";
@@ -39,6 +42,7 @@ export type HopperInstallFailureReason =
| "destination_exists"
| "mount"
| "bundle"
| "publisher_verification_failed"
| "copy";
/** Map provider installer failures to stable setup codes and safe recovery. */
@@ -115,6 +119,12 @@ export const setupInstallFailure = (
remediation:
"The mounted package did not contain the expected Hopper application bundle. Retry setup; if it repeats, update REA before installing.",
};
case "publisher_verification_failed":
return {
status: "failed",
code: "publisher_verification_failed",
remediation: `The mounted Hopper application is not signed by the publisher REA pins (${HOPPER_PUBLISHER.bundleIdentifier}, Apple team ${HOPPER_PUBLISHER.teamIdentifier}); nothing was copied or launched. Install Hopper yourself and set HOPPER_LAUNCHER_PATH to its launcher, then rerun rea setup.`,
};
case "copy":
return {
status: "failed",
@@ -17,6 +17,7 @@ import { DirectoryArtifactReader } from "../DirectoryArtifactReader.js";
import { SafeOutputTree } from "../SafeOutputTree.js";
import { SafeOutputTreeCreationFailure } from "../SafeOutputTreeCreationFailure.js";
import { ZipArtifactReader } from "../ZipArtifactReader.js";
import { isZipPackageFormat } from "../../domain/zipPackageFormat.js";
import { MachOSliceArtifactReader } from "../MachOSliceArtifactReader.js";
import {
artifactExtractionResultSchema,
@@ -400,13 +401,6 @@ interface ExtractionInventory {
readonly integrityContradictions: readonly IntegrityContradiction[];
}
const ZIP_FORMATS = ["ipa", "apk", "msix", "appx", "zip"] as const;
const isZipFormat = (
format: BinaryTarget["format"],
): format is (typeof ZIP_FORMATS)[number] =>
(ZIP_FORMATS as readonly string[]).includes(format);
/**
* Refuse a format without an extraction reader before inventory work starts.
* The target kind, not the host, is unsupported by extraction. The error keeps
@@ -422,7 +416,7 @@ const requireExtractableFormat = async (
!directory &&
format !== "asar" &&
!isMachOFormat(format) &&
!isZipFormat(format)
!isZipPackageFormat(format)
)
throw new AnalysisUnsupportedTargetError(
"extract_artifact",
@@ -443,7 +437,7 @@ const createReader = async (
if (await requireExtractableFormat(path, input))
return new DirectoryArtifactReader(path);
if (format === "asar") return new AsarArtifactReader(path);
if (isZipFormat(format)) return new ZipArtifactReader(path, format);
if (isZipPackageFormat(format)) return new ZipArtifactReader(path, format);
return new MachOSliceArtifactReader(path, input.environment);
};
+2 -1
View File
@@ -144,7 +144,8 @@ const projectHar = (
(literal) =>
item.includes(literal) ||
contentBase64.includes(literal) ||
sha256.includes(literal),
sha256.includes(literal) ||
String(bytes.length).includes(literal),
);
binary_fields.push(
hidden
+130
View File
@@ -597,6 +597,136 @@ describe("dyld load order", () => {
});
});
describe("loader-relative dylib resolution", () => {
it("does not reuse already loaded images by install name for @loader_path dependencies", async () => {
const pluginA = "Contents/PlugIns/A/pluginA.dylib";
const helperA = "Contents/PlugIns/A/libhelper.dylib";
const pluginB = "Contents/PlugIns/B/pluginB.dylib";
const trace = await traceDylibLoading(
memoryView({
[MAIN]: executable({
dependencies: [
dependency("@executable_path/../PlugIns/A/pluginA.dylib"),
dependency("@executable_path/../PlugIns/B/pluginB.dylib"),
],
}),
[pluginA]: parsed(
slice({
dependencies: [dependency("@loader_path/libhelper.dylib")],
}),
),
[helperA]: parsed(
slice({
install_name: "@loader_path/libhelper.dylib",
}),
),
[pluginB]: parsed(
slice({
dependencies: [dependency("@loader_path/libhelper.dylib")],
}),
),
}),
{ roots: [MAIN] },
);
const edgeA = edgeFor(trace, pluginA, "@loader_path/libhelper.dylib");
expect(edgeA.resolution).toEqual({
status: "resolved",
image: helperA,
});
expect(edgeA.candidates).toEqual([
expect.objectContaining({
source: "loader_path",
outcome: "resolved",
resolved_path: helperA,
}),
]);
const edgeB = edgeFor(trace, pluginB, "@loader_path/libhelper.dylib");
expect(edgeB.resolution).toEqual({
status: "unresolved",
image: null,
});
expect(edgeB.candidates).toEqual([
expect.objectContaining({
path: "Contents/PlugIns/B/libhelper.dylib",
source: "loader_path",
outcome: "absent",
resolved_path: null,
}),
]);
expect(trace.findings).toContainEqual(
expect.objectContaining({
kind: "required-load-unresolved",
image: pluginB,
}),
);
});
it("resolves @loader_path dependencies to the loader's own directory when multiple helpers exist", async () => {
const pluginA = "Contents/PlugIns/A/pluginA.dylib";
const helperA = "Contents/PlugIns/A/libhelper.dylib";
const pluginB = "Contents/PlugIns/B/pluginB.dylib";
const helperB = "Contents/PlugIns/B/libhelper.dylib";
const trace = await traceDylibLoading(
memoryView({
[MAIN]: executable({
dependencies: [
dependency("@executable_path/../PlugIns/A/pluginA.dylib"),
dependency("@executable_path/../PlugIns/B/pluginB.dylib"),
],
}),
[pluginA]: parsed(
slice({
dependencies: [dependency("@loader_path/libhelper.dylib")],
}),
),
[helperA]: parsed(
slice({
install_name: "@loader_path/libhelper.dylib",
}),
),
[pluginB]: parsed(
slice({
dependencies: [dependency("@loader_path/libhelper.dylib")],
}),
),
[helperB]: parsed(
slice({
install_name: "@loader_path/libhelper.dylib",
}),
),
}),
{ roots: [MAIN] },
);
expect(
edgeFor(trace, pluginA, "@loader_path/libhelper.dylib"),
).toMatchObject({
resolution: { status: "resolved", image: helperA },
candidates: [
expect.objectContaining({
source: "loader_path",
outcome: "resolved",
resolved_path: helperA,
}),
],
});
expect(
edgeFor(trace, pluginB, "@loader_path/libhelper.dylib"),
).toMatchObject({
resolution: { status: "resolved", image: helperB },
candidates: [
expect.objectContaining({
source: "loader_path",
outcome: "resolved",
resolved_path: helperB,
}),
],
});
});
});
describe("dyld slice compatibility and coverage", () => {
it("lets an x86_64h process load generic x86_64 but not arm64e load arm64", async () => {
const files = {
+8 -2
View File
@@ -427,7 +427,9 @@ const resolveDependency = async (
): Promise<Edge> => {
const current = context.loaded.get(loader);
const chain = current?.chain ?? [loader];
const loaded = context.byInstallName.get(dependency.install_name);
const loaded = dependency.install_name.startsWith("@rpath/")
? context.byInstallName.get(dependency.install_name)
: undefined;
const candidates: Candidate[] = [];
if (loaded !== undefined)
candidates.push({
@@ -506,7 +508,10 @@ const traceProcess = async (
chain: [context.root],
conditional: false,
});
if (rootSlice.install_name !== null)
if (
rootSlice.install_name !== null &&
rootSlice.install_name.startsWith("@rpath/")
)
context.byInstallName.set(rootSlice.install_name, context.root);
const pending = [context.root];
while (pending.length > 0) {
@@ -537,6 +542,7 @@ const traceProcess = async (
});
if (
slice.install_name !== null &&
slice.install_name.startsWith("@rpath/") &&
!context.byInstallName.has(slice.install_name)
)
context.byInstallName.set(slice.install_name, image);
+1 -1
View File
@@ -91,7 +91,7 @@ export const DYLIB_RESOLUTION_LIMITATIONS = [
"Slices are matched by dyld's graded architectures (an x86_64h process also loads x86_64). arm64e processes that disable pointer authentication can also load arm64 slices; that fallback is not modeled.",
"Absolute install names and rpaths are outside the analyzed root and are not evaluated, including /System and /usr/lib libraries that the dyld shared cache usually provides.",
"Leaf and relative install names depend on dyld fallback paths, DYLD_* variables, and the working directory; they are undetermined.",
"Load order follows dyld's dependents-first traversal in load-command order. An image reached through several chains is resolved once per process, with the rpath stack and conditionality of the first chain; a later request whose install name matches an already loaded image reuses it.",
"Load order follows dyld's dependents-first traversal in load-command order. An image reached through several chains is resolved once per process, with the rpath stack and conditionality of the first chain; a later @rpath request whose install name matches an already loaded image reuses it.",
"@loader_path uses each image's symlink-resolved path within the analyzed root.",
"Code-signing checks that can reject a found image, such as library validation and the hardened runtime, are not evaluated.",
"Dylib compatibility versions are not compared. Apple's linker documentation describes a load-time rejection when an image's compatibility version is older than the loader requires, but dyld on macOS 26 was observed to load such an image.",
@@ -116,6 +116,24 @@ it("keeps unsupported profile reasons distinct from malformed input", () => {
expect(JSON.stringify(projectAnalysisError(result))).not.toContain("private");
});
it("preserves a retryable capability failure through explicit-value redaction", () => {
// Retryability is a semantic field of the error, not presentation: dropping
// it turns a transient admission failure into a permanent one and changes
// the remediation the caller is shown.
const error = new AnalysisCapabilityUnavailableError(
"mitmproxy",
"inspect_web_network_capture",
"Runtime admission for /targets/private/capture failed transiently",
{ retryable: true },
);
expect(projectAnalysisError(error).retryable).toBe(true);
const result = redactExplicitFailure(error, ["private"]);
expect(result).toBeInstanceOf(AnalysisCapabilityUnavailableError);
expect((result as AnalysisCapabilityUnavailableError).retryable).toBe(true);
expect(projectAnalysisError(result).retryable).toBe(true);
expect(JSON.stringify(projectAnalysisError(result))).not.toContain("private");
});
it("coarsens format issue pointers without creating replacement coordinates", () => {
const error = new AnalysisInputError(
"inspect_web_network_capture",
+1
View File
@@ -154,6 +154,7 @@ export const redactExplicitFailure = (
...(error.userMessage === undefined
? {}
: { userMessage: text(error.userMessage) }),
...(error.retryable ? { retryable: true } : {}),
},
);
if (error instanceof AnalysisResourceConstraintError)
@@ -1,4 +1,4 @@
import { posix, relative, win32 } from "node:path";
import { posix, win32 } from "node:path";
import type { ApplicationNode } from "./javascriptApplicationGraphSchemas.js";
import type { JavaScriptApplicationGraph } from "./javascriptApplicationGraph.js";
@@ -216,7 +216,7 @@ const pathBelowRoot = (root: string, value: string): string | null => {
const remainder =
rootStyle === "windows"
? win32.relative(root, value)
: relative(root, value);
: posix.relative(root, value);
const portableRemainder = remainder.replaceAll("\\", "/");
if (
remainder === "" ||
+21
View File
@@ -33,3 +33,24 @@ it("rejects incomplete headers, invalid signatures and zero dimensions", () => {
expect(readPngHeaderDimensions(zero)).toBeUndefined();
}
});
it.each([0, 12, 14, 0xffff_ffff])("rejects IHDR data length %s", (length) => {
const bytes = Buffer.from(png);
bytes.writeUInt32BE(length, 8);
expect(readPngHeaderDimensions(bytes)).toBeUndefined();
});
it.each([16, 20])("rejects out-of-range PNG dimension at %s", (offset) => {
const bytes = Buffer.from(png);
bytes.writeUInt32BE(0x8000_0000, offset);
expect(readPngHeaderDimensions(bytes)).toBeUndefined();
});
it("accepts the largest dimension representable by the PNG specification", () => {
const bytes = Buffer.from(png);
bytes.writeUInt32BE(0x7fff_ffff, 16);
expect(readPngHeaderDimensions(bytes)).toEqual({
width: 0x7fff_ffff,
height: 1,
});
});
+7 -1
View File
@@ -8,10 +8,16 @@ export const readPngHeaderDimensions = (
if (
bytes.byteLength < 24 ||
!bytes.subarray(0, 8).equals(PNG_SIGNATURE) ||
bytes.readUInt32BE(8) !== 13 ||
!bytes.subarray(12, 16).equals(IHDR_TYPE)
)
return undefined;
const width = bytes.readUInt32BE(16);
const height = bytes.readUInt32BE(20);
return width === 0 || height === 0 ? undefined : { width, height };
return width === 0 ||
height === 0 ||
width > 0x7fff_ffff ||
height > 0x7fff_ffff
? undefined
: { width, height };
};
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import { parseProcessCapture } from "./processCaptureParsing.js";
import type { ProcessTraceSpecification } from "./processTraceSpecification.js";
import { processTraceSpecificationSchema as specificationSchema } from "./processTraceSpecification.js";
import { processTraceComparisonResultSchema } from "./processTraceEvaluation.js";
import {
capture,
@@ -100,6 +101,33 @@ describe("generic capture trace comparison", () => {
right: { matched_variant: "two" },
});
});
it("compares a declared identifier the comparison result can represent", () => {
// The specification owns the trace identifier vocabulary and the result
// echoes those identifiers verbatim, so both must accept the same values
// rather than handing the caller a raw schema error for its own input.
const eventId = `e${"0".repeat(64)}`;
const specification: ProcessTraceSpecification = {
events: [
{
id: eventId,
source: "terminal_raw",
exact: terminal,
cardinality: { kind: "required" },
},
],
language: {
kind: "finite_traces",
variants: [{ id: "only", trace: [eventId] }],
},
};
expect(specificationSchema.safeParse(specification).success).toBe(true);
const left = capture(values(["terminal", "process"]));
expect(compareProcessTraces(left, left, specification)).toMatchObject({
verdict: "equivalent",
left: { matched_variant: "only", raw_trace: [{ event_id: eventId }] },
});
});
});
describe("process trace constraints and evidence sufficiency", () => {
+4 -5
View File
@@ -13,13 +13,12 @@ import {
import {
canonicalTraceJson,
processTraceCardinalityBounds,
processTraceIdentifierSchema,
type ProcessTraceSpecification,
} from "./processTraceSpecification.js";
const identifierSchema = z.string().regex(/^[A-Za-z][A-Za-z0-9._\x2d]{0,63}$/u);
const matchedEventSchema = z.strictObject({
event_id: identifierSchema,
event_id: processTraceIdentifierSchema,
location: processObservationLocationSchema,
});
@@ -32,7 +31,7 @@ const sideResultSchema = z.union([
z.strictObject({
...sideResultShape,
status: z.literal("pass"),
matched_variant: identifierSchema.nullable(),
matched_variant: processTraceIdentifierSchema.nullable(),
}),
z.strictObject({
...sideResultShape,
@@ -53,7 +52,7 @@ const diagnosticSchema = z.strictObject({
]),
side: z.enum(["left", "right"]),
message: z.string(),
event_ids: z.array(identifierSchema),
event_ids: z.array(processTraceIdentifierSchema),
locations: z.array(processObservationLocationSchema),
});
+23 -12
View File
@@ -9,7 +9,16 @@ import {
processObservationSourceSchema,
} from "./processObservation.js";
const identifierSchema = z.string().regex(IDENTIFIER_PATTERN);
/**
* A declared trace, event or variant identifier. The specification owns this
* vocabulary and the comparison result echoes those identifiers verbatim, so
* the result module must reuse this schema rather than restate the pattern:
* two bounds on the same identifier would reject the result of an accepted
* specification.
*/
export const processTraceIdentifierSchema = z
.string()
.regex(IDENTIFIER_PATTERN);
const cardinalitySchema = z.discriminatedUnion("kind", [
z.strictObject({ kind: z.literal("required") }),
@@ -31,7 +40,7 @@ const cardinalitySchema = z.discriminatedUnion("kind", [
]);
const eventDeclarationSchema = z.strictObject({
id: identifierSchema,
id: processTraceIdentifierSchema,
source: processObservationSourceSchema,
exact: jsonValueSchema,
ignore_fields: z
@@ -56,29 +65,31 @@ const partialOrderLanguageSchema = z.strictObject({
happens_before: z
.array(
z.strictObject({
before: identifierSchema,
after: identifierSchema,
before: processTraceIdentifierSchema,
after: processTraceIdentifierSchema,
}),
)
.default([]),
not_before: z
.array(
z.strictObject({
event: identifierSchema,
anchor: identifierSchema,
event: processTraceIdentifierSchema,
anchor: processTraceIdentifierSchema,
}),
)
.default([]),
unordered_groups: z
.array(z.strictObject({ events: z.array(identifierSchema).min(2) }))
.array(
z.strictObject({ events: z.array(processTraceIdentifierSchema).min(2) }),
)
.default([]),
prefix: z.array(identifierSchema).default([]),
suffix: z.array(identifierSchema).default([]),
prefix: z.array(processTraceIdentifierSchema).default([]),
suffix: z.array(processTraceIdentifierSchema).default([]),
});
const finiteTraceTokenSchema = z.union([
identifierSchema,
z.strictObject({ unordered: z.array(identifierSchema).min(2) }),
processTraceIdentifierSchema,
z.strictObject({ unordered: z.array(processTraceIdentifierSchema).min(2) }),
]);
const finiteTraceLanguageSchema = z.strictObject({
@@ -86,7 +97,7 @@ const finiteTraceLanguageSchema = z.strictObject({
variants: z
.array(
z.strictObject({
id: identifierSchema,
id: processTraceIdentifierSchema,
trace: z.array(finiteTraceTokenSchema),
}),
)
+3 -2
View File
@@ -23,6 +23,7 @@ import {
AnalysisUnsupportedTargetError,
} from "../domain/analysisErrorCore.js";
import { AnalysisProtocolError } from "../domain/analysisErrorCore.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import { err, ok, type Result } from "../domain/result.js";
import {
@@ -759,7 +760,7 @@ export class FlutterBuildProvider {
toolchain_capped: value.libflutter.toolchainCapped,
},
}))
.sort((left, right) => left.abi.localeCompare(right.abi));
.sort((left, right) => compareUnicodeCodePoints(left.abi, right.abi));
const flutterDetected = abis.some((entry) => entry.libapp.present);
const partial =
abis.some(
@@ -871,7 +872,7 @@ export class FlutterBuildProvider {
(left, right) =>
(preference.indexOf(left.abi) + 1 || preference.length + 1) -
(preference.indexOf(right.abi) + 1 || preference.length + 1) ||
left.abi.localeCompare(right.abi),
compareUnicodeCodePoints(left.abi, right.abi),
)[0]!
: candidates.find((candidate) => candidate.abi === abi);
if (selected === undefined)
+4 -2
View File
@@ -85,8 +85,10 @@ export class IdaWorkspace {
slice === undefined
? position + bytes.length
: Math.min(position + bytes.length, slice.offset + slice.size);
const admitted = bytes.subarray(start - position, end - position);
if (admitted.length > 0) {
// A chunk after the slice has end < position, and a negative subarray
// bound would count from the chunk's end instead of being empty.
if (end > start) {
const admitted = bytes.subarray(start - position, end - position);
inputHash.update(admitted);
await input.write(admitted);
}
+92 -1
View File
@@ -5,7 +5,7 @@ import { afterEach, describe, expect, it } from "vitest";
import { parseBinaryTarget } from "../application/BinaryTargetResolver.js";
import { parseExecutableHeader } from "../domain/binaryTarget.js";
import { fat } from "../domain/binaryTarget.fixture.js";
import { fat, thinMach } from "../domain/binaryTarget.fixture.js";
import {
createIdaTarget,
RecordingIdaMcp,
@@ -35,6 +35,45 @@ const universalTarget = async (hostArchitecture: "arm64" | "x64") => {
return { bytes, target: resolved.value };
};
/** One slice of a synthetic universal file: CPU type, offset and size. */
interface Layout {
readonly cpu: number;
readonly offset: number;
readonly size: number;
}
/**
* Write a universal file whose slices span more than one 64 KiB read, each
* filled with its own byte so bytes outside the selected slice are visible.
*/
const largeUniversalTarget = async (
layout: readonly Layout[],
hostArchitecture: "arm64" | "x64",
) => {
const directory = await createTestTempDirectory("rea-ida-thin-large-");
roots.push(directory);
const path = join(directory, "universal");
const total = Math.max(...layout.map(({ offset, size }) => offset + size));
const bytes = Buffer.alloc(total);
bytes.writeUInt32BE(0xcafebabe, 0);
bytes.writeUInt32BE(layout.length, 4);
layout.forEach(({ cpu, offset, size }, index) => {
const entry = 8 + index * 20;
bytes.writeUInt32BE(cpu, entry);
bytes.writeUInt32BE(offset, entry + 8);
bytes.writeUInt32BE(size, entry + 12);
bytes.writeUInt32BE(14, entry + 16);
bytes.fill(0x11 * (index + 1), offset, offset + size);
thinMach(0xfeedfacf, cpu).copy(bytes, offset);
});
await writeFile(path, bytes);
const resolved = await parseBinaryTarget(path, { hostArchitecture });
if (!resolved.ok) throw resolved.error;
if (resolved.value.format !== "mach-o-universal")
throw new Error("the universal fixture did not resolve as a FAT container");
return { bytes, target: resolved.value };
};
describe("IDA workspace input thinning", () => {
it.skipIf(process.platform === "win32")(
"thins the selected arm64 slice into the private headless input",
@@ -78,6 +117,58 @@ describe("IDA workspace input thinning", () => {
},
);
it.skipIf(process.platform === "win32")(
"copies exactly the selected slice when later slices follow it across read boundaries",
async () => {
const { bytes, target } = await largeUniversalTarget(
[
{ cpu: 0x01000007, offset: 4096, size: 8480 },
{ cpu: 0x0100000c, offset: 16384, size: 33464 },
{ cpu: 0x00000007, offset: 65536, size: 33464 },
],
"arm64",
);
const workspace = await IdaWorkspace.allocate(target);
roots.push(workspace.directory);
await workspace.copyInput();
const input = await readFile(workspace.inputPath);
const { offset, size } = target.universalSlice;
expect(size, "the arm64 slice is selected").toBe(33464);
expect(input.length, "no byte after the slice is copied").toBe(size);
expect(input.equals(bytes.subarray(offset, offset + size))).toBe(true);
expect(workspace.inputSha256).toBe(
createHash("sha256")
.update(bytes.subarray(offset, offset + size))
.digest("hex"),
);
await workspace.remove();
},
);
it.skipIf(process.platform === "win32")(
"copies exactly the first slice when it is selected and others follow",
async () => {
const { bytes, target } = await largeUniversalTarget(
[
{ cpu: 0x01000007, offset: 16384, size: 37456 },
{ cpu: 0x0100000c, offset: 65536, size: 33464 },
],
"x64",
);
const workspace = await IdaWorkspace.allocate(target);
roots.push(workspace.directory);
await workspace.copyInput();
const input = await readFile(workspace.inputPath);
const { offset, size } = target.universalSlice;
expect(size, "the x86_64 slice is selected").toBe(37456);
expect(input.length, "no byte after the slice is copied").toBe(size);
expect(input.equals(bytes.subarray(offset, offset + size))).toBe(true);
await workspace.remove();
},
);
it("keeps a whole-file copy for thin targets", async () => {
const { root, target } = await createIdaTarget("arm64");
roots.push(root);
+31
View File
@@ -35,6 +35,37 @@ const validPng = Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jv4sAAAAASUVORK5CYII=",
"base64",
);
it.each([
{ offset: 8, value: 12 },
{ offset: 16, value: 0x8000_0000 },
{ offset: 20, value: 0x8000_0000 },
])(
"rejects invalid IHDR metadata with a matching digest",
async ({ offset, value }) => {
const bytes = Buffer.from(validPng);
bytes.writeUInt32BE(value, offset);
const screenshot = {
mime_type: "image/png",
base64: bytes.toString("base64"),
sha256: createHash("sha256").update(bytes).digest("hex"),
width: bytes.readUInt32BE(16),
height: bytes.readUInt32BE(20),
};
const result = await observeNativeUi(
target,
"observe_native_ui",
{ ...scope, screenshot: true },
{
environment: {},
invoke: async () => ({
ok: true,
result: { ...snapshot, screenshot },
}),
},
);
expect(result.ok).toBe(false);
},
);
describe("native UI screenshot validation", () => {
it("rejects malformed or mismatched screenshot bytes from the helper", async () => {
const screenshot = {
+18
View File
@@ -83,6 +83,24 @@ it("counts IPv6 endpoints once per packet and preserves every examined fact", as
expect(result.partial).toBe(false);
});
it("orders equal-count endpoints and protocols by code point, not host locale", async () => {
// Locale collation puts "fe80::1" first and, under da-DK, "aarp" after "zz".
const result = await parseTsharkJsonOutput(
capture([
{ "ipv6.src": ["fe80::1"], "frame.protocols": ["eth:llc:zz"] },
{ "ipv6.src": ["fe80:1::1"], "frame.protocols": ["eth:llc:aarp"] },
]),
);
expect(result.endpoints.map(({ address }) => address)).toEqual([
"fe80:1::1",
"fe80::1",
]);
expect(result.protocolDistribution.map(({ protocol }) => protocol)).toEqual([
"eth:llc:aarp",
"eth:llc:zz",
]);
});
it("preserves all DNS addresses and their exact examined count", async () => {
const result = await parseTsharkJsonOutput(
capture(
+3 -2
View File
@@ -4,6 +4,7 @@ import {
AnalysisResourceConstraintError,
} from "../domain/analysisErrorCore.js";
import { parseRecordedTransportUrl } from "../domain/recordedTransportUrl.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
const OPERATION = "inspect_pcap_capture";
/** Bounds JSON decoding plus its expanded object graph before JSON.parse. */
@@ -284,7 +285,7 @@ export const parseTsharkJsonOutput = async (
signal?.throwIfAborted();
return {
endpoints: [...endpoints]
.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
.sort((a, b) => b[1] - a[1] || compareUnicodeCodePoints(a[0], b[0]))
.map(([address, packet_count]) => ({
address,
port: null,
@@ -300,7 +301,7 @@ export const parseTsharkJsonOutput = async (
tlsSniValues: [...sni],
tlsSniCount: sni.size,
protocolDistribution: [...protocols]
.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
.sort((a, b) => b[1] - a[1] || compareUnicodeCodePoints(a[0], b[0]))
.map(([protocol, packet_count]) => ({ protocol, packet_count })),
protocolCount: protocols.size,
httpRequestUris: [...uris],
+47 -31
View File
@@ -12,6 +12,8 @@ import { err, ok } from "../domain/result.js";
import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
import { inspectEvidenceBundle } from "../application/investigation/InspectEvidenceBundle.js";
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
import { withAdmittedAnalysis } from "./analysisAdmission.js";
import { runAdmittedToolOperation } from "./admittedToolOperation.js";
interface EvidenceToolRegistration {
readonly server: EvidenceMcpServer;
@@ -92,40 +94,54 @@ const registerImportEvidenceTool = ({
resources,
importContract,
}: EvidenceToolRegistration): void => {
const admission = withAdmittedAnalysis({ kind: "session", session });
server.registerTool(
importContract.name,
toolRegistrationOptions(importContract),
async (input, context) => {
const path = input.path;
const signal = context.mcpReq.signal;
const loaded = await readImmutableEvidenceBundle(path, signal, resources);
if (!loaded.ok)
return server.delivery.toCallToolResult(loaded, importContract);
const retainedUnknownRevisions = new Set(
bundleForSerialization(session).unknowns.map((unknown) =>
unknownRevisionKey(unknown),
),
);
if (signal.aborted)
return server.delivery.toCallToolResult(
err(new AnalysisCancelledError("import_evidence_bundle")),
importContract,
);
const imported = session.importEvidenceBundle(loaded.value);
return imported.ok
? server.delivery.toCallToolResult(
ok({
imported: imported.value,
unknowns_added: loaded.value.unknowns.filter(
(unknown) =>
!retainedUnknownRevisions.has(unknownRevisionKey(unknown)),
).length,
total: bundleForSerialization(session).records.length,
}),
importContract,
)
: server.delivery.toCallToolResult(imported, importContract);
},
async (input, context) =>
runAdmittedToolOperation(
server,
admission,
importContract.name,
context.mcpReq.signal,
async () => {
const path = input.path;
const signal = context.mcpReq.signal;
const loaded = await readImmutableEvidenceBundle(
path,
signal,
resources,
);
if (!loaded.ok)
return server.delivery.toCallToolResult(loaded, importContract);
const retainedUnknownRevisions = new Set(
bundleForSerialization(session).unknowns.map((unknown) =>
unknownRevisionKey(unknown),
),
);
if (signal.aborted)
return server.delivery.toCallToolResult(
err(new AnalysisCancelledError("import_evidence_bundle")),
importContract,
);
const imported = session.importEvidenceBundle(loaded.value);
return imported.ok
? server.delivery.toCallToolResult(
ok({
imported: imported.value,
unknowns_added: loaded.value.unknowns.filter(
(unknown) =>
!retainedUnknownRevisions.has(
unknownRevisionKey(unknown),
),
).length,
total: bundleForSerialization(session).records.length,
}),
importContract,
)
: server.delivery.toCallToolResult(imported, importContract);
},
),
);
};
@@ -3,6 +3,37 @@ import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
import { captureWebScreenshotInputSchema } from "../../../src/domain/webScreenshot.js";
import { startFakeCdpBrowser } from "../../fixtures/fakeCdpBrowser.js";
describe("screenshot committed document identity", () => {
it.each([
{ offset: 8, value: 14 },
{ offset: 16, value: 0x8000_0000 },
{ offset: 20, value: 0x8000_0000 },
])("rejects invalid screenshot IHDR metadata", async ({ offset, value }) => {
const bytes = Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jv4sAAAAASUVORK5CYII=",
"base64",
);
bytes.writeUInt32BE(value, offset);
const browser = await startFakeCdpBrowser({
commandResult: ({ method }) =>
method === "Page.captureScreenshot"
? { data: bytes.toString("base64") }
: undefined,
});
onTestFinished(async () => {
await browser.close();
});
const result = await new CdpBrowserProvider().captureScreenshot(
captureWebScreenshotInputSchema.parse({
cdp_endpoint: browser.endpoint,
allowed_origins: [browser.allowedOrigin],
target_id: "allowed-page",
}),
);
expect(result).toMatchObject({
ok: false,
error: { reason: "protocol_error" },
});
});
it.each(["loader-main", "loader-reloaded"])(
"distinguishes %s for the same URL",
async (screenshotDocumentLoader) => {
@@ -7,6 +7,9 @@ import { execFile } from "node:child_process";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { webNetworkCaptureSchema } from "../../../src/domain/webNetworkCapture.js";
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const entrypoint = fileURLToPath(
new URL("../../../scripts/rea.mjs", import.meta.url),
);
@@ -41,6 +44,91 @@ const cli = async (
};
import { historicalHar } from "../../fixtures/historicalHar.js";
it("excludes declared binary lengths through CLI, MCP and retained capture pages", async () => {
const root = await createTestTempDirectory("rea-har-byte-length-");
const path = join(root, "capture.har");
const fixture = historicalHar();
const entry = fixture.log.entries[0];
if (entry === undefined) throw new Error("fixture missing");
const body = Buffer.alloc(12_345, "A");
const content = body.toString("base64");
const digest = createHash("sha256").update(body).digest("hex");
await writeFile(
path,
JSON.stringify({
log: {
...fixture.log,
entries: [
{
...entry,
response: {
...entry.response,
content: {
size: 99,
mimeType: "text/plain",
encoding: "base64",
text: content,
},
},
},
],
},
}),
);
const { call } = await connectLocalToolsMcp();
const args = { capture_path: path, format: "har" };
const control = await call("inspect_web_network_capture", args);
expect(control.isError).not.toBe(true);
const retained = parseEvidence(control.structuredContent);
const controlCapture = webNetworkCaptureSchema.parse(
retained.normalized_result,
);
expect(controlCapture.records[0]?.binary_fields[0]).toMatchObject({
state: "retained",
bytes: body.length,
content_base64: content,
sha256: digest,
});
for (const literal of ["12345", "2345"]) {
// Only the derived count matches, so this cannot pass via another exclusion.
expect(content).not.toContain(literal);
expect(digest).not.toContain(literal);
const fromCli = await cli(path, "har", ["--sensitive-value", literal]);
expect(fromCli.ok, fromCli.stdout).toBe(true);
const evidence = parseEvidence(JSON.parse(fromCli.stdout));
const response = await call("inspect_web_network_capture", {
...args,
sensitive_values: [literal],
});
expect(response.isError).not.toBe(true);
const fromMcp = parseEvidence(response.structuredContent);
expect(fromMcp.normalized_result).toEqual(evidence.normalized_result);
const capture = webNetworkCaptureSchema.parse(evidence.normalized_result);
expect(capture.records[0]?.reported).toMatchObject({
response: { content: { size: 99, text: null } },
});
expect(capture.records[0]?.binary_fields[0]).toEqual({
pointer: "/response/content/text",
representation: "har-base64-content",
state: "redacted",
bytes: null,
content_base64: null,
sha256: null,
});
for (const detail of ["preview", "complete"]) {
const page = await call("inspect_analysis_view", {
source: { kind: "retained-evidence", evidence_id: fromMcp.evidence_id },
view: { kind: "capture", detail },
});
expect(page.isError).not.toBe(true);
const result = parseEvidence(page.structuredContent);
expect(result.normalized_result).toMatchObject({
items: [{ binary_fields: [{ state: "redacted", bytes: null }] }],
});
}
}
}, 60_000);
it("reads actual upstream HAR packages in an owned process and retains selected producer order", async () => {
const root = await mkdtemp(join(tmpdir(), "rea-history-har-"));
onTestFinished(() => rm(root, { recursive: true, force: true }));
@@ -21,6 +21,7 @@ import {
type ApplicationVersionComparisonResult,
} from "../../../src/domain/javascript/javascriptApplicationVersionComparisonSchemas.js";
import { javascriptRuntimeReconciliationResultSchema } from "../../../src/domain/javascript/javascriptRuntimeReconciliationSchemas.js";
import { electronPageInspectionSchema } from "../../../src/domain/javascript/electronObservation.js";
import { compareJavaScriptApplicationVersions } from "../../../src/domain/javascript/javascriptApplicationVersionComparison.js";
import { createJavaScriptApplicationGraph } from "../../../src/domain/javascript/javascriptApplicationGraph.js";
import { traceApplicationFeature } from "../../../src/domain/javascript/javascriptFeatureTrace.js";
@@ -444,6 +445,73 @@ describe("JavaScript application workflow error diagnostics", () => {
});
describe("JavaScript runtime reconciliation local paths", () => {
it.each([
{
name: "case-sensitive POSIX input root",
root: null,
path: "/applications/Example.app/Contents/Resources/app/renderer.js",
status: "unknown",
},
{
name: "case-sensitive POSIX mapping root",
root: "/runtime/App",
path: "/runtime/app/renderer.js",
status: "unknown",
},
{
name: "matching POSIX mapping root",
root: "/runtime/App",
path: "/runtime/App/renderer.js",
status: "matched",
},
{
name: "case-insensitive Windows mapping root",
root: String.raw`C:\runtime\App`,
path: String.raw`c:\runtime\app\renderer.js`,
status: "matched",
},
])("uses $name on every host", ({ root, path, status }) => {
const base = JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE;
const original = base.runtime_observations[0]!;
const inspection = electronPageInspectionSchema.parse(
original.normalized_result,
);
const runtime = createEvidence(undefined, original.provider, {
predicateType: original.predicate_type,
operation: original.operation,
parameters: { ...original.parameters, include_script_sources: false },
result: {
...inspection,
scripts: {
...inspection.scripts,
items: inspection.scripts.items.map((script) => ({
...script,
file_path: path,
source: { included: false, reason: "not-requested" },
})),
},
},
confidence: original.confidence,
authority: original.authority,
});
const reconciled = reconcileJavaScriptRuntimeEvidence({
static_layers: base.static_layers.map((layer) => ({
...layer,
runtime_mappings: root === null ? [] : [{ kind: "file-root", root }],
})),
runtime_observations: [runtime],
});
if (!reconciled.ok) throw reconciled.error;
const result = javascriptRuntimeReconciliationResultSchema.parse(
reconciled.value.normalized_result,
);
expect(
result.reconciliations.find(
({ entity_kind }) => entity_kind === "script",
),
).toMatchObject({ status });
});
it("resolves relative file mapping roots before deriving result Evidence", () => {
const absoluteRoot = resolve(process.cwd(), "runtime-cache-fixture");
const relativeRoot = relative(process.cwd(), absoluteRoot);
@@ -0,0 +1,155 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect, it, onTestFinished, vi } from "vitest";
import { createEvidence } from "../../../src/domain/evidence.js";
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
import { OwnedFileHandle } from "../../../src/filesystem/OwnedFileHandle.js";
import { createServer } from "../../../src/server/createServer.js";
import {
createDeferred,
createTestBinarySession,
} from "../../fixtures/binarySession.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const connectImportSession = async () => {
const root = await createTestTempDirectory("rea-mcp-import-lifecycle-");
const session = createTestBinarySession(() => {
throw new Error("Evidence import must not start a binary provider");
});
const server = createServer({ kind: "session", session });
const client = new Client({
name: "evidence-import-lifecycle",
version: "1",
});
const readCompleted = createDeferred<void>();
const releaseRead = createDeferred<void>();
const originalFileClose = OwnedFileHandle.prototype.close;
vi.spyOn(OwnedFileHandle.prototype, "close").mockImplementationOnce(
async function (this: OwnedFileHandle) {
await originalFileClose.call(this);
readCompleted.resolve();
await releaseRead.promise;
},
);
const closeStarted = createDeferred<void>();
const originalSessionClose = session.close.bind(session);
const events: string[] = [];
vi.spyOn(session, "close").mockImplementation((...args) => {
const closing = originalSessionClose(...args);
closeStarted.resolve();
return closing.then((result) => {
events.push("close");
return result;
});
});
const originalImport = session.importEvidenceBundle.bind(session);
vi.spyOn(session, "importEvidenceBundle").mockImplementation((bundle) => {
const imported = originalImport(bundle);
events.push("import");
return imported;
});
onTestFinished(async () => {
releaseRead.resolve();
vi.restoreAllMocks();
await client.close();
await server.close();
await session.close();
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
const laterImportDispatched = createDeferred<void>();
let importsDispatched = 0;
const send = clientTransport.send.bind(clientTransport);
vi.spyOn(clientTransport, "send").mockImplementation(
async (message, ...args) => {
await send(message, ...args);
if (
"method" in message &&
message.method === "tools/call" &&
message.params?.name === "import_evidence_bundle"
) {
importsDispatched += 1;
if (importsDispatched === 2) laterImportDispatched.resolve();
}
},
);
await server.connect(serverTransport);
await client.connect(clientTransport);
const importBundle = async (operation: string) => {
const record = createEvidence(
undefined,
{ id: "fixture", name: "Fixture", version: "1" },
{ operation, parameters: {}, result: { retained: operation } },
);
const path = join(root, `${operation}.json`);
await writeFile(path, JSON.stringify(createEvidenceBundle([record])));
return client.callTool({
name: "import_evidence_bundle",
arguments: { path },
});
};
return {
client,
session,
events,
importBundle,
readCompleted: readCompleted.promise,
closeStarted: closeStarted.promise,
laterImportDispatched: laterImportDispatched.promise,
releaseRead: () => releaseRead.resolve(),
};
};
it("drains a file import before close_binary clears the session", async () => {
const fixture = await connectImportSession();
const importing = fixture.importBundle("before_close");
await fixture.readCompleted;
const closing = fixture.client.callTool({
name: "close_binary",
arguments: {},
});
await fixture.closeStarted;
await fixture.client.ping();
fixture.releaseRead();
const [imported, closed] = await Promise.all([importing, closing]);
expect(imported.isError, JSON.stringify(imported)).not.toBe(true);
expect(imported.structuredContent).toMatchObject({
result: { imported: 1, unknowns_added: 0, total: 1 },
});
expect(closed.isError, JSON.stringify(closed)).not.toBe(true);
expect(fixture.events).toEqual(["import", "close"]);
expect(fixture.session.exportEvidenceBundle().records).toEqual([]);
await fixture.client.ping();
});
it("admits a later import after close_binary without retaining the earlier bundle", async () => {
const fixture = await connectImportSession();
const earlier = fixture.importBundle("before_close");
await fixture.readCompleted;
const closing = fixture.client.callTool({
name: "close_binary",
arguments: {},
});
await fixture.closeStarted;
const later = fixture.importBundle("after_close");
await fixture.laterImportDispatched;
await fixture.client.ping();
fixture.releaseRead();
const results = await Promise.all([earlier, closing, later]);
for (const result of results)
expect(result.isError, JSON.stringify(result)).not.toBe(true);
expect(results[2]?.structuredContent).toMatchObject({
result: { imported: 1, unknowns_added: 0, total: 1 },
});
expect(fixture.events).toEqual(["import", "close", "import"]);
expect(
fixture.session
.exportEvidenceBundle()
.records.map((record) => record.operation),
).toEqual(["after_close"]);
await fixture.client.ping();
});
@@ -0,0 +1,173 @@
import { execFile } from "node:child_process";
import { randomUUID } from "node:crypto";
import {
chmod,
copyFile,
readFile,
symlink,
unlink,
writeFile,
} from "node:fs/promises";
import { join } from "node:path";
import { promisify } from "node:util";
import { expect, it } from "vitest";
import { assertCleanLinuxHopperRuntime } from "../../../scripts/lib/clean-linux-hopper-runtime.mjs";
import { completeVerifierRun } from "../../../scripts/lib/verifier-run.mjs";
import { cleanupOwnedProcessGroup } from "../../../src/process/ProcessOwnership.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const execFileAsync = promisify(execFile);
it.runIf(process.platform === "linux")(
"does not treat runtime names in another process's arguments as a runtime",
async () => {
const observer = new URL(
"../../../scripts/lib/clean-linux-hopper-runtime.mjs",
import.meta.url,
).href;
const code = `
const { assertCleanLinuxHopperRuntime } = await import(${JSON.stringify(observer)});
await assertCleanLinuxHopperRuntime([]);
console.log('clean');
`;
const { stdout } = await execFileAsync(
process.execPath,
[
"--input-type=module",
"-e",
code,
"Xvfb",
"/opt/hopper/bin/Hopper",
"hopper-demo-x11.py",
],
{ timeout: 10_000 },
);
expect(stdout.trim()).toBe("clean");
},
);
it.runIf(process.platform === "linux")(
"distinguishes an ordinary Node script with the helper's filename",
async () => {
const directory = await createTestTempDirectory("rea-runtime-arguments-");
const script = join(directory, "hopper-demo-x11.py");
const observer = new URL(
"../../../scripts/lib/clean-linux-hopper-runtime.mjs",
import.meta.url,
).href;
await writeFile(
script,
`
import(${JSON.stringify(observer)}).then(async ({ assertCleanLinuxHopperRuntime }) => {
await assertCleanLinuxHopperRuntime([]);
console.log('clean');
});
`,
);
const { stdout } = await execFileAsync(process.execPath, [script], {
timeout: 10_000,
});
expect(stdout.trim()).toBe("clean");
},
);
it
.runIf(process.platform === "linux")
.each(["demo helper", "alternate launcher"])(
"rejects a reparented %s without signaling it",
async (mode) => {
const runId = randomUUID();
const childCode =
"process.title = 'Xvfb'; setInterval(() => {}, 1000); process.send('ready');";
const directory = await createTestTempDirectory("rea-clean-runtime-test-");
const launcher = join(directory, "Hopper");
const alternate = join(directory, "Hopper-alternate");
const alternateMode = mode === "alternate launcher";
if (alternateMode) {
await copyFile("/usr/bin/sleep", launcher);
await chmod(launcher, 0o700);
await symlink(launcher, alternate);
}
const command = alternateMode ? alternate : process.execPath;
const arguments_ = alternateMode ? ["30"] : ["-e", childCode];
const parentCode = `
const { spawn } = require('node:child_process');
const child = spawn(${JSON.stringify(command)}, ${JSON.stringify(arguments_)}, {
detached: true, stdio: ${JSON.stringify(alternateMode ? "ignore" : ["ignore", "ignore", "ignore", "ipc"])}
});
child.once('error', () => process.exit(1));
child.once(${JSON.stringify(alternateMode ? "spawn" : "message")}, () => {
process.stdout.write(JSON.stringify({ pid: child.pid, parentPid: process.pid }));
if (child.connected) child.disconnect();
child.unref();
});
`;
const parent = execFileAsync(process.execPath, ["-e", parentCode], {
env: { ...process.env, REA_PROCESS_RUN_ID: runId },
timeout: 10_000,
});
const parentPid = parent.child.pid;
if (parentPid === undefined)
throw new Error("Fixture parent did not spawn");
let orphanPid: number | undefined;
try {
const { stdout } = await parent;
const { pid } = JSON.parse(stdout) as { pid: number };
orphanPid = pid;
const { stdout: coordinates } = await execFileAsync("ps", [
"-p",
String(pid),
"-o",
"ppid=,pgid=",
]);
const [currentParent, group] = coordinates
.trim()
.split(/\s+/u)
.map(Number);
expect(currentParent).not.toBe(parentPid);
expect(group).toBe(pid);
const lineage = await completeVerifierRun({
run_id: runId,
verifier_pid: process.pid,
parent_pid: process.ppid,
});
expect(lineage.process_lineage.status).toBe("verified");
if (lineage.process_lineage.status === "verified")
expect(
lineage.process_lineage.descendants.some((p) => p.pid === pid),
).toBe(false);
if (alternateMode) {
const commandLine = await readFile(
`/proc/${String(pid)}/cmdline`,
"utf8",
);
expect(commandLine.split("\0")[0]).toBe(alternate);
await unlink(alternate);
}
await expect(
assertCleanLinuxHopperRuntime(alternateMode ? [launcher] : []),
).rejects.toThrow("Clean Linux runner retained a Hopper demo process");
// Observation must not terminate the fixture, even though it resembles Xvfb.
const { stdout: alive } = await execFileAsync("ps", [
"-p",
String(pid),
"-o",
"stat=",
]);
expect(alive.trim()).not.toMatch(/^Z/u);
} finally {
if (orphanPid !== undefined) {
const cleanup = await cleanupOwnedProcessGroup({
runId,
leaderPid: orphanPid,
processGroupId: orphanPid,
});
expect(cleanup.cleaned, JSON.stringify(cleanup)).toBe(true);
}
}
},
);
@@ -3,10 +3,12 @@ import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { writeOrderedZip } from "../../../fixtures/artifactEntryOrder.js";
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js";
import { artifactExtractionExecutionSchema } from "../../../../src/contracts/artifactToolContracts.js";
import { artifactExtractionResultSchema } from "../../../../src/domain/artifactGraph.js";
import type { BinaryTarget } from "../../../../src/domain/binaryTargetTypes.js";
describe("artifact extraction format support", () => {
@@ -42,6 +44,33 @@ describe("artifact extraction format support", () => {
});
await expect(access(output)).rejects.toThrow();
});
it.each(["zip", "hap", "hsp", "app-pack"] as const)(
"extracts the ZIP-backed %s package family that inventory already supports",
async (format) => {
const root = await createTestTempDirectory("rea-extract-zip-family-");
const archive = join(
root,
`Payload.${format === "app-pack" ? "app" : format}`,
);
await writeOrderedZip(archive, ["payload.txt"]);
const result = await new ArtifactProvider(process.env)
.createClient(archiveTarget(archive, format))
.execute(
"extract_artifact",
artifactExtractionExecutionSchema.parse({
output_root: join(root, "output"),
}),
);
if (!result.ok) throw result.error;
const extracted = artifactExtractionResultSchema.parse(
result.value.result,
);
expect(
extracted.artifacts.map(({ relative_path }) => relative_path),
).toEqual(["payload.txt"]);
},
);
});
const archiveTarget = (
@@ -0,0 +1,108 @@
import { execFile } from "node:child_process";
import { appendFile, copyFile, mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { promisify } from "node:util";
import { describe, expect, it } from "vitest";
import {
HOPPER_PUBLISHER,
macHopperInstallDisclosure,
systemMacHopperInstallHost,
} from "../../../src/application/MacHopper.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
const run = promisify(execFile);
const itDarwin = it.skipIf(process.platform !== "darwin");
const executableSegments = ["Contents", "MacOS", "hopper"];
const infoPlist = (identifier: string): string =>
`<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleIdentifier</key>
<string>${identifier}</string>
<key>CFBundleExecutable</key>
<string>hopper</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
</dict>
</plist>
`;
/** Build a minimal `.app` whose launcher is a real signed Mach-O copy. */
const buildBundle = async (
root: string,
identifier: string,
options: { readonly sign?: boolean } = {},
): Promise<string> => {
const app = join(root, "Hopper Disassembler.app");
const executable = join(app, ...executableSegments);
await mkdir(join(app, "Contents", "MacOS"), { recursive: true });
await copyFile("/usr/bin/true", executable);
await writeFile(join(app, "Contents", "Info.plist"), infoPlist(identifier));
if (options.sign !== false)
await run("/usr/bin/codesign", [
"--sign",
"-",
"--force",
"--deep",
"--identifier",
identifier,
app,
]);
return app;
};
const host = () =>
systemMacHopperInstallHost("/home/rea-test", { ...process.env });
describe("macOS Hopper publisher verification", () => {
itDarwin(
"rejects an ad-hoc signed bundle carrying the pinned bundle identifier",
async () => {
const root = await createTestTempDirectory("rea-hopper-publisher-");
const app = await buildBundle(root, HOPPER_PUBLISHER.bundleIdentifier);
// The pre-pinned checks accept this bundle: `codesign --verify` succeeds
// for ad-hoc signatures and the identifier clause alone also matches.
await run("/usr/bin/codesign", ["--verify", "--deep", "--strict", app]);
await expect(host().validBundle(app)).resolves.toBe(
"unverified_publisher",
);
},
);
itDarwin("rejects an unsigned bundle before any copy", async () => {
const root = await createTestTempDirectory("rea-hopper-unsigned-");
const app = await buildBundle(root, HOPPER_PUBLISHER.bundleIdentifier, {
sign: false,
});
await expect(host().validBundle(app)).resolves.toBe("invalid_signature");
});
itDarwin("rejects a bundle modified after it was signed", async () => {
const root = await createTestTempDirectory("rea-hopper-tampered-");
const app = await buildBundle(root, HOPPER_PUBLISHER.bundleIdentifier);
await appendFile(join(app, ...executableSegments), "appended\n");
await expect(host().validBundle(app)).resolves.toBe("invalid_signature");
});
it("discloses the exact code requirement the installer enforces", () => {
expect(macHopperInstallDisclosure.commands).toContain(
`codesign --verify --strict '-R= identifier "${HOPPER_PUBLISHER.bundleIdentifier}" and anchor apple generic and certificate leaf[subject.OU] = "${HOPPER_PUBLISHER.teamIdentifier}"' <mounted-hopper.app>`,
);
});
// Opt-in positive control: point this at a mounted official Hopper bundle,
// for example `hdiutil attach -readonly -nobrowse Hopper-6.6.0-demo.dmg`.
// It proves the pinned requirement is satisfiable by the real publisher, so
// a quoting or argument mistake cannot hide behind the rejection arms.
const realApp = process.env.REA_HOPPER_MACOS_APP;
it.skipIf(realApp === undefined)(
"accepts the officially signed Hopper application",
async () => {
await expect(host().validBundle(realApp ?? "")).resolves.toBe("verified");
},
);
});
+15 -4
View File
@@ -5,13 +5,24 @@ volatile int rea_c_global = 7;
#define REA_LONG_CHUNK "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
#define REA_LONG_256 REA_LONG_CHUNK REA_LONG_CHUNK REA_LONG_CHUNK REA_LONG_CHUNK
#define REA_LONG_1024 REA_LONG_256 REA_LONG_256 REA_LONG_256 REA_LONG_256
/* Keep the full-size literal even when a loader does not type it as a string. */
__attribute__((used)) const char rea_long_literal[] =
"REA_LONG_LITERAL_" REA_LONG_1024 REA_LONG_1024 REA_LONG_1024 REA_LONG_1024 "needle";
/* Linux Hopper 6.4.2 recognizes this extent and splits it into native objects. */
__attribute__((used)) const char rea_fragmented_literal[] =
"REA_FRAGMENTED_LITERAL_" REA_LONG_256 REA_LONG_256 "fragment_tail";
__attribute__((used)) const char rea_utf8_literal[] = "REA_UTF8_é_😀";
__attribute__((used)) const char rea_ellipsis_literal[] = "REA_LITERAL_…";
__attribute__((used)) const char rea_latin1_literal[] = "REA_LATIN1_\xff";
__attribute__((noinline, used)) void rea_long_literal_procedure(void) {
puts("REA_LONG_LITERAL_" REA_LONG_1024 REA_LONG_1024 REA_LONG_1024 REA_LONG_1024 "needle");
puts("REA_UTF8_é_😀");
puts(rea_long_literal);
puts(rea_fragmented_literal);
puts(rea_utf8_literal);
puts("REA_ESCAPED_\"\\line\nend\t\r");
puts("REA_LITERAL_BACKSLASH_\\n");
puts("REA_LITERAL_…");
puts("REA_LATIN1_\xff");
puts(rea_ellipsis_literal);
puts(rea_latin1_literal);
}
__attribute__((noinline, used)) int rea_leaf(int value) {
@@ -0,0 +1,97 @@
import { expect, it } from "vitest";
import { verifyHopperStringObjects } from "../../../../scripts/lib/real-hopper-search.mjs";
const value = "REA_UTF8_é_😀";
const address = "0x402020";
const bytes = Buffer.from(`${value}\0`);
const item = {
address,
value,
string: {
encoding: "utf-8",
encoding_status: "inferred" as const,
termination: "present_or_not_required" as const,
byte_length: bytes.length,
},
};
const expectation = {
value,
encoding: "utf-8",
symbol: "rea_utf8_literal",
recognitionOptional: true,
};
it("keeps source identity and unknown decoding when the same text exists elsewhere", async () => {
const report = await verifyHopperStringObjects(
fixtureCall(),
[expectation],
[{ ...item, address: "0x403000" }],
);
expect(report.recognition).toEqual([
{ value, address, state: "not_observed", decodedObject: "unverified" },
]);
});
it("reuses source bytes and inventory while checking real address filters and searches", async () => {
const calls: string[] = [];
const report = await verifyHopperStringObjects(
fixtureCall(calls),
[expectation],
[item],
);
expect(report.recognition).toEqual([
{ value, address, state: "observed", decodedObject: "verified" },
]);
expect(calls).toEqual([
"read_bytes:rea_utf8_literal",
`list_strings:${address}`,
`search_strings:${value}`,
"search_strings:\\xC3\\xA9",
]);
});
it.each([
["changed source bytes", { bytes_hex: "00" }, item],
["incomplete source read", { complete: false }, item],
["wrong decoded value", {}, { ...item, value: "wrong" }],
[
"wrong decoded extent",
{},
{ ...item, string: { ...item.string, byte_length: 1 } },
],
])(
"rejects %s even when native recognition is optional",
async (_label, override, decoded) => {
await expect(
verifyHopperStringObjects(
fixtureCall([], override),
[expectation],
[decoded],
),
).rejects.toThrow();
},
);
function fixtureCall(
calls: string[] = [],
override: Record<string, unknown> = {},
) {
return async (name: string, arguments_: Record<string, unknown> = {}) => {
calls.push(
`${name}:${String(arguments_.address ?? arguments_.pattern ?? "")}`,
);
if (name === "read_bytes")
return {
address,
bytes_hex: bytes.toString("hex"),
complete: true,
...override,
};
if (name === "list_strings" && arguments_.address === address)
return [item];
if (name === "search_strings")
return arguments_.pattern === value ? [item] : [];
throw new Error(`Unmodeled verifier call: ${name}`);
};
}
+36
View File
@@ -4,6 +4,7 @@
#include <winioctl.h>
#include <cstdio>
#include <cstring>
#include <cwchar>
#include <string>
#include <vector>
@@ -33,6 +34,41 @@ int wmain(int count, wchar_t** args) {
value(L"REA_\u00df") == expectedSharp && value(L"REA_SS") == L"double" ? "true" : "false");
return 0;
}
if ((count == 2 || count == 3) && std::wstring(args[1]) == L"affinity") {
// Without a process id this observes itself, which is what an owned child
// reports. With one it observes that process, so a caller's own affinity is
// read from the process that spawns the child rather than from a separate
// probe Windows may place in another processor group.
HANDLE opened = nullptr;
if (count == 3) {
opened = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE,
static_cast<DWORD>(std::wcstoul(args[2], nullptr, 10)));
if (!opened) return 9;
}
const HANDLE target = opened ? opened : GetCurrentProcess();
DWORD_PTR affinity = 0, systemAffinity = 0;
USHORT groupCount = 1;
USHORT groups[1]{};
const bool read = GetProcessAffinityMask(target, &affinity, &systemAffinity) != 0;
const bool single = read && GetProcessGroupAffinity(target, &groupCount, groups) && groupCount == 1;
if (opened) CloseHandle(opened);
if (!read) return 8;
// A mask can set bits above JavaScript's safe-integer range, so masks cross
// as fixed-width hexadecimal strings and are compared without rounding. The
// group's own active set distinguishes an unconstrained process from one
// deliberately pinned to fewer processors.
auto mask = [](DWORD_PTR value, char* text) {
std::snprintf(text, 19, "0x%08lX%08lX", static_cast<unsigned long>(value >> 32),
static_cast<unsigned long>(value & 0xFFFFFFFFu));
return text;
};
char affinityText[19]{}, systemText[19]{};
std::printf("{\"affinityMask\":\"%s\",\"systemMask\":\"%s\","
"\"singleProcessorGroup\":%s,\"processorGroup\":%u}\n",
mask(affinity, affinityText), mask(systemAffinity, systemText),
single ? "true" : "false", single ? static_cast<unsigned>(groups[0]) : 0u);
return 0;
}
if (count == 4 && std::wstring(args[1]) == L"reparse-directory") {
// Only the conformance lane's disposable, nonempty source directory is used.
const auto substitute = L"\\??\\" + std::wstring(args[3]);