feat(ghidra): enable Windows x64 read-only analysis (#699)
* feat(ghidra): enable Windows x64 read-only analysis * test(ghidra): exercise native Windows runtime boundaries * test(ghidra): verify current Windows inventory and isolate ACL observer * fix(ghidra): align Windows admission and address P0 review
This commit is contained in:
@@ -83,7 +83,7 @@ export const parseBinaryTarget = async (
|
||||
)
|
||||
return ok({
|
||||
path,
|
||||
sourcePath: canonical,
|
||||
sourcePath: process.platform === "win32" ? candidate : canonical,
|
||||
sha256: await sha256Handle(handle),
|
||||
kind: "database",
|
||||
format: "analysis-database",
|
||||
@@ -92,7 +92,7 @@ export const parseBinaryTarget = async (
|
||||
if (artifactFormat !== undefined) {
|
||||
const identity = {
|
||||
path,
|
||||
sourcePath: canonical,
|
||||
sourcePath: process.platform === "win32" ? candidate : canonical,
|
||||
sha256: await sha256Handle(handle),
|
||||
};
|
||||
return isArchiveFormat(artifactFormat)
|
||||
@@ -103,7 +103,7 @@ export const parseBinaryTarget = async (
|
||||
if (!detected.ok) return err(new BinaryTargetError(path, detected.error));
|
||||
return ok({
|
||||
path,
|
||||
sourcePath: canonical,
|
||||
sourcePath: process.platform === "win32" ? candidate : canonical,
|
||||
sha256: await sha256Handle(handle),
|
||||
kind: "executable",
|
||||
...detected.value,
|
||||
|
||||
@@ -63,7 +63,8 @@ export interface DoctorProviderInspection {
|
||||
readonly configured: boolean;
|
||||
readonly available: boolean;
|
||||
readonly providerVersion: string | null;
|
||||
/** Exact non-secret variables safe to persist in an approved registration. */
|
||||
/** Adapter-validated non-secret settings, independent of runtime readiness.
|
||||
* Invalid installations publish no settings. */
|
||||
readonly registrationEnvironment: Readonly<Record<string, string>>;
|
||||
readonly checks: readonly DoctorProviderCheck[];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { DoctorProviderInspection } from "./Doctor.js";
|
||||
import { providerRegistrationEnvironment } from "./SetupRegistrationEnvironment.js";
|
||||
|
||||
const inspection = (
|
||||
overrides: Partial<DoctorProviderInspection> = {},
|
||||
): DoctorProviderInspection => ({
|
||||
id: "fixture",
|
||||
configured: true,
|
||||
available: false,
|
||||
providerVersion: "1",
|
||||
registrationEnvironment: {
|
||||
REA_FIXTURE_PROVIDER_ROOT: "C:\\Tools\\Provider",
|
||||
},
|
||||
checks: [],
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe("provider registration settings", () => {
|
||||
it("retains valid published paths when runtime capabilities are unavailable", () => {
|
||||
expect(providerRegistrationEnvironment([inspection()])).toEqual({
|
||||
REA_FIXTURE_PROVIDER_ROOT: "C:\\Tools\\Provider",
|
||||
});
|
||||
});
|
||||
|
||||
it("does not invent settings when the adapter cannot publish an installation", () => {
|
||||
expect(
|
||||
providerRegistrationEnvironment([
|
||||
inspection({ configured: false, registrationEnvironment: {} }),
|
||||
]),
|
||||
).toEqual({});
|
||||
});
|
||||
|
||||
it("keeps available-provider settings unchanged", () => {
|
||||
expect(
|
||||
providerRegistrationEnvironment([inspection({ available: true })]),
|
||||
).toEqual({ REA_FIXTURE_PROVIDER_ROOT: "C:\\Tools\\Provider" });
|
||||
});
|
||||
});
|
||||
@@ -1,12 +1,11 @@
|
||||
import type { DoctorProviderInspection } from "./Doctor.js";
|
||||
|
||||
/** Select exact non-secret settings published by available providers. */
|
||||
/** Preserve adapter-published settings independently of runtime readiness. */
|
||||
export const providerRegistrationEnvironment = (
|
||||
inspections: readonly DoctorProviderInspection[],
|
||||
): Readonly<Record<string, string>> =>
|
||||
Object.fromEntries(
|
||||
inspections
|
||||
.filter(({ available }) => available)
|
||||
.flatMap(({ registrationEnvironment }) =>
|
||||
Object.entries(registrationEnvironment),
|
||||
)
|
||||
|
||||
@@ -26,6 +26,7 @@ export interface WindowsCapabilityDependencies {
|
||||
probePrivateAcl(): WindowsCapabilityOutcome;
|
||||
probeUnixDomainSocket(): WindowsCapabilityOutcome;
|
||||
probePty(): Promise<ProcessCaptureCapability>;
|
||||
nativeCapabilities?(): WindowsNativeCapabilitySet;
|
||||
}
|
||||
|
||||
/** Machine-readable facts for features that need Windows-specific security. */
|
||||
@@ -63,7 +64,9 @@ export const probeWindowsCapabilities = async (
|
||||
? { available: true, reason: null }
|
||||
: { available: false, reason: pty.reason },
|
||||
},
|
||||
security: windowsNativeCapabilities(dependencies.platform),
|
||||
security:
|
||||
dependencies.nativeCapabilities?.() ??
|
||||
windowsNativeCapabilities(dependencies.platform),
|
||||
};
|
||||
};
|
||||
|
||||
@@ -73,10 +76,9 @@ const systemDependencies = (): WindowsCapabilityDependencies => ({
|
||||
probeSymlinkCreation,
|
||||
probeNoFollowOpen: () =>
|
||||
systemNoFollowOpenCapability(process.platform, constants.O_NOFOLLOW),
|
||||
probePrivateAcl: () => ({
|
||||
available: false,
|
||||
reason: "Windows ACL enforcement is not implemented by this REA build",
|
||||
}),
|
||||
probePrivateAcl: () =>
|
||||
windowsNativeCapabilities(process.platform).private_runtime_dacl,
|
||||
nativeCapabilities: () => windowsNativeCapabilities(process.platform),
|
||||
probeUnixDomainSocket: () =>
|
||||
process.platform === "win32"
|
||||
? {
|
||||
@@ -95,7 +97,8 @@ export const systemNoFollowOpenCapability = (
|
||||
if (platform === "win32")
|
||||
return {
|
||||
available: false,
|
||||
reason: "Windows reparse-safe handle admission is not implemented",
|
||||
reason:
|
||||
"Node pathname O_NOFOLLOW is not Windows handle authority; native admission is reported separately in security.",
|
||||
};
|
||||
return typeof noFollow === "number"
|
||||
? { available: true, reason: null }
|
||||
|
||||
@@ -62,7 +62,7 @@ export type GhidraOperation =
|
||||
/** Owns one authenticated, private, read-only Ghidra headless session. */
|
||||
export class GhidraClient {
|
||||
readonly #options: Required<
|
||||
Pick<GhidraClientOptions, "startupTimeoutMs" | "transport">
|
||||
Pick<GhidraClientOptions, "startupTimeoutMs" | "transport" | "platform">
|
||||
> &
|
||||
GhidraClientOptions;
|
||||
readonly #logger: Logger;
|
||||
@@ -76,6 +76,7 @@ export class GhidraClient {
|
||||
#process: ProviderProcessSupervisor | undefined;
|
||||
#runtimeRoot: PrivateRuntimeRoot | undefined;
|
||||
#snapshotPath: string | undefined;
|
||||
#targetAdmission: JsonValue | undefined;
|
||||
#token: string | undefined;
|
||||
// Retain authentication identities for diagnostics from late request settlement.
|
||||
readonly #authenticationTokens = new Set<string>();
|
||||
@@ -120,6 +121,7 @@ export class GhidraClient {
|
||||
this.#options = {
|
||||
...options,
|
||||
startupTimeoutMs: options.startupTimeoutMs ?? GHIDRA_STARTUP_TIMEOUT_MS,
|
||||
platform: options.platform ?? process.platform,
|
||||
transport: options.transport ?? "unix-socket",
|
||||
};
|
||||
this.#logger = options.logger ?? silentLogger;
|
||||
@@ -281,6 +283,7 @@ export class GhidraClient {
|
||||
this.#runtimeRoot = await PrivateRuntimeRoot.create({
|
||||
parent: SESSION_ROOT,
|
||||
prefix: "rea-ghidra-",
|
||||
platform: this.#options.platform,
|
||||
});
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
@@ -302,9 +305,12 @@ export class GhidraClient {
|
||||
this.#options.targetPath,
|
||||
this.#runtimeRoot.path,
|
||||
this.#options.targetSha256,
|
||||
{ signal: deadline.signal, platform: this.#options.platform },
|
||||
);
|
||||
this.#snapshotPath = snapshot.path;
|
||||
this.#targetAdmission = snapshot.admission;
|
||||
} catch (cause: unknown) {
|
||||
if (deadline.signal.aborted) return this.#startupInterrupted(deadline);
|
||||
const failure = this.#failure(
|
||||
"start",
|
||||
"Ghidra target snapshot failed admission",
|
||||
@@ -403,6 +409,9 @@ export class GhidraClient {
|
||||
providerVersion: this.#options.providerVersion,
|
||||
profileDigest: this.#options.profileDigest,
|
||||
targetSha256: this.#options.targetSha256,
|
||||
...(this.#targetAdmission === undefined
|
||||
? {}
|
||||
: { targetAdmission: this.#targetAdmission }),
|
||||
...(this.#options.expectedLanguageId === undefined
|
||||
? {}
|
||||
: { expectedLanguageId: this.#options.expectedLanguageId }),
|
||||
@@ -583,6 +592,9 @@ export class GhidraClient {
|
||||
return createGhidraDiagnostics({
|
||||
targetPath: this.#options.targetPath,
|
||||
targetSha256: this.#options.targetSha256,
|
||||
...(this.#targetAdmission === undefined
|
||||
? {}
|
||||
: { targetAdmission: this.#targetAdmission }),
|
||||
transport: this.#options.transport,
|
||||
providerVersion: this.#options.providerVersion,
|
||||
profileDigest: this.#options.profileDigest,
|
||||
|
||||
@@ -36,6 +36,8 @@ export interface GhidraClientOptions {
|
||||
readonly runId?: string;
|
||||
readonly targetPath: string;
|
||||
readonly targetSha256: string;
|
||||
/** Installation host shared by runtime allocation and snapshot admission. */
|
||||
readonly platform?: NodeJS.Platform;
|
||||
readonly transport?: GhidraTransportKind;
|
||||
readonly providerVersion: string;
|
||||
readonly profileDigest: string;
|
||||
|
||||
@@ -9,6 +9,7 @@ import type { GhidraTransportKind } from "./GhidraTransport.js";
|
||||
export interface GhidraDiagnosticsOptions {
|
||||
readonly targetPath: string;
|
||||
readonly targetSha256: string;
|
||||
readonly targetAdmission?: JsonValue;
|
||||
readonly transport: GhidraTransportKind;
|
||||
readonly providerVersion: string;
|
||||
readonly profileDigest: string;
|
||||
@@ -37,6 +38,9 @@ export const createGhidraDiagnostics = (
|
||||
return {
|
||||
target_path: options.targetPath,
|
||||
target_sha256: options.targetSha256,
|
||||
...(options.targetAdmission === undefined
|
||||
? {}
|
||||
: { target_admission: options.targetAdmission }),
|
||||
transport: options.transport,
|
||||
provider_version: options.providerVersion,
|
||||
profile_digest: options.profileDigest,
|
||||
|
||||
@@ -2,6 +2,8 @@ import { describe, expect, it } from "vitest";
|
||||
|
||||
import { runDoctor, type DoctorHost } from "../application/Doctor.js";
|
||||
import { createDoctorHostFixture } from "../application/Doctor.fixture.js";
|
||||
import { providerRegistrationEnvironment } from "../application/SetupRegistrationEnvironment.js";
|
||||
import { WINDOWS_NATIVE_AUTHORITY_UNAVAILABLE_REASON } from "../process/WindowsAuthority.js";
|
||||
import {
|
||||
inspectGhidraInstallation,
|
||||
type GhidraInstallationHost,
|
||||
@@ -99,28 +101,6 @@ describe("Ghidra doctor integration", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("accepts the experimental Windows x64 Ghidra provider boundary", async () => {
|
||||
const ghidra = inspection({
|
||||
installDir: "C:\\tools\\ghidra_12.1.4_PUBLIC",
|
||||
platform: "win32",
|
||||
});
|
||||
const result = await runDoctor(undefined, {
|
||||
...doctorHost(ghidra),
|
||||
platform: "win32",
|
||||
architecture: "x64",
|
||||
linuxDistribution: () => Promise.resolve(undefined),
|
||||
});
|
||||
|
||||
expect(result.healthy).toBe(true);
|
||||
expect(result.checks.find(({ name }) => name === "host")).toMatchObject({
|
||||
ok: true,
|
||||
detail: "win32 x64",
|
||||
});
|
||||
expect(result.checks.find(({ name }) => name === "ghidra")).toMatchObject({
|
||||
ok: true,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
"bad installation",
|
||||
@@ -181,3 +161,95 @@ describe("Ghidra doctor integration", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Windows Ghidra doctor authority", () => {
|
||||
it("distinguishes a valid Windows installation from unavailable native authority", async () => {
|
||||
const ghidra = inspection({
|
||||
installDir: "C:\\tools\\ghidra_12.1.4_PUBLIC",
|
||||
platform: "win32",
|
||||
});
|
||||
const result = await runDoctor(undefined, {
|
||||
...doctorHost(ghidra),
|
||||
platform: "win32",
|
||||
architecture: "x64",
|
||||
linuxDistribution: () => Promise.resolve(undefined),
|
||||
});
|
||||
|
||||
expect(result.healthy).toBe(false);
|
||||
expect(result.providerInspections?.[0]).toMatchObject({
|
||||
available: false,
|
||||
providerVersion: "12.1.4",
|
||||
registrationEnvironment: {
|
||||
GHIDRA_INSTALL_DIR: "C:\\tools\\ghidra_12.1.4_PUBLIC",
|
||||
},
|
||||
});
|
||||
expect(
|
||||
providerRegistrationEnvironment(result.providerInspections ?? []),
|
||||
).toMatchObject({
|
||||
GHIDRA_INSTALL_DIR: "C:\\tools\\ghidra_12.1.4_PUBLIC",
|
||||
});
|
||||
expect(result.checks.find(({ name }) => name === "host")).toMatchObject({
|
||||
ok: true,
|
||||
detail: "win32 x64",
|
||||
});
|
||||
expect(result.checks.find(({ name }) => name === "ghidra")).toMatchObject({
|
||||
ok: true,
|
||||
});
|
||||
expect(
|
||||
result.checks.find(({ name }) => name === "ghidra-java"),
|
||||
).toMatchObject({ ok: true });
|
||||
expect(
|
||||
result.checks.find(({ name }) => name === "ghidra-native_authority"),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
classification: "unsupported_host",
|
||||
detail: WINDOWS_NATIVE_AUTHORITY_UNAVAILABLE_REASON,
|
||||
remediation: expect.stringContaining("cannot enable"),
|
||||
});
|
||||
});
|
||||
|
||||
it("fails provider-scoped Windows readiness without blaming installation", async () => {
|
||||
const ghidra = inspection({
|
||||
installDir: "C:\\tools\\ghidra_12.1.4_PUBLIC",
|
||||
platform: "win32",
|
||||
});
|
||||
const result = await runDoctor(
|
||||
undefined,
|
||||
{
|
||||
...doctorHost(ghidra),
|
||||
platform: "win32",
|
||||
linuxDistribution: () => Promise.resolve(undefined),
|
||||
},
|
||||
{ providers: ["ghidra"] },
|
||||
);
|
||||
expect(result.healthy).toBe(false);
|
||||
expect(result.scope_checks).toContainEqual(
|
||||
expect.objectContaining({
|
||||
name: "ghidra-native_authority",
|
||||
classification: "unsupported_host",
|
||||
detail: WINDOWS_NATIVE_AUTHORITY_UNAVAILABLE_REASON,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps missing Windows Java actionable as a dependency failure", () => {
|
||||
const projected = projectGhidraDoctorInspection(
|
||||
inspection(
|
||||
{
|
||||
installDir: "C:\\tools\\ghidra_12.1.4_PUBLIC",
|
||||
platform: "win32",
|
||||
},
|
||||
{ probeJava: () => undefined },
|
||||
),
|
||||
);
|
||||
expect(projected.available).toBe(false);
|
||||
expect(projected.checks).toContainEqual(
|
||||
expect.objectContaining({
|
||||
name: "java",
|
||||
ok: false,
|
||||
classification: "missing_dependency",
|
||||
remediation: expect.any(String),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
+46
-17
@@ -2,31 +2,60 @@ import type {
|
||||
DoctorProviderCheck,
|
||||
DoctorProviderInspection,
|
||||
} from "../application/Doctor.js";
|
||||
import {
|
||||
hasWindowsNativeAuthority,
|
||||
windowsNativeAuthorityUnavailableReason,
|
||||
} from "../process/WindowsAuthority.js";
|
||||
import {
|
||||
inspectGhidraInstallation,
|
||||
type GhidraInstallationCheck,
|
||||
type GhidraInstallationInspection,
|
||||
} from "./GhidraInstallation.js";
|
||||
|
||||
/** Project adapter-owned installation facts into the generic doctor contract. */
|
||||
/** Project installation and runtime-authority facts into the doctor contract. */
|
||||
export const projectGhidraDoctorInspection = (
|
||||
inspection: GhidraInstallationInspection,
|
||||
): DoctorProviderInspection => ({
|
||||
id: "ghidra",
|
||||
configured: inspection.installDir !== null,
|
||||
available: inspection.status === "available",
|
||||
providerVersion: inspection.providerVersion,
|
||||
registrationEnvironment:
|
||||
inspection.status === "available"
|
||||
? {
|
||||
GHIDRA_INSTALL_DIR: inspection.installDir,
|
||||
JAVA_HOME: inspection.javaHome,
|
||||
}
|
||||
: {},
|
||||
checks: selectedChecks(inspection).map((check) =>
|
||||
projectCheck(check, inspection.installDir !== null),
|
||||
),
|
||||
});
|
||||
): DoctorProviderInspection => {
|
||||
const windowsAuthorityUnavailable =
|
||||
inspection.status === "available" &&
|
||||
inspection.platform === "win32" &&
|
||||
!hasWindowsNativeAuthority(inspection.platform);
|
||||
return {
|
||||
id: "ghidra",
|
||||
configured: inspection.installDir !== null,
|
||||
available:
|
||||
inspection.status === "available" && !windowsAuthorityUnavailable,
|
||||
providerVersion: inspection.providerVersion,
|
||||
registrationEnvironment:
|
||||
inspection.status === "available"
|
||||
? {
|
||||
GHIDRA_INSTALL_DIR: inspection.installDir,
|
||||
JAVA_HOME: inspection.javaHome,
|
||||
}
|
||||
: {},
|
||||
checks: [
|
||||
...selectedChecks(inspection).map((check) =>
|
||||
projectCheck(check, inspection.installDir !== null),
|
||||
),
|
||||
...(inspection.status === "available" && inspection.platform === "win32"
|
||||
? [
|
||||
{
|
||||
name: "native_authority",
|
||||
ok: !windowsAuthorityUnavailable,
|
||||
code: windowsAuthorityUnavailable ? "unsupported_host" : null,
|
||||
detail: windowsAuthorityUnavailable
|
||||
? windowsNativeAuthorityUnavailableReason(inspection.platform)
|
||||
: "Verified Windows native Job Object, private DACL, and reparse-safe handle controls; local NTFS only.",
|
||||
remediation: windowsAuthorityUnavailable
|
||||
? "Use the matching Windows x64 REA package with its bundled native addon and a writable local NTFS temporary directory. The native failure above identifies the failed constraint; Ghidra installation or registration changes cannot enable a missing native backend."
|
||||
: null,
|
||||
classification: "unsupported_host" as const,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
],
|
||||
};
|
||||
};
|
||||
|
||||
/** Inspect the process-configured BYO Ghidra installation for `rea doctor`. */
|
||||
export const inspectSystemGhidraProvider =
|
||||
|
||||
@@ -487,7 +487,7 @@ const systemGhidraInstallationHost = (): GhidraInstallationHost => ({
|
||||
probeJava(command, environment) {
|
||||
const observed = spawnSync(
|
||||
command,
|
||||
["-XshowSettings:properties", "-version"],
|
||||
["-XX:-UsePerfData", "-XshowSettings:properties", "-version"],
|
||||
{
|
||||
encoding: "utf8",
|
||||
env: environment,
|
||||
|
||||
@@ -3,6 +3,8 @@ import { basename, dirname, join, win32 } from "node:path";
|
||||
|
||||
import writeFileAtomic from "write-file-atomic";
|
||||
|
||||
import { windowsPrivateRuntime } from "../windows/WindowsPrivateRuntime.js";
|
||||
|
||||
import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
@@ -80,17 +82,8 @@ export class GhidraHeadlessLauncher implements GhidraLauncher {
|
||||
const platform = this.options.platform ?? process.platform;
|
||||
let started: SpawnedOwnedProviderProcess | undefined;
|
||||
try {
|
||||
await Promise.all(
|
||||
[
|
||||
paths.projectRoot,
|
||||
paths.homeRoot,
|
||||
paths.tempRoot,
|
||||
paths.cacheRoot,
|
||||
paths.configRoot,
|
||||
paths.dataRoot,
|
||||
].map((path) => mkdir(path, { recursive: true, mode: 0o700 })),
|
||||
);
|
||||
await writeFileAtomic(
|
||||
await createGhidraRuntimeDirectories(paths, platform);
|
||||
await writeGhidraRuntimeFile(
|
||||
paths.descriptorPath,
|
||||
`${JSON.stringify({
|
||||
transport: session.transport,
|
||||
@@ -101,7 +94,7 @@ export class GhidraHeadlessLauncher implements GhidraLauncher {
|
||||
provider_version: session.providerVersion,
|
||||
profile_digest: session.profileDigest,
|
||||
})}\n`,
|
||||
{ encoding: "utf8", mode: 0o600 },
|
||||
platform,
|
||||
);
|
||||
if (isAborted(options.signal))
|
||||
return err(new AnalysisCancelledError("open_binary"));
|
||||
@@ -138,7 +131,7 @@ export class GhidraHeadlessLauncher implements GhidraLauncher {
|
||||
platform,
|
||||
env: ghidraLaunchEnvironment(paths, this.options.javaHome, platform),
|
||||
});
|
||||
await writeFileAtomic(
|
||||
await writeGhidraRuntimeFile(
|
||||
paths.ownershipPath,
|
||||
`${JSON.stringify({
|
||||
run_id: session.runId,
|
||||
@@ -146,13 +139,11 @@ export class GhidraHeadlessLauncher implements GhidraLauncher {
|
||||
process_group_id: started.ownership.processGroupId,
|
||||
parent_pid: process.pid,
|
||||
ownership_kind:
|
||||
platform === "win32"
|
||||
? "windows-process-tree-p0"
|
||||
: "posix-process-group",
|
||||
platform === "win32" ? "windows-job-object" : "posix-process-group",
|
||||
launcher: this.options.analyzeHeadlessPath,
|
||||
created_at: new Date().toISOString(),
|
||||
})}\n`,
|
||||
{ encoding: "utf8", mode: 0o600 },
|
||||
platform,
|
||||
);
|
||||
if (isAborted(options.signal)) {
|
||||
await cleanupStartedProcess(started, platform);
|
||||
@@ -258,9 +249,11 @@ const cleanupStartedProcess = (
|
||||
started: SpawnedOwnedProviderProcess,
|
||||
platform: NodeJS.Platform,
|
||||
): Promise<ProcessCleanupResult> =>
|
||||
platform === "win32"
|
||||
? cleanupWindowsProcessTree(started.ownership.leaderPid)
|
||||
: cleanupOwnedProcessGroup(started.ownership);
|
||||
started.cleanup !== undefined
|
||||
? started.cleanup()
|
||||
: platform === "win32"
|
||||
? cleanupWindowsProcessTree(started.ownership.leaderPid)
|
||||
: cleanupOwnedProcessGroup(started.ownership);
|
||||
|
||||
/** Paths encoded into one bounded analyzeHeadless invocation. */
|
||||
export interface GhidraHeadlessArgumentOptions {
|
||||
@@ -332,22 +325,62 @@ const ghidraRuntimePaths = (runtimeRoot: string) => ({
|
||||
scriptLogPath: join(runtimeRoot, "script.log"),
|
||||
});
|
||||
|
||||
const createGhidraRuntimeDirectories = async (
|
||||
paths: ReturnType<typeof ghidraRuntimePaths>,
|
||||
platform: NodeJS.Platform,
|
||||
): Promise<void> => {
|
||||
if (platform === "win32") {
|
||||
const runtime = windowsPrivateRuntime(dirname(paths.projectRoot));
|
||||
for (const path of [
|
||||
paths.projectRoot,
|
||||
paths.homeRoot,
|
||||
paths.tempRoot,
|
||||
paths.cacheRoot,
|
||||
paths.configRoot,
|
||||
paths.dataRoot,
|
||||
])
|
||||
runtime.mkdir(basename(path));
|
||||
return;
|
||||
}
|
||||
await Promise.all(
|
||||
[
|
||||
paths.projectRoot,
|
||||
paths.homeRoot,
|
||||
paths.tempRoot,
|
||||
paths.cacheRoot,
|
||||
paths.configRoot,
|
||||
paths.dataRoot,
|
||||
].map((path) => mkdir(path, { recursive: true, mode: 0o700 })),
|
||||
);
|
||||
};
|
||||
|
||||
const writeGhidraRuntimeFile = async (
|
||||
path: string,
|
||||
content: string,
|
||||
platform: NodeJS.Platform,
|
||||
): Promise<void> => {
|
||||
if (platform === "win32") {
|
||||
windowsPrivateRuntime(dirname(path)).writeFile(basename(path), content);
|
||||
return;
|
||||
}
|
||||
await writeFileAtomic(path, content, { encoding: "utf8", mode: 0o600 });
|
||||
};
|
||||
|
||||
const ghidraLaunchEnvironment = (
|
||||
paths: ReturnType<typeof ghidraRuntimePaths>,
|
||||
javaHome: string | undefined,
|
||||
platform: NodeJS.Platform,
|
||||
): NodeJS.ProcessEnv => {
|
||||
// analyzeHeadless.bat wraps GHIDRA_HEADLESS_JAVA_OPTIONS in its own quotes
|
||||
// when it builds VMARG_LIST. Nested quotes break cmd.exe tokenization before
|
||||
// Ghidra starts, so keep this option list unquoted on every platform.
|
||||
const javaOptions = `-Duser.home=${paths.homeRoot} -Djava.io.tmpdir=${paths.tempRoot}`;
|
||||
return {
|
||||
...ghidraJavaEnvironment(javaHome, process.env, platform),
|
||||
...ghidraHeadlessJavaOptions(paths.homeRoot, paths.tempRoot, platform),
|
||||
HOME: paths.homeRoot,
|
||||
TMPDIR: paths.tempRoot,
|
||||
...(platform === "win32"
|
||||
? {
|
||||
USERPROFILE: paths.homeRoot,
|
||||
APPDATA: paths.configRoot,
|
||||
LOCALAPPDATA: paths.cacheRoot,
|
||||
TEMP: paths.tempRoot,
|
||||
TMP: paths.tempRoot,
|
||||
}
|
||||
@@ -355,8 +388,33 @@ const ghidraLaunchEnvironment = (
|
||||
XDG_CACHE_HOME: paths.cacheRoot,
|
||||
XDG_CONFIG_HOME: paths.configRoot,
|
||||
XDG_DATA_HOME: paths.dataRoot,
|
||||
GHIDRA_HEADLESS_JAVA_OPTIONS: javaOptions,
|
||||
};
|
||||
};
|
||||
|
||||
/** Encode provider-owned JVM paths for the parser that actually consumes them. */
|
||||
export const ghidraHeadlessJavaOptions = (
|
||||
homeRoot: string,
|
||||
tempRoot: string,
|
||||
platform: NodeJS.Platform,
|
||||
): Pick<
|
||||
NodeJS.ProcessEnv,
|
||||
"JDK_JAVA_OPTIONS" | "GHIDRA_HEADLESS_JAVA_OPTIONS"
|
||||
> => {
|
||||
const options = [`-Duser.home=${homeRoot}`, `-Djava.io.tmpdir=${tempRoot}`];
|
||||
// analyzeHeadless.bat quotes VMARG_LIST, then launch.bat expands it again.
|
||||
// Inner quotes fail in cmd.exe; unquoted paths with spaces split at the JVM.
|
||||
// JDK_JAVA_OPTIONS is parsed by Java itself, outside that batch expansion.
|
||||
return platform === "win32"
|
||||
? {
|
||||
JDK_JAVA_OPTIONS: [...options, "-XX:-UsePerfData"]
|
||||
.map(quoteWindowsBatchToken)
|
||||
.join(" "),
|
||||
GHIDRA_HEADLESS_JAVA_OPTIONS: "",
|
||||
}
|
||||
: {
|
||||
JDK_JAVA_OPTIONS: "",
|
||||
GHIDRA_HEADLESS_JAVA_OPTIONS: options.join(" "),
|
||||
};
|
||||
};
|
||||
|
||||
const isAborted = (signal?: AbortSignal): boolean => signal?.aborted === true;
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { ghidraHeadlessJavaOptions } from "./GhidraLauncher.js";
|
||||
|
||||
describe("Ghidra headless JVM environment", () => {
|
||||
it("passes Windows paths with spaces to Java's environment parser", () => {
|
||||
expect(
|
||||
ghidraHeadlessJavaOptions(
|
||||
"C:\\REA Runtime\\home",
|
||||
"C:\\REA Runtime\\tmp",
|
||||
"win32",
|
||||
),
|
||||
).toEqual({
|
||||
JDK_JAVA_OPTIONS:
|
||||
'"-Duser.home=C:\\REA Runtime\\home" "-Djava.io.tmpdir=C:\\REA Runtime\\tmp" "-XX:-UsePerfData"',
|
||||
GHIDRA_HEADLESS_JAVA_OPTIONS: "",
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["linux", "darwin"] as const)(
|
||||
"keeps the %s headless-script option list and clears inherited JDK options",
|
||||
(platform) => {
|
||||
expect(
|
||||
ghidraHeadlessJavaOptions("/tmp/rea/home", "/tmp/rea/tmp", platform),
|
||||
).toEqual({
|
||||
JDK_JAVA_OPTIONS: "",
|
||||
GHIDRA_HEADLESS_JAVA_OPTIONS:
|
||||
"-Duser.home=/tmp/rea/home -Djava.io.tmpdir=/tmp/rea/tmp",
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["%TEMP%", 'quote"', "amp&", "line\n", "nul\0"])(
|
||||
"rejects interpreter metacharacters in either Windows JVM path: %s",
|
||||
(suffix) => {
|
||||
for (const [home, temp] of [
|
||||
[`C:\\runtime\\${suffix}`, "C:\\runtime\\tmp"],
|
||||
["C:\\runtime\\home", `C:\\runtime\\${suffix}`],
|
||||
] as const)
|
||||
expect(() => ghidraHeadlessJavaOptions(home, temp, "win32")).toThrow(
|
||||
/metacharacters/u,
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -224,7 +224,9 @@ describe("Ghidra platform support", () => {
|
||||
expect(ghidra.inspectAvailability()).toMatchObject({
|
||||
status: "unavailable",
|
||||
code: "unsupported_host",
|
||||
reason: expect.stringContaining("native authority is unavailable"),
|
||||
reason: expect.stringContaining(
|
||||
"Windows native controls are unavailable",
|
||||
),
|
||||
diagnostics: {
|
||||
windows_security: {
|
||||
job_object_process_ownership: expect.objectContaining({
|
||||
@@ -249,8 +251,12 @@ describe("Ghidra platform support", () => {
|
||||
available: false,
|
||||
availabilityCode: "unsupported_host",
|
||||
limitations: expect.arrayContaining([
|
||||
expect.stringContaining("bounded taskkill cleanup"),
|
||||
expect.stringContaining("private DACL enforcement"),
|
||||
expect.stringContaining(
|
||||
"matching packaged Windows x64 native addon",
|
||||
),
|
||||
expect.stringContaining(
|
||||
"private DACLs, and Job Object ownership automatically",
|
||||
),
|
||||
]),
|
||||
}),
|
||||
]),
|
||||
@@ -354,6 +360,7 @@ describe("Ghidra client projection", () => {
|
||||
expect(factoryOptions).toEqual([
|
||||
expect.objectContaining({
|
||||
runId: "11111111-1111-4111-8111-111111111111",
|
||||
platform: "linux",
|
||||
}),
|
||||
]);
|
||||
expect(toolCalls).toEqual([
|
||||
|
||||
@@ -58,7 +58,7 @@ import { resolveGhidraAnalysisProfile } from "./GhidraAnalysisProfile.js";
|
||||
import type { GhidraSessionError } from "./GhidraSessionError.js";
|
||||
import {
|
||||
CAPABILITIES,
|
||||
WINDOWS_P0_CAPABILITIES,
|
||||
windowsP0Capabilities,
|
||||
GHIDRA_PROVIDER_IDENTITY,
|
||||
GHIDRA_PROVIDER_TOOL_CONTRACTS,
|
||||
healthLimitations,
|
||||
@@ -66,7 +66,7 @@ import {
|
||||
limitationsFor,
|
||||
} from "./GhidraProviderCapabilities.js";
|
||||
import {
|
||||
WINDOWS_NATIVE_AUTHORITY_UNAVAILABLE_REASON,
|
||||
windowsNativeAuthorityUnavailableReason,
|
||||
hasWindowsNativeAuthority,
|
||||
windowsNativeCapabilities,
|
||||
} from "../process/WindowsAuthority.js";
|
||||
@@ -99,7 +99,7 @@ export class GhidraProvider implements AnalysisProviderCandidate {
|
||||
|
||||
capabilities(): readonly CapabilityDescriptor[] {
|
||||
return (this.installationHost?.platform ?? process.platform) === "win32"
|
||||
? WINDOWS_P0_CAPABILITIES
|
||||
? windowsP0Capabilities()
|
||||
: CAPABILITIES;
|
||||
}
|
||||
|
||||
@@ -114,7 +114,7 @@ export class GhidraProvider implements AnalysisProviderCandidate {
|
||||
return {
|
||||
status: "unavailable",
|
||||
code: "unsupported_host",
|
||||
reason: WINDOWS_NATIVE_AUTHORITY_UNAVAILABLE_REASON,
|
||||
reason: windowsNativeAuthorityUnavailableReason(installation.platform),
|
||||
diagnostics: {
|
||||
...diagnostics,
|
||||
windows_security: jsonObjectSchema.parse(
|
||||
@@ -213,6 +213,7 @@ export class GhidraProvider implements AnalysisProviderCandidate {
|
||||
]
|
||||
: [];
|
||||
const client = this.clientFactory({
|
||||
platform: installation.platform,
|
||||
launcher: new GhidraHeadlessLauncher({
|
||||
analyzeHeadlessPath: prerequisites.value.analyzeHeadlessPath,
|
||||
...(this.config.ghidraJavaHome === undefined
|
||||
@@ -225,7 +226,10 @@ export class GhidraProvider implements AnalysisProviderCandidate {
|
||||
...(target.format === "dos-com" ? { dosCom: true } : {}),
|
||||
platform: installation.platform,
|
||||
}),
|
||||
targetPath: target.path,
|
||||
targetPath:
|
||||
installation.platform === "win32"
|
||||
? (target.sourcePath ?? target.path)
|
||||
: target.path,
|
||||
targetSha256: target.sha256,
|
||||
transport:
|
||||
installation.platform === "win32"
|
||||
@@ -450,7 +454,7 @@ const ghidraClientPrerequisites = (
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
"ghidra",
|
||||
"health",
|
||||
WINDOWS_NATIVE_AUTHORITY_UNAVAILABLE_REASON,
|
||||
windowsNativeAuthorityUnavailableReason(installation.platform),
|
||||
),
|
||||
);
|
||||
if (profile === undefined || profile.provider.id !== "ghidra")
|
||||
|
||||
@@ -2,7 +2,10 @@ import type {
|
||||
CapabilityDescriptor,
|
||||
ProviderIdentity,
|
||||
} from "../application/AnalysisProvider.js";
|
||||
import { WINDOWS_NATIVE_AUTHORITY_UNAVAILABLE_REASON } from "../process/WindowsAuthority.js";
|
||||
import {
|
||||
hasWindowsNativeAuthority,
|
||||
windowsNativeAuthorityUnavailableReason,
|
||||
} from "../process/WindowsAuthority.js";
|
||||
import { GENERATED_MCP_TOOL_CATALOG } from "../generatedMcpToolCatalog.js";
|
||||
import { GHIDRA_FUNCTION_OPERATIONS } from "./GhidraFunctionValues.js";
|
||||
import { GHIDRA_INVENTORY_OPERATIONS } from "./GhidraInventoryValues.js";
|
||||
@@ -44,7 +47,7 @@ export const healthLimitations = Object.freeze([
|
||||
export const windowsP0Limitations = Object.freeze([
|
||||
"Windows Ghidra P0 accepts approved native x86-64 PE applications only; DLL, managed, hostile, sensitive, and mutable-path targets are unsupported.",
|
||||
"The Windows bridge uses authenticated IPv4 loopback because Node path-based IPC does not expose Java AF_UNIX sockets; the endpoint file contains no bearer token.",
|
||||
"Windows P0 is not admitted until a native authority proves Job Object ownership, private DACL enforcement, and reparse-safe path admission; bounded taskkill cleanup and chmod(0700) do not prove those controls.",
|
||||
"Windows sessions require the matching packaged Windows x64 native addon, local NTFS targets and runtimes, and Windows 10 or later. Native handles enforce path admission, private DACLs, and Job Object ownership automatically.",
|
||||
]);
|
||||
|
||||
/** Limitation text for one admitted operation, including the common base. */
|
||||
@@ -172,18 +175,23 @@ export const CAPABILITIES: readonly CapabilityDescriptor[] = Object.freeze(
|
||||
);
|
||||
|
||||
/** Capabilities advertised for the experimental Windows x64 P0 boundary. */
|
||||
export const WINDOWS_P0_CAPABILITIES: readonly CapabilityDescriptor[] =
|
||||
Object.freeze(
|
||||
CAPABILITIES.map((capability) =>
|
||||
Object.freeze({
|
||||
...capability,
|
||||
available: false,
|
||||
reason: WINDOWS_NATIVE_AUTHORITY_UNAVAILABLE_REASON,
|
||||
availabilityCode: "unsupported_host" as const,
|
||||
limitations: Object.freeze([
|
||||
...capability.limitations,
|
||||
...windowsP0Limitations,
|
||||
]),
|
||||
}),
|
||||
),
|
||||
export const windowsP0Capabilities = (): readonly CapabilityDescriptor[] => {
|
||||
const available = hasWindowsNativeAuthority("win32");
|
||||
return Object.freeze(
|
||||
CAPABILITIES.map((capability): CapabilityDescriptor => {
|
||||
const limitations = Object.freeze([
|
||||
...capability.limitations,
|
||||
...windowsP0Limitations,
|
||||
]);
|
||||
return available
|
||||
? Object.freeze({ ...capability, limitations })
|
||||
: Object.freeze({
|
||||
...capability,
|
||||
available: false,
|
||||
reason: windowsNativeAuthorityUnavailableReason("win32"),
|
||||
availabilityCode: "unsupported_host",
|
||||
limitations,
|
||||
});
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
@@ -3,10 +3,14 @@ import { constants, createReadStream } from "node:fs";
|
||||
import { chmod, copyFile, rm } from "node:fs/promises";
|
||||
import { extname, join } from "node:path";
|
||||
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { windowsPrivateRuntime } from "../windows/WindowsPrivateRuntime.js";
|
||||
|
||||
/** Immutable target copy admitted to one ephemeral Ghidra import. */
|
||||
export interface GhidraTargetSnapshot {
|
||||
readonly path: string;
|
||||
readonly sha256: string;
|
||||
readonly admission?: JsonValue;
|
||||
}
|
||||
|
||||
/** Copy one target and require its bytes to match the parsed target identity. */
|
||||
@@ -14,6 +18,10 @@ export const createGhidraTargetSnapshot = async (
|
||||
sourcePath: string,
|
||||
runtimeRoot: string,
|
||||
expectedSha256: string,
|
||||
options: {
|
||||
readonly signal?: AbortSignal;
|
||||
readonly platform?: NodeJS.Platform;
|
||||
} = {},
|
||||
): Promise<GhidraTargetSnapshot> => {
|
||||
if (!/^[a-f0-9]{64}$/u.test(expectedSha256))
|
||||
throw new TypeError("Ghidra target SHA-256 commitment is invalid");
|
||||
@@ -22,6 +30,22 @@ export const createGhidraTargetSnapshot = async (
|
||||
runtimeRoot,
|
||||
`target-${expectedSha256.slice(0, 12)}${suffix}`,
|
||||
);
|
||||
if ((options.platform ?? process.platform) === "win32") {
|
||||
const observed = await windowsPrivateRuntime(runtimeRoot).snapshot(
|
||||
sourcePath,
|
||||
`target-${expectedSha256.slice(0, 12)}${suffix}`,
|
||||
options.signal,
|
||||
);
|
||||
if (observed.sha256 !== expectedSha256)
|
||||
throw new Error(
|
||||
`Ghidra target snapshot digest mismatch: expected ${expectedSha256}, observed ${observed.sha256}`,
|
||||
);
|
||||
return {
|
||||
path: snapshotPath,
|
||||
sha256: observed.sha256,
|
||||
admission: { source: observed.source, snapshot: observed.snapshot },
|
||||
};
|
||||
}
|
||||
try {
|
||||
await copyFile(sourcePath, snapshotPath, constants.COPYFILE_EXCL);
|
||||
await chmod(snapshotPath, 0o600);
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { access, open } from "node:fs/promises";
|
||||
|
||||
import { readWindowsPrivateRuntimeFile } from "../windows/WindowsPrivateRuntime.js";
|
||||
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { GhidraSessionError } from "./GhidraSessionError.js";
|
||||
|
||||
@@ -37,6 +39,24 @@ export const observeGhidraEndpoint = async (
|
||||
);
|
||||
}
|
||||
}
|
||||
if (process.platform === "win32") {
|
||||
try {
|
||||
return parseTcpEndpoint(
|
||||
endpoint,
|
||||
readWindowsPrivateRuntimeFile(endpoint.path),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return isMissing(cause) || isWindowsEndpointWriterBusy(cause)
|
||||
? ok(null)
|
||||
: err(
|
||||
endpointFailure(
|
||||
endpoint,
|
||||
"Ghidra endpoint observation failed",
|
||||
cause,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
let handle;
|
||||
try {
|
||||
handle = await open(endpoint.path, "r");
|
||||
@@ -120,3 +140,6 @@ const endpointFailure = (
|
||||
|
||||
const isMissing = (cause: unknown): boolean =>
|
||||
cause instanceof Error && "code" in cause && cause.code === "ENOENT";
|
||||
|
||||
const isWindowsEndpointWriterBusy = (cause: unknown): boolean =>
|
||||
cause instanceof Error && "win32Code" in cause && cause.win32Code === 32;
|
||||
|
||||
@@ -2,6 +2,8 @@ import { chmod, mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { WindowsPrivateRuntime } from "../windows/WindowsPrivateRuntime.js";
|
||||
|
||||
import {
|
||||
windowsNativeCapabilities,
|
||||
type WindowsNativeCapability,
|
||||
@@ -43,7 +45,7 @@ export class PrivateRuntimeRootUnavailableError extends Error {
|
||||
}
|
||||
|
||||
/**
|
||||
* Owns one POSIX mode-0700 temporary runtime root and removes it idempotently.
|
||||
* Owns a private temporary runtime root and removes it idempotently.
|
||||
*
|
||||
* Protocol adapters decide what belongs inside the directory; this primitive
|
||||
* establishes a private filesystem boundary on POSIX and deterministic cleanup.
|
||||
@@ -52,7 +54,10 @@ export class PrivateRuntimeRootUnavailableError extends Error {
|
||||
export class PrivateRuntimeRoot {
|
||||
#closePromise: Promise<void> | undefined;
|
||||
|
||||
private constructor(readonly path: string) {}
|
||||
private constructor(
|
||||
readonly path: string,
|
||||
private readonly windowsRuntime?: WindowsPrivateRuntime,
|
||||
) {}
|
||||
|
||||
/** Allocate a new private runtime root without performing protocol work. */
|
||||
static async create(
|
||||
@@ -62,6 +67,13 @@ export class PrivateRuntimeRoot {
|
||||
const capability = privateRuntimeRootCapability(platform);
|
||||
if (!capability.available)
|
||||
throw new PrivateRuntimeRootUnavailableError(capability.reason);
|
||||
if (platform === "win32") {
|
||||
const runtime = WindowsPrivateRuntime.create(
|
||||
options.parent ?? tmpdir(),
|
||||
options.prefix ?? "rea-provider-",
|
||||
);
|
||||
return new PrivateRuntimeRoot(runtime.observation.path, runtime);
|
||||
}
|
||||
const path = await mkdtemp(
|
||||
join(options.parent ?? tmpdir(), options.prefix ?? "rea-provider-"),
|
||||
);
|
||||
@@ -76,7 +88,10 @@ export class PrivateRuntimeRoot {
|
||||
|
||||
/** Remove the runtime root; concurrent and repeated callers share cleanup. */
|
||||
close(): Promise<void> {
|
||||
this.#closePromise ??= rm(this.path, { recursive: true, force: true });
|
||||
this.#closePromise ??=
|
||||
this.windowsRuntime === undefined
|
||||
? rm(this.path, { recursive: true, force: true })
|
||||
: Promise.resolve().then(() => this.windowsRuntime?.close());
|
||||
return this.#closePromise;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import type { EventEmitter } from "node:events";
|
||||
import type { Readable } from "node:stream";
|
||||
|
||||
import { WindowsOwnedProcess } from "../windows/WindowsOwnedProcess.js";
|
||||
|
||||
import type {
|
||||
OwnedProcessGroup,
|
||||
ProcessCleanupResult,
|
||||
@@ -28,20 +31,34 @@ export interface OwnedProviderProcessSpawnOptions {
|
||||
|
||||
/** Spawned process paired with the identity proof required for group cleanup. */
|
||||
export interface SpawnedOwnedProviderProcess {
|
||||
readonly process: ChildProcess;
|
||||
readonly process: ProviderProcessHandle;
|
||||
readonly ownership: OwnedProcessGroup;
|
||||
readonly cleanup?: () => Promise<ProcessCleanupResult>;
|
||||
}
|
||||
|
||||
/** Process events and streams required by provider lifecycle supervision. */
|
||||
export interface ProviderProcessHandle extends Pick<
|
||||
EventEmitter,
|
||||
"on" | "once" | "off"
|
||||
> {
|
||||
readonly pid?: number | undefined;
|
||||
readonly stdout: Readable | null;
|
||||
readonly stderr: Readable | null;
|
||||
readonly exitCode: number | null;
|
||||
readonly signalCode: NodeJS.Signals | null;
|
||||
kill(signal?: NodeJS.Signals | number): boolean;
|
||||
}
|
||||
|
||||
/** Process handle returned by a provider-specific launcher. */
|
||||
export type ProviderProcessLaunch =
|
||||
| {
|
||||
readonly process: ChildProcess;
|
||||
readonly process: ProviderProcessHandle;
|
||||
readonly ownsProcessLifetime: false;
|
||||
readonly ownership?: never;
|
||||
readonly cleanup?: never;
|
||||
}
|
||||
| {
|
||||
readonly process: ChildProcess;
|
||||
readonly process: ProviderProcessHandle;
|
||||
readonly ownsProcessLifetime: true;
|
||||
readonly ownership?: OwnedProcessGroup;
|
||||
readonly cleanup?: () => Promise<ProcessCleanupResult>;
|
||||
@@ -102,7 +119,7 @@ export type ProviderProcessStopResult =
|
||||
| { readonly status: "incomplete"; readonly reason: string };
|
||||
|
||||
/**
|
||||
* Spawn a provider in a dedicated POSIX process group with an ownership token.
|
||||
* Spawn a provider in an owned Windows job or dedicated POSIX process group.
|
||||
*
|
||||
* The caller remains responsible for persisting any ownership manifest and for
|
||||
* selecting provider-specific command arguments or environment values.
|
||||
@@ -112,17 +129,37 @@ export const spawnOwnedProviderProcess = async (
|
||||
): Promise<SpawnedOwnedProviderProcess> => {
|
||||
const platform = options.platform ?? process.platform;
|
||||
const hostEnvironment = options.hostEnvironment ?? process.env;
|
||||
const environment = {
|
||||
...hostEnvironment,
|
||||
...options.env,
|
||||
REA_PROCESS_RUN_ID: options.runId,
|
||||
};
|
||||
if (platform === "win32" && process.platform === "win32") {
|
||||
const child = new WindowsOwnedProcess(
|
||||
options.command,
|
||||
options.arguments,
|
||||
options.cwd,
|
||||
environment,
|
||||
options.windowsVerbatimArguments ?? false,
|
||||
);
|
||||
return {
|
||||
process: child,
|
||||
ownership: {
|
||||
runId: options.runId,
|
||||
leaderPid: child.pid,
|
||||
processGroupId: child.pid,
|
||||
expectedParentPid: process.pid,
|
||||
},
|
||||
cleanup: () => child.cleanup(),
|
||||
};
|
||||
}
|
||||
const child = spawn(options.command, [...options.arguments], {
|
||||
shell: false,
|
||||
windowsHide: true,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
detached: platform !== "win32",
|
||||
windowsVerbatimArguments: options.windowsVerbatimArguments ?? false,
|
||||
env: {
|
||||
...hostEnvironment,
|
||||
...options.env,
|
||||
REA_PROCESS_RUN_ID: options.runId,
|
||||
},
|
||||
env: environment,
|
||||
...(options.cwd === undefined ? {} : { cwd: options.cwd }),
|
||||
});
|
||||
await waitForSpawn(child);
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
/**
|
||||
* Provider-neutral security controls that require a verified Windows native
|
||||
* authority. Runtime probes and POSIX permissions do not satisfy these
|
||||
* controls.
|
||||
*/
|
||||
import { systemWindowsNativeAuthority } from "../windows/WindowsNativeLoader.js";
|
||||
|
||||
/** Windows controls are proven by the packaged native boundary, not POSIX flags. */
|
||||
export type WindowsNativeCapability =
|
||||
| {
|
||||
readonly available: true;
|
||||
@@ -24,7 +22,7 @@ export interface WindowsNativeCapabilitySet {
|
||||
|
||||
/** Stable explanation used whenever the native Windows authority is absent. */
|
||||
export const WINDOWS_NATIVE_AUTHORITY_UNAVAILABLE_REASON =
|
||||
"Verified Windows native authority is unavailable: Job Object process ownership, private runtime DACL enforcement, and reparse-safe path admission are not implemented; chmod(0700) is insufficient for Windows private DACL proof, and taskkill is not a Job Object security proof";
|
||||
"Windows native controls are unavailable in this runtime; use the Windows x64 REA package with its matching bundled native artifact.";
|
||||
|
||||
/**
|
||||
* Describe native Windows controls without inferring them from taskkill,
|
||||
@@ -46,6 +44,22 @@ export const windowsNativeCapabilities = (
|
||||
};
|
||||
}
|
||||
|
||||
if (process.platform === "win32") {
|
||||
const loaded = systemWindowsNativeAuthority();
|
||||
const capability = loaded.available
|
||||
? ({ available: true, reason: null, proof: "native-authority" } as const)
|
||||
: ({
|
||||
available: false,
|
||||
reason: loaded.reason,
|
||||
proof: "not-proven",
|
||||
} as const);
|
||||
return {
|
||||
job_object_process_ownership: capability,
|
||||
private_runtime_dacl: capability,
|
||||
reparse_safe_path_admission: capability,
|
||||
};
|
||||
}
|
||||
|
||||
const notProven = {
|
||||
available: false,
|
||||
reason: WINDOWS_NATIVE_AUTHORITY_UNAVAILABLE_REASON,
|
||||
@@ -63,3 +77,10 @@ export const hasWindowsNativeAuthority = (platform: NodeJS.Platform): boolean =>
|
||||
Object.values(windowsNativeCapabilities(platform)).every(
|
||||
({ available }) => available,
|
||||
);
|
||||
|
||||
/** Preserve the actual loader or operating-system constraint in provider errors. */
|
||||
export const windowsNativeAuthorityUnavailableReason = (
|
||||
platform: NodeJS.Platform,
|
||||
): string =>
|
||||
windowsNativeCapabilities(platform).job_object_process_ownership.reason ??
|
||||
WINDOWS_NATIVE_AUTHORITY_UNAVAILABLE_REASON;
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
loadWindowsNativeAuthority,
|
||||
type WindowsNativeLoadHost,
|
||||
} from "./WindowsNativeLoader.js";
|
||||
|
||||
const fixture = () => {
|
||||
const bytes = Buffer.alloc(128);
|
||||
bytes.write("MZ");
|
||||
bytes.writeUInt32LE(64, 0x3c);
|
||||
bytes.write("PE\0\0", 64, "ascii");
|
||||
bytes.writeUInt16LE(0x8664, 68);
|
||||
bytes.writeUInt16LE(0x20b, 88);
|
||||
const manifest = {
|
||||
packageVersion: "1.0.0",
|
||||
platform: "win32",
|
||||
architecture: "x64",
|
||||
abiVersion: 1,
|
||||
nodeApiVersion: 8,
|
||||
artifact: "rea-windows-x64.node",
|
||||
artifactSha256: createHash("sha256").update(bytes).digest("hex"),
|
||||
};
|
||||
const identity = {
|
||||
requestedPath: "D:\\fixture\\runtime",
|
||||
finalPath: "\\\\?\\D:\\fixture\\runtime",
|
||||
filesystem: "NTFS",
|
||||
volumeSerial: "0123456789abcdef",
|
||||
fileId: "0123456789abcdef0123456789abcdef",
|
||||
size: 0,
|
||||
directory: true,
|
||||
};
|
||||
let loads = 0;
|
||||
const host: WindowsNativeLoadHost = {
|
||||
platform: "win32",
|
||||
architecture: "x64",
|
||||
nodeApiVersion: "8",
|
||||
packageVersion: "1.0.0",
|
||||
readManifest: () => manifest,
|
||||
readArtifact: () => bytes,
|
||||
loadArtifact: () => {
|
||||
loads++;
|
||||
return {
|
||||
call: () => ({
|
||||
abiVersion: 1,
|
||||
nodeApiVersion: 8,
|
||||
architecture: "x64",
|
||||
filesystem: identity,
|
||||
privateDacl: true,
|
||||
atomicJobAssignment: true,
|
||||
killOnOwnerClose: true,
|
||||
}),
|
||||
};
|
||||
},
|
||||
};
|
||||
return { host, manifest, bytes, loads: () => loads };
|
||||
};
|
||||
|
||||
describe("packaged Windows native admission", () => {
|
||||
it("loads only after compatibility and digest checks, preserving producer identity", () => {
|
||||
const value = fixture();
|
||||
expect(loadWindowsNativeAuthority(value.host)).toMatchObject({
|
||||
available: true,
|
||||
authority: {
|
||||
inspection: { filesystem: { requestedPath: "D:\\fixture\\runtime" } },
|
||||
},
|
||||
});
|
||||
expect(value.loads()).toBe(1);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ platform: "linux" as const },
|
||||
{ architecture: "arm64" },
|
||||
{ nodeApiVersion: "7" },
|
||||
{ nodeApiVersion: undefined },
|
||||
{ packageVersion: "2.0.0" },
|
||||
])("rejects incompatible host metadata before loading: %j", (override) => {
|
||||
const value = fixture();
|
||||
expect(
|
||||
loadWindowsNativeAuthority({ ...value.host, ...override }).available,
|
||||
).toBe(false);
|
||||
expect(value.loads()).toBe(0);
|
||||
});
|
||||
|
||||
it("rejects tampering even when the original file was a valid PE image", () => {
|
||||
const value = fixture();
|
||||
value.bytes[127] = 1;
|
||||
expect(loadWindowsNativeAuthority(value.host)).toMatchObject({
|
||||
available: false,
|
||||
reason: expect.stringContaining("SHA-256"),
|
||||
});
|
||||
expect(value.loads()).toBe(0);
|
||||
});
|
||||
|
||||
it.each(["abiVersion", "nodeApiVersion", "architecture", "artifact"])(
|
||||
"rejects invalid manifest %s",
|
||||
(key) => {
|
||||
const value = fixture();
|
||||
expect(
|
||||
loadWindowsNativeAuthority({
|
||||
...value.host,
|
||||
readManifest: () => ({ ...value.manifest, [key]: "invalid" }),
|
||||
}).available,
|
||||
).toBe(false);
|
||||
expect(value.loads()).toBe(0);
|
||||
},
|
||||
);
|
||||
|
||||
it("rejects a digest-valid artifact for another machine", () => {
|
||||
const value = fixture();
|
||||
value.bytes.writeUInt16LE(0xaa64, 68);
|
||||
value.manifest.artifactSha256 = createHash("sha256")
|
||||
.update(value.bytes)
|
||||
.digest("hex");
|
||||
expect(loadWindowsNativeAuthority(value.host)).toMatchObject({
|
||||
available: false,
|
||||
reason: expect.stringContaining("PE32+"),
|
||||
});
|
||||
expect(value.loads()).toBe(0);
|
||||
});
|
||||
|
||||
it("preserves host permission failure rather than promoting a partial probe", () => {
|
||||
const value = fixture();
|
||||
expect(
|
||||
loadWindowsNativeAuthority({
|
||||
...value.host,
|
||||
loadArtifact: () => ({
|
||||
call: () => {
|
||||
throw new Error("private DACL: access denied");
|
||||
},
|
||||
}),
|
||||
}),
|
||||
).toMatchObject({
|
||||
available: false,
|
||||
reason: expect.stringContaining("private DACL: access denied"),
|
||||
});
|
||||
});
|
||||
|
||||
it("requires every inspected native fact", () => {
|
||||
const value = fixture();
|
||||
expect(
|
||||
loadWindowsNativeAuthority({
|
||||
...value.host,
|
||||
loadArtifact: () => ({ call: () => ({ privateDacl: true }) }),
|
||||
}).available,
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,173 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
import { PACKAGE_METADATA } from "../generatedPackageMetadata.js";
|
||||
|
||||
/** A native resource remains opaque until the addon validates its object tag. */
|
||||
export const windowsHandleSchema = z.custom<object>(
|
||||
(value): value is object =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value),
|
||||
);
|
||||
|
||||
/** Observed identity of an opened local NTFS object. */
|
||||
export const windowsFileIdentitySchema = z.strictObject({
|
||||
requestedPath: z.string(),
|
||||
finalPath: z.string(),
|
||||
filesystem: z.literal("NTFS"),
|
||||
volumeSerial: z.string().regex(/^[a-f0-9]{16}$/u),
|
||||
fileId: z.string().regex(/^[a-f0-9]{32}$/u),
|
||||
size: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
|
||||
directory: z.boolean(),
|
||||
});
|
||||
|
||||
/** Metadata bound to one packaged Windows x64 Node-API artifact. */
|
||||
export const windowsNativeManifestSchema = z.strictObject({
|
||||
packageVersion: z.string(),
|
||||
platform: z.literal("win32"),
|
||||
architecture: z.literal("x64"),
|
||||
abiVersion: z.literal(1),
|
||||
nodeApiVersion: z.literal(8),
|
||||
artifact: z.literal("rea-windows-x64.node"),
|
||||
artifactSha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
});
|
||||
|
||||
const inspectionSchema = z.strictObject({
|
||||
abiVersion: z.literal(1),
|
||||
nodeApiVersion: z.literal(8),
|
||||
architecture: z.literal("x64"),
|
||||
filesystem: windowsFileIdentitySchema,
|
||||
privateDacl: z.literal(true),
|
||||
atomicJobAssignment: z.literal(true),
|
||||
killOnOwnerClose: z.literal(true),
|
||||
});
|
||||
|
||||
type NativeCall = (
|
||||
operation: string,
|
||||
arguments_: readonly unknown[],
|
||||
) => unknown;
|
||||
const bindingSchema = z.strictObject({
|
||||
call: z.custom<NativeCall>(
|
||||
(value): value is NativeCall => typeof value === "function",
|
||||
),
|
||||
});
|
||||
|
||||
/** Validated native operations and the observations establishing readiness. */
|
||||
export interface WindowsNativeAuthority {
|
||||
readonly call: NativeCall;
|
||||
readonly inspection: z.infer<typeof inspectionSchema>;
|
||||
}
|
||||
|
||||
/** Availability of the bundled native implementation, including load failures. */
|
||||
export type WindowsNativeLoadResult =
|
||||
| { readonly available: true; readonly authority: WindowsNativeAuthority }
|
||||
| { readonly available: false; readonly reason: string };
|
||||
|
||||
/** Trusted package reads and module loading, replaceable in loader tests. */
|
||||
export interface WindowsNativeLoadHost {
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly architecture: string;
|
||||
readonly nodeApiVersion: string | undefined;
|
||||
readonly packageVersion: string;
|
||||
readManifest(): unknown;
|
||||
readArtifact(): Buffer;
|
||||
loadArtifact(): unknown;
|
||||
}
|
||||
|
||||
/** Validate compatibility and artifact identity before invoking the native addon. */
|
||||
export const loadWindowsNativeAuthority = (
|
||||
host: WindowsNativeLoadHost,
|
||||
): WindowsNativeLoadResult => {
|
||||
if (host.platform !== "win32" || host.architecture !== "x64")
|
||||
return {
|
||||
available: false,
|
||||
reason: "REA Windows native controls require a Windows x64 host.",
|
||||
};
|
||||
try {
|
||||
const manifest = windowsNativeManifestSchema.parse(host.readManifest());
|
||||
if (manifest.packageVersion !== host.packageVersion)
|
||||
throw new Error("Windows native artifact belongs to another REA version");
|
||||
const nodeApiVersion = Number(host.nodeApiVersion);
|
||||
if (!Number.isSafeInteger(nodeApiVersion) || nodeApiVersion < 8)
|
||||
throw new Error("Windows native artifact requires Node-API 8 or newer");
|
||||
const artifact = host.readArtifact();
|
||||
if (
|
||||
createHash("sha256").update(artifact).digest("hex") !==
|
||||
manifest.artifactSha256
|
||||
)
|
||||
throw new Error(
|
||||
"Windows native artifact SHA-256 does not match package metadata",
|
||||
);
|
||||
assertWindowsX64Artifact(artifact);
|
||||
const binding = bindingSchema.parse(host.loadArtifact());
|
||||
const inspection = inspectionSchema.parse(binding.call("inspect", []));
|
||||
return { available: true, authority: { call: binding.call, inspection } };
|
||||
} catch (cause: unknown) {
|
||||
return {
|
||||
available: false,
|
||||
reason: `REA Windows native controls are unavailable: ${cause instanceof Error ? cause.message : String(cause)}`,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const assertWindowsX64Artifact = (bytes: Buffer): void => {
|
||||
if (bytes.length < 64 || bytes.toString("ascii", 0, 2) !== "MZ")
|
||||
throw new Error("Windows native artifact is not a PE image");
|
||||
const offset = bytes.readUInt32LE(0x3c);
|
||||
if (
|
||||
offset > bytes.length - 26 ||
|
||||
bytes.toString("ascii", offset, offset + 4) !== "PE\0\0" ||
|
||||
bytes.readUInt16LE(offset + 4) !== 0x8664 ||
|
||||
bytes.readUInt16LE(offset + 24) !== 0x20b
|
||||
)
|
||||
throw new Error("Windows native artifact is not a Windows x64 PE32+ image");
|
||||
};
|
||||
|
||||
let cached: WindowsNativeLoadResult | undefined;
|
||||
|
||||
/** Load only the package-owned artifact, lazily and once per process. */
|
||||
export const systemWindowsNativeAuthority = (): WindowsNativeLoadResult => {
|
||||
cached ??= loadWindowsNativeAuthority({
|
||||
platform: process.platform,
|
||||
architecture: process.arch,
|
||||
nodeApiVersion: process.versions.napi,
|
||||
packageVersion: PACKAGE_METADATA.version,
|
||||
readManifest: () => {
|
||||
const encoded = readFileSync(
|
||||
new URL("../../native/windows/build/manifest.json", import.meta.url),
|
||||
"utf8",
|
||||
);
|
||||
const value: unknown = JSON.parse(encoded);
|
||||
return value;
|
||||
},
|
||||
readArtifact: () =>
|
||||
readFileSync(
|
||||
new URL(
|
||||
"../../native/windows/build/rea-windows-x64.node",
|
||||
import.meta.url,
|
||||
),
|
||||
),
|
||||
loadArtifact: () => {
|
||||
const value: unknown = createRequire(import.meta.url)(
|
||||
fileURLToPath(
|
||||
new URL(
|
||||
"../../native/windows/build/rea-windows-x64.node",
|
||||
import.meta.url,
|
||||
),
|
||||
),
|
||||
);
|
||||
return value;
|
||||
},
|
||||
});
|
||||
return cached;
|
||||
};
|
||||
|
||||
/** Require the verified backend when an operation depends on native authority. */
|
||||
export const requireWindowsNativeAuthority = (): WindowsNativeAuthority => {
|
||||
const loaded = systemWindowsNativeAuthority();
|
||||
if (!loaded.available) throw new Error(loaded.reason);
|
||||
return loaded.authority;
|
||||
};
|
||||
@@ -0,0 +1,20 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { quoteWindowsProcessArgument } from "./WindowsOwnedProcess.js";
|
||||
|
||||
describe("Windows process argument representation", () => {
|
||||
it.each([
|
||||
["", '""'],
|
||||
["plain", '"plain"'],
|
||||
["two words", '"two words"'],
|
||||
['embedded"quote', '"embedded\\"quote"'],
|
||||
["D:\\folder\\", '"D:\\folder\\\\"'],
|
||||
['slash\\"quote', '"slash\\\\\\"quote"'],
|
||||
])("quotes %j without changing its CRT argument", (input, expected) => {
|
||||
expect(quoteWindowsProcessArgument(input)).toBe(expected);
|
||||
});
|
||||
|
||||
it("rejects NUL before crossing the native boundary", () => {
|
||||
expect(() => quoteWindowsProcessArgument("a\0b")).toThrow("NUL");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,190 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import { PassThrough } from "node:stream";
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
import type { ProcessCleanupResult } from "../process/ProcessOwnership.js";
|
||||
import {
|
||||
requireWindowsNativeAuthority,
|
||||
windowsHandleSchema,
|
||||
type WindowsNativeAuthority,
|
||||
} from "./WindowsNativeLoader.js";
|
||||
|
||||
const launchSchema = z.strictObject({
|
||||
pid: z.number().int().positive().max(0xffff_ffff),
|
||||
handle: windowsHandleSchema,
|
||||
jobAssigned: z.literal(true),
|
||||
killOnOwnerClose: z.literal(true),
|
||||
});
|
||||
const pollSchema = z.strictObject({
|
||||
stdout: z.instanceof(Buffer),
|
||||
stderr: z.instanceof(Buffer),
|
||||
stdoutEnded: z.boolean(),
|
||||
stderrEnded: z.boolean(),
|
||||
exitCode: z.number().int().nonnegative().max(0xffff_ffff).nullable(),
|
||||
activeProcesses: z.number().int().nonnegative(),
|
||||
});
|
||||
|
||||
/** Encode one ordinary Windows argv token using the CRT backslash rules. */
|
||||
export const quoteWindowsProcessArgument = (value: string): string => {
|
||||
if (value.includes("\0"))
|
||||
throw new TypeError("Windows process argument contains NUL");
|
||||
return `"${value.replace(/(\\*)"/gu, '$1$1\\"').replace(/(\\+)$/u, "$1$1")}"`;
|
||||
};
|
||||
|
||||
/** Process events and streams backed by a retained native Job Object. */
|
||||
export class WindowsOwnedProcess extends EventEmitter {
|
||||
readonly stdout = new PassThrough();
|
||||
readonly stderr = new PassThrough();
|
||||
readonly signalCode: NodeJS.Signals | null = null;
|
||||
exitCode: number | null = null;
|
||||
readonly pid: number;
|
||||
readonly #handle: object;
|
||||
readonly #authority: WindowsNativeAuthority;
|
||||
readonly #settled: Promise<void>;
|
||||
#settle: (() => void) | undefined;
|
||||
#closed = false;
|
||||
#verifiedSettlement = false;
|
||||
#failure: string | undefined;
|
||||
#timer: NodeJS.Timeout | undefined;
|
||||
#cleanup: Promise<ProcessCleanupResult> | undefined;
|
||||
|
||||
constructor(
|
||||
command: string,
|
||||
arguments_: readonly string[],
|
||||
cwd: string | undefined,
|
||||
environment: NodeJS.ProcessEnv,
|
||||
verbatim: boolean,
|
||||
) {
|
||||
super();
|
||||
this.#authority = requireWindowsNativeAuthority();
|
||||
const entries = Object.entries(environment)
|
||||
.filter((entry): entry is [string, string] => entry[1] !== undefined)
|
||||
.map(([key, value]) => `${key}=${value}`);
|
||||
const line = [
|
||||
quoteWindowsProcessArgument(command),
|
||||
...arguments_.map((value) =>
|
||||
verbatim ? value : quoteWindowsProcessArgument(value),
|
||||
),
|
||||
].join(" ");
|
||||
const launched = launchSchema.parse(
|
||||
this.#authority.call("process_spawn", [
|
||||
command,
|
||||
line,
|
||||
cwd ?? "",
|
||||
entries,
|
||||
]),
|
||||
);
|
||||
this.pid = launched.pid;
|
||||
this.#handle = launched.handle;
|
||||
this.#settled = new Promise((resolve) => {
|
||||
this.#settle = resolve;
|
||||
});
|
||||
this.#schedule();
|
||||
}
|
||||
|
||||
/** Terminate the retained job, never a PID supplied by another caller. */
|
||||
kill(signal?: NodeJS.Signals | number): boolean {
|
||||
if (signal === 0)
|
||||
return (
|
||||
!this.#closed &&
|
||||
z
|
||||
.number()
|
||||
.parse(this.#authority.call("process_alive", [this.#handle])) > 0
|
||||
);
|
||||
return this.#closed
|
||||
? false
|
||||
: z
|
||||
.boolean()
|
||||
.parse(this.#authority.call("process_terminate", [this.#handle]));
|
||||
}
|
||||
|
||||
/** Terminate and verify that the entire job has settled before releasing it. */
|
||||
cleanup(): Promise<ProcessCleanupResult> {
|
||||
this.#cleanup ??= this.#stop();
|
||||
return this.#cleanup;
|
||||
}
|
||||
|
||||
async #stop(): Promise<ProcessCleanupResult> {
|
||||
if (this.#closed)
|
||||
return this.#verifiedSettlement
|
||||
? { cleaned: true, signaled: false }
|
||||
: {
|
||||
cleaned: false,
|
||||
reason:
|
||||
this.#failure ?? "Windows Job Object settlement was not verified",
|
||||
};
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
try {
|
||||
const signaled = this.kill();
|
||||
const settled = await Promise.race([
|
||||
this.#settled.then(() => true),
|
||||
new Promise<boolean>((resolve) => {
|
||||
timer = setTimeout(() => resolve(false), 5_000);
|
||||
}),
|
||||
]);
|
||||
return settled && this.#verifiedSettlement
|
||||
? { cleaned: true, signaled }
|
||||
: {
|
||||
cleaned: false,
|
||||
reason:
|
||||
this.#failure ??
|
||||
"Windows Job Object did not settle within the cleanup deadline",
|
||||
};
|
||||
} catch (cause: unknown) {
|
||||
return {
|
||||
cleaned: false,
|
||||
reason: cause instanceof Error ? cause.message : String(cause),
|
||||
};
|
||||
} finally {
|
||||
if (timer !== undefined) clearTimeout(timer);
|
||||
if (!this.#closed) this.#release();
|
||||
}
|
||||
}
|
||||
|
||||
#schedule(): void {
|
||||
this.#timer = setTimeout(() => this.#poll(), 25);
|
||||
}
|
||||
|
||||
#poll(): void {
|
||||
if (this.#closed) return;
|
||||
try {
|
||||
const state = pollSchema.parse(
|
||||
this.#authority.call("process_poll", [this.#handle]),
|
||||
);
|
||||
if (state.stdout.length > 0) this.stdout.write(state.stdout);
|
||||
if (state.stderr.length > 0) this.stderr.write(state.stderr);
|
||||
if (state.exitCode !== null && this.exitCode === null) {
|
||||
this.exitCode = state.exitCode;
|
||||
this.emit("exit", state.exitCode, null);
|
||||
}
|
||||
if (
|
||||
state.exitCode !== null &&
|
||||
state.stdoutEnded &&
|
||||
state.stderrEnded &&
|
||||
state.activeProcesses === 0
|
||||
) {
|
||||
this.#verifiedSettlement = true;
|
||||
this.#release();
|
||||
} else this.#schedule();
|
||||
} catch (cause: unknown) {
|
||||
const failure = cause instanceof Error ? cause : new Error(String(cause));
|
||||
this.#failure = failure.message;
|
||||
// Native lifecycle failures belong to the error/cleanup channels, never
|
||||
// the captured stderr observation produced by the child itself.
|
||||
if (this.listenerCount("error") > 0) this.emit("error", failure);
|
||||
this.#release();
|
||||
}
|
||||
}
|
||||
|
||||
#release(): void {
|
||||
if (this.#closed) return;
|
||||
if (this.#timer !== undefined) clearTimeout(this.#timer);
|
||||
this.#authority.call("process_close", [this.#handle]);
|
||||
this.#closed = true;
|
||||
this.stdout.end();
|
||||
this.stderr.end();
|
||||
this.#settle?.();
|
||||
this.emit("close", this.exitCode, null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
import { win32 } from "node:path";
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
requireWindowsNativeAuthority,
|
||||
windowsFileIdentitySchema,
|
||||
windowsHandleSchema,
|
||||
type WindowsNativeAuthority,
|
||||
} from "./WindowsNativeLoader.js";
|
||||
|
||||
const runtimeSchema = windowsFileIdentitySchema.extend({
|
||||
path: z.string(),
|
||||
handle: windowsHandleSchema,
|
||||
privateDacl: z.literal(true),
|
||||
});
|
||||
const snapshotSchema = z.strictObject({
|
||||
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
source: windowsFileIdentitySchema,
|
||||
snapshot: windowsFileIdentitySchema,
|
||||
});
|
||||
const fileSchema = windowsFileIdentitySchema.extend({
|
||||
handle: windowsHandleSchema,
|
||||
});
|
||||
const runtimes = new Map<string, WindowsPrivateRuntime>();
|
||||
|
||||
/** Retain private DACL and path handles until native recursive cleanup settles. */
|
||||
export class WindowsPrivateRuntime {
|
||||
// One native snapshot can own cancellation for this runtime at a time. A
|
||||
// second request throws ERROR_BUSY before #pending or its abort listener is
|
||||
// replaced, so aborting a rejected request cannot cancel the accepted copy.
|
||||
#pending: Promise<unknown> | undefined;
|
||||
#closed = false;
|
||||
#closePromise: Promise<void> | undefined;
|
||||
private constructor(
|
||||
readonly observation: z.infer<typeof runtimeSchema>,
|
||||
private readonly authority: WindowsNativeAuthority,
|
||||
) {}
|
||||
|
||||
/** Create a new directory with its private DACL installed at creation. */
|
||||
static create(parent: string, prefix: string): WindowsPrivateRuntime {
|
||||
const authority = requireWindowsNativeAuthority();
|
||||
const observation = runtimeSchema.parse(
|
||||
authority.call("runtime_create", [parent, prefix]),
|
||||
);
|
||||
const runtime = new WindowsPrivateRuntime(observation, authority);
|
||||
runtimes.set(observation.path.toLowerCase(), runtime);
|
||||
return runtime;
|
||||
}
|
||||
|
||||
/** Open a private child directory through retained, verified parent handles. */
|
||||
mkdir(relativePath: string): void {
|
||||
this.authority.call("runtime_mkdir", [
|
||||
this.observation.handle,
|
||||
relativePath,
|
||||
]);
|
||||
}
|
||||
|
||||
/** Write a new private file once and retain its immutable handle. */
|
||||
writeFile(relativePath: string, content: string): void {
|
||||
this.authority.call("runtime_write", [
|
||||
this.observation.handle,
|
||||
relativePath,
|
||||
Buffer.from(content),
|
||||
]);
|
||||
}
|
||||
|
||||
/** Copy admitted source bytes and digest the bytes actually written. */
|
||||
async snapshot(
|
||||
sourcePath: string,
|
||||
relativePath: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<z.infer<typeof snapshotSchema>> {
|
||||
// Admission is synchronous; record ownership only after native acceptance.
|
||||
const pending = Promise.resolve(
|
||||
this.authority.call("runtime_snapshot", [
|
||||
this.observation.handle,
|
||||
sourcePath,
|
||||
relativePath,
|
||||
]),
|
||||
);
|
||||
this.#pending = pending;
|
||||
const cancel = (): void => {
|
||||
this.authority.call("runtime_snapshot_cancel", [this.observation.handle]);
|
||||
};
|
||||
signal?.addEventListener("abort", cancel, { once: true });
|
||||
if (signal?.aborted === true) cancel();
|
||||
try {
|
||||
return snapshotSchema.parse(await pending);
|
||||
} finally {
|
||||
signal?.removeEventListener("abort", cancel);
|
||||
if (this.#pending === pending) this.#pending = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/** Read a private endpoint from an opened file, without re-opening its path. */
|
||||
readFile(relativePath: string): string {
|
||||
const file = fileSchema.parse(
|
||||
this.authority.call("runtime_open", [
|
||||
this.observation.handle,
|
||||
relativePath,
|
||||
]),
|
||||
);
|
||||
try {
|
||||
const chunks: Buffer[] = [];
|
||||
for (let offset = 0; offset < file.size;) {
|
||||
const value = z
|
||||
.instanceof(Buffer)
|
||||
.parse(
|
||||
this.authority.call("read", [
|
||||
file.handle,
|
||||
offset,
|
||||
Math.min(65_536, file.size - offset),
|
||||
]),
|
||||
);
|
||||
if (value.length === 0)
|
||||
throw new Error(
|
||||
"Private runtime file ended before its observed size",
|
||||
);
|
||||
offset += value.length;
|
||||
chunks.push(value);
|
||||
}
|
||||
return Buffer.concat(chunks).toString("utf8");
|
||||
} finally {
|
||||
this.authority.call("close", [file.handle]);
|
||||
}
|
||||
}
|
||||
|
||||
/** Remove owned objects by handle, unlinking reparse entries without traversal. */
|
||||
close(): Promise<void> {
|
||||
this.#closePromise ??= this.#remove();
|
||||
return this.#closePromise;
|
||||
}
|
||||
|
||||
async #remove(): Promise<void> {
|
||||
if (this.#closed) return;
|
||||
if (this.#pending !== undefined)
|
||||
this.authority.call("runtime_snapshot_cancel", [this.observation.handle]);
|
||||
await this.#pending?.catch(() => undefined);
|
||||
try {
|
||||
this.authority.call("runtime_close", [this.observation.handle]);
|
||||
} finally {
|
||||
this.#closed = true;
|
||||
runtimes.delete(this.observation.path.toLowerCase());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Select an already-owned runtime; an arbitrary pathname cannot grant authority. */
|
||||
export const windowsPrivateRuntime = (
|
||||
rootPath: string,
|
||||
): WindowsPrivateRuntime => {
|
||||
const runtime = runtimes.get(rootPath.toLowerCase());
|
||||
if (runtime === undefined)
|
||||
throw new Error(`No native private runtime owns ${rootPath}`);
|
||||
return runtime;
|
||||
};
|
||||
|
||||
/** Read a runtime endpoint using the lease that owns its parent directory. */
|
||||
export const readWindowsPrivateRuntimeFile = (path: string): string => {
|
||||
const parent = win32.dirname(path);
|
||||
return windowsPrivateRuntime(parent).readFile(win32.basename(path));
|
||||
};
|
||||
Reference in New Issue
Block a user