Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
34661d816c | ||
|
|
e74e4e951b | ||
|
|
68ecf3df8c | ||
|
|
ab62ee9dcf | ||
|
|
2c6a4fac4f | ||
|
|
c6acd19b6d | ||
|
|
1a1b67c888 | ||
|
|
12303812a8 | ||
|
|
f6556ad2bc | ||
|
|
d73ed6fce2 | ||
|
|
60f771a11e | ||
|
|
650237efb0 | ||
|
|
7017c4d68c | ||
|
|
141d2095f5 | ||
|
|
18831491cf |
@@ -72,3 +72,5 @@ Thumbs.db
|
|||||||
|
|
||||||
# Complete static website output, including generated language editions.
|
# Complete static website output, including generated language editions.
|
||||||
website/_site/
|
website/_site/
|
||||||
|
# Temporary translation output prepared before replacing the complete site.
|
||||||
|
website/.i18n-*/
|
||||||
|
|||||||
@@ -93,7 +93,7 @@ def project_record(state, secrets):
|
|||||||
safe_bytes, credential_url = transport_value(value, path, transport_url)
|
safe_bytes, credential_url = transport_value(value, path, transport_url)
|
||||||
content_base64 = base64.b64encode(value).decode("ascii")
|
content_base64 = base64.b64encode(value).decode("ascii")
|
||||||
digest = hashlib.sha256(value).hexdigest()
|
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
|
safe_text = None
|
||||||
try:
|
try:
|
||||||
safe_text = safe_bytes.decode("utf-8", errors="strict")
|
safe_text = safe_bytes.decode("utf-8", errors="strict")
|
||||||
|
|||||||
@@ -174,7 +174,7 @@ Resolution follows dyld:
|
|||||||
- `@rpath` tries each `LC_RPATH` of the loading image first, then those of the
|
- `@rpath` tries each `LC_RPATH` of the loading image first, then those of the
|
||||||
image that loaded it, up to the process root.
|
image that loaded it, up to the process root.
|
||||||
- Dependencies load dependents-first in load-command order, and each image
|
- 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.
|
already loaded image reuses it.
|
||||||
- Symlinks such as `Versions/Current` are followed inside the analyzed root.
|
- Symlinks such as `Versions/Current` are followed inside the analyzed root.
|
||||||
An escape through `..` or an absolute link is `escapes-target`.
|
An escape through `..` or an absolute link is `escapes-target`.
|
||||||
|
|||||||
@@ -298,13 +298,42 @@ subsequent wire recovery and clean shutdown. Caller timeout does not interrupt
|
|||||||
Hopper's synchronous native operation. Socket boundary tests deterministically
|
Hopper's synchronous native operation. Socket boundary tests deterministically
|
||||||
cover active and queued expiry, late replies and timer cleanup.
|
cover active and queued expiry, late replies and timer cleanup.
|
||||||
|
|
||||||
The Linux demo lane remains a separate `verify:hopper:linux` command. Its
|
The Linux demo lane remains a separate `verify:hopper:linux` command. Hopper
|
||||||
lifecycle checks attempt competing CLI launches for the active target and a
|
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
|
different target, requiring rejection before either can change the owning
|
||||||
MCP session's documents or procedures. Lease boundary tests also preserve
|
MCP session's documents or procedures. Lease boundary tests also preserve
|
||||||
unresponsive or malformed live endpoints while allowing confirmed stale
|
unresponsive or malformed live endpoints while allowing confirmed stale
|
||||||
sockets to recover.
|
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
|
`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
|
existing Xcode clang/lipo toolchain. It compiles arm64/x86-64 thin executables and
|
||||||
one- and two-slice FAT32 containers, verifies exact/interior address mappings
|
one- and two-slice FAT32 containers, verifies exact/interior address mappings
|
||||||
|
|||||||
@@ -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.
|
Process creation assigns a suspended child atomically to an owned Job Object.
|
||||||
Membership and kill-on-owner-close policy are verified before resume.
|
Membership and kill-on-owner-close policy are verified before resume.
|
||||||
Breakaway is disabled. Only the child's default file owner is normalized;
|
Breakaway is disabled. Only the child's default file owner is normalized;
|
||||||
the caller token stays unchanged. Caller CPU affinity and priority are
|
the caller token stays unchanged. Caller priority is preserved, and caller CPU
|
||||||
preserved. Close, cancellation, timeout, startup failure, and provider failure
|
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.
|
terminate the job and verify all members have settled before runtime cleanup.
|
||||||
Cleanup removes admitted objects by handle and unlinks reparse entries without
|
Cleanup removes admitted objects by handle and unlinks reparse entries without
|
||||||
following their targets. Abrupt owner death kills the job but can leave
|
following their targets. Abrupt owner death kills the job but can leave
|
||||||
|
|||||||
@@ -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
|
limits only for its JavaScript helpers when running on Bun, which ignores
|
||||||
their V8 heap flags; Node.js launches are unchanged.
|
their V8 heap flags; Node.js launches are unchanged.
|
||||||
- Only the suspended child's default file owner is normalized. Caller token
|
- Only the suspended child's default file owner is normalized. Caller token
|
||||||
privileges and ownership remain unchanged. Caller CPU affinity and process
|
privileges and ownership remain unchanged. Caller process priority is
|
||||||
priority are preserved in the child. Environment names are sorted and
|
preserved in the child, and caller CPU affinity whenever both occupy the same
|
||||||
deduplicated using Windows ordinal comparison, preserving their native Unicode
|
processor group. Windows chooses a new process's group itself and rejects a
|
||||||
semantics and caller-selected values.
|
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
|
- Cleanup walks locked directory objects, removes files by handle, and unlinks
|
||||||
reparse entries without traversing their targets. Failed removal retains the
|
reparse entries without traversing their targets. Failed removal retains the
|
||||||
root and ancestor leases for retry; a partially removed runtime accepts only
|
root and ancestor leases for retry; a partially removed runtime accepts only
|
||||||
|
|||||||
@@ -68,6 +68,18 @@ static ULONGLONG jobMemoryLimit(napi_env env, napi_value value) {
|
|||||||
return limit;
|
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) {
|
static void pipe(Handle& read, Handle& write, bool parentReads = true) {
|
||||||
SECURITY_ATTRIBUTES attributes{sizeof(SECURITY_ATTRIBUTES), nullptr, TRUE};
|
SECURITY_ATTRIBUTES attributes{sizeof(SECURITY_ATTRIBUTES), nullptr, TRUE};
|
||||||
HANDLE rawRead, rawWrite;
|
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};
|
TOKEN_OWNER owner{reinterpret_cast<TOKEN_USER*>(tokenUser.data())->User.Sid};
|
||||||
require(SetTokenInformation(token.get(), TokenOwner, &owner, sizeof(owner)),
|
require(SetTokenInformation(token.get(), TokenOwner, &owner, sizeof(owner)),
|
||||||
"Set suspended process file owner failed", command);
|
"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;
|
DWORD_PTR affinity = 0, systemAffinity = 0;
|
||||||
require(GetProcessAffinityMask(GetCurrentProcess(), &affinity, &systemAffinity),
|
require(GetProcessAffinityMask(GetCurrentProcess(), &affinity, &systemAffinity),
|
||||||
"Read caller process affinity failed", command);
|
"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);
|
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());
|
const DWORD priority = GetPriorityClass(GetCurrentProcess());
|
||||||
require(priority != 0 && SetPriorityClass(result->process.get(), priority),
|
require(priority != 0 && SetPriorityClass(result->process.get(), priority),
|
||||||
"Preserve caller process priority failed", command);
|
"Preserve caller process priority failed", command);
|
||||||
|
|||||||
+1
-1
@@ -207,7 +207,7 @@
|
|||||||
"fixtures:harmony": "node scripts/fixtures/harmony/fetch.mjs",
|
"fixtures:harmony": "node scripts/fixtures/harmony/fetch.mjs",
|
||||||
"verify:agent": "npm run build:cached && node scripts/verify-agent-experience.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: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:fixtures": "node scripts/build-conformance-fixtures.mjs",
|
||||||
"build:ghidra-windows-fixture": "node scripts/create-ghidra-windows-fixture.mjs",
|
"build:ghidra-windows-fixture": "node scripts/create-ghidra-windows-fixture.mjs",
|
||||||
"verify:fixtures": "npm run build:fixtures && node scripts/verify-conformance-fixtures.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
|
assert "ows-secret" not in json.dumps(projected), projected
|
||||||
if isinstance(value, bytes):
|
if isinstance(value, bytes):
|
||||||
assert projected["binary_fields"][-1]["state"] == "redacted", projected
|
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}))
|
(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 = 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"
|
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;
|
||||||
|
};
|
||||||
@@ -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;
|
||||||
|
}>;
|
||||||
@@ -1,13 +1,16 @@
|
|||||||
import assert from "node:assert/strict";
|
import assert from "node:assert/strict";
|
||||||
import { mcpTextValue } from "./mcp-verifier-results.mjs";
|
import { mcpTextValue } from "./mcp-verifier-results.mjs";
|
||||||
|
|
||||||
|
const fixtureSymbolPrefix = process.platform === "darwin" ? "_" : "";
|
||||||
|
|
||||||
/** Exercise literal/regex search, Unicode identities and cache invalidation in Hopper. */
|
/** Exercise literal/regex search, Unicode identities and cache invalidation in Hopper. */
|
||||||
export async function verifyHopperSearch(call, invalid, procedure) {
|
export async function verifyHopperSearch(call, invalid, procedure) {
|
||||||
const address = procedure.address;
|
const address = procedure.address;
|
||||||
const original = await call("address_name", { address });
|
const original = await call("address_name", { address });
|
||||||
|
let stringCoverage;
|
||||||
try {
|
try {
|
||||||
await verifySymbolNames(call, invalid, address);
|
await verifySymbolNames(call, invalid, address);
|
||||||
await verifySearchModes(call, address);
|
stringCoverage = await verifySearchModes(call, address);
|
||||||
} finally {
|
} finally {
|
||||||
await call("set_address_name", { address, name: original });
|
await call("set_address_name", { address, name: original });
|
||||||
}
|
}
|
||||||
@@ -26,7 +29,7 @@ export async function verifyHopperSearch(call, invalid, procedure) {
|
|||||||
symbolUtf16LimitValidatedBeforeMutation: true,
|
symbolUtf16LimitValidatedBeforeMutation: true,
|
||||||
regexAndCaseModes: true,
|
regexAndCaseModes: true,
|
||||||
annotationCacheInvalidation: true,
|
annotationCacheInvalidation: true,
|
||||||
escapedUtf8AndByteStrings: true,
|
stringCoverage,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -103,11 +106,26 @@ async function verifySearchModes(call, address) {
|
|||||||
[{ address, value: "REA_Search_Upper" }],
|
[{ address, value: "REA_Search_Upper" }],
|
||||||
);
|
);
|
||||||
const strings = await call("list_strings");
|
const strings = await call("list_strings");
|
||||||
const long = "REA_LONG_LITERAL_" + "x".repeat(4096) + "needle";
|
const linux = process.platform === "linux";
|
||||||
const longItem = strings.find((item) =>
|
const fullLiteral = "REA_LONG_LITERAL_" + "x".repeat(4096) + "needle";
|
||||||
item.value.startsWith("REA_LONG_LITERAL_"),
|
// 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");
|
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(long.startsWith(longItem.value));
|
||||||
assert.ok(longItem.provider_value.endsWith("…"));
|
assert.ok(longItem.provider_value.endsWith("…"));
|
||||||
assert.equal(longItem.string.termination, "missing");
|
assert.equal(longItem.string.termination, "missing");
|
||||||
@@ -158,7 +176,7 @@ async function verifySearchModes(call, address) {
|
|||||||
}
|
}
|
||||||
assert.deepEqual(
|
assert.deepEqual(
|
||||||
await call("search_strings", {
|
await call("search_strings", {
|
||||||
pattern: "needle",
|
pattern: linux ? "fragment_tail" : "needle",
|
||||||
mode: "literal",
|
mode: "literal",
|
||||||
case_sensitive: true,
|
case_sensitive: true,
|
||||||
}),
|
}),
|
||||||
@@ -176,36 +194,122 @@ async function verifySearchModes(call, address) {
|
|||||||
}),
|
}),
|
||||||
expected,
|
expected,
|
||||||
);
|
);
|
||||||
await verifyHopperStringObjects(call, [
|
const objects = await verifyHopperStringObjects(
|
||||||
{ value: "REA_UTF8_é_😀", encoding: "utf-8" },
|
call,
|
||||||
{ 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_UTF8_é_😀",
|
||||||
{ value: "REA_LATIN1_ÿ", encoding: "latin-1" },
|
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. */
|
/** Compare native string identities and values with the source fixture's bytes. */
|
||||||
export async function verifyHopperStringObjects(call, expectations) {
|
export async function verifyHopperStringObjects(
|
||||||
const strings = await call("list_strings");
|
call,
|
||||||
for (const { value, encoding } of expectations) {
|
expectations,
|
||||||
const item = strings.find((candidate) => candidate.value === value);
|
inventory = null,
|
||||||
assert.ok(
|
) {
|
||||||
item,
|
// Reuse only the caller's inventory for this unchanged document, never live
|
||||||
`Hopper omitted the decoded string ${JSON.stringify(value)}`,
|
// state from an earlier session. Address-filter and search checks remain real.
|
||||||
);
|
const strings = inventory ?? (await call("list_strings"));
|
||||||
assert.equal(item.string.encoding, encoding);
|
const recognition = [];
|
||||||
assert.equal(item.string.encoding_status, "inferred");
|
for (const {
|
||||||
assert.equal(item.string.termination, "present_or_not_required");
|
value,
|
||||||
|
encoding,
|
||||||
|
symbol,
|
||||||
|
recognitionOptional = false,
|
||||||
|
} of expectations) {
|
||||||
const expectedBytes = Buffer.from(
|
const expectedBytes = Buffer.from(
|
||||||
value + "\0",
|
value + "\0",
|
||||||
encoding.replaceAll("-", ""),
|
encoding.replaceAll("-", ""),
|
||||||
);
|
);
|
||||||
assert.equal(item.string.byte_length, expectedBytes.length);
|
let sourceBytes;
|
||||||
const bytes = await call("read_bytes", {
|
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,
|
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.equal(bytes.bytes_hex, expectedBytes.toString("hex"));
|
||||||
assert.deepEqual(await call("list_strings", { address: item.address }), [
|
assert.deepEqual(await call("list_strings", { address: item.address }), [
|
||||||
item,
|
item,
|
||||||
@@ -225,7 +329,7 @@ export async function verifyHopperStringObjects(call, expectations) {
|
|||||||
);
|
);
|
||||||
return {
|
return {
|
||||||
sourceBytesVerified: true,
|
sourceBytesVerified: true,
|
||||||
inferredEncodingReported: true,
|
recognition,
|
||||||
displayEscapesExcludedFromMatching: true,
|
displayEscapesExcludedFromMatching: true,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import { tmpdir } from "node:os";
|
|||||||
import { promisify } from "node:util";
|
import { promisify } from "node:util";
|
||||||
|
|
||||||
import { completeVerifierRun, createVerifierRun } from "./lib/verifier-run.mjs";
|
import { completeVerifierRun, createVerifierRun } from "./lib/verifier-run.mjs";
|
||||||
|
import { assertCleanLinuxHopperRuntime } from "./lib/clean-linux-hopper-runtime.mjs";
|
||||||
|
|
||||||
const execFileAsync = promisify(execFile);
|
const execFileAsync = promisify(execFile);
|
||||||
const verifierRun = createVerifierRun();
|
const verifierRun = createVerifierRun();
|
||||||
@@ -19,12 +20,12 @@ const command = process.env.REA_VERIFY_SERVER_COMMAND;
|
|||||||
if (process.platform !== "linux" || process.getuid?.() !== 0)
|
if (process.platform !== "linux" || process.getuid?.() !== 0)
|
||||||
throw new Error("Linux setup verification requires a root Linux runner");
|
throw new Error("Linux setup verification requires a root Linux runner");
|
||||||
if (!command) throw new Error("REA_VERIFY_SERVER_COMMAND is required");
|
if (!command) throw new Error("REA_VERIFY_SERVER_COMMAND is required");
|
||||||
|
await assertCleanLinuxHopperRuntime();
|
||||||
try {
|
try {
|
||||||
await access("/opt/hopper/bin/Hopper");
|
await access("/opt/hopper/bin/Hopper");
|
||||||
throw new Error("Linux setup verification requires a clean runner");
|
throw new Error("Linux setup verification requires a clean runner");
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error instanceof Error && error.message.includes("clean runner"))
|
if (error?.code !== "ENOENT") throw error;
|
||||||
throw error;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const runJson = async (args) => {
|
const runJson = async (args) => {
|
||||||
@@ -35,14 +36,25 @@ const runJson = async (args) => {
|
|||||||
return JSON.parse(stdout);
|
return JSON.parse(stdout);
|
||||||
};
|
};
|
||||||
|
|
||||||
const plan = await runJson(["setup", "--json"]);
|
const plan = await runJson([
|
||||||
if (plan.status !== "needs_confirmation")
|
"setup",
|
||||||
throw new Error("setup did not produce a read-only confirmation plan");
|
"--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(
|
await access("/opt/hopper/bin/Hopper").then(
|
||||||
() => {
|
() => {
|
||||||
throw new Error("setup plan mutated the clean runner");
|
throw new Error("setup plan mutated the clean runner");
|
||||||
},
|
},
|
||||||
() => undefined,
|
(error) => {
|
||||||
|
if (error?.code !== "ENOENT") throw error;
|
||||||
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
const installed = await runJson([
|
const installed = await runJson([
|
||||||
@@ -58,7 +70,7 @@ if (
|
|||||||
throw new Error(
|
throw new Error(
|
||||||
`approved setup did not become ready: ${JSON.stringify(installed)}`,
|
`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)
|
if (doctor.healthy !== true)
|
||||||
throw new Error(`doctor is unhealthy: ${JSON.stringify(doctor)}`);
|
throw new Error(`doctor is unhealthy: ${JSON.stringify(doctor)}`);
|
||||||
|
|
||||||
@@ -67,8 +79,6 @@ await execFileAsync(command, ["analyze", "/usr/bin/true"], {
|
|||||||
timeout: 180_000,
|
timeout: 180_000,
|
||||||
maxBuffer: 10 * 1024 * 1024,
|
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"]';
|
process.env.REA_VERIFY_SERVER_ARGS_JSON = '["mcp"]';
|
||||||
await import("./verify-real-hopper-linux.mjs");
|
await import("./verify-real-hopper-linux.mjs");
|
||||||
|
|
||||||
@@ -95,28 +105,24 @@ try {
|
|||||||
await rm(modifiedDirectory, { recursive: true, force: true });
|
await rm(modifiedDirectory, { recursive: true, force: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
const repeated = await runJson([
|
const repeated = await runJson(["setup", "--yes", "--json"]);
|
||||||
"setup",
|
|
||||||
"--yes",
|
|
||||||
"--install-hopper",
|
|
||||||
"--json",
|
|
||||||
]);
|
|
||||||
if (
|
if (
|
||||||
repeated.status !== "ready" ||
|
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");
|
throw new Error("a second setup was not idempotent");
|
||||||
const { stdout: processes } = await execFileAsync("ps", [
|
await assertCleanLinuxHopperRuntime();
|
||||||
"-ax",
|
const completedVerifierRun = await completeVerifierRun(verifierRun);
|
||||||
"-o",
|
if (
|
||||||
"command=",
|
completedVerifierRun.process_lineage.status !== "verified" ||
|
||||||
]);
|
completedVerifierRun.process_lineage.descendants.length !== 0
|
||||||
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");
|
throw new Error("Linux setup verification did not prove owned child cleanup");
|
||||||
|
|
||||||
console.log(
|
console.log(
|
||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
verifier_run: await completeVerifierRun(verifierRun),
|
verifier_run: completedVerifierRun,
|
||||||
status: "verified",
|
status: "verified",
|
||||||
setup: true,
|
setup: true,
|
||||||
cli: true,
|
cli: true,
|
||||||
|
|||||||
@@ -11,7 +11,8 @@ createVerifierRun();
|
|||||||
|
|
||||||
if (process.platform !== "linux")
|
if (process.platform !== "linux")
|
||||||
throw new Error("Linux real-Hopper verification must run on 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(launcher);
|
||||||
await access("/usr/bin/Xvfb");
|
await access("/usr/bin/Xvfb");
|
||||||
await access("/usr/bin/xauth");
|
await access("/usr/bin/xauth");
|
||||||
@@ -28,5 +29,7 @@ try {
|
|||||||
process.env.HOPPER_LAUNCHER_PATH = alternateLauncher;
|
process.env.HOPPER_LAUNCHER_PATH = alternateLauncher;
|
||||||
await import("./verify-real-hopper.mjs");
|
await import("./verify-real-hopper.mjs");
|
||||||
} finally {
|
} finally {
|
||||||
|
if (configuredLauncher === undefined) delete process.env.HOPPER_LAUNCHER_PATH;
|
||||||
|
else process.env.HOPPER_LAUNCHER_PATH = configuredLauncher;
|
||||||
await rm(alternateDirectory, { recursive: true, force: true });
|
await rm(alternateDirectory, { recursive: true, force: true });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -662,6 +662,42 @@ setInterval(()=>{},1000);\n`,
|
|||||||
unicodeNamesPreserved: true,
|
unicodeNamesPreserved: true,
|
||||||
});
|
});
|
||||||
report.processes.windowsEnvironmentSemantics = 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 ownerFixture = join(workspace, "owner.mjs");
|
||||||
const ownerPidFile = join(workspace, "crash-child.pid");
|
const ownerPidFile = join(workspace, "crash-child.pid");
|
||||||
|
|||||||
@@ -2,12 +2,16 @@ import { createHash } from "node:crypto";
|
|||||||
|
|
||||||
import { describe, expect, it } from "vitest";
|
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 {
|
class FakeMacHopperHost implements MacHopperInstallHost {
|
||||||
readonly archive = new TextEncoder().encode("hopper-dmg");
|
readonly archive = new TextEncoder().encode("hopper-dmg");
|
||||||
archiveOk = true;
|
archiveOk = true;
|
||||||
valid = true;
|
verification: MacHopperBundleVerification = "verified";
|
||||||
existing = false;
|
existing = false;
|
||||||
mountSucceeds = true;
|
mountSucceeds = true;
|
||||||
copySucceeds = true;
|
copySucceeds = true;
|
||||||
@@ -15,6 +19,7 @@ class FakeMacHopperHost implements MacHopperInstallHost {
|
|||||||
badHash = false;
|
badHash = false;
|
||||||
unmounts = 0;
|
unmounts = 0;
|
||||||
cleanups = 0;
|
cleanups = 0;
|
||||||
|
installs = 0;
|
||||||
opens = 0;
|
opens = 0;
|
||||||
replaces = false;
|
replaces = false;
|
||||||
|
|
||||||
@@ -47,7 +52,7 @@ class FakeMacHopperHost implements MacHopperInstallHost {
|
|||||||
return Promise.resolve();
|
return Promise.resolve();
|
||||||
};
|
};
|
||||||
appBundle = () => Promise.resolve("/mounted/Hopper Disassembler.app");
|
appBundle = () => Promise.resolve("/mounted/Hopper Disassembler.app");
|
||||||
validBundle = () => Promise.resolve(this.valid);
|
validBundle = () => Promise.resolve(this.verification);
|
||||||
destinationExists = () => Promise.resolve(this.existing);
|
destinationExists = () => Promise.resolve(this.existing);
|
||||||
installBundle = (
|
installBundle = (
|
||||||
_source: string,
|
_source: string,
|
||||||
@@ -55,6 +60,7 @@ class FakeMacHopperHost implements MacHopperInstallHost {
|
|||||||
_stage: string,
|
_stage: string,
|
||||||
replaceExisting: boolean,
|
replaceExisting: boolean,
|
||||||
) => {
|
) => {
|
||||||
|
this.installs += 1;
|
||||||
this.replaces = replaceExisting;
|
this.replaces = replaceExisting;
|
||||||
return Promise.resolve(this.copySucceeds);
|
return Promise.resolve(this.copySucceeds);
|
||||||
};
|
};
|
||||||
@@ -115,7 +121,7 @@ describe("macOS Hopper installation", () => {
|
|||||||
|
|
||||||
it("cleans and detaches after bundle validation fails", async () => {
|
it("cleans and detaches after bundle validation fails", async () => {
|
||||||
const host = new FakeMacHopperHost();
|
const host = new FakeMacHopperHost();
|
||||||
host.valid = false;
|
host.verification = "invalid_signature";
|
||||||
await expect(installMacHopper({}, host)).resolves.toEqual({
|
await expect(installMacHopper({}, host)).resolves.toEqual({
|
||||||
status: "failed",
|
status: "failed",
|
||||||
reason: "bundle",
|
reason: "bundle",
|
||||||
@@ -123,4 +129,17 @@ describe("macOS Hopper installation", () => {
|
|||||||
expect(host.unmounts).toBe(1);
|
expect(host.unmounts).toBe(1);
|
||||||
expect(host.cleanups).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);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -24,7 +24,35 @@ const execFileAsync = promisify(execFile);
|
|||||||
const RELEASES_URL =
|
const RELEASES_URL =
|
||||||
"https://www.hopperapp.com/include/files-api.php?request=releases&public=true";
|
"https://www.hopperapp.com/include/files-api.php?request=releases&public=true";
|
||||||
const DOWNLOAD_PREFIX = "https://www.hopperapp.com:443/downloader/public/";
|
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. */
|
/** Stable network and command effects disclosed before macOS Hopper setup. */
|
||||||
export const macHopperInstallDisclosure = {
|
export const macHopperInstallDisclosure = {
|
||||||
@@ -32,6 +60,7 @@ export const macHopperInstallDisclosure = {
|
|||||||
commands: [
|
commands: [
|
||||||
"hdiutil attach -readonly -nobrowse -mountpoint <private-mount> <verified-hopper.dmg>",
|
"hdiutil attach -readonly -nobrowse -mountpoint <private-mount> <verified-hopper.dmg>",
|
||||||
"codesign --verify --deep --strict <mounted-hopper.app>",
|
"codesign --verify --deep --strict <mounted-hopper.app>",
|
||||||
|
`codesign --verify --strict '-R${HOPPER_PUBLISHER_REQUIREMENT}' <mounted-hopper.app>`,
|
||||||
"ditto <mounted-hopper.app> <user-Applications-stage>",
|
"ditto <mounted-hopper.app> <user-Applications-stage>",
|
||||||
"open <installed-hopper.app>",
|
"open <installed-hopper.app>",
|
||||||
] as const,
|
] as const,
|
||||||
@@ -52,6 +81,7 @@ export type MacHopperInstallResult =
|
|||||||
| "integrity"
|
| "integrity"
|
||||||
| "mount"
|
| "mount"
|
||||||
| "bundle"
|
| "bundle"
|
||||||
|
| "publisher_verification_failed"
|
||||||
| "destination_exists"
|
| "destination_exists"
|
||||||
| "copy"
|
| "copy"
|
||||||
| "launcher_missing";
|
| "launcher_missing";
|
||||||
@@ -69,7 +99,7 @@ export interface MacHopperInstallHost {
|
|||||||
mount(packagePath: string, mountPath: string): Promise<boolean>;
|
mount(packagePath: string, mountPath: string): Promise<boolean>;
|
||||||
unmount(mountPath: string): Promise<void>;
|
unmount(mountPath: string): Promise<void>;
|
||||||
appBundle(mountPath: string): Promise<string | undefined>;
|
appBundle(mountPath: string): Promise<string | undefined>;
|
||||||
validBundle(appPath: string): Promise<boolean>;
|
validBundle(appPath: string): Promise<MacHopperBundleVerification>;
|
||||||
destinationExists(path: string): Promise<boolean>;
|
destinationExists(path: string): Promise<boolean>;
|
||||||
installBundle(
|
installBundle(
|
||||||
source: string,
|
source: string,
|
||||||
@@ -124,8 +154,12 @@ export const installMacHopper = async (
|
|||||||
return { status: "failed", reason: "mount" };
|
return { status: "failed", reason: "mount" };
|
||||||
mounted = true;
|
mounted = true;
|
||||||
const source = await host.appBundle(mountPath);
|
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" };
|
return { status: "failed", reason: "bundle" };
|
||||||
|
if (verification === "unverified_publisher")
|
||||||
|
return { status: "failed", reason: "publisher_verification_failed" };
|
||||||
const stage = `${destination}.rea-stage`;
|
const stage = `${destination}.rea-stage`;
|
||||||
if (
|
if (
|
||||||
!(await host.installBundle(
|
!(await host.installBundle(
|
||||||
@@ -222,25 +256,21 @@ export const systemMacHopperInstallHost = (
|
|||||||
environment,
|
environment,
|
||||||
))
|
))
|
||||||
)
|
)
|
||||||
return false;
|
return "invalid_signature";
|
||||||
try {
|
if (
|
||||||
const identifier = (
|
!(await commandSucceeds(
|
||||||
await execFileAsync(
|
"codesign",
|
||||||
"/usr/libexec/PlistBuddy",
|
[
|
||||||
[
|
"--verify",
|
||||||
"-c",
|
"--strict",
|
||||||
"Print :CFBundleIdentifier",
|
`-R${HOPPER_PUBLISHER_REQUIREMENT}`,
|
||||||
join(appPath, "Contents/Info.plist"),
|
appPath,
|
||||||
],
|
],
|
||||||
{ env: environment },
|
environment,
|
||||||
)
|
))
|
||||||
).stdout.trim();
|
)
|
||||||
return identifier === BUNDLE_IDENTIFIER;
|
return "unverified_publisher";
|
||||||
} catch (cause: unknown) {
|
return "verified";
|
||||||
// best-effort cleanup: optional bundle probing; unreadable means invalid.
|
|
||||||
void cause;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
async destinationExists(path) {
|
async destinationExists(path) {
|
||||||
try {
|
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.",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { HOPPER_PUBLISHER } from "./MacHopper.js";
|
||||||
|
|
||||||
export type SetupFailureCode =
|
export type SetupFailureCode =
|
||||||
| "unsupported_host"
|
| "unsupported_host"
|
||||||
| "download_failed"
|
| "download_failed"
|
||||||
@@ -10,6 +12,7 @@ export type SetupFailureCode =
|
|||||||
| "destination_exists"
|
| "destination_exists"
|
||||||
| "mount_failed"
|
| "mount_failed"
|
||||||
| "bundle_invalid"
|
| "bundle_invalid"
|
||||||
|
| "publisher_verification_failed"
|
||||||
| "copy_failed"
|
| "copy_failed"
|
||||||
| "skill_install_failed"
|
| "skill_install_failed"
|
||||||
| "cleanup_failed";
|
| "cleanup_failed";
|
||||||
@@ -39,6 +42,7 @@ export type HopperInstallFailureReason =
|
|||||||
| "destination_exists"
|
| "destination_exists"
|
||||||
| "mount"
|
| "mount"
|
||||||
| "bundle"
|
| "bundle"
|
||||||
|
| "publisher_verification_failed"
|
||||||
| "copy";
|
| "copy";
|
||||||
|
|
||||||
/** Map provider installer failures to stable setup codes and safe recovery. */
|
/** Map provider installer failures to stable setup codes and safe recovery. */
|
||||||
@@ -115,6 +119,12 @@ export const setupInstallFailure = (
|
|||||||
remediation:
|
remediation:
|
||||||
"The mounted package did not contain the expected Hopper application bundle. Retry setup; if it repeats, update REA before installing.",
|
"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":
|
case "copy":
|
||||||
return {
|
return {
|
||||||
status: "failed",
|
status: "failed",
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ import { DirectoryArtifactReader } from "../DirectoryArtifactReader.js";
|
|||||||
import { SafeOutputTree } from "../SafeOutputTree.js";
|
import { SafeOutputTree } from "../SafeOutputTree.js";
|
||||||
import { SafeOutputTreeCreationFailure } from "../SafeOutputTreeCreationFailure.js";
|
import { SafeOutputTreeCreationFailure } from "../SafeOutputTreeCreationFailure.js";
|
||||||
import { ZipArtifactReader } from "../ZipArtifactReader.js";
|
import { ZipArtifactReader } from "../ZipArtifactReader.js";
|
||||||
|
import { isZipPackageFormat } from "../../domain/zipPackageFormat.js";
|
||||||
import { MachOSliceArtifactReader } from "../MachOSliceArtifactReader.js";
|
import { MachOSliceArtifactReader } from "../MachOSliceArtifactReader.js";
|
||||||
import {
|
import {
|
||||||
artifactExtractionResultSchema,
|
artifactExtractionResultSchema,
|
||||||
@@ -400,13 +401,6 @@ interface ExtractionInventory {
|
|||||||
readonly integrityContradictions: readonly IntegrityContradiction[];
|
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.
|
* Refuse a format without an extraction reader before inventory work starts.
|
||||||
* The target kind, not the host, is unsupported by extraction. The error keeps
|
* The target kind, not the host, is unsupported by extraction. The error keeps
|
||||||
@@ -422,7 +416,7 @@ const requireExtractableFormat = async (
|
|||||||
!directory &&
|
!directory &&
|
||||||
format !== "asar" &&
|
format !== "asar" &&
|
||||||
!isMachOFormat(format) &&
|
!isMachOFormat(format) &&
|
||||||
!isZipFormat(format)
|
!isZipPackageFormat(format)
|
||||||
)
|
)
|
||||||
throw new AnalysisUnsupportedTargetError(
|
throw new AnalysisUnsupportedTargetError(
|
||||||
"extract_artifact",
|
"extract_artifact",
|
||||||
@@ -443,7 +437,7 @@ const createReader = async (
|
|||||||
if (await requireExtractableFormat(path, input))
|
if (await requireExtractableFormat(path, input))
|
||||||
return new DirectoryArtifactReader(path);
|
return new DirectoryArtifactReader(path);
|
||||||
if (format === "asar") return new AsarArtifactReader(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);
|
return new MachOSliceArtifactReader(path, input.environment);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -144,7 +144,8 @@ const projectHar = (
|
|||||||
(literal) =>
|
(literal) =>
|
||||||
item.includes(literal) ||
|
item.includes(literal) ||
|
||||||
contentBase64.includes(literal) ||
|
contentBase64.includes(literal) ||
|
||||||
sha256.includes(literal),
|
sha256.includes(literal) ||
|
||||||
|
String(bytes.length).includes(literal),
|
||||||
);
|
);
|
||||||
binary_fields.push(
|
binary_fields.push(
|
||||||
hidden
|
hidden
|
||||||
|
|||||||
@@ -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", () => {
|
describe("dyld slice compatibility and coverage", () => {
|
||||||
it("lets an x86_64h process load generic x86_64 but not arm64e load arm64", async () => {
|
it("lets an x86_64h process load generic x86_64 but not arm64e load arm64", async () => {
|
||||||
const files = {
|
const files = {
|
||||||
|
|||||||
@@ -427,7 +427,9 @@ const resolveDependency = async (
|
|||||||
): Promise<Edge> => {
|
): Promise<Edge> => {
|
||||||
const current = context.loaded.get(loader);
|
const current = context.loaded.get(loader);
|
||||||
const chain = current?.chain ?? [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[] = [];
|
const candidates: Candidate[] = [];
|
||||||
if (loaded !== undefined)
|
if (loaded !== undefined)
|
||||||
candidates.push({
|
candidates.push({
|
||||||
@@ -506,7 +508,10 @@ const traceProcess = async (
|
|||||||
chain: [context.root],
|
chain: [context.root],
|
||||||
conditional: false,
|
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);
|
context.byInstallName.set(rootSlice.install_name, context.root);
|
||||||
const pending = [context.root];
|
const pending = [context.root];
|
||||||
while (pending.length > 0) {
|
while (pending.length > 0) {
|
||||||
@@ -537,6 +542,7 @@ const traceProcess = async (
|
|||||||
});
|
});
|
||||||
if (
|
if (
|
||||||
slice.install_name !== null &&
|
slice.install_name !== null &&
|
||||||
|
slice.install_name.startsWith("@rpath/") &&
|
||||||
!context.byInstallName.has(slice.install_name)
|
!context.byInstallName.has(slice.install_name)
|
||||||
)
|
)
|
||||||
context.byInstallName.set(slice.install_name, image);
|
context.byInstallName.set(slice.install_name, image);
|
||||||
|
|||||||
@@ -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.",
|
"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.",
|
"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.",
|
"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.",
|
"@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.",
|
"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.",
|
"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");
|
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", () => {
|
it("coarsens format issue pointers without creating replacement coordinates", () => {
|
||||||
const error = new AnalysisInputError(
|
const error = new AnalysisInputError(
|
||||||
"inspect_web_network_capture",
|
"inspect_web_network_capture",
|
||||||
|
|||||||
@@ -154,6 +154,7 @@ export const redactExplicitFailure = (
|
|||||||
...(error.userMessage === undefined
|
...(error.userMessage === undefined
|
||||||
? {}
|
? {}
|
||||||
: { userMessage: text(error.userMessage) }),
|
: { userMessage: text(error.userMessage) }),
|
||||||
|
...(error.retryable ? { retryable: true } : {}),
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
if (error instanceof AnalysisResourceConstraintError)
|
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 { ApplicationNode } from "./javascriptApplicationGraphSchemas.js";
|
||||||
import type { JavaScriptApplicationGraph } from "./javascriptApplicationGraph.js";
|
import type { JavaScriptApplicationGraph } from "./javascriptApplicationGraph.js";
|
||||||
@@ -216,7 +216,7 @@ const pathBelowRoot = (root: string, value: string): string | null => {
|
|||||||
const remainder =
|
const remainder =
|
||||||
rootStyle === "windows"
|
rootStyle === "windows"
|
||||||
? win32.relative(root, value)
|
? win32.relative(root, value)
|
||||||
: relative(root, value);
|
: posix.relative(root, value);
|
||||||
const portableRemainder = remainder.replaceAll("\\", "/");
|
const portableRemainder = remainder.replaceAll("\\", "/");
|
||||||
if (
|
if (
|
||||||
remainder === "" ||
|
remainder === "" ||
|
||||||
|
|||||||
@@ -33,3 +33,24 @@ it("rejects incomplete headers, invalid signatures and zero dimensions", () => {
|
|||||||
expect(readPngHeaderDimensions(zero)).toBeUndefined();
|
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,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -8,10 +8,16 @@ export const readPngHeaderDimensions = (
|
|||||||
if (
|
if (
|
||||||
bytes.byteLength < 24 ||
|
bytes.byteLength < 24 ||
|
||||||
!bytes.subarray(0, 8).equals(PNG_SIGNATURE) ||
|
!bytes.subarray(0, 8).equals(PNG_SIGNATURE) ||
|
||||||
|
bytes.readUInt32BE(8) !== 13 ||
|
||||||
!bytes.subarray(12, 16).equals(IHDR_TYPE)
|
!bytes.subarray(12, 16).equals(IHDR_TYPE)
|
||||||
)
|
)
|
||||||
return undefined;
|
return undefined;
|
||||||
const width = bytes.readUInt32BE(16);
|
const width = bytes.readUInt32BE(16);
|
||||||
const height = bytes.readUInt32BE(20);
|
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 { describe, expect, it } from "vitest";
|
||||||
import { parseProcessCapture } from "./processCaptureParsing.js";
|
import { parseProcessCapture } from "./processCaptureParsing.js";
|
||||||
import type { ProcessTraceSpecification } from "./processTraceSpecification.js";
|
import type { ProcessTraceSpecification } from "./processTraceSpecification.js";
|
||||||
|
import { processTraceSpecificationSchema as specificationSchema } from "./processTraceSpecification.js";
|
||||||
import { processTraceComparisonResultSchema } from "./processTraceEvaluation.js";
|
import { processTraceComparisonResultSchema } from "./processTraceEvaluation.js";
|
||||||
import {
|
import {
|
||||||
capture,
|
capture,
|
||||||
@@ -100,6 +101,33 @@ describe("generic capture trace comparison", () => {
|
|||||||
right: { matched_variant: "two" },
|
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", () => {
|
describe("process trace constraints and evidence sufficiency", () => {
|
||||||
|
|||||||
@@ -13,13 +13,12 @@ import {
|
|||||||
import {
|
import {
|
||||||
canonicalTraceJson,
|
canonicalTraceJson,
|
||||||
processTraceCardinalityBounds,
|
processTraceCardinalityBounds,
|
||||||
|
processTraceIdentifierSchema,
|
||||||
type ProcessTraceSpecification,
|
type ProcessTraceSpecification,
|
||||||
} from "./processTraceSpecification.js";
|
} from "./processTraceSpecification.js";
|
||||||
|
|
||||||
const identifierSchema = z.string().regex(/^[A-Za-z][A-Za-z0-9._\x2d]{0,63}$/u);
|
|
||||||
|
|
||||||
const matchedEventSchema = z.strictObject({
|
const matchedEventSchema = z.strictObject({
|
||||||
event_id: identifierSchema,
|
event_id: processTraceIdentifierSchema,
|
||||||
location: processObservationLocationSchema,
|
location: processObservationLocationSchema,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -32,7 +31,7 @@ const sideResultSchema = z.union([
|
|||||||
z.strictObject({
|
z.strictObject({
|
||||||
...sideResultShape,
|
...sideResultShape,
|
||||||
status: z.literal("pass"),
|
status: z.literal("pass"),
|
||||||
matched_variant: identifierSchema.nullable(),
|
matched_variant: processTraceIdentifierSchema.nullable(),
|
||||||
}),
|
}),
|
||||||
z.strictObject({
|
z.strictObject({
|
||||||
...sideResultShape,
|
...sideResultShape,
|
||||||
@@ -53,7 +52,7 @@ const diagnosticSchema = z.strictObject({
|
|||||||
]),
|
]),
|
||||||
side: z.enum(["left", "right"]),
|
side: z.enum(["left", "right"]),
|
||||||
message: z.string(),
|
message: z.string(),
|
||||||
event_ids: z.array(identifierSchema),
|
event_ids: z.array(processTraceIdentifierSchema),
|
||||||
locations: z.array(processObservationLocationSchema),
|
locations: z.array(processObservationLocationSchema),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -9,7 +9,16 @@ import {
|
|||||||
processObservationSourceSchema,
|
processObservationSourceSchema,
|
||||||
} from "./processObservation.js";
|
} 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", [
|
const cardinalitySchema = z.discriminatedUnion("kind", [
|
||||||
z.strictObject({ kind: z.literal("required") }),
|
z.strictObject({ kind: z.literal("required") }),
|
||||||
@@ -31,7 +40,7 @@ const cardinalitySchema = z.discriminatedUnion("kind", [
|
|||||||
]);
|
]);
|
||||||
|
|
||||||
const eventDeclarationSchema = z.strictObject({
|
const eventDeclarationSchema = z.strictObject({
|
||||||
id: identifierSchema,
|
id: processTraceIdentifierSchema,
|
||||||
source: processObservationSourceSchema,
|
source: processObservationSourceSchema,
|
||||||
exact: jsonValueSchema,
|
exact: jsonValueSchema,
|
||||||
ignore_fields: z
|
ignore_fields: z
|
||||||
@@ -56,29 +65,31 @@ const partialOrderLanguageSchema = z.strictObject({
|
|||||||
happens_before: z
|
happens_before: z
|
||||||
.array(
|
.array(
|
||||||
z.strictObject({
|
z.strictObject({
|
||||||
before: identifierSchema,
|
before: processTraceIdentifierSchema,
|
||||||
after: identifierSchema,
|
after: processTraceIdentifierSchema,
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
.default([]),
|
.default([]),
|
||||||
not_before: z
|
not_before: z
|
||||||
.array(
|
.array(
|
||||||
z.strictObject({
|
z.strictObject({
|
||||||
event: identifierSchema,
|
event: processTraceIdentifierSchema,
|
||||||
anchor: identifierSchema,
|
anchor: processTraceIdentifierSchema,
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
.default([]),
|
.default([]),
|
||||||
unordered_groups: z
|
unordered_groups: z
|
||||||
.array(z.strictObject({ events: z.array(identifierSchema).min(2) }))
|
.array(
|
||||||
|
z.strictObject({ events: z.array(processTraceIdentifierSchema).min(2) }),
|
||||||
|
)
|
||||||
.default([]),
|
.default([]),
|
||||||
prefix: z.array(identifierSchema).default([]),
|
prefix: z.array(processTraceIdentifierSchema).default([]),
|
||||||
suffix: z.array(identifierSchema).default([]),
|
suffix: z.array(processTraceIdentifierSchema).default([]),
|
||||||
});
|
});
|
||||||
|
|
||||||
const finiteTraceTokenSchema = z.union([
|
const finiteTraceTokenSchema = z.union([
|
||||||
identifierSchema,
|
processTraceIdentifierSchema,
|
||||||
z.strictObject({ unordered: z.array(identifierSchema).min(2) }),
|
z.strictObject({ unordered: z.array(processTraceIdentifierSchema).min(2) }),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const finiteTraceLanguageSchema = z.strictObject({
|
const finiteTraceLanguageSchema = z.strictObject({
|
||||||
@@ -86,7 +97,7 @@ const finiteTraceLanguageSchema = z.strictObject({
|
|||||||
variants: z
|
variants: z
|
||||||
.array(
|
.array(
|
||||||
z.strictObject({
|
z.strictObject({
|
||||||
id: identifierSchema,
|
id: processTraceIdentifierSchema,
|
||||||
trace: z.array(finiteTraceTokenSchema),
|
trace: z.array(finiteTraceTokenSchema),
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ import {
|
|||||||
AnalysisUnsupportedTargetError,
|
AnalysisUnsupportedTargetError,
|
||||||
} from "../domain/analysisErrorCore.js";
|
} from "../domain/analysisErrorCore.js";
|
||||||
import { AnalysisProtocolError } from "../domain/analysisErrorCore.js";
|
import { AnalysisProtocolError } from "../domain/analysisErrorCore.js";
|
||||||
|
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
|
||||||
import { AnalysisError } from "../domain/analysisErrorBase.js";
|
import { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||||
import { err, ok, type Result } from "../domain/result.js";
|
import { err, ok, type Result } from "../domain/result.js";
|
||||||
import {
|
import {
|
||||||
@@ -759,7 +760,7 @@ export class FlutterBuildProvider {
|
|||||||
toolchain_capped: value.libflutter.toolchainCapped,
|
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 flutterDetected = abis.some((entry) => entry.libapp.present);
|
||||||
const partial =
|
const partial =
|
||||||
abis.some(
|
abis.some(
|
||||||
@@ -871,7 +872,7 @@ export class FlutterBuildProvider {
|
|||||||
(left, right) =>
|
(left, right) =>
|
||||||
(preference.indexOf(left.abi) + 1 || preference.length + 1) -
|
(preference.indexOf(left.abi) + 1 || preference.length + 1) -
|
||||||
(preference.indexOf(right.abi) + 1 || preference.length + 1) ||
|
(preference.indexOf(right.abi) + 1 || preference.length + 1) ||
|
||||||
left.abi.localeCompare(right.abi),
|
compareUnicodeCodePoints(left.abi, right.abi),
|
||||||
)[0]!
|
)[0]!
|
||||||
: candidates.find((candidate) => candidate.abi === abi);
|
: candidates.find((candidate) => candidate.abi === abi);
|
||||||
if (selected === undefined)
|
if (selected === undefined)
|
||||||
|
|||||||
@@ -85,8 +85,10 @@ export class IdaWorkspace {
|
|||||||
slice === undefined
|
slice === undefined
|
||||||
? position + bytes.length
|
? position + bytes.length
|
||||||
: Math.min(position + bytes.length, slice.offset + slice.size);
|
: Math.min(position + bytes.length, slice.offset + slice.size);
|
||||||
const admitted = bytes.subarray(start - position, end - position);
|
// A chunk after the slice has end < position, and a negative subarray
|
||||||
if (admitted.length > 0) {
|
// 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);
|
inputHash.update(admitted);
|
||||||
await input.write(admitted);
|
await input.write(admitted);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import { afterEach, describe, expect, it } from "vitest";
|
|||||||
|
|
||||||
import { parseBinaryTarget } from "../application/BinaryTargetResolver.js";
|
import { parseBinaryTarget } from "../application/BinaryTargetResolver.js";
|
||||||
import { parseExecutableHeader } from "../domain/binaryTarget.js";
|
import { parseExecutableHeader } from "../domain/binaryTarget.js";
|
||||||
import { fat } from "../domain/binaryTarget.fixture.js";
|
import { fat, thinMach } from "../domain/binaryTarget.fixture.js";
|
||||||
import {
|
import {
|
||||||
createIdaTarget,
|
createIdaTarget,
|
||||||
RecordingIdaMcp,
|
RecordingIdaMcp,
|
||||||
@@ -35,6 +35,45 @@ const universalTarget = async (hostArchitecture: "arm64" | "x64") => {
|
|||||||
return { bytes, target: resolved.value };
|
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", () => {
|
describe("IDA workspace input thinning", () => {
|
||||||
it.skipIf(process.platform === "win32")(
|
it.skipIf(process.platform === "win32")(
|
||||||
"thins the selected arm64 slice into the private headless input",
|
"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 () => {
|
it("keeps a whole-file copy for thin targets", async () => {
|
||||||
const { root, target } = await createIdaTarget("arm64");
|
const { root, target } = await createIdaTarget("arm64");
|
||||||
roots.push(root);
|
roots.push(root);
|
||||||
|
|||||||
@@ -35,6 +35,37 @@ const validPng = Buffer.from(
|
|||||||
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jv4sAAAAASUVORK5CYII=",
|
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jv4sAAAAASUVORK5CYII=",
|
||||||
"base64",
|
"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", () => {
|
describe("native UI screenshot validation", () => {
|
||||||
it("rejects malformed or mismatched screenshot bytes from the helper", async () => {
|
it("rejects malformed or mismatched screenshot bytes from the helper", async () => {
|
||||||
const screenshot = {
|
const screenshot = {
|
||||||
|
|||||||
@@ -83,6 +83,24 @@ it("counts IPv6 endpoints once per packet and preserves every examined fact", as
|
|||||||
expect(result.partial).toBe(false);
|
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 () => {
|
it("preserves all DNS addresses and their exact examined count", async () => {
|
||||||
const result = await parseTsharkJsonOutput(
|
const result = await parseTsharkJsonOutput(
|
||||||
capture(
|
capture(
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import {
|
|||||||
AnalysisResourceConstraintError,
|
AnalysisResourceConstraintError,
|
||||||
} from "../domain/analysisErrorCore.js";
|
} from "../domain/analysisErrorCore.js";
|
||||||
import { parseRecordedTransportUrl } from "../domain/recordedTransportUrl.js";
|
import { parseRecordedTransportUrl } from "../domain/recordedTransportUrl.js";
|
||||||
|
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
|
||||||
|
|
||||||
const OPERATION = "inspect_pcap_capture";
|
const OPERATION = "inspect_pcap_capture";
|
||||||
/** Bounds JSON decoding plus its expanded object graph before JSON.parse. */
|
/** Bounds JSON decoding plus its expanded object graph before JSON.parse. */
|
||||||
@@ -284,7 +285,7 @@ export const parseTsharkJsonOutput = async (
|
|||||||
signal?.throwIfAborted();
|
signal?.throwIfAborted();
|
||||||
return {
|
return {
|
||||||
endpoints: [...endpoints]
|
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]) => ({
|
.map(([address, packet_count]) => ({
|
||||||
address,
|
address,
|
||||||
port: null,
|
port: null,
|
||||||
@@ -300,7 +301,7 @@ export const parseTsharkJsonOutput = async (
|
|||||||
tlsSniValues: [...sni],
|
tlsSniValues: [...sni],
|
||||||
tlsSniCount: sni.size,
|
tlsSniCount: sni.size,
|
||||||
protocolDistribution: [...protocols]
|
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 })),
|
.map(([protocol, packet_count]) => ({ protocol, packet_count })),
|
||||||
protocolCount: protocols.size,
|
protocolCount: protocols.size,
|
||||||
httpRequestUris: [...uris],
|
httpRequestUris: [...uris],
|
||||||
|
|||||||
@@ -12,6 +12,8 @@ import { err, ok } from "../domain/result.js";
|
|||||||
import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
|
import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
|
||||||
import { inspectEvidenceBundle } from "../application/investigation/InspectEvidenceBundle.js";
|
import { inspectEvidenceBundle } from "../application/investigation/InspectEvidenceBundle.js";
|
||||||
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
|
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
|
||||||
|
import { withAdmittedAnalysis } from "./analysisAdmission.js";
|
||||||
|
import { runAdmittedToolOperation } from "./admittedToolOperation.js";
|
||||||
|
|
||||||
interface EvidenceToolRegistration {
|
interface EvidenceToolRegistration {
|
||||||
readonly server: EvidenceMcpServer;
|
readonly server: EvidenceMcpServer;
|
||||||
@@ -92,40 +94,54 @@ const registerImportEvidenceTool = ({
|
|||||||
resources,
|
resources,
|
||||||
importContract,
|
importContract,
|
||||||
}: EvidenceToolRegistration): void => {
|
}: EvidenceToolRegistration): void => {
|
||||||
|
const admission = withAdmittedAnalysis({ kind: "session", session });
|
||||||
server.registerTool(
|
server.registerTool(
|
||||||
importContract.name,
|
importContract.name,
|
||||||
toolRegistrationOptions(importContract),
|
toolRegistrationOptions(importContract),
|
||||||
async (input, context) => {
|
async (input, context) =>
|
||||||
const path = input.path;
|
runAdmittedToolOperation(
|
||||||
const signal = context.mcpReq.signal;
|
server,
|
||||||
const loaded = await readImmutableEvidenceBundle(path, signal, resources);
|
admission,
|
||||||
if (!loaded.ok)
|
importContract.name,
|
||||||
return server.delivery.toCallToolResult(loaded, importContract);
|
context.mcpReq.signal,
|
||||||
const retainedUnknownRevisions = new Set(
|
async () => {
|
||||||
bundleForSerialization(session).unknowns.map((unknown) =>
|
const path = input.path;
|
||||||
unknownRevisionKey(unknown),
|
const signal = context.mcpReq.signal;
|
||||||
),
|
const loaded = await readImmutableEvidenceBundle(
|
||||||
);
|
path,
|
||||||
if (signal.aborted)
|
signal,
|
||||||
return server.delivery.toCallToolResult(
|
resources,
|
||||||
err(new AnalysisCancelledError("import_evidence_bundle")),
|
);
|
||||||
importContract,
|
if (!loaded.ok)
|
||||||
);
|
return server.delivery.toCallToolResult(loaded, importContract);
|
||||||
const imported = session.importEvidenceBundle(loaded.value);
|
const retainedUnknownRevisions = new Set(
|
||||||
return imported.ok
|
bundleForSerialization(session).unknowns.map((unknown) =>
|
||||||
? server.delivery.toCallToolResult(
|
unknownRevisionKey(unknown),
|
||||||
ok({
|
),
|
||||||
imported: imported.value,
|
);
|
||||||
unknowns_added: loaded.value.unknowns.filter(
|
if (signal.aborted)
|
||||||
(unknown) =>
|
return server.delivery.toCallToolResult(
|
||||||
!retainedUnknownRevisions.has(unknownRevisionKey(unknown)),
|
err(new AnalysisCancelledError("import_evidence_bundle")),
|
||||||
).length,
|
importContract,
|
||||||
total: bundleForSerialization(session).records.length,
|
);
|
||||||
}),
|
const imported = session.importEvidenceBundle(loaded.value);
|
||||||
importContract,
|
return imported.ok
|
||||||
)
|
? server.delivery.toCallToolResult(
|
||||||
: server.delivery.toCallToolResult(imported, importContract);
|
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 { captureWebScreenshotInputSchema } from "../../../src/domain/webScreenshot.js";
|
||||||
import { startFakeCdpBrowser } from "../../fixtures/fakeCdpBrowser.js";
|
import { startFakeCdpBrowser } from "../../fixtures/fakeCdpBrowser.js";
|
||||||
describe("screenshot committed document identity", () => {
|
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"])(
|
it.each(["loader-main", "loader-reloaded"])(
|
||||||
"distinguishes %s for the same URL",
|
"distinguishes %s for the same URL",
|
||||||
async (screenshotDocumentLoader) => {
|
async (screenshotDocumentLoader) => {
|
||||||
|
|||||||
@@ -7,6 +7,9 @@ import { execFile } from "node:child_process";
|
|||||||
import { fileURLToPath } from "node:url";
|
import { fileURLToPath } from "node:url";
|
||||||
import { promisify } from "node:util";
|
import { promisify } from "node:util";
|
||||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
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(
|
const entrypoint = fileURLToPath(
|
||||||
new URL("../../../scripts/rea.mjs", import.meta.url),
|
new URL("../../../scripts/rea.mjs", import.meta.url),
|
||||||
);
|
);
|
||||||
@@ -41,6 +44,91 @@ const cli = async (
|
|||||||
};
|
};
|
||||||
import { historicalHar } from "../../fixtures/historicalHar.js";
|
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 () => {
|
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-"));
|
const root = await mkdtemp(join(tmpdir(), "rea-history-har-"));
|
||||||
onTestFinished(() => rm(root, { recursive: true, force: true }));
|
onTestFinished(() => rm(root, { recursive: true, force: true }));
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ import {
|
|||||||
type ApplicationVersionComparisonResult,
|
type ApplicationVersionComparisonResult,
|
||||||
} from "../../../src/domain/javascript/javascriptApplicationVersionComparisonSchemas.js";
|
} from "../../../src/domain/javascript/javascriptApplicationVersionComparisonSchemas.js";
|
||||||
import { javascriptRuntimeReconciliationResultSchema } from "../../../src/domain/javascript/javascriptRuntimeReconciliationSchemas.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 { compareJavaScriptApplicationVersions } from "../../../src/domain/javascript/javascriptApplicationVersionComparison.js";
|
||||||
import { createJavaScriptApplicationGraph } from "../../../src/domain/javascript/javascriptApplicationGraph.js";
|
import { createJavaScriptApplicationGraph } from "../../../src/domain/javascript/javascriptApplicationGraph.js";
|
||||||
import { traceApplicationFeature } from "../../../src/domain/javascript/javascriptFeatureTrace.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", () => {
|
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", () => {
|
it("resolves relative file mapping roots before deriving result Evidence", () => {
|
||||||
const absoluteRoot = resolve(process.cwd(), "runtime-cache-fixture");
|
const absoluteRoot = resolve(process.cwd(), "runtime-cache-fixture");
|
||||||
const relativeRoot = relative(process.cwd(), absoluteRoot);
|
const relativeRoot = relative(process.cwd(), absoluteRoot);
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { spawnSync } from "node:child_process";
|
import { spawnSync } from "node:child_process";
|
||||||
import { access, mkdir, readFile, writeFile } from "node:fs/promises";
|
import { access, mkdir, readFile, writeFile } from "node:fs/promises";
|
||||||
import { join, sep } from "node:path";
|
import { dirname, join, sep } from "node:path";
|
||||||
import { fileURLToPath } from "node:url";
|
import { fileURLToPath } from "node:url";
|
||||||
import { expect, it } from "vitest";
|
import { expect, it } from "vitest";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
@@ -138,6 +138,36 @@ it("keeps lint errors failing and visible alongside the retained warnings", asyn
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("excludes translation staging while retaining authored website errors", async () => {
|
||||||
|
const root = await fixture();
|
||||||
|
for (const name of [".gitignore", ".oxlintrc.json"])
|
||||||
|
await writeFile(join(root, name), await readFile(join(repository, name)));
|
||||||
|
const authored = "website/public/assets/authored.js";
|
||||||
|
const staged =
|
||||||
|
"website/.i18n-regression/site/examples/notes-electron/main.js";
|
||||||
|
for (const name of [authored, staged]) {
|
||||||
|
const path = join(root, name);
|
||||||
|
await mkdir(dirname(path), { recursive: true });
|
||||||
|
await writeFile(
|
||||||
|
path,
|
||||||
|
'const source = require("node:fs");\nconsole.log(source);\n',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = invoke(root, "lint");
|
||||||
|
expect(result.error).toBeUndefined();
|
||||||
|
expect(result.status).toBe(1);
|
||||||
|
expect(result.stdout).toContain("1 errors, 0 warnings");
|
||||||
|
expect(result.stderr).toContain(authored);
|
||||||
|
expect(await lintDiagnostics(root)).toEqual([
|
||||||
|
expect.objectContaining({
|
||||||
|
severity: "error",
|
||||||
|
code: "typescript(no-var-requires)",
|
||||||
|
filename: authored,
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
it("keeps malformed source failing with its parser diagnostic", async () => {
|
it("keeps malformed source failing with its parser diagnostic", async () => {
|
||||||
const root = await fixture();
|
const root = await fixture();
|
||||||
await writeFile(join(root, "src/malformed.js"), "const value = ;\n");
|
await writeFile(join(root, "src/malformed.js"), "const value = ;\n");
|
||||||
|
|||||||
@@ -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 { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
|
import { writeOrderedZip } from "../../../fixtures/artifactEntryOrder.js";
|
||||||
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
|
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
|
||||||
|
|
||||||
import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js";
|
import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js";
|
||||||
import { artifactExtractionExecutionSchema } from "../../../../src/contracts/artifactToolContracts.js";
|
import { artifactExtractionExecutionSchema } from "../../../../src/contracts/artifactToolContracts.js";
|
||||||
|
import { artifactExtractionResultSchema } from "../../../../src/domain/artifactGraph.js";
|
||||||
import type { BinaryTarget } from "../../../../src/domain/binaryTargetTypes.js";
|
import type { BinaryTarget } from "../../../../src/domain/binaryTargetTypes.js";
|
||||||
|
|
||||||
describe("artifact extraction format support", () => {
|
describe("artifact extraction format support", () => {
|
||||||
@@ -42,6 +44,33 @@ describe("artifact extraction format support", () => {
|
|||||||
});
|
});
|
||||||
await expect(access(output)).rejects.toThrow();
|
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 = (
|
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");
|
||||||
|
},
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -5,13 +5,24 @@ volatile int rea_c_global = 7;
|
|||||||
#define REA_LONG_CHUNK "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
|
#define REA_LONG_CHUNK "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
|
||||||
#define REA_LONG_256 REA_LONG_CHUNK REA_LONG_CHUNK REA_LONG_CHUNK REA_LONG_CHUNK
|
#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
|
#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) {
|
__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_long_literal);
|
||||||
puts("REA_UTF8_é_😀");
|
puts(rea_fragmented_literal);
|
||||||
|
puts(rea_utf8_literal);
|
||||||
puts("REA_ESCAPED_\"\\line\nend\t\r");
|
puts("REA_ESCAPED_\"\\line\nend\t\r");
|
||||||
puts("REA_LITERAL_BACKSLASH_\\n");
|
puts("REA_LITERAL_BACKSLASH_\\n");
|
||||||
puts("REA_LITERAL_…");
|
puts(rea_ellipsis_literal);
|
||||||
puts("REA_LATIN1_\xff");
|
puts(rea_latin1_literal);
|
||||||
}
|
}
|
||||||
|
|
||||||
__attribute__((noinline, used)) int rea_leaf(int value) {
|
__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
@@ -4,6 +4,7 @@
|
|||||||
#include <winioctl.h>
|
#include <winioctl.h>
|
||||||
#include <cstdio>
|
#include <cstdio>
|
||||||
#include <cstring>
|
#include <cstring>
|
||||||
|
#include <cwchar>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <vector>
|
#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");
|
value(L"REA_\u00df") == expectedSharp && value(L"REA_SS") == L"double" ? "true" : "false");
|
||||||
return 0;
|
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") {
|
if (count == 4 && std::wstring(args[1]) == L"reparse-directory") {
|
||||||
// Only the conformance lane's disposable, nonempty source directory is used.
|
// Only the conformance lane's disposable, nonempty source directory is used.
|
||||||
const auto substitute = L"\\??\\" + std::wstring(args[3]);
|
const auto substitute = L"\\??\\" + std::wstring(args[3]);
|
||||||
|
|||||||
Reference in New Issue
Block a user