fix(tools)!: simplify direct invocation and harden boundary contracts (#555)
Remove REA permission grants, scope ceilings, approval confirmations, and inert settings. Preserve selected local evidence, accept caller-chosen commands and paths, and report actual runtime failures. Harden provider results, schema serialization, snapshot evidence binding, archive paths, source maps, native screenshots, managed EH parsing, and cancellation cleanup. Regenerate tool metadata and document direct invocation. BREAKING CHANGE: Removed permission configuration and policy commands, approval fields, filesystem scope inputs, and fixed confirmation options. Process capture inherits the host environment and accepts command names; callers must refresh tool schemas and migrate removed fields.
This commit is contained in:
@@ -9,7 +9,9 @@ import {
|
||||
type AnalysisOperationPort,
|
||||
} from "./AnalysisProvider.js";
|
||||
import {
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisCancelledError,
|
||||
AnalysisOutputError,
|
||||
AnalysisProtocolError,
|
||||
} from "../domain/errors.js";
|
||||
import { err, ok } from "../domain/result.js";
|
||||
@@ -92,6 +94,111 @@ describe("analysis context queries: navigation", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("analysis context queries: headless document resolution", () => {
|
||||
it("resolves a sole headless document when current-document selection is unavailable", async () => {
|
||||
const calls: string[] = [];
|
||||
const analysis: AnalysisOperationPort = {
|
||||
execute: (operation) => {
|
||||
calls.push(operation);
|
||||
if (operation === "current_document")
|
||||
return Promise.resolve(
|
||||
err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
"ghidra",
|
||||
operation,
|
||||
"headless sessions have no cursor-selected document",
|
||||
),
|
||||
),
|
||||
);
|
||||
if (operation === "list_documents")
|
||||
return Promise.resolve(
|
||||
ok(createAnalysisExecution(["fixture"], provider)),
|
||||
);
|
||||
if (operation === "resolve_containing_procedure")
|
||||
return Promise.resolve(
|
||||
ok(
|
||||
createAnalysisExecution(
|
||||
{
|
||||
query_address: "0x401000",
|
||||
found: false,
|
||||
procedure: null,
|
||||
reason: "not_in_procedure",
|
||||
},
|
||||
provider,
|
||||
),
|
||||
),
|
||||
);
|
||||
return Promise.resolve(
|
||||
err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
"ghidra",
|
||||
operation,
|
||||
"unsupported",
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
await expect(
|
||||
inspectAddressContext(analysis, { address: "0x401000" }),
|
||||
).resolves.toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
document: "fixture",
|
||||
name: { state: "unavailable" },
|
||||
procedure: { state: "available" },
|
||||
comment: { state: "unavailable" },
|
||||
inline_comment: { state: "unavailable" },
|
||||
bookmarks: { state: "unavailable" },
|
||||
},
|
||||
});
|
||||
expect(calls.slice(0, 2)).toEqual(["current_document", "list_documents"]);
|
||||
});
|
||||
|
||||
it("does not use list-documents fallback for non-capability document errors", async () => {
|
||||
const failure = new AnalysisProtocolError(
|
||||
"current-document response malformed",
|
||||
);
|
||||
const calls: string[] = [];
|
||||
const analysis: AnalysisOperationPort = {
|
||||
execute: (operation) => {
|
||||
calls.push(operation);
|
||||
return Promise.resolve(err(failure));
|
||||
},
|
||||
};
|
||||
|
||||
await expect(
|
||||
inspectAddressContext(analysis, { address: "0x401000" }),
|
||||
).resolves.toEqual(err(failure));
|
||||
expect(calls).toEqual(["current_document"]);
|
||||
});
|
||||
|
||||
it("requires exactly one listed document for a headless fallback", async () => {
|
||||
const analysis: AnalysisOperationPort = {
|
||||
execute: (operation) =>
|
||||
Promise.resolve(
|
||||
operation === "current_document"
|
||||
? err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
"ghidra",
|
||||
operation,
|
||||
"no selected document",
|
||||
),
|
||||
)
|
||||
: ok(createAnalysisExecution(["one", "two"], provider)),
|
||||
),
|
||||
};
|
||||
|
||||
await expect(
|
||||
inspectAddressContext(analysis, { address: "0x401000" }),
|
||||
).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: expect.any(AnalysisOutputError),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("analysis context queries: address facets", () => {
|
||||
it("keeps unsupported address facets local and filters bookmarks", async () => {
|
||||
const bookmarkInputs: Readonly<Record<string, unknown>>[] = [];
|
||||
|
||||
@@ -3,8 +3,13 @@ import type {
|
||||
AnalysisOperation,
|
||||
AnalysisOperationPort,
|
||||
} from "./AnalysisProvider.js";
|
||||
import { AnalysisOutputError, type AnalysisError } from "../domain/errors.js";
|
||||
import {
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisOutputError,
|
||||
type AnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { parseDocuments } from "../domain/hopperValues.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
|
||||
type Facet =
|
||||
@@ -138,7 +143,41 @@ const resolveDocument = async (
|
||||
{},
|
||||
executionOptions(signal),
|
||||
);
|
||||
if (!current.ok) return current;
|
||||
if (!current.ok) {
|
||||
if (!(current.error instanceof AnalysisCapabilityUnavailableError))
|
||||
return current;
|
||||
const listed = await analysis.execute(
|
||||
"list_documents",
|
||||
{},
|
||||
executionOptions(signal),
|
||||
);
|
||||
if (!listed.ok) return listed;
|
||||
const parsed = parseDocuments(listed.value.result);
|
||||
if (!parsed.ok)
|
||||
return err(
|
||||
new AnalysisOutputError(
|
||||
"list_documents",
|
||||
"expected one document identity when resolving a headless provider",
|
||||
{ cause: parsed.error },
|
||||
),
|
||||
);
|
||||
if (parsed.value.length !== 1)
|
||||
return err(
|
||||
new AnalysisOutputError(
|
||||
"list_documents",
|
||||
`expected exactly one document identity for a provider without current-document selection, received ${parsed.value.length}`,
|
||||
),
|
||||
);
|
||||
const [documentName] = parsed.value;
|
||||
if (documentName === undefined)
|
||||
return err(
|
||||
new AnalysisOutputError(
|
||||
"list_documents",
|
||||
"provider returned no document identity",
|
||||
),
|
||||
);
|
||||
return ok(documentName);
|
||||
}
|
||||
return typeof current.value.result === "string"
|
||||
? ok(current.value.result)
|
||||
: err(
|
||||
@@ -167,8 +206,7 @@ const isMissingCurrentProcedure = (error: AnalysisError): boolean =>
|
||||
const isRequestLevelFailure = (error: AnalysisError): boolean =>
|
||||
error._tag === "AnalysisCancelledError" ||
|
||||
error._tag === "AnalysisTimeoutError" ||
|
||||
error._tag === "NoBinaryOpenError" ||
|
||||
error._tag === "PermissionRequiredError";
|
||||
error._tag === "NoBinaryOpenError";
|
||||
|
||||
const containingProcedureName = (value: JsonValue): string | null => {
|
||||
if (typeof value !== "object" || value === null || Array.isArray(value))
|
||||
|
||||
@@ -6,7 +6,9 @@ import {
|
||||
ANALYSIS_SNAPSHOT_PROVIDER,
|
||||
ANALYSIS_SNAPSHOT_TARGET,
|
||||
} from "../domain/analysisSnapshot.fixture.js";
|
||||
import { createEvidence } from "../domain/evidence.js";
|
||||
import { createEvidenceBundle } from "../domain/evidenceBundle.js";
|
||||
import { ok } from "../domain/result.js";
|
||||
import { createAnalysisExecution } from "./AnalysisProvider.js";
|
||||
import { AnalysisSnapshotCache } from "./AnalysisSnapshotCache.js";
|
||||
|
||||
@@ -16,7 +18,18 @@ describe("analysis snapshot cache partitioning", () => {
|
||||
const execution = createAnalysisExecution(
|
||||
"main",
|
||||
ANALYSIS_SNAPSHOT_PROVIDER,
|
||||
{ analysisProfile: ANALYSIS_SNAPSHOT_PROFILE },
|
||||
{
|
||||
analysisProfile: ANALYSIS_SNAPSHOT_PROFILE,
|
||||
rawResult: "main",
|
||||
subject: {
|
||||
path: ANALYSIS_SNAPSHOT_TARGET.path,
|
||||
sha256: ANALYSIS_SNAPSHOT_TARGET.sha256,
|
||||
format: ANALYSIS_SNAPSHOT_TARGET.format,
|
||||
...(ANALYSIS_SNAPSHOT_TARGET.architecture === undefined
|
||||
? {}
|
||||
: { architecture: ANALYSIS_SNAPSHOT_TARGET.architecture }),
|
||||
},
|
||||
},
|
||||
);
|
||||
cache.record({
|
||||
target: ANALYSIS_SNAPSHOT_TARGET,
|
||||
@@ -25,13 +38,37 @@ describe("analysis snapshot cache partitioning", () => {
|
||||
parameters: { address: "0x1000", document: "fixture" },
|
||||
execution,
|
||||
});
|
||||
const evidence = createEvidence(
|
||||
ANALYSIS_SNAPSHOT_TARGET,
|
||||
ANALYSIS_SNAPSHOT_PROVIDER,
|
||||
{
|
||||
operation: "address_name",
|
||||
parameters: { address: "0x1000", document: "fixture" },
|
||||
result: "main",
|
||||
rawResult: "main",
|
||||
analysisProfile: ANALYSIS_SNAPSHOT_PROFILE,
|
||||
},
|
||||
);
|
||||
const exported = cache.export(
|
||||
ANALYSIS_SNAPSHOT_TARGET,
|
||||
ANALYSIS_SNAPSHOT_PROFILE,
|
||||
createEvidenceBundle([]),
|
||||
createEvidenceBundle([evidence]),
|
||||
);
|
||||
expect(exported.ok).toBe(true);
|
||||
if (!exported.ok) throw new Error("snapshot export failed");
|
||||
const tampered = structuredClone(exported.value);
|
||||
const tamperedEntry = tampered.entries[0];
|
||||
if (tamperedEntry === undefined)
|
||||
throw new Error("exported snapshot entry missing");
|
||||
tamperedEntry.execution.result = "changed without Evidence";
|
||||
let mergedEvidence = false;
|
||||
expect(
|
||||
new AnalysisSnapshotCache().import(tampered, undefined, () => {
|
||||
mergedEvidence = true;
|
||||
return ok(0);
|
||||
}).ok,
|
||||
).toBe(false);
|
||||
expect(mergedEvidence).toBe(false);
|
||||
const entry = exported.value.entries[0];
|
||||
if (entry === undefined) throw new Error("exported snapshot entry missing");
|
||||
Reflect.set(entry.execution, "provider", {
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
snapshotMatchesProfile,
|
||||
snapshotMatchesTarget,
|
||||
snapshotTarget,
|
||||
parseAnalysisSnapshot,
|
||||
type AnalysisSnapshot,
|
||||
type AnalysisSnapshotEntry,
|
||||
type AnalysisSnapshotBinding,
|
||||
@@ -127,15 +128,28 @@ export class AnalysisSnapshotCache {
|
||||
target: BinaryTarget | undefined,
|
||||
profile: AnalysisProfileCommitment | undefined,
|
||||
evidenceBundle: EvidenceBundle,
|
||||
): Result<AnalysisSnapshot, NoBinaryOpenError> {
|
||||
): Result<AnalysisSnapshot, AnalysisError> {
|
||||
if (target === undefined || profile === undefined)
|
||||
return err(new NoBinaryOpenError());
|
||||
return ok({
|
||||
target: snapshotTarget(target),
|
||||
binding: snapshotBinding(profile),
|
||||
entries: this.entries(),
|
||||
evidence_bundle: structuredClone(evidenceBundle),
|
||||
});
|
||||
try {
|
||||
const snapshotTargetIdentity = snapshotTarget(target);
|
||||
const binding = snapshotBinding(profile);
|
||||
const retainedEvidence = structuredClone(evidenceBundle);
|
||||
return ok(
|
||||
parseAnalysisSnapshot({
|
||||
target: snapshotTargetIdentity,
|
||||
binding,
|
||||
entries: this.entries(),
|
||||
evidence_bundle: retainedEvidence,
|
||||
}),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new EvidenceIntegrityError("Analysis snapshot validation failed", {
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Validate target identity, merge evidence atomically, then stage entries. */
|
||||
@@ -151,18 +165,28 @@ export class AnalysisSnapshotCache {
|
||||
bundle: EvidenceBundle,
|
||||
) => Result<number, EvidenceIntegrityError>,
|
||||
): Result<number, AnalysisError> {
|
||||
let validated: AnalysisSnapshot;
|
||||
try {
|
||||
validated = parseAnalysisSnapshot(snapshot);
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new EvidenceIntegrityError("Analysis snapshot validation failed", {
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (
|
||||
active !== undefined &&
|
||||
(!snapshotMatchesTarget(snapshot.target, active.target) ||
|
||||
!snapshotMatchesProfile(snapshot.binding, active.profile))
|
||||
(!snapshotMatchesTarget(validated.target, active.target) ||
|
||||
!snapshotMatchesProfile(validated.binding, active.profile))
|
||||
)
|
||||
return err(
|
||||
new EvidenceIntegrityError(
|
||||
"Analysis snapshot profile_mismatch: target, provider, or analysis profile does not match the active binary",
|
||||
),
|
||||
);
|
||||
const importedEvidence = mergeEvidence(snapshot.evidence_bundle);
|
||||
return importedEvidence.ok ? ok(this.stage(snapshot)) : importedEvidence;
|
||||
const importedEvidence = mergeEvidence(validated.evidence_bundle);
|
||||
return importedEvidence.ok ? ok(this.stage(validated)) : importedEvidence;
|
||||
}
|
||||
|
||||
/** Return canonical entries for persistence. */
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { PermissionAuthority } from "./PermissionAuthority.js";
|
||||
import { artifactExtractionPermissionRequest } from "./ArtifactExtractionDestination.js";
|
||||
import { createPermissionPolicy } from "../domain/permissionPolicy.js";
|
||||
|
||||
describe("artifact extraction permission", () => {
|
||||
it("authorizes the REA-selected temporary destination with one stable grant", async () => {
|
||||
const request = artifactExtractionPermissionRequest();
|
||||
const { operation_identity: operationIdentity, ...scope } = request;
|
||||
const authority = new PermissionAuthority(
|
||||
createPermissionPolicy(
|
||||
[scope],
|
||||
[
|
||||
{
|
||||
...scope,
|
||||
grant_id: "artifact-extraction-once",
|
||||
lifetime: "once",
|
||||
operation_identity: operationIdentity,
|
||||
expires_at: null,
|
||||
},
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
await expect(authority.authorize(request, "write")).resolves.toMatchObject({
|
||||
ok: true,
|
||||
});
|
||||
await expect(authority.authorize(request, "write")).resolves.toMatchObject({
|
||||
ok: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,22 +1,7 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import type { PermissionRequest } from "../domain/permissionPolicy.js";
|
||||
|
||||
/** Choose a fresh temporary destination for an artifact extraction. */
|
||||
export const createArtifactExtractionDestination = (): string =>
|
||||
join(tmpdir(), `rea-extracted-${randomUUID()}`);
|
||||
|
||||
/** Stable parent scope used to authorize REA-owned extraction destinations. */
|
||||
export const artifactExtractionPermissionRoot = (): string => tmpdir();
|
||||
|
||||
/** Stable filesystem scope for the destination selected internally by REA. */
|
||||
export const artifactExtractionPermissionRequest = (): PermissionRequest => ({
|
||||
capability: "artifact_extract",
|
||||
roots: [artifactExtractionPermissionRoot()],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
network: "none",
|
||||
mount: false,
|
||||
operation_identity: "extract_artifact:temporary_output",
|
||||
});
|
||||
|
||||
@@ -10,7 +10,6 @@ import type {
|
||||
ArtifactIntegrityPolicy,
|
||||
ArtifactInventoryOptions,
|
||||
ArtifactInventorySnapshot,
|
||||
ArtifactNativeMountPolicy,
|
||||
} from "./ArtifactInventory/types.js";
|
||||
|
||||
export { scanCanonicalArtifactInventory } from "./ArtifactInventory/scanCanonical.js";
|
||||
@@ -19,7 +18,6 @@ export type {
|
||||
ArtifactIntegrityPolicy,
|
||||
ArtifactInventoryOptions,
|
||||
ArtifactInventorySnapshot,
|
||||
ArtifactNativeMountPolicy,
|
||||
} from "./ArtifactInventory/types.js";
|
||||
|
||||
/** Inventory one local artifact and return every graph collection inline. */
|
||||
@@ -27,7 +25,6 @@ export const inventoryArtifact = async (
|
||||
inputPath: string,
|
||||
options: {
|
||||
readonly signal?: AbortSignal;
|
||||
readonly nativeMount?: ArtifactNativeMountPolicy;
|
||||
readonly integrity?: ArtifactIntegrityPolicy;
|
||||
} = {},
|
||||
): Promise<ArtifactInventoryResult> => {
|
||||
|
||||
@@ -1,38 +1,11 @@
|
||||
import { ArtifactReaderFailure } from "../../artifacts/ArtifactReader.js";
|
||||
import type {
|
||||
ArtifactIntegrityPolicy,
|
||||
ArtifactNativeMountPolicy,
|
||||
} from "./types.js";
|
||||
import type { ArtifactIntegrityPolicy } from "./types.js";
|
||||
|
||||
/** Parsed caller intent for integrity mismatch handling. */
|
||||
export type ArtifactIntegrityIntent =
|
||||
| { readonly mode: "fail" }
|
||||
| { readonly mode: "record-and-continue" };
|
||||
|
||||
/** Resolve caller approval and operator policy before native reader selection. */
|
||||
export const resolveNativeMountPolicy = (
|
||||
approved: boolean,
|
||||
enabled: boolean,
|
||||
): ArtifactNativeMountPolicy => {
|
||||
if (!approved) return { status: "disabled" };
|
||||
if (!enabled)
|
||||
throw new ArtifactReaderFailure(
|
||||
"unavailable",
|
||||
"Native DMG mounting is disabled by operator policy",
|
||||
);
|
||||
return { status: "approved" };
|
||||
};
|
||||
|
||||
/** Resolve parsed caller intent and operator policy before artifact scanning. */
|
||||
/** Preserve the explicit integrity admission choice without changing verification. */
|
||||
export const resolveArtifactIntegrityPolicy = (
|
||||
intent: ArtifactIntegrityIntent,
|
||||
enabled: boolean,
|
||||
): ArtifactIntegrityPolicy => {
|
||||
if (intent.mode === "fail") return intent;
|
||||
if (!enabled)
|
||||
throw new ArtifactReaderFailure(
|
||||
"policy",
|
||||
"Integrity continuation requires explicit approval and operator policy",
|
||||
);
|
||||
return intent;
|
||||
};
|
||||
): ArtifactIntegrityPolicy => intent;
|
||||
|
||||
@@ -5,12 +5,10 @@ import { MachOSliceArtifactReader } from "../../artifacts/MachOSliceArtifactRead
|
||||
import { NativeDmgArtifactReader } from "../../artifacts/NativeDmgArtifactReader.js";
|
||||
import { ZipArtifactReader } from "../../artifacts/ZipArtifactReader.js";
|
||||
import type { ArtifactNode } from "../../domain/artifactGraph.js";
|
||||
import type { ArtifactNativeMountPolicy } from "./types.js";
|
||||
|
||||
export const createReader = async (
|
||||
path: string,
|
||||
format: ArtifactNode["format"],
|
||||
nativeMount: ArtifactNativeMountPolicy,
|
||||
signal?: AbortSignal,
|
||||
): Promise<ArtifactReader | undefined> => {
|
||||
switch (format) {
|
||||
@@ -29,7 +27,7 @@ export const createReader = async (
|
||||
? new MachOSliceArtifactReader(path)
|
||||
: undefined;
|
||||
case "dmg":
|
||||
if (nativeMount.status === "disabled") return undefined;
|
||||
if (process.platform !== "darwin") return undefined;
|
||||
return NativeDmgArtifactReader.create(path, signal);
|
||||
default:
|
||||
return undefined;
|
||||
@@ -43,7 +41,7 @@ export const inventoryLimitations = (
|
||||
if (reader !== undefined) return [];
|
||||
if (format === "dmg" || format === "pkg")
|
||||
return [
|
||||
`${format.toUpperCase()} root hash is observed; child inventory requires an approved native macOS adapter.`,
|
||||
`${format.toUpperCase()} root hash is observed; child inventory requires a native macOS adapter.`,
|
||||
];
|
||||
if (format === "mach-o-universal" && process.platform !== "darwin")
|
||||
return ["Universal Mach-O slices require the native macOS lipo adapter."];
|
||||
|
||||
@@ -30,7 +30,6 @@ import {
|
||||
type PendingIntegrityContradiction,
|
||||
} from "./scanReader.js";
|
||||
import {
|
||||
NATIVE_MOUNT_DISABLED,
|
||||
STRICT_INTEGRITY_POLICY,
|
||||
type ArtifactInventoryOptions,
|
||||
type ArtifactInventorySnapshot,
|
||||
@@ -46,12 +45,7 @@ export const scanCanonicalArtifactInventory = async (
|
||||
const rootDigest = metadata.isDirectory()
|
||||
? null
|
||||
: await hashReadable(createReadStream(path), options.signal);
|
||||
const reader = await createReader(
|
||||
path,
|
||||
rootFormat,
|
||||
options.nativeMount ?? NATIVE_MOUNT_DISABLED,
|
||||
options.signal,
|
||||
);
|
||||
const reader = await createReader(path, rootFormat, options.signal);
|
||||
|
||||
try {
|
||||
const { nodes, occurrences, pendingContradictions } = await scanReader(
|
||||
|
||||
@@ -4,15 +4,6 @@ import type {
|
||||
IntegrityContradiction,
|
||||
} from "../../domain/artifactGraph.js";
|
||||
|
||||
/** Resolved native mount authority admitted to the artifact reader. */
|
||||
export type ArtifactNativeMountPolicy =
|
||||
| { readonly status: "disabled" }
|
||||
| { readonly status: "approved" };
|
||||
|
||||
export const NATIVE_MOUNT_DISABLED: ArtifactNativeMountPolicy = {
|
||||
status: "disabled",
|
||||
};
|
||||
|
||||
/** Resolved integrity behavior admitted to the artifact scanner. */
|
||||
export type ArtifactIntegrityPolicy =
|
||||
| { readonly mode: "fail" }
|
||||
@@ -25,7 +16,6 @@ export const STRICT_INTEGRITY_POLICY: ArtifactIntegrityPolicy = {
|
||||
/** Options shared by artifact inventory scans. */
|
||||
export interface ArtifactInventoryOptions {
|
||||
readonly signal?: AbortSignal | undefined;
|
||||
readonly nativeMount?: ArtifactNativeMountPolicy | undefined;
|
||||
readonly integrity?: ArtifactIntegrityPolicy | undefined;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,29 +1,14 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
resolveArtifactIntegrityPolicy,
|
||||
resolveNativeMountPolicy,
|
||||
} from "./ArtifactInventory/policy.js";
|
||||
import { resolveArtifactIntegrityPolicy } from "./ArtifactInventory/policy.js";
|
||||
|
||||
describe("artifact inventory policy resolution", () => {
|
||||
it("admits native mounting only when caller and operator both allow it", () => {
|
||||
expect(resolveNativeMountPolicy(false, true)).toEqual({
|
||||
status: "disabled",
|
||||
it("preserves the selected integrity behavior without disabling verification", () => {
|
||||
expect(resolveArtifactIntegrityPolicy({ mode: "fail" })).toEqual({
|
||||
mode: "fail",
|
||||
});
|
||||
expect(() => resolveNativeMountPolicy(true, false)).toThrow(
|
||||
"disabled by operator policy",
|
||||
);
|
||||
expect(resolveNativeMountPolicy(true, true)).toEqual({
|
||||
status: "approved",
|
||||
});
|
||||
});
|
||||
|
||||
it("admits parsed continuation intent only under operator policy", () => {
|
||||
expect(() =>
|
||||
resolveArtifactIntegrityPolicy({ mode: "record-and-continue" }, false),
|
||||
).toThrow("requires explicit approval and operator policy");
|
||||
expect(
|
||||
resolveArtifactIntegrityPolicy({ mode: "record-and-continue" }, true),
|
||||
resolveArtifactIntegrityPolicy({ mode: "record-and-continue" }),
|
||||
).toEqual({ mode: "record-and-continue" });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -7,12 +7,11 @@ import {
|
||||
} from "../domain/analysisProfile.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
ProviderAdapterError,
|
||||
type AnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import type { EvidenceSubjectTarget } from "../domain/evidence.js";
|
||||
import { createEvidence } from "../domain/evidence.js";
|
||||
import type {
|
||||
AnalysisClient,
|
||||
AnalysisExecution,
|
||||
@@ -33,7 +32,11 @@ import {
|
||||
resolveSessionOpen,
|
||||
type BinarySessionOpenOptions,
|
||||
} from "./BinarySessionOpen.js";
|
||||
import { prepareSessionExecution } from "./BinarySessionExecution.js";
|
||||
import {
|
||||
bindExecutionTarget,
|
||||
commitExecutionProfile,
|
||||
prepareSessionExecution,
|
||||
} from "./BinarySessionExecution.js";
|
||||
import { closeAnalysisClient } from "./AnalysisClientCleanup.js";
|
||||
export type { BinarySessionPort } from "./BinarySessionPort.js";
|
||||
const OFFICIAL_OPERATIONS: ReadonlySet<string> = new Set(
|
||||
@@ -211,8 +214,10 @@ export class BinarySession
|
||||
runId,
|
||||
};
|
||||
this.#clearRuntimeAvailability();
|
||||
if (profile === null) this.clearSnapshot();
|
||||
else this.selectSnapshot(target, profile);
|
||||
if (options.snapshot === undefined) {
|
||||
if (profile === null) this.clearSnapshot();
|
||||
else this.selectSnapshot(target, profile);
|
||||
}
|
||||
if (options.snapshot !== undefined) {
|
||||
const imported = this.importAnalysisSnapshot(options.snapshot);
|
||||
if (!imported.ok) {
|
||||
@@ -329,7 +334,22 @@ export class BinarySession
|
||||
name !== "decode_interface_builder" &&
|
||||
name !== "inspect_asset_catalog" &&
|
||||
name !== "inspect_keyed_archive"
|
||||
)
|
||||
) {
|
||||
const evidence = createEvidence(
|
||||
profiled.value.subject ?? active.target,
|
||||
profiled.value.provider,
|
||||
{
|
||||
operation: name,
|
||||
parameters: arguments_,
|
||||
result: profiled.value.result,
|
||||
analysisProfile: profile,
|
||||
rawResult: profiled.value.rawResult,
|
||||
limitations: profiled.value.limitations,
|
||||
locations: profiled.value.locations,
|
||||
},
|
||||
);
|
||||
const recorded = this.recordEvidence(evidence);
|
||||
if (!recorded.ok) return recorded;
|
||||
this.recordSnapshot({
|
||||
target: active.target,
|
||||
profile,
|
||||
@@ -337,7 +357,7 @@ export class BinarySession
|
||||
parameters: arguments_,
|
||||
execution: profiled.value,
|
||||
});
|
||||
else if (profiled.ok && capability?.effects.mutatesArtifact === true) {
|
||||
} else if (profiled.ok && capability?.effects.mutatesArtifact === true) {
|
||||
this.invalidateSnapshot();
|
||||
}
|
||||
return profiled;
|
||||
@@ -495,64 +515,3 @@ export class BinarySession
|
||||
|
||||
const isAborted = (signal: AbortSignal | undefined): boolean =>
|
||||
signal?.aborted === true;
|
||||
|
||||
const commitExecutionProfile = (
|
||||
operation: AnalysisOperation,
|
||||
result: Result<AnalysisExecution, AnalysisError>,
|
||||
profile: AnalysisProfileCommitment | undefined,
|
||||
): Result<AnalysisExecution, AnalysisError> => {
|
||||
if (!result.ok || profile === undefined) return result;
|
||||
const provider = result.value.provider;
|
||||
if (
|
||||
provider.id !== profile.provider.id ||
|
||||
provider.name !== profile.provider.name ||
|
||||
provider.version !== profile.provider.version
|
||||
)
|
||||
return err(
|
||||
new ProviderAdapterError(profile.provider.id, `${operation}:profile`),
|
||||
);
|
||||
return ok({
|
||||
...result.value,
|
||||
analysisProfile: structuredClone(profile),
|
||||
});
|
||||
};
|
||||
|
||||
const bindExecutionTarget = (
|
||||
result: Result<AnalysisExecution, AnalysisError>,
|
||||
operation: AnalysisOperation,
|
||||
target: BinaryTarget,
|
||||
): Result<AnalysisExecution, AnalysisError> => {
|
||||
if (!result.ok) return result;
|
||||
const subject: EvidenceSubjectTarget = {
|
||||
path: target.path,
|
||||
sha256: target.sha256,
|
||||
format:
|
||||
target.format === "analysis-database"
|
||||
? "analysis-database"
|
||||
: target.format,
|
||||
...(target.architecture === undefined
|
||||
? {}
|
||||
: { architecture: target.architecture }),
|
||||
};
|
||||
if (
|
||||
result.value.subject !== null &&
|
||||
result.value.subject.sha256 !== target.sha256
|
||||
) {
|
||||
if (!isArtifactInventorySubject(operation, result.value.subject, target))
|
||||
return err(
|
||||
new ProviderAdapterError(
|
||||
result.value.provider.id,
|
||||
`${operation}:subject`,
|
||||
),
|
||||
);
|
||||
}
|
||||
return ok({ ...result.value, subject: result.value.subject ?? subject });
|
||||
};
|
||||
|
||||
const isArtifactInventorySubject = (
|
||||
operation: AnalysisOperation,
|
||||
subject: EvidenceSubjectTarget,
|
||||
target: BinaryTarget,
|
||||
): boolean =>
|
||||
(operation === "inventory_artifact" || operation === "inspect_artifact") &&
|
||||
subject.path === (target.sourcePath ?? target.path);
|
||||
|
||||
@@ -3,9 +3,11 @@ import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import {
|
||||
AnalysisCapabilityUnavailableError,
|
||||
NoBinaryOpenError,
|
||||
ProviderAdapterError,
|
||||
type AnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import type { EvidenceSubjectTarget } from "../domain/evidence.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import type {
|
||||
AnalysisClient,
|
||||
@@ -88,3 +90,65 @@ export const prepareSessionExecution = (
|
||||
: undefined;
|
||||
return ok({ active, capability, profile, cacheable, cached });
|
||||
};
|
||||
|
||||
/** Attach the selected profile only when the provider identity agrees. */
|
||||
export const commitExecutionProfile = (
|
||||
operation: AnalysisOperation,
|
||||
result: Result<AnalysisExecution, AnalysisError>,
|
||||
profile: AnalysisProfileCommitment | undefined,
|
||||
): Result<AnalysisExecution, AnalysisError> => {
|
||||
if (!result.ok || profile === undefined) return result;
|
||||
const provider = result.value.provider;
|
||||
if (
|
||||
provider.id !== profile.provider.id ||
|
||||
provider.name !== profile.provider.name ||
|
||||
provider.version !== profile.provider.version
|
||||
)
|
||||
return err(
|
||||
new ProviderAdapterError(profile.provider.id, `${operation}:profile`),
|
||||
);
|
||||
return ok({
|
||||
...result.value,
|
||||
analysisProfile: structuredClone(profile),
|
||||
});
|
||||
};
|
||||
|
||||
/** Bind an execution to the selected target, preserving valid artifact subjects. */
|
||||
export const bindExecutionTarget = (
|
||||
result: Result<AnalysisExecution, AnalysisError>,
|
||||
operation: AnalysisOperation,
|
||||
target: BinaryTarget,
|
||||
): Result<AnalysisExecution, AnalysisError> => {
|
||||
if (!result.ok) return result;
|
||||
const subject: EvidenceSubjectTarget = {
|
||||
path: target.path,
|
||||
sha256: target.sha256,
|
||||
format:
|
||||
target.format === "analysis-database"
|
||||
? "analysis-database"
|
||||
: target.format,
|
||||
...(target.architecture === undefined
|
||||
? {}
|
||||
: { architecture: target.architecture }),
|
||||
};
|
||||
if (
|
||||
result.value.subject !== null &&
|
||||
result.value.subject.sha256 !== target.sha256 &&
|
||||
!isArtifactInventorySubject(operation, result.value.subject, target)
|
||||
)
|
||||
return err(
|
||||
new ProviderAdapterError(
|
||||
result.value.provider.id,
|
||||
`${operation}:subject`,
|
||||
),
|
||||
);
|
||||
return ok({ ...result.value, subject: result.value.subject ?? subject });
|
||||
};
|
||||
|
||||
const isArtifactInventorySubject = (
|
||||
operation: AnalysisOperation,
|
||||
subject: EvidenceSubjectTarget,
|
||||
target: BinaryTarget,
|
||||
): boolean =>
|
||||
(operation === "inventory_artifact" || operation === "inspect_artifact") &&
|
||||
subject.path === (target.sourcePath ?? target.path);
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
type EvidenceObservation,
|
||||
} from "../domain/evidence.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
|
||||
import type {
|
||||
BrowserTargetList,
|
||||
InspectWebPageInput,
|
||||
@@ -63,7 +64,7 @@ type BrowserEvidenceOperation =
|
||||
| "capture_web_screenshot"
|
||||
| "compare_web_screenshots";
|
||||
|
||||
/** Create Evidence for a policy-scoped external browser observation. */
|
||||
/** Create Evidence for one request-scoped external browser observation. */
|
||||
export const createBrowserEvidence = (
|
||||
operation: BrowserEvidenceOperation,
|
||||
input: BrowserEvidenceInput,
|
||||
@@ -73,7 +74,7 @@ export const createBrowserEvidence = (
|
||||
createEvidence(undefined, provider, {
|
||||
predicateType: browserPredicate(operation),
|
||||
operation,
|
||||
parameters: browserParameters(input),
|
||||
parameters: browserParameters(input, result),
|
||||
result: jsonValueSchema.parse(result),
|
||||
confidence: "observed",
|
||||
authority: "external-service",
|
||||
@@ -91,6 +92,7 @@ export const createBrowserEvidence = (
|
||||
|
||||
const browserParameters = (
|
||||
input: BrowserEvidenceInput,
|
||||
result: BrowserEvidenceResult,
|
||||
): EvidenceObservation["parameters"] => {
|
||||
if (!("cdp_endpoint" in input)) {
|
||||
if (
|
||||
@@ -129,9 +131,15 @@ const browserParameters = (
|
||||
};
|
||||
throw new Error("Browser comparison input did not match a comparison type");
|
||||
}
|
||||
const observedOrigin = browserResultTargetOrigin(result);
|
||||
const scope = {
|
||||
cdp_endpoint: input.cdp_endpoint,
|
||||
allowed_origins: input.allowed_origins,
|
||||
allowed_origins:
|
||||
input.allowed_origins.length > 0
|
||||
? input.allowed_origins
|
||||
: "target_id" in input && observedOrigin !== undefined
|
||||
? [observedOrigin]
|
||||
: [],
|
||||
};
|
||||
if (!("target_id" in input)) return scope;
|
||||
return {
|
||||
@@ -159,6 +167,27 @@ const browserParameters = (
|
||||
};
|
||||
};
|
||||
|
||||
const browserResultTargetOrigin = (
|
||||
result: BrowserEvidenceResult,
|
||||
): string | undefined => {
|
||||
if (
|
||||
"inspection" in result &&
|
||||
typeof result.inspection === "object" &&
|
||||
result.inspection !== null &&
|
||||
"target" in result.inspection &&
|
||||
typeof result.inspection.target === "object" &&
|
||||
result.inspection.target !== null &&
|
||||
"origin" in result.inspection.target &&
|
||||
typeof result.inspection.target.origin === "string"
|
||||
)
|
||||
return result.inspection.target.origin;
|
||||
if (!("target" in result)) return undefined;
|
||||
if ("origin" in result.target) return result.target.origin;
|
||||
if ("initial_url" in result.target)
|
||||
return sanitizeBrowserUrl(result.target.initial_url).origin ?? undefined;
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const isScreenshotComparison = (
|
||||
input: BrowserEvidenceInput,
|
||||
): input is CompareWebScreenshotsInput => "channel_threshold" in input;
|
||||
|
||||
@@ -2,47 +2,23 @@ import { describe, expect, it } from "vitest";
|
||||
|
||||
import { listBrowserTargetsInputSchema } from "../domain/browserObservation.js";
|
||||
import { listBrowserTargets } from "./BrowserObservationService.js";
|
||||
import { createPermissionAuthority } from "./PermissionAuthority.js";
|
||||
|
||||
describe("browser observation authorization", () => {
|
||||
it("requests loopback authority for an IPv6-only browser origin", async () => {
|
||||
describe("browser observation service prerequisites", () => {
|
||||
it("reports a missing provider without requiring a permission grant", async () => {
|
||||
const endpoint = "http://127.0.0.1:9222";
|
||||
const origin = "http://[::1]:3000";
|
||||
const ceiling = {
|
||||
capability: "browser_observe" as const,
|
||||
roots: [],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
origins: [endpoint, origin],
|
||||
network: "loopback" as const,
|
||||
mount: false,
|
||||
};
|
||||
const authority = await createPermissionAuthority(
|
||||
[ceiling],
|
||||
[
|
||||
{
|
||||
...ceiling,
|
||||
grant_id: "administrator:browser_observe",
|
||||
lifetime: "administrator",
|
||||
operation_identity: null,
|
||||
expires_at: null,
|
||||
},
|
||||
],
|
||||
);
|
||||
if (!authority.ok) throw authority.error;
|
||||
|
||||
const result = await listBrowserTargets(
|
||||
undefined,
|
||||
authority.value,
|
||||
listBrowserTargetsInputSchema.parse({
|
||||
cdp_endpoint: endpoint,
|
||||
allowed_origins: [origin],
|
||||
approved: true,
|
||||
}),
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisCapabilityUnavailableError" },
|
||||
error: {
|
||||
_tag: "AnalysisCapabilityUnavailableError",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
import { projectPermissionFailure } from "./PermissionFailure.js";
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
import {
|
||||
isLiteralLoopbackHostname,
|
||||
type InspectWebPageInput,
|
||||
type ListBrowserTargetsInput,
|
||||
import type {
|
||||
InspectWebPageInput,
|
||||
ListBrowserTargetsInput,
|
||||
} from "../domain/browserObservation.js";
|
||||
import type { AnalyzeWebBundleInput } from "../domain/webBundleAnalysis.js";
|
||||
import type { ObserveWebSessionInput } from "../domain/browserSession.js";
|
||||
@@ -20,27 +18,15 @@ import {
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import type { ExecutionOptions } from "./AnalysisProvider.js";
|
||||
import type { BrowserObservationPort } from "./BrowserObservationPort.js";
|
||||
import type { PermissionAuthority } from "./PermissionAuthority.js";
|
||||
import { createBrowserEvidence } from "./BrowserEvidence.js";
|
||||
|
||||
type ScopedBrowserInput = Pick<
|
||||
ListBrowserTargetsInput,
|
||||
"cdp_endpoint" | "allowed_origins"
|
||||
> & { readonly target_id?: string };
|
||||
|
||||
/** Authorize and execute one policy-scoped target discovery observation. */
|
||||
/** List browser targets within the endpoint and origin scope in the request. */
|
||||
export const listBrowserTargets = async (
|
||||
browser: BrowserObservationPort | undefined,
|
||||
authority: PermissionAuthority | undefined,
|
||||
input: ListBrowserTargetsInput,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<Evidence, AnalysisError>> => {
|
||||
const ready = await prepare(
|
||||
browser,
|
||||
authority,
|
||||
input,
|
||||
"list_browser_targets",
|
||||
);
|
||||
const ready = requireBrowser(browser, "list_browser_targets");
|
||||
if (!ready.ok) return ready;
|
||||
const result = await ready.value.listTargets(input, options);
|
||||
return result.ok
|
||||
@@ -55,14 +41,13 @@ export const listBrowserTargets = async (
|
||||
: result;
|
||||
};
|
||||
|
||||
/** Authorize and execute one policy-scoped passive page inspection. */
|
||||
/** Inspect one page within the endpoint and origin scope in the request. */
|
||||
export const inspectWebPage = async (
|
||||
browser: BrowserObservationPort | undefined,
|
||||
authority: PermissionAuthority | undefined,
|
||||
input: InspectWebPageInput,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<Evidence, AnalysisError>> => {
|
||||
const ready = await prepare(browser, authority, input, "inspect_web_page");
|
||||
const ready = requireBrowser(browser, "inspect_web_page");
|
||||
if (!ready.ok) return ready;
|
||||
const result = await ready.value.inspectPage(input, options);
|
||||
return result.ok
|
||||
@@ -77,14 +62,13 @@ export const inspectWebPage = async (
|
||||
: result;
|
||||
};
|
||||
|
||||
/** Capture approved sources and derive bounded static web-bundle evidence. */
|
||||
/** Capture requested sources and derive static web-bundle evidence. */
|
||||
export const analyzeWebBundle = async (
|
||||
browser: BrowserObservationPort | undefined,
|
||||
authority: PermissionAuthority | undefined,
|
||||
input: AnalyzeWebBundleInput,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<Evidence, AnalysisError>> => {
|
||||
const ready = await prepare(browser, authority, input, "analyze_web_bundle");
|
||||
const ready = requireBrowser(browser, "analyze_web_bundle");
|
||||
if (!ready.ok) return ready;
|
||||
const analyzed = await ready.value.analyzeBundle(input, options);
|
||||
if (!analyzed.ok) return analyzed;
|
||||
@@ -101,11 +85,10 @@ export const analyzeWebBundle = async (
|
||||
/** Observe navigation caused by external user actions during one armed window. */
|
||||
export const observeWebSession = async (
|
||||
browser: BrowserObservationPort | undefined,
|
||||
authority: PermissionAuthority | undefined,
|
||||
input: ObserveWebSessionInput,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<Evidence, AnalysisError>> => {
|
||||
const ready = await prepare(browser, authority, input, "observe_web_session");
|
||||
const ready = requireBrowser(browser, "observe_web_session");
|
||||
if (!ready.ok) return ready;
|
||||
const observed = await ready.value.observeSession(input, options);
|
||||
return observed.ok
|
||||
@@ -123,16 +106,10 @@ export const observeWebSession = async (
|
||||
/** Discover WebMCP declarations without exposing an invocation surface. */
|
||||
export const discoverWebMcpTools = async (
|
||||
browser: BrowserObservationPort | undefined,
|
||||
authority: PermissionAuthority | undefined,
|
||||
input: DiscoverWebMcpToolsInput,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<Evidence, AnalysisError>> => {
|
||||
const ready = await prepare(
|
||||
browser,
|
||||
authority,
|
||||
input,
|
||||
"discover_webmcp_tools",
|
||||
);
|
||||
const ready = requireBrowser(browser, "discover_webmcp_tools");
|
||||
if (!ready.ok) return ready;
|
||||
const discovered = await ready.value.discoverWebMcpTools(input, options);
|
||||
return discovered.ok
|
||||
@@ -167,19 +144,13 @@ export const compareWebCaptureEvidence = async (
|
||||
: compared;
|
||||
};
|
||||
|
||||
/** Capture one explicitly approved visible-viewport screenshot. */
|
||||
/** Capture one visible-viewport screenshot for the requested target. */
|
||||
export const captureWebScreenshot = async (
|
||||
browser: BrowserObservationPort | undefined,
|
||||
authority: PermissionAuthority | undefined,
|
||||
input: CaptureWebScreenshotInput,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<Evidence, AnalysisError>> => {
|
||||
const ready = await prepare(
|
||||
browser,
|
||||
authority,
|
||||
input,
|
||||
"capture_web_screenshot",
|
||||
);
|
||||
const ready = requireBrowser(browser, "capture_web_screenshot");
|
||||
if (!ready.ok) return ready;
|
||||
const captured = await ready.value.captureScreenshot(input, options);
|
||||
return captured.ok
|
||||
@@ -214,51 +185,6 @@ export const compareWebScreenshotEvidence = async (
|
||||
: compared;
|
||||
};
|
||||
|
||||
const prepare = async (
|
||||
browser: BrowserObservationPort | undefined,
|
||||
authority: PermissionAuthority | undefined,
|
||||
input: ScopedBrowserInput,
|
||||
operation:
|
||||
| "list_browser_targets"
|
||||
| "inspect_web_page"
|
||||
| "analyze_web_bundle"
|
||||
| "observe_web_session"
|
||||
| "discover_webmcp_tools"
|
||||
| "capture_web_screenshot",
|
||||
): Promise<Result<BrowserObservationPort, AnalysisError>> => {
|
||||
if (authority === undefined)
|
||||
return err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
"rea-cdp-browser",
|
||||
operation,
|
||||
"browser observation permission policy is not configured",
|
||||
),
|
||||
);
|
||||
const authorized = await authority.authorize(
|
||||
{
|
||||
capability: "browser_observe",
|
||||
roots: [],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
origins: [input.cdp_endpoint, ...input.allowed_origins],
|
||||
network: browserNetworkScope(input.allowed_origins),
|
||||
mount: false,
|
||||
operation_identity: `${operation}:${input.target_id ?? input.cdp_endpoint}`,
|
||||
},
|
||||
"read",
|
||||
);
|
||||
if (!authorized.ok) return err(projectPermissionFailure(authorized.error));
|
||||
return browser === undefined
|
||||
? err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
"rea-cdp-browser",
|
||||
operation,
|
||||
"browser observation provider is not configured",
|
||||
),
|
||||
)
|
||||
: ok(browser);
|
||||
};
|
||||
|
||||
const requireBrowser = (
|
||||
browser: BrowserObservationPort | undefined,
|
||||
operation: string,
|
||||
@@ -268,17 +194,7 @@ const requireBrowser = (
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
"rea-cdp-browser",
|
||||
operation,
|
||||
"browser comparison provider is not configured",
|
||||
"browser observation provider is not configured",
|
||||
),
|
||||
)
|
||||
: ok(browser);
|
||||
|
||||
const browserNetworkScope = (
|
||||
allowedOrigins: readonly string[],
|
||||
): "loopback" | "external" =>
|
||||
allowedOrigins.every((origin) => {
|
||||
const hostname = new URL(origin).hostname;
|
||||
return isLiteralLoopbackHostname(hostname);
|
||||
})
|
||||
? "loopback"
|
||||
: "external";
|
||||
|
||||
@@ -1,74 +1,23 @@
|
||||
import { projectPermissionFailure } from "./PermissionFailure.js";
|
||||
import type { ExecutionOptions } from "./AnalysisProvider.js";
|
||||
import type { BrowserScenarioCapturePort } from "./BrowserScenarioCapturePort.js";
|
||||
import { createBrowserScenarioEvidence } from "./BrowserScenarioEvidence.js";
|
||||
import type { PermissionAuthority } from "./PermissionAuthority.js";
|
||||
import { digestJson } from "./JavaScriptReplayPlanning.js";
|
||||
import {
|
||||
AnalysisCapabilityUnavailableError,
|
||||
type AnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
import { isLiteralLoopbackHostname } from "../domain/browserObservation.js";
|
||||
import type { BrowserScenario } from "../domain/browserScenario.js";
|
||||
import { err, type Result } from "../domain/result.js";
|
||||
|
||||
const OPERATION = "capture_browser_scenario" as const;
|
||||
const PROVIDER_ID = "rea-playwright-browser-scenario";
|
||||
|
||||
const networkScope = (origins: readonly string[]): "loopback" | "external" =>
|
||||
origins.every((origin) => isLiteralLoopbackHostname(new URL(origin).hostname))
|
||||
? "loopback"
|
||||
: "external";
|
||||
|
||||
const authorizeScenario = async (
|
||||
authority: PermissionAuthority | undefined,
|
||||
scenario: BrowserScenario,
|
||||
): Promise<Result<true, AnalysisError>> => {
|
||||
if (authority === undefined)
|
||||
return err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
PROVIDER_ID,
|
||||
OPERATION,
|
||||
"browser scenario permission policy is not configured",
|
||||
),
|
||||
);
|
||||
const authorized = await authority.authorize(
|
||||
{
|
||||
capability: "browser_automate",
|
||||
roots: [],
|
||||
executables:
|
||||
scenario.browser.mode === "launch"
|
||||
? [scenario.browser.executable_path]
|
||||
: [],
|
||||
environment_names: scenario.secrets.map(
|
||||
({ environment_variable: name }) => name,
|
||||
),
|
||||
origins: [
|
||||
...(scenario.browser.mode === "connect"
|
||||
? [scenario.browser.cdp_endpoint]
|
||||
: []),
|
||||
...scenario.allowed_origins,
|
||||
],
|
||||
network: networkScope(scenario.allowed_origins),
|
||||
mount: false,
|
||||
operation_identity: `${OPERATION}:${digestJson(scenario)}`,
|
||||
},
|
||||
"write",
|
||||
);
|
||||
if (!authorized.ok) return err(projectPermissionFailure(authorized.error));
|
||||
return { ok: true, value: true };
|
||||
};
|
||||
|
||||
/** Authorize and execute one controlled browser scenario. */
|
||||
/** Execute one controlled browser scenario using its explicit request scope. */
|
||||
export const captureBrowserScenario = async (
|
||||
provider: BrowserScenarioCapturePort | undefined,
|
||||
authority: PermissionAuthority | undefined,
|
||||
scenario: BrowserScenario,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<Evidence, AnalysisError>> => {
|
||||
const authorized = await authorizeScenario(authority, scenario);
|
||||
if (!authorized.ok) return authorized;
|
||||
if (provider === undefined)
|
||||
return err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
|
||||
@@ -15,8 +15,12 @@ const browserScenarioParameters = (
|
||||
): EvidenceObservation["parameters"] => ({
|
||||
scenario_sha256: digestJson(scenario),
|
||||
browser_mode: scenario.browser.mode,
|
||||
...(scenario.browser.mode === "launch"
|
||||
? { browser_headless: scenario.browser.headless }
|
||||
: {}),
|
||||
start_url: sanitizeBrowserUrl(scenario.start_url.url),
|
||||
allowed_origins: scenario.allowed_origins,
|
||||
environment: scenario.environment,
|
||||
actions: scenario.actions.map(({ step_id, action }) => ({
|
||||
step_id,
|
||||
action,
|
||||
@@ -25,11 +29,9 @@ const browserScenarioParameters = (
|
||||
"timeout_ms" in item ? (item.timeout_ms ?? null) : null,
|
||||
),
|
||||
secret_declarations: scenario.secrets.map(
|
||||
({ secret_id, environment_variable, purpose, redaction }) => ({
|
||||
({ secret_id, environment_variable }) => ({
|
||||
secret_id,
|
||||
environment_variable,
|
||||
purpose,
|
||||
redaction,
|
||||
}),
|
||||
),
|
||||
capture: scenario.capture,
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import type { ClientFeatureAvailability } from "../contracts/toolOutputSchemaPrimitives.js";
|
||||
|
||||
type ClientFeatureName = keyof ClientFeatureAvailability;
|
||||
|
||||
/** Empty MCP client feature declaration used when the caller supplies none. */
|
||||
export const NO_CLIENT_FEATURES: ClientFeatureAvailability = {
|
||||
elicitation_form: false,
|
||||
@@ -10,30 +8,12 @@ export const NO_CLIENT_FEATURES: ClientFeatureAvailability = {
|
||||
sampling: false,
|
||||
};
|
||||
|
||||
const CLIENT_FEATURE_REQUIREMENTS: Readonly<
|
||||
Record<
|
||||
string,
|
||||
{
|
||||
readonly required: readonly ClientFeatureName[];
|
||||
readonly optional: readonly ClientFeatureName[];
|
||||
}
|
||||
>
|
||||
> = {
|
||||
capture_process_scenario: {
|
||||
required: [],
|
||||
optional: ["elicitation_form"],
|
||||
},
|
||||
};
|
||||
|
||||
/** Project a tool's client requirements against the negotiated feature set. */
|
||||
export const clientRequirementsFor = (
|
||||
name: string,
|
||||
_name: string,
|
||||
clientFeatures: ClientFeatureAvailability,
|
||||
) => {
|
||||
const requirements = CLIENT_FEATURE_REQUIREMENTS[name] ?? {
|
||||
required: [],
|
||||
optional: [],
|
||||
};
|
||||
const requirements = { required: [], optional: [] } as const;
|
||||
return {
|
||||
required: [...requirements.required],
|
||||
optional: [...requirements.optional],
|
||||
|
||||
@@ -4,12 +4,11 @@ import { buildCapabilityInventory } from "./CapabilityInventory.js";
|
||||
|
||||
const enabledPolicy: Parameters<typeof buildCapabilityInventory>[1] = {
|
||||
processCaptureEnabled: true,
|
||||
controlledReplayEnabled: true,
|
||||
browserObservationEnabled: true,
|
||||
browserScenarioEnabled: true,
|
||||
electronObservationEnabled: true,
|
||||
v8InspectorObservationEnabled: true,
|
||||
javascriptReplayEnabled: true,
|
||||
managedRuntimeEnabled: true,
|
||||
};
|
||||
|
||||
const status = (
|
||||
@@ -141,25 +140,45 @@ describe("capability inventory: provider status", () => {
|
||||
else expect(availability.remediation).toContain(remediation);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["capture_process_scenario", { processCaptureEnabled: false }],
|
||||
["inspect_web_page", { browserObservationEnabled: false }],
|
||||
["capture_browser_scenario", { browserScenarioEnabled: false }],
|
||||
["inspect_electron_page", { electronObservationEnabled: false }],
|
||||
["observe_javascript_runtime", { v8InspectorObservationEnabled: false }],
|
||||
["run_controlled_replay", { javascriptReplayEnabled: false }],
|
||||
["plan_managed_runtime_correlation", { managedRuntimeEnabled: false }],
|
||||
] as const)("reports stable policy denial for %s", (name, override) => {
|
||||
const availability = entry(name, status(), {
|
||||
it("keeps configured workflows callable and reports only real host or provider limits", () => {
|
||||
const inventory = buildCapabilityInventory(status(), {
|
||||
...enabledPolicy,
|
||||
...override,
|
||||
processCaptureEnabled: false,
|
||||
browserObservationEnabled: false,
|
||||
browserScenarioEnabled: false,
|
||||
electronObservationEnabled: false,
|
||||
electronAutomationEnabled: false,
|
||||
v8InspectorObservationEnabled: false,
|
||||
});
|
||||
expect(availability).toMatchObject({
|
||||
const byName = new Map(inventory.map((item) => [item.name, item]));
|
||||
expect(byName.get("capture_process_scenario")).toMatchObject({
|
||||
available: false,
|
||||
reason: "policy_disabled",
|
||||
reason: "unsupported_host",
|
||||
});
|
||||
expect(byName.get("inspect_web_page")).toMatchObject({
|
||||
available: false,
|
||||
reason: "provider_missing",
|
||||
});
|
||||
expect(byName.get("run_controlled_replay")).toMatchObject({
|
||||
available: true,
|
||||
reason: "available",
|
||||
});
|
||||
expect(byName.get("plan_managed_runtime_correlation")).toMatchObject({
|
||||
available: true,
|
||||
reason: "available",
|
||||
});
|
||||
});
|
||||
|
||||
it("reports controlled replay as unsupported on other host targets", () => {
|
||||
const replay = entry("run_controlled_replay", status(), {
|
||||
...enabledPolicy,
|
||||
controlledReplayEnabled: false,
|
||||
});
|
||||
expect(replay).toMatchObject({
|
||||
available: false,
|
||||
reason: "unsupported_host",
|
||||
remediation: "Run controlled replay on a Linux x86_64 host.",
|
||||
});
|
||||
expect(availability.remediation).toEqual(expect.any(String));
|
||||
expect(availability.remediation?.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -171,8 +190,6 @@ describe("capability inventory: caller guidance", () => {
|
||||
browserObservationEnabled: false,
|
||||
electronObservationEnabled: false,
|
||||
v8InspectorObservationEnabled: false,
|
||||
javascriptReplayEnabled: false,
|
||||
managedRuntimeEnabled: false,
|
||||
});
|
||||
for (const availability of inventory)
|
||||
if (!availability.available) {
|
||||
@@ -182,7 +199,7 @@ describe("capability inventory: caller guidance", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("projects negotiated client features into per-tool requirements", () => {
|
||||
it("does not require interactive elicitation for process capture", () => {
|
||||
const withoutElicitation = buildCapabilityInventory(
|
||||
status(),
|
||||
enabledPolicy,
|
||||
@@ -196,13 +213,13 @@ describe("capability inventory: caller guidance", () => {
|
||||
|
||||
expect(withoutElicitation?.client_requirements).toEqual({
|
||||
required: [],
|
||||
optional: ["elicitation_form"],
|
||||
optional: [],
|
||||
missing_required: [],
|
||||
missing_optional: ["elicitation_form"],
|
||||
missing_optional: [],
|
||||
});
|
||||
expect(withElicitation?.client_requirements).toEqual({
|
||||
required: [],
|
||||
optional: ["elicitation_form"],
|
||||
optional: [],
|
||||
missing_required: [],
|
||||
missing_optional: [],
|
||||
});
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
import type { ToolKind } from "../contracts/toolContractTypes.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { GENERATED_MCP_TOOL_CATALOG } from "../generatedMcpToolCatalog.js";
|
||||
import { isSupportedControlledReplayHost } from "./ControlledReplayHostSupport.js";
|
||||
import {
|
||||
clientRequirementsFor,
|
||||
NO_CLIENT_FEATURES,
|
||||
@@ -28,13 +29,12 @@ type ToolAvailabilityReason = "available" | ToolUnavailabilityReason;
|
||||
type ProviderDescriptor = ProviderCapability;
|
||||
export type AvailabilityPolicy = {
|
||||
readonly processCaptureEnabled: boolean;
|
||||
readonly controlledReplayEnabled?: boolean;
|
||||
readonly browserObservationEnabled?: boolean;
|
||||
readonly browserScenarioEnabled?: boolean;
|
||||
readonly electronObservationEnabled?: boolean;
|
||||
readonly electronAutomationEnabled?: boolean;
|
||||
readonly v8InspectorObservationEnabled?: boolean;
|
||||
readonly javascriptReplayEnabled?: boolean;
|
||||
readonly managedRuntimeEnabled?: boolean;
|
||||
};
|
||||
|
||||
type AvailabilityFacts = {
|
||||
@@ -185,8 +185,8 @@ const availabilityFor = (context: AvailabilityContext): Availability => {
|
||||
return navigationContextAvailability(context.descriptors);
|
||||
const javascriptApplication = javascriptApplicationAvailability(context);
|
||||
if (javascriptApplication !== null) return javascriptApplication;
|
||||
const policyDecision = policyAvailability(context);
|
||||
if (policyDecision !== null) return policyDecision;
|
||||
const workflowAvailability = workflowAvailabilityFor(context);
|
||||
if (workflowAvailability !== null) return workflowAvailability;
|
||||
const targetDecision = targetAvailability(context);
|
||||
if (targetDecision !== null) return targetDecision;
|
||||
return providerAvailability(context);
|
||||
@@ -202,54 +202,44 @@ const javascriptApplicationAvailability = ({
|
||||
: null;
|
||||
};
|
||||
|
||||
const policyAvailability = ({
|
||||
const workflowAvailabilityFor = ({
|
||||
name,
|
||||
kind,
|
||||
policy,
|
||||
}: AvailabilityContext): Availability | null => {
|
||||
const browser = browserPolicyAvailability(name, kind, policy);
|
||||
const browser = browserProviderAvailability(name, kind, policy);
|
||||
if (browser !== null) return browser;
|
||||
if (name === "capture_process_scenario" && !policy.processCaptureEnabled)
|
||||
return {
|
||||
reason: "policy_disabled",
|
||||
remediation:
|
||||
"Enable or grant process_capture within the administrator ceiling.",
|
||||
};
|
||||
if (name === "run_controlled_replay" && !policy.javascriptReplayEnabled)
|
||||
return {
|
||||
reason: "policy_disabled",
|
||||
remediation:
|
||||
"Enable javascript_replay with exact source roots and sandbox executables.",
|
||||
reason: "unsupported_host",
|
||||
remediation: "Run process capture on a supported Linux or macOS host.",
|
||||
};
|
||||
if (name === "run_controlled_replay")
|
||||
return { reason: "available", remediation: null };
|
||||
if (
|
||||
name === "plan_managed_runtime_correlation" &&
|
||||
!policy.managedRuntimeEnabled
|
||||
)
|
||||
return {
|
||||
reason: "policy_disabled",
|
||||
remediation:
|
||||
"Enable managed_runtime with exact artifact roots and a runtime executable.",
|
||||
};
|
||||
return (policy.controlledReplayEnabled ??
|
||||
isSupportedControlledReplayHost(process.platform, process.arch))
|
||||
? { reason: "available", remediation: null }
|
||||
: {
|
||||
reason: "unsupported_host",
|
||||
remediation: "Run controlled replay on a Linux x86_64 host.",
|
||||
};
|
||||
if (name === "plan_managed_runtime_correlation")
|
||||
return { reason: "available", remediation: null };
|
||||
if (kind === "application") return { reason: "available", remediation: null };
|
||||
const electron = electronPolicyAvailability(name, kind, policy);
|
||||
const electron = electronProviderAvailability(name, kind, policy);
|
||||
if (electron !== null) return electron;
|
||||
if (kind === "runtime-provider")
|
||||
return policy.v8InspectorObservationEnabled === true
|
||||
? { reason: "available", remediation: null }
|
||||
: {
|
||||
reason: "policy_disabled",
|
||||
reason: "provider_missing",
|
||||
remediation:
|
||||
"Enable V8 Inspector observation; pass the user's literal-loopback Inspector endpoint to the tool.",
|
||||
"Start REA with its JavaScript runtime provider available.",
|
||||
};
|
||||
if (kind === "session") return { reason: "available", remediation: null };
|
||||
return null;
|
||||
};
|
||||
|
||||
const electronPolicyAvailability = (
|
||||
const electronProviderAvailability = (
|
||||
name: string,
|
||||
kind: ToolKind,
|
||||
policy: AvailabilityPolicy,
|
||||
@@ -259,20 +249,20 @@ const electronPolicyAvailability = (
|
||||
return policy.electronAutomationEnabled === true
|
||||
? { reason: "available", remediation: null }
|
||||
: {
|
||||
reason: "policy_disabled",
|
||||
reason: "provider_missing",
|
||||
remediation:
|
||||
"Enable active Electron automation and configure exact executable and application roots.",
|
||||
"Start REA with the Electron scenario provider available.",
|
||||
};
|
||||
return policy.electronObservationEnabled === true
|
||||
? { reason: "available", remediation: null }
|
||||
: {
|
||||
reason: "policy_disabled",
|
||||
reason: "provider_missing",
|
||||
remediation:
|
||||
"Enable Electron observation; pass the user's literal-loopback CDP endpoint to the tool.",
|
||||
"Start REA with its Electron observation provider available.",
|
||||
};
|
||||
};
|
||||
|
||||
const browserPolicyAvailability = (
|
||||
const browserProviderAvailability = (
|
||||
name: string,
|
||||
kind: ToolKind,
|
||||
policy: AvailabilityPolicy,
|
||||
@@ -281,17 +271,17 @@ const browserPolicyAvailability = (
|
||||
return policy.browserScenarioEnabled === true
|
||||
? { reason: "available", remediation: null }
|
||||
: {
|
||||
reason: "policy_disabled",
|
||||
reason: "provider_missing",
|
||||
remediation:
|
||||
"Enable browser scenarios and configure exact executable roots or loopback CDP endpoints, page origins, and environment secret names.",
|
||||
"Start REA with its browser scenario provider available.",
|
||||
};
|
||||
if (kind !== "browser-provider") return null;
|
||||
return policy.browserObservationEnabled === true
|
||||
? { reason: "available", remediation: null }
|
||||
: {
|
||||
reason: "policy_disabled",
|
||||
reason: "provider_missing",
|
||||
remediation:
|
||||
"Enable browser observation and configure exact CDP endpoint and page origins.",
|
||||
"Start REA with its browser observation provider available.",
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
import { realpath } from "node:fs/promises";
|
||||
|
||||
/** Canonicalize configured policy roots while ignoring stale missing entries. */
|
||||
export const canonicalizeConfiguredRoots = async (
|
||||
roots: readonly string[],
|
||||
): Promise<string[]> => {
|
||||
const canonical: string[] = [];
|
||||
for (const root of roots) {
|
||||
try {
|
||||
canonical.push(await realpath(root));
|
||||
} catch (cause: unknown) {
|
||||
if (!isMissingPath(cause)) throw cause;
|
||||
}
|
||||
}
|
||||
return canonical;
|
||||
};
|
||||
|
||||
const isMissingPath = (cause: unknown): boolean =>
|
||||
typeof cause === "object" &&
|
||||
cause !== null &&
|
||||
"code" in cause &&
|
||||
cause.code === "ENOENT";
|
||||
@@ -0,0 +1,12 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { isSupportedControlledReplayHost } from "./ControlledReplayHostSupport.js";
|
||||
|
||||
describe("controlled replay host support", () => {
|
||||
it("admits only Linux x86_64", () => {
|
||||
expect(isSupportedControlledReplayHost("linux", "x64")).toBe(true);
|
||||
expect(isSupportedControlledReplayHost("linux", "arm64")).toBe(false);
|
||||
expect(isSupportedControlledReplayHost("darwin", "x64")).toBe(false);
|
||||
expect(isSupportedControlledReplayHost("win32", "x64")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,5 @@
|
||||
/** Return whether this host has the platform boundary required by replay v1. */
|
||||
export const isSupportedControlledReplayHost = (
|
||||
platform: string,
|
||||
architecture: string,
|
||||
): boolean => platform === "linux" && architecture === "x64";
|
||||
@@ -1,6 +1,4 @@
|
||||
import { projectPermissionFailure } from "./PermissionFailure.js";
|
||||
import { artifactExtractionPermissionRequest } from "./ArtifactExtractionDestination.js";
|
||||
import { parseConfig, type AppConfig } from "../config.js";
|
||||
import { parseConfig } from "../config.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { EnhancedTools } from "./EnhancedTools.js";
|
||||
import { createBinarySession } from "./runtime.js";
|
||||
@@ -29,8 +27,6 @@ import {
|
||||
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import type { AnalysisSnapshot } from "../domain/analysisSnapshot.js";
|
||||
import { loadConfiguredPermissionAuthority } from "./PermissionConfiguration.js";
|
||||
import type { PermissionAuthority } from "./PermissionAuthority.js";
|
||||
import {
|
||||
REA_WORKFLOW_PROVIDER,
|
||||
workflowAnalysisProfile,
|
||||
@@ -73,7 +69,6 @@ export const runDirectAnalysis = async (
|
||||
readonly logger?: Logger;
|
||||
readonly snapshotPath?: string | undefined;
|
||||
readonly signal?: AbortSignal;
|
||||
readonly permissionAuthority?: PermissionAuthority;
|
||||
readonly providerId?: AnalysisProviderSelector;
|
||||
} = {},
|
||||
): Promise<JsonValue> =>
|
||||
@@ -85,9 +80,6 @@ export const runDirectAnalysis = async (
|
||||
...(options.providerId === undefined
|
||||
? {}
|
||||
: { providerId: options.providerId }),
|
||||
...(options.permissionAuthority === undefined
|
||||
? {}
|
||||
: { permissionAuthority: options.permissionAuthority }),
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -109,78 +101,6 @@ export const runProviderAnalysis = async (
|
||||
}),
|
||||
);
|
||||
|
||||
const authorizeAnalysis = async (
|
||||
authority: PermissionAuthority,
|
||||
tool:
|
||||
| NativeToolName
|
||||
| ArtifactAnalysisOperation
|
||||
| ManagedToolName
|
||||
| DirectAnalysisTool,
|
||||
arguments_: Readonly<Record<string, JsonValue>>,
|
||||
): Promise<Result<null, AnalysisError>> => {
|
||||
const requests = [];
|
||||
if (tool === "extract_artifact" && typeof arguments_.output_root === "string")
|
||||
requests.push({
|
||||
request: artifactExtractionPermissionRequest(),
|
||||
access: "write" as const,
|
||||
});
|
||||
for (const request of requests) {
|
||||
const result = await authority.authorize(request.request, request.access);
|
||||
if (!result.ok) return err(projectPermissionFailure(result.error));
|
||||
}
|
||||
if (
|
||||
["inventory_artifact", "inspect_artifact"].includes(tool) &&
|
||||
arguments_.native_mount_approved === true
|
||||
) {
|
||||
const result = await authority.authorize(
|
||||
{
|
||||
capability: "native_mount",
|
||||
roots: [],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
network: "none",
|
||||
mount: true,
|
||||
operation_identity: `${tool}:native_mount`,
|
||||
},
|
||||
"read",
|
||||
);
|
||||
if (!result.ok) return err(projectPermissionFailure(result.error));
|
||||
}
|
||||
return ok(null);
|
||||
};
|
||||
|
||||
const permissionAuthorityFor = (
|
||||
config: AppConfig,
|
||||
supplied: PermissionAuthority | undefined,
|
||||
): ReturnType<typeof loadConfiguredPermissionAuthority> =>
|
||||
supplied === undefined
|
||||
? loadConfiguredPermissionAuthority(config)
|
||||
: Promise.resolve(ok(supplied));
|
||||
|
||||
const authorizeAnalysisRun = async (input: {
|
||||
readonly config: AppConfig;
|
||||
readonly suppliedAuthority: PermissionAuthority | undefined;
|
||||
readonly tool:
|
||||
| NativeToolName
|
||||
| ArtifactAnalysisOperation
|
||||
| ManagedToolName
|
||||
| DirectAnalysisTool;
|
||||
readonly arguments: Readonly<Record<string, JsonValue>>;
|
||||
}): Promise<Result<null, AnalysisError>> => {
|
||||
const authority = await permissionAuthorityFor(
|
||||
input.config,
|
||||
input.suppliedAuthority,
|
||||
);
|
||||
if (!authority.ok) return authority;
|
||||
const operation = await authorizeAnalysis(
|
||||
authority.value,
|
||||
input.tool,
|
||||
input.arguments,
|
||||
);
|
||||
if (!operation.ok) return operation;
|
||||
return ok(null);
|
||||
};
|
||||
|
||||
const runAnalysis = async (
|
||||
path: string,
|
||||
tool:
|
||||
@@ -193,7 +113,6 @@ const runAnalysis = async (
|
||||
readonly logger: Logger;
|
||||
readonly snapshotPath: string | undefined;
|
||||
readonly signal: AbortSignal;
|
||||
readonly permissionAuthority?: PermissionAuthority;
|
||||
readonly providerId?: AnalysisProviderSelector;
|
||||
/**
|
||||
* Environment the configuration is read from. Defaults to the process
|
||||
@@ -208,13 +127,6 @@ const runAnalysis = async (
|
||||
const { logger, signal, snapshotPath } = options;
|
||||
const config = parseConfig(options.environment ?? process.env);
|
||||
if (!config.ok) return cliError(config.error);
|
||||
const authorization = await authorizeAnalysisRun({
|
||||
config: config.value,
|
||||
suppliedAuthority: options.permissionAuthority,
|
||||
tool,
|
||||
arguments: arguments_,
|
||||
});
|
||||
if (!authorization.ok) return cliError(authorization.error);
|
||||
const session = createBinarySession(config.value, logger);
|
||||
try {
|
||||
const prepared = await prepareSnapshot({
|
||||
|
||||
@@ -3,6 +3,33 @@ import type { ClientRegistrationStatus } from "./ClientRegistrationStatus.js";
|
||||
import { createDoctorHostFixture as host } from "./Doctor.fixture.js";
|
||||
import { runDoctor } from "./Doctor.js";
|
||||
|
||||
it("reports unavailable replay without blocking installation or Hopper readiness", async () => {
|
||||
const replayCheck = {
|
||||
name: "javascript-replay",
|
||||
ok: false,
|
||||
classification: "unsupported_host" as const,
|
||||
detail: "Controlled replay requires Linux x86_64",
|
||||
};
|
||||
const doctorHost = host({
|
||||
javascriptReplayCheck: () => Promise.resolve(replayCheck),
|
||||
});
|
||||
for (const scope of [undefined, { providers: ["hopper"] }]) {
|
||||
const report = await runDoctor(undefined, doctorHost, scope);
|
||||
expect(report.healthy).toBe(true);
|
||||
expect(report.checks).toContainEqual(replayCheck);
|
||||
expect(report.informational_checks).toContainEqual(replayCheck);
|
||||
expect(report.scope_checks).not.toContainEqual(replayCheck);
|
||||
}
|
||||
const unhealthy = await runDoctor(
|
||||
undefined,
|
||||
host({
|
||||
nodeVersion: "20.0.0",
|
||||
javascriptReplayCheck: () => Promise.resolve(replayCheck),
|
||||
}),
|
||||
);
|
||||
expect(unhealthy.healthy).toBe(false);
|
||||
});
|
||||
|
||||
describe("doctor", () => {
|
||||
it("returns exact recovery for every failed diagnostic", async () => {
|
||||
const result = await runDoctor(
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
import {
|
||||
collectDoctorDiagnostics,
|
||||
doctorHealthy,
|
||||
isOptionalDoctorCheck,
|
||||
} from "./DoctorDiagnostics.js";
|
||||
import {
|
||||
normalizeDoctorScope,
|
||||
@@ -187,9 +188,14 @@ export const runDoctor = async (
|
||||
healthy: scope.mode === "audit-wide" ? environmentHealthy : scoped.healthy,
|
||||
environment_healthy: environmentHealthy,
|
||||
scope,
|
||||
scope_checks: scope.mode === "audit-wide" ? checks : scoped.scopeChecks,
|
||||
scope_checks:
|
||||
scope.mode === "audit-wide"
|
||||
? checks.filter(({ name }) => !isOptionalDoctorCheck(name))
|
||||
: scoped.scopeChecks,
|
||||
informational_checks:
|
||||
scope.mode === "audit-wide" ? [] : scoped.informationalChecks,
|
||||
scope.mode === "audit-wide"
|
||||
? checks.filter(({ name }) => isOptionalDoctorCheck(name))
|
||||
: scoped.informationalChecks,
|
||||
...(hopperPath === undefined ? {} : { hopperPath }),
|
||||
...(providerInspections === undefined ? {} : { providerInspections }),
|
||||
checks,
|
||||
|
||||
@@ -70,16 +70,19 @@ export const doctorHealthy = (
|
||||
| undefined;
|
||||
},
|
||||
): boolean => {
|
||||
const requiredChecks = checks.filter(
|
||||
({ name }) => !isOptionalDoctorCheck(name),
|
||||
);
|
||||
if (providers.providerInspections === undefined)
|
||||
return checks.every(({ ok }) => ok);
|
||||
const providerChecks = checks.filter(
|
||||
return requiredChecks.every(({ ok }) => ok);
|
||||
const providerChecks = requiredChecks.filter(
|
||||
({ name }) =>
|
||||
name.startsWith("hopper") ||
|
||||
providers.providerInspections?.some((inspection) =>
|
||||
providerCheckName(inspection.id, name),
|
||||
) === true,
|
||||
);
|
||||
const coreHealthy = checks
|
||||
const coreHealthy = requiredChecks
|
||||
.filter((candidate) => !providerChecks.includes(candidate))
|
||||
.every(({ ok }) => ok);
|
||||
const configuredProvidersHealthy = providerChecks
|
||||
@@ -99,6 +102,10 @@ export const doctorHealthy = (
|
||||
);
|
||||
};
|
||||
|
||||
/** Identify workflow diagnostics that do not gate core installation readiness. */
|
||||
export const isOptionalDoctorCheck = (name: string): boolean =>
|
||||
name === "javascript-replay";
|
||||
|
||||
const nodeCheck = (host: DoctorHost): DoctorCheck =>
|
||||
check("node", supportsNodeVersion(host.nodeVersion), host.nodeVersion, {
|
||||
remediation: "Install Node.js 22.19+ or 24.11+.",
|
||||
|
||||
@@ -7,7 +7,7 @@ import type {
|
||||
DoctorProviderInspection,
|
||||
DoctorScope,
|
||||
} from "./Doctor.js";
|
||||
import { doctorHealthy } from "./DoctorDiagnostics.js";
|
||||
import { doctorHealthy, isOptionalDoctorCheck } from "./DoctorDiagnostics.js";
|
||||
|
||||
/** Normalized readiness boundary included in every doctor response. */
|
||||
export interface DoctorScopeReport {
|
||||
@@ -58,6 +58,7 @@ export const scopeDoctorChecks = (
|
||||
const coreChecks = input.checks.filter(
|
||||
({ name }) =>
|
||||
!isProviderCheck(name, input.providers.providerInspections) &&
|
||||
!isOptionalDoctorCheck(name) &&
|
||||
name !== "skill:identity" &&
|
||||
!name.startsWith("registration:"),
|
||||
);
|
||||
|
||||
@@ -8,9 +8,14 @@ import type {
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import { digestJson } from "./JavaScriptReplayPlanning.js";
|
||||
|
||||
type CanonicalElectronActiveObservationInput =
|
||||
ElectronActiveObservationInput & {
|
||||
readonly application_root: string;
|
||||
};
|
||||
|
||||
/** Create Evidence without retaining arbitrary runtime argument values. */
|
||||
export const createElectronActiveEvidence = (
|
||||
input: ElectronActiveObservationInput,
|
||||
input: CanonicalElectronActiveObservationInput,
|
||||
result: ElectronActiveObservationResult,
|
||||
provider: ProviderIdentity,
|
||||
): Evidence =>
|
||||
@@ -31,46 +36,18 @@ export const createElectronActiveEvidence = (
|
||||
});
|
||||
|
||||
const scenarioProjection = (
|
||||
input: ElectronActiveObservationInput,
|
||||
input: CanonicalElectronActiveObservationInput,
|
||||
): EvidenceObservation["parameters"] => ({
|
||||
executable_path: input.executable_path,
|
||||
application_path: input.application_path,
|
||||
application_root: input.application_root,
|
||||
args: redactArguments(input.args),
|
||||
args: [...input.args],
|
||||
actions: input.actions.map(({ step_id, kind }) => ({ step_id, kind })),
|
||||
});
|
||||
|
||||
const parameters = (
|
||||
input: ElectronActiveObservationInput,
|
||||
input: CanonicalElectronActiveObservationInput,
|
||||
): EvidenceObservation["parameters"] => ({
|
||||
...scenarioProjection(input),
|
||||
scenario_sha256: digestJson(scenarioProjection(input)),
|
||||
});
|
||||
|
||||
const redactArguments = (arguments_: readonly string[]): string[] => {
|
||||
let redactNext = false;
|
||||
return arguments_.map((argument) => {
|
||||
if (redactNext) {
|
||||
redactNext = false;
|
||||
return "<redacted>";
|
||||
}
|
||||
if (sensitiveFlag.test(argument)) {
|
||||
redactNext = true;
|
||||
return argument;
|
||||
}
|
||||
return redactArgument(argument);
|
||||
});
|
||||
};
|
||||
|
||||
const sensitiveFlag =
|
||||
/^--?(?:password|token|secret|api[-_]?key|authorization|cookie)$/iu;
|
||||
|
||||
const redactArgument = (argument: string): string => {
|
||||
if (
|
||||
/^--?(?:password|token|secret|api[-_]?key|authorization|cookie)=/iu.test(
|
||||
argument,
|
||||
)
|
||||
)
|
||||
return `${argument.slice(0, argument.indexOf("=") + 1)}<redacted>`;
|
||||
return argument;
|
||||
};
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
import { projectPermissionFailure } from "./PermissionFailure.js";
|
||||
import { dirname } from "node:path";
|
||||
import { realpath } from "node:fs/promises";
|
||||
|
||||
import type { ExecutionOptions } from "./AnalysisProvider.js";
|
||||
import type { ElectronActiveObservationPort } from "./ElectronActiveObservationPort.js";
|
||||
import type { PermissionAuthority } from "./PermissionAuthority.js";
|
||||
import { digestJson } from "./JavaScriptReplayPlanning.js";
|
||||
import {
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisInputError,
|
||||
@@ -12,34 +10,28 @@ import {
|
||||
} from "../domain/errors.js";
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
import type { ElectronActiveObservationInput } from "../domain/electronActiveObservation.js";
|
||||
import { isPathContained } from "../domain/permissionPolicy.js";
|
||||
import { err, type Result } from "../domain/result.js";
|
||||
import { createElectronActiveEvidence } from "./ElectronActiveEvidence.js";
|
||||
|
||||
const OPERATION = "capture_electron_scenario" as const;
|
||||
const PROVIDER_ID = "rea-playwright-electron-active";
|
||||
type CanonicalElectronActiveObservationInput =
|
||||
ElectronActiveObservationInput & {
|
||||
readonly application_root: string;
|
||||
};
|
||||
|
||||
const canonicalizeInput = async (
|
||||
input: ElectronActiveObservationInput,
|
||||
): Promise<Result<ElectronActiveObservationInput, AnalysisError>> => {
|
||||
): Promise<Result<CanonicalElectronActiveObservationInput, AnalysisError>> => {
|
||||
try {
|
||||
const [executablePath, applicationPath, applicationRoot] =
|
||||
await Promise.all([
|
||||
realpath(input.executable_path),
|
||||
realpath(input.application_path),
|
||||
realpath(input.application_root),
|
||||
]);
|
||||
if (!isPathContained(applicationRoot, applicationPath))
|
||||
return err(
|
||||
new AnalysisInputError(OPERATION, undefined, [
|
||||
{
|
||||
path: ["application_path"],
|
||||
reason: "invalid_value",
|
||||
message:
|
||||
"application_path must remain beneath application_root after symlink resolution",
|
||||
},
|
||||
]),
|
||||
);
|
||||
const [executablePath, applicationPath] = await Promise.all([
|
||||
realpath(input.executable_path),
|
||||
realpath(input.application_path),
|
||||
]);
|
||||
const applicationRoot =
|
||||
input.application_root === undefined
|
||||
? dirname(applicationPath)
|
||||
: await realpath(input.application_root);
|
||||
return {
|
||||
ok: true,
|
||||
value: {
|
||||
@@ -63,45 +55,14 @@ const canonicalizeInput = async (
|
||||
}
|
||||
};
|
||||
|
||||
const authorize = async (
|
||||
authority: PermissionAuthority | undefined,
|
||||
input: ElectronActiveObservationInput,
|
||||
): Promise<Result<ElectronActiveObservationInput, AnalysisError>> => {
|
||||
const canonical = await canonicalizeInput(input);
|
||||
if (!canonical.ok) return canonical;
|
||||
if (authority === undefined)
|
||||
return err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
PROVIDER_ID,
|
||||
OPERATION,
|
||||
"active Electron observation permission policy is not configured",
|
||||
),
|
||||
);
|
||||
const authorized = await authority.authorize(
|
||||
{
|
||||
capability: "electron_automate",
|
||||
roots: [canonical.value.application_root],
|
||||
executables: [canonical.value.executable_path],
|
||||
environment_names: [],
|
||||
network: "external",
|
||||
mount: false,
|
||||
operation_identity: `${OPERATION}:${digestJson(canonical.value)}`,
|
||||
},
|
||||
"write",
|
||||
);
|
||||
if (!authorized.ok) return err(projectPermissionFailure(authorized.error));
|
||||
return canonical;
|
||||
};
|
||||
|
||||
/** Authorize and execute one bounded, provider-owned Electron experiment. */
|
||||
/** Canonicalize request paths and execute one provider-owned Electron run. */
|
||||
export const captureElectronScenario = async (
|
||||
provider: ElectronActiveObservationPort | undefined,
|
||||
authority: PermissionAuthority | undefined,
|
||||
input: ElectronActiveObservationInput,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<Evidence, AnalysisError>> => {
|
||||
const authorized = await authorize(authority, input);
|
||||
if (!authorized.ok) return authorized;
|
||||
const canonical = await canonicalizeInput(input);
|
||||
if (!canonical.ok) return canonical;
|
||||
if (provider === undefined)
|
||||
return err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
@@ -110,12 +71,12 @@ export const captureElectronScenario = async (
|
||||
"active Electron observation provider is not configured",
|
||||
),
|
||||
);
|
||||
const captured = await provider.capture(authorized.value, options);
|
||||
const captured = await provider.capture(canonical.value, options);
|
||||
return captured.ok
|
||||
? {
|
||||
ok: true,
|
||||
value: createElectronActiveEvidence(
|
||||
authorized.value,
|
||||
canonical.value,
|
||||
captured.value,
|
||||
provider.identity(),
|
||||
),
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import { projectPermissionFailure } from "./PermissionFailure.js";
|
||||
import type { ExecutionOptions } from "./AnalysisProvider.js";
|
||||
import type { ElectronObservationPort } from "./ElectronObservationPort.js";
|
||||
import type { PermissionAuthority } from "./PermissionAuthority.js";
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
import type {
|
||||
InspectElectronPageInput,
|
||||
@@ -14,19 +12,13 @@ import {
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { createElectronEvidence } from "./ElectronEvidence.js";
|
||||
|
||||
/** Authorize and list Electron file pages exposed by the selected endpoint. */
|
||||
/** List local file pages exposed by the explicitly selected endpoint. */
|
||||
export const listElectronTargets = async (
|
||||
provider: ElectronObservationPort | undefined,
|
||||
authority: PermissionAuthority | undefined,
|
||||
input: ListElectronTargetsInput,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<Evidence, AnalysisError>> => {
|
||||
const ready = await prepare(
|
||||
provider,
|
||||
authority,
|
||||
input,
|
||||
"list_electron_targets",
|
||||
);
|
||||
const ready = requireProvider(provider, "list_electron_targets");
|
||||
if (!ready.ok) return ready;
|
||||
const result = await ready.value.listTargets(input, options);
|
||||
return result.ok
|
||||
@@ -41,19 +33,13 @@ export const listElectronTargets = async (
|
||||
: result;
|
||||
};
|
||||
|
||||
/** Authorize and inspect one root-confined Electron page. */
|
||||
/** Inspect one local file page from the explicitly selected endpoint. */
|
||||
export const inspectElectronPage = async (
|
||||
provider: ElectronObservationPort | undefined,
|
||||
authority: PermissionAuthority | undefined,
|
||||
input: InspectElectronPageInput,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<Evidence, AnalysisError>> => {
|
||||
const ready = await prepare(
|
||||
provider,
|
||||
authority,
|
||||
input,
|
||||
"inspect_electron_page",
|
||||
);
|
||||
const ready = requireProvider(provider, "inspect_electron_page");
|
||||
if (!ready.ok) return ready;
|
||||
const result = await ready.value.inspectPage(input, options);
|
||||
return result.ok
|
||||
@@ -68,34 +54,11 @@ export const inspectElectronPage = async (
|
||||
: result;
|
||||
};
|
||||
|
||||
const prepare = async (
|
||||
const requireProvider = (
|
||||
provider: ElectronObservationPort | undefined,
|
||||
authority: PermissionAuthority | undefined,
|
||||
input: ListElectronTargetsInput | InspectElectronPageInput,
|
||||
operation: "list_electron_targets" | "inspect_electron_page",
|
||||
): Promise<Result<ElectronObservationPort, AnalysisError>> => {
|
||||
if (authority === undefined)
|
||||
return err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
"rea-cdp-electron",
|
||||
operation,
|
||||
"Electron observation permission policy is not configured",
|
||||
),
|
||||
);
|
||||
const authorized = await authority.authorize(
|
||||
{
|
||||
capability: "electron_observe",
|
||||
roots: [],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
network: "loopback",
|
||||
mount: false,
|
||||
operation_identity: `${operation}:${"target_id" in input ? input.target_id : input.cdp_endpoint}`,
|
||||
},
|
||||
"read",
|
||||
);
|
||||
if (!authorized.ok) return err(projectPermissionFailure(authorized.error));
|
||||
return provider === undefined
|
||||
): Result<ElectronObservationPort, AnalysisError> =>
|
||||
provider === undefined
|
||||
? err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
"rea-cdp-electron",
|
||||
@@ -104,4 +67,3 @@ const prepare = async (
|
||||
),
|
||||
)
|
||||
: ok(provider);
|
||||
};
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { isPathWithinRoot } from "../domain/localPath.js";
|
||||
import { createHash } from "node:crypto";
|
||||
import { constants as fsConstants } from "node:fs";
|
||||
import { lstat, open, readdir, readlink } from "node:fs/promises";
|
||||
@@ -98,17 +97,13 @@ export const snapshotRoots = async (
|
||||
truncated = true;
|
||||
return;
|
||||
}
|
||||
const safeTarget = isPathWithinRoot(root, target)
|
||||
? relative(root, target) || "."
|
||||
: "<outside-declared-root>";
|
||||
if (safeTarget === "<outside-declared-root>") truncated = true;
|
||||
entries.push({
|
||||
path: `${rootAlias}:${relativePath}`,
|
||||
type: "symlink",
|
||||
mode: stats.mode,
|
||||
size: stats.size,
|
||||
sha256: null,
|
||||
symlink_target: safeTarget,
|
||||
symlink_target: target,
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -148,7 +143,12 @@ export const snapshotRoots = async (
|
||||
for (const child of children.sort())
|
||||
await visit(root, rootAlias, join(path, child), depth + 1);
|
||||
};
|
||||
for (const [index, root] of scenario.filesystem_roots.entries())
|
||||
for (const [index, root] of scenario.filesystem_observation_paths.entries()) {
|
||||
if ((await lstatIfPresent(root)) === undefined) {
|
||||
truncated = true;
|
||||
continue;
|
||||
}
|
||||
await visit(root, `root_${String(index)}`, root, 0);
|
||||
}
|
||||
return { files: entries, truncated };
|
||||
};
|
||||
|
||||
@@ -55,7 +55,9 @@ export class InstrumentedJavaScriptReplayHost implements JavaScriptReplayHost {
|
||||
return this.delegate.seccompDigest();
|
||||
}
|
||||
|
||||
probe(policy: Parameters<JavaScriptReplayHost["probe"]>[0]): Promise<void> {
|
||||
return this.delegate.probe(policy);
|
||||
probe(
|
||||
configuration: Parameters<JavaScriptReplayHost["probe"]>[0],
|
||||
): Promise<void> {
|
||||
return this.delegate.probe(configuration);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -157,7 +157,8 @@ const assertApplicationSubject = (
|
||||
if (
|
||||
evidence.subject === null ||
|
||||
evidence.subject.digest.sha256 !== result.root_artifact_sha256 ||
|
||||
evidence.subject.format !== result.format
|
||||
evidence.subject.format !== result.format ||
|
||||
evidence.subject.local_path !== result.input_path
|
||||
)
|
||||
throw new TypeError(
|
||||
"JavaScript application Evidence subject does not match its result",
|
||||
|
||||
@@ -73,7 +73,7 @@ export const traceApplicationFeatureEvidenceValidated = (
|
||||
),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return workflowFailure(operation, cause);
|
||||
return workflowFailure(operation, cause, input);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -136,7 +136,7 @@ export const compareApplicationVersionsEvidenceValidated = (
|
||||
),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return workflowFailure(operation, cause);
|
||||
return workflowFailure(operation, cause, input);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -165,7 +165,7 @@ export const compareSourceToBundleEvidenceValidated = (
|
||||
),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return workflowFailure(operation, cause);
|
||||
return workflowFailure(operation, cause, input);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -225,19 +225,56 @@ export const compareJavaScriptExportShapesEvidenceValidated = (
|
||||
),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return workflowFailure(operation, cause);
|
||||
return workflowFailure(operation, cause, input);
|
||||
}
|
||||
};
|
||||
|
||||
const workflowFailure = (
|
||||
operation: string,
|
||||
cause: unknown,
|
||||
input: unknown,
|
||||
): Result<never, AnalysisError> =>
|
||||
err(
|
||||
cause instanceof z.ZodError || cause instanceof TypeError
|
||||
? new AnalysisInputError(operation)
|
||||
: new AnalysisProtocolError(
|
||||
"JavaScript application workflow produced an invalid result",
|
||||
{ cause },
|
||||
cause instanceof z.ZodError
|
||||
? err(
|
||||
new AnalysisInputError(
|
||||
operation,
|
||||
undefined,
|
||||
projectInputIssues(cause.issues, input),
|
||||
),
|
||||
);
|
||||
)
|
||||
: cause instanceof TypeError &&
|
||||
SAFE_APPLICATION_INPUT_CONSTRAINTS.has(cause.message)
|
||||
? err(
|
||||
new AnalysisInputError(operation, undefined, [
|
||||
{ path: [], reason: "invalid_value", message: cause.message },
|
||||
]),
|
||||
)
|
||||
: err(
|
||||
new AnalysisProtocolError(
|
||||
"JavaScript application workflow produced an invalid result",
|
||||
{ cause },
|
||||
),
|
||||
);
|
||||
|
||||
const SAFE_APPLICATION_INPUT_CONSTRAINTS = new Set([
|
||||
"Evidence semantic identifier does not match its record",
|
||||
"Application workflow requires authenticated analyze_javascript_application, reconcile_javascript_runtime, or project_managed_application_graph Evidence",
|
||||
"JavaScript application Evidence authority or confidence is invalid",
|
||||
"JavaScript application Evidence predicate does not match its result shape",
|
||||
"JavaScript application Evidence subject does not match its result",
|
||||
"Runtime reconciliation Evidence authority or confidence is invalid",
|
||||
"Runtime reconciliation result references Evidence outside its envelope",
|
||||
"Runtime reconciliation application layer is missing",
|
||||
"Managed application graph Evidence authority or confidence is invalid",
|
||||
"Managed application graph result references Evidence outside its envelope",
|
||||
"Native handoff Evidence requires an artifact subject",
|
||||
"Native handoff Evidence must be unique",
|
||||
...[
|
||||
"analyze_javascript_application",
|
||||
"reconcile_javascript_runtime",
|
||||
"project_managed_application_graph",
|
||||
].map(
|
||||
(operation) =>
|
||||
`Evidence does not match the supported ${operation} contract`,
|
||||
),
|
||||
]);
|
||||
|
||||
@@ -3,6 +3,7 @@ import { createHash } from "node:crypto";
|
||||
import { analyzeParsedJavaScriptStaticSource } from "../domain/javascriptStaticAnalysis.js";
|
||||
import { analyzeParsedJavaScriptSemantics } from "../domain/javascriptSemanticAnalysis.js";
|
||||
import { parseJavaScriptSource } from "../domain/javascriptSourceParser.js";
|
||||
import { hasValidSourceMapContents } from "../domain/sourceMapContents.js";
|
||||
import type {
|
||||
JavaScriptSourceRange,
|
||||
JavaScriptSourcePoint,
|
||||
@@ -249,9 +250,12 @@ const collectSourceMapOriginals = (
|
||||
const names = map.sources;
|
||||
if (!Array.isArray(names))
|
||||
return invalidSourceMap(file, "Source map has no sources array.");
|
||||
const contents = Array.isArray(map.sourcesContent)
|
||||
? map.sourcesContent
|
||||
: [];
|
||||
const contents = map.sourcesContent;
|
||||
if (!hasValidSourceMapContents(names.length, contents))
|
||||
return invalidSourceMap(
|
||||
file,
|
||||
"Source map sourcesContent must contain one string or null entry per source.",
|
||||
);
|
||||
const root = typeof map.sourceRoot === "string" ? map.sourceRoot : "";
|
||||
for (const [index, raw] of names.entries()) {
|
||||
if (typeof raw !== "string")
|
||||
@@ -259,8 +263,8 @@ const collectSourceMapOriginals = (
|
||||
file,
|
||||
"Source map contains a non-string source name.",
|
||||
);
|
||||
const content =
|
||||
typeof contents[index] === "string" ? contents[index] : null;
|
||||
const rawContent = Array.isArray(contents) ? contents[index] : undefined;
|
||||
const content = typeof rawContent === "string" ? rawContent : null;
|
||||
sources.push({
|
||||
source: resolveSourceName(root, raw),
|
||||
content,
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
import type { ControlledReplayInput } from "../domain/javascriptReplay.js";
|
||||
import type { EnabledJavaScriptReplayPolicy } from "./JavaScriptReplayPlanning.js";
|
||||
|
||||
/** Build the exact permission request for one controlled replay operation. */
|
||||
export const replayPermissionRequest = (
|
||||
input: ControlledReplayInput,
|
||||
policy: EnabledJavaScriptReplayPolicy,
|
||||
) => ({
|
||||
capability: "javascript_replay" as const,
|
||||
roots: [...input.left.modules, ...(input.right?.modules ?? [])].map(
|
||||
({ path }) => path,
|
||||
),
|
||||
executables: [
|
||||
policy.nodePath,
|
||||
policy.bubblewrapPath,
|
||||
policy.systemdRunPath,
|
||||
policy.systemctlPath,
|
||||
policy.shellPath,
|
||||
],
|
||||
environment_names: [],
|
||||
network: "none" as const,
|
||||
mount: true,
|
||||
operation_identity: `run_controlled_replay:${input.mode === "plan" ? "plan" : input.plan_digest}`,
|
||||
});
|
||||
@@ -2,15 +2,13 @@ import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
prepareReplayPlan,
|
||||
type EnabledJavaScriptReplayPolicy,
|
||||
type JavaScriptReplayConfiguration,
|
||||
type JavaScriptReplayHost,
|
||||
} from "./JavaScriptReplayPlanning.js";
|
||||
import { controlledReplayInputSchema } from "../domain/javascriptReplay.js";
|
||||
|
||||
const root = "/approved";
|
||||
const policy: EnabledJavaScriptReplayPolicy = {
|
||||
status: "enabled",
|
||||
roots: [root],
|
||||
const root = "/replay-fixture";
|
||||
const configuration: JavaScriptReplayConfiguration = {
|
||||
nodePath: "/runtime/node",
|
||||
bubblewrapPath: "/runtime/bwrap",
|
||||
systemdRunPath: "/runtime/systemd-run",
|
||||
@@ -100,7 +98,7 @@ describe("controlled replay planning input bounds", () => {
|
||||
limits: { protocol_bytes: 1024 * 1024 },
|
||||
});
|
||||
|
||||
await expect(prepareReplayPlan(input, policy, host)).rejects.toThrow(
|
||||
await expect(prepareReplayPlan(input, configuration, host)).rejects.toThrow(
|
||||
"Replay plan input exceeds its protocol byte limit",
|
||||
);
|
||||
expect(probe).not.toHaveBeenCalled();
|
||||
|
||||
@@ -41,10 +41,8 @@ export interface ReplayRuntimeFileIdentity {
|
||||
readonly sha256: string;
|
||||
}
|
||||
|
||||
/** Complete executable and source authority for enabled JavaScript replay. */
|
||||
export interface EnabledJavaScriptReplayPolicy {
|
||||
readonly status: "enabled";
|
||||
readonly roots: readonly [string, ...string[]];
|
||||
/** Executable paths required to establish isolated Linux JavaScript replay. */
|
||||
export interface JavaScriptReplayConfiguration {
|
||||
readonly nodePath: string;
|
||||
readonly bubblewrapPath: string;
|
||||
readonly systemdRunPath: string;
|
||||
@@ -52,11 +50,6 @@ export interface EnabledJavaScriptReplayPolicy {
|
||||
readonly shellPath: string;
|
||||
}
|
||||
|
||||
/** Parsed JavaScript replay configuration. */
|
||||
export type JavaScriptReplayPolicy =
|
||||
| { readonly status: "disabled" }
|
||||
| EnabledJavaScriptReplayPolicy;
|
||||
|
||||
export interface JavaScriptReplayHost {
|
||||
readonly readSource: (
|
||||
path: string,
|
||||
@@ -71,7 +64,9 @@ export interface JavaScriptReplayHost {
|
||||
nodePath: string,
|
||||
) => Promise<readonly ReplayRuntimeFileIdentity[]>;
|
||||
readonly seccompDigest: () => string;
|
||||
readonly probe: (policy: EnabledJavaScriptReplayPolicy) => Promise<void>;
|
||||
readonly probe: (
|
||||
configuration: JavaScriptReplayConfiguration,
|
||||
) => Promise<void>;
|
||||
}
|
||||
|
||||
export interface PreparedReplayPlan {
|
||||
@@ -83,7 +78,7 @@ export interface PreparedReplayPlan {
|
||||
export interface JavaScriptReplayRunner {
|
||||
readonly execute: (
|
||||
prepared: PreparedReplayPlan,
|
||||
policy: EnabledJavaScriptReplayPolicy,
|
||||
configuration: JavaScriptReplayConfiguration,
|
||||
signal?: AbortSignal,
|
||||
) => Promise<ReplayExecutionResult>;
|
||||
}
|
||||
@@ -101,7 +96,7 @@ const assertReplayManifestWithinProtocolLimit = (
|
||||
/** Read, normalize, and content-address every input to one replay experiment. */
|
||||
export const prepareReplayPlan = async (
|
||||
input: ControlledReplayInput,
|
||||
policy: EnabledJavaScriptReplayPolicy,
|
||||
configuration: JavaScriptReplayConfiguration,
|
||||
host: JavaScriptReplayHost,
|
||||
): Promise<PreparedReplayPlan> => {
|
||||
assertReplayManifestWithinProtocolLimit(input);
|
||||
@@ -115,7 +110,7 @@ export const prepareReplayPlan = async (
|
||||
).byteLength > input.limits.input_bytes
|
||||
)
|
||||
throw new RangeError("Replay case inputs exceed the aggregate byte limit");
|
||||
await host.probe(policy);
|
||||
await host.probe(configuration);
|
||||
const [
|
||||
runtime,
|
||||
bubblewrap,
|
||||
@@ -127,13 +122,13 @@ export const prepareReplayPlan = async (
|
||||
left,
|
||||
right,
|
||||
] = await Promise.all([
|
||||
host.identifyExecutable(policy.nodePath, ["--version"]),
|
||||
host.identifyExecutable(policy.bubblewrapPath, ["--version"]),
|
||||
host.identifyExecutable(policy.systemdRunPath, ["--version"]),
|
||||
host.identifyExecutable(policy.systemctlPath, ["--version"]),
|
||||
host.identifyExecutable(policy.shellPath, ["--version"]),
|
||||
host.identifyExecutable(configuration.nodePath, ["--version"]),
|
||||
host.identifyExecutable(configuration.bubblewrapPath, ["--version"]),
|
||||
host.identifyExecutable(configuration.systemdRunPath, ["--version"]),
|
||||
host.identifyExecutable(configuration.systemctlPath, ["--version"]),
|
||||
host.identifyExecutable(configuration.shellPath, ["--version"]),
|
||||
host.identifyWorker(),
|
||||
host.identifyRuntimeClosure(policy.nodePath),
|
||||
host.identifyRuntimeClosure(configuration.nodePath),
|
||||
prepareSide(input.left, input.limits.module_bytes, host),
|
||||
input.right === undefined
|
||||
? Promise.resolve(undefined)
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { projectPermissionFailure } from "./PermissionFailure.js";
|
||||
import { z } from "zod";
|
||||
import writeFileAtomic from "write-file-atomic";
|
||||
|
||||
@@ -23,14 +22,11 @@ import { projectInputIssues } from "../domain/inputIssueProjection.js";
|
||||
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import type { ExecutionOptions } from "./AnalysisProvider.js";
|
||||
import type { PermissionAuthority } from "./PermissionAuthority.js";
|
||||
import { replayPermissionRequest } from "./JavaScriptReplayPermission.js";
|
||||
import {
|
||||
digestBytes,
|
||||
prepareReplayPlan,
|
||||
type EnabledJavaScriptReplayPolicy,
|
||||
type JavaScriptReplayConfiguration,
|
||||
type JavaScriptReplayHost,
|
||||
type JavaScriptReplayPolicy,
|
||||
type JavaScriptReplayRunner,
|
||||
} from "./JavaScriptReplayPlanning.js";
|
||||
|
||||
@@ -39,10 +35,9 @@ const isAborted = (signal: AbortSignal | undefined): boolean =>
|
||||
signal?.aborted === true;
|
||||
|
||||
export interface JavaScriptReplayDependencies {
|
||||
readonly policy: () => JavaScriptReplayPolicy;
|
||||
readonly configuration: () => JavaScriptReplayConfiguration;
|
||||
readonly host: JavaScriptReplayHost;
|
||||
readonly runner: JavaScriptReplayRunner;
|
||||
readonly authority: PermissionAuthority | undefined;
|
||||
}
|
||||
|
||||
/** Plan or execute one content-bound extracted-module replay experiment. */
|
||||
@@ -69,17 +64,13 @@ export const runControlledReplayValidated = async (
|
||||
input: ControlledReplayInput,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<JsonValue, AnalysisError>> => {
|
||||
const authorized = await authorizeReplay(
|
||||
dependencies,
|
||||
dependencies.policy(),
|
||||
input,
|
||||
options.signal,
|
||||
);
|
||||
if (!authorized.ok) return authorized;
|
||||
if (isAborted(options.signal))
|
||||
return err(new AnalysisCancelledError(OPERATION));
|
||||
const configuration = dependencies.configuration();
|
||||
|
||||
const prepared = await prepareValidatedReplay(
|
||||
dependencies,
|
||||
authorized.value,
|
||||
configuration,
|
||||
input,
|
||||
options.signal,
|
||||
);
|
||||
@@ -105,12 +96,12 @@ export const runControlledReplayValidated = async (
|
||||
),
|
||||
);
|
||||
|
||||
const exportContext = await authorizeReproducerExport(input);
|
||||
const exportContext = prepareReproducerExport(input);
|
||||
if (!exportContext.ok) return exportContext;
|
||||
|
||||
const executed = await executeValidatedReplay({
|
||||
runner: dependencies.runner,
|
||||
policy: authorized.value,
|
||||
configuration,
|
||||
prepared: prepared.value,
|
||||
exportContext: exportContext.value,
|
||||
options,
|
||||
@@ -137,42 +128,9 @@ export const runControlledReplayValidated = async (
|
||||
}
|
||||
};
|
||||
|
||||
const authorizeReplay = async (
|
||||
dependencies: JavaScriptReplayDependencies,
|
||||
policy: JavaScriptReplayPolicy,
|
||||
input: ControlledReplayInput,
|
||||
signal: AbortSignal | undefined,
|
||||
): Promise<Result<EnabledJavaScriptReplayPolicy, AnalysisError>> => {
|
||||
if (policy.status === "disabled")
|
||||
return err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
"rea-javascript-replay",
|
||||
OPERATION,
|
||||
"controlled replay is disabled; configure exact roots and executables before enabling it",
|
||||
),
|
||||
);
|
||||
if (dependencies.authority === undefined)
|
||||
return err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
"rea-javascript-replay",
|
||||
OPERATION,
|
||||
"JavaScript replay permission policy is not configured",
|
||||
),
|
||||
);
|
||||
if (isAborted(signal)) return err(new AnalysisCancelledError(OPERATION));
|
||||
|
||||
const request = replayPermissionRequest(input, policy);
|
||||
const authorized =
|
||||
input.mode === "plan"
|
||||
? await dependencies.authority.explain(request, "read")
|
||||
: await dependencies.authority.authorize(request, "read");
|
||||
if (!authorized.ok) return err(projectPermissionFailure(authorized.error));
|
||||
return ok(policy);
|
||||
};
|
||||
|
||||
const prepareValidatedReplay = async (
|
||||
dependencies: JavaScriptReplayDependencies,
|
||||
policy: EnabledJavaScriptReplayPolicy,
|
||||
configuration: JavaScriptReplayConfiguration,
|
||||
input: ControlledReplayInput,
|
||||
signal: AbortSignal | undefined,
|
||||
): Promise<
|
||||
@@ -180,7 +138,7 @@ const prepareValidatedReplay = async (
|
||||
> => {
|
||||
if (isAborted(signal)) return err(new AnalysisCancelledError(OPERATION));
|
||||
try {
|
||||
return ok(await prepareReplayPlan(input, policy, dependencies.host));
|
||||
return ok(await prepareReplayPlan(input, configuration, dependencies.host));
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
@@ -197,7 +155,7 @@ interface ReproducerExportContext {
|
||||
readonly includeSources: boolean;
|
||||
}
|
||||
|
||||
const authorizeReproducerExport = (
|
||||
const prepareReproducerExport = (
|
||||
input: ControlledReplayExecutionInput,
|
||||
): Result<ReproducerExportContext | undefined, AnalysisError> => {
|
||||
if (input.reproducer_export === undefined) return ok(undefined);
|
||||
@@ -209,7 +167,7 @@ const authorizeReproducerExport = (
|
||||
|
||||
interface ReplayExecutionContext {
|
||||
readonly runner: JavaScriptReplayRunner;
|
||||
readonly policy: EnabledJavaScriptReplayPolicy;
|
||||
readonly configuration: JavaScriptReplayConfiguration;
|
||||
readonly prepared: Awaited<ReturnType<typeof prepareReplayPlan>>;
|
||||
readonly exportContext: ReproducerExportContext | undefined;
|
||||
readonly options: ExecutionOptions;
|
||||
@@ -226,19 +184,19 @@ const executeValidatedReplay = async (
|
||||
AnalysisError
|
||||
>
|
||||
> => {
|
||||
const { runner, policy, prepared, exportContext, options } = context;
|
||||
const { runner, configuration, prepared, exportContext, options } = context;
|
||||
await options.progress?.report({
|
||||
phase: OPERATION,
|
||||
completed: 0,
|
||||
total: 1,
|
||||
message: "Admitting approved modules into the isolated replay worker",
|
||||
message: "Starting the isolated replay worker",
|
||||
});
|
||||
if (isAborted(options.signal))
|
||||
return err(new AnalysisCancelledError(OPERATION));
|
||||
|
||||
try {
|
||||
let executed = replayExecutionResultSchema.parse(
|
||||
await runner.execute(prepared, policy, options.signal),
|
||||
await runner.execute(prepared, configuration, options.signal),
|
||||
);
|
||||
await options.progress?.report({
|
||||
phase: OPERATION,
|
||||
@@ -302,7 +260,7 @@ const applyReproducerExport = async (
|
||||
...executed,
|
||||
limitations: [
|
||||
...executed.limitations,
|
||||
"Replay completed, but the separately approved reproducer export failed.",
|
||||
"Replay completed, but the requested reproducer export failed.",
|
||||
],
|
||||
reproducer: {
|
||||
state: "failed",
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import { projectPermissionFailure } from "./PermissionFailure.js";
|
||||
import type { ExecutionOptions } from "./AnalysisProvider.js";
|
||||
import type { JavaScriptRuntimeObservationPort } from "./JavaScriptRuntimeObservationPort.js";
|
||||
import type { PermissionAuthority } from "./PermissionAuthority.js";
|
||||
import { createJavaScriptRuntimeObservationEvidence } from "./JavaScriptRuntimeObservationEvidence.js";
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
import {
|
||||
@@ -14,19 +12,13 @@ import type {
|
||||
} from "../domain/javascriptRuntimeObservation.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
|
||||
/** Authorize and list attachable Node/Electron Inspector targets. */
|
||||
/** List targets exposed by the explicitly selected loopback Inspector. */
|
||||
export const listJavaScriptRuntimeTargets = async (
|
||||
provider: JavaScriptRuntimeObservationPort | undefined,
|
||||
authority: PermissionAuthority | undefined,
|
||||
input: ListJavaScriptRuntimeTargetsInput,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<Evidence, AnalysisError>> => {
|
||||
const ready = await prepare(
|
||||
provider,
|
||||
authority,
|
||||
input,
|
||||
"list_javascript_runtime_targets",
|
||||
);
|
||||
const ready = requireProvider(provider, "list_javascript_runtime_targets");
|
||||
if (!ready.ok) return ready;
|
||||
const result = await ready.value.listTargets(input, options);
|
||||
return result.ok
|
||||
@@ -41,19 +33,13 @@ export const listJavaScriptRuntimeTargets = async (
|
||||
: result;
|
||||
};
|
||||
|
||||
/** Authorize one bounded attach-only Inspector observation. */
|
||||
/** Observe one attach-only Inspector target selected by the request. */
|
||||
export const observeJavaScriptRuntime = async (
|
||||
provider: JavaScriptRuntimeObservationPort | undefined,
|
||||
authority: PermissionAuthority | undefined,
|
||||
input: ObserveJavaScriptRuntimeInput,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<Evidence, AnalysisError>> => {
|
||||
const ready = await prepare(
|
||||
provider,
|
||||
authority,
|
||||
input,
|
||||
"observe_javascript_runtime",
|
||||
);
|
||||
const ready = requireProvider(provider, "observe_javascript_runtime");
|
||||
if (!ready.ok) return ready;
|
||||
const result = await ready.value.observe(input, options);
|
||||
return result.ok
|
||||
@@ -68,34 +54,11 @@ export const observeJavaScriptRuntime = async (
|
||||
: result;
|
||||
};
|
||||
|
||||
const prepare = async (
|
||||
const requireProvider = (
|
||||
provider: JavaScriptRuntimeObservationPort | undefined,
|
||||
authority: PermissionAuthority | undefined,
|
||||
input: ListJavaScriptRuntimeTargetsInput | ObserveJavaScriptRuntimeInput,
|
||||
operation: "list_javascript_runtime_targets" | "observe_javascript_runtime",
|
||||
): Promise<Result<JavaScriptRuntimeObservationPort, AnalysisError>> => {
|
||||
if (authority === undefined)
|
||||
return err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
"rea-v8-inspector",
|
||||
operation,
|
||||
"V8 Inspector observation permission policy is not configured",
|
||||
),
|
||||
);
|
||||
const authorized = await authority.authorize(
|
||||
{
|
||||
capability: "v8_inspector_observe",
|
||||
roots: [],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
network: "loopback",
|
||||
mount: false,
|
||||
operation_identity: `${operation}:${"target_id" in input ? input.target_id : input.inspector_endpoint}`,
|
||||
},
|
||||
"read",
|
||||
);
|
||||
if (!authorized.ok) return err(projectPermissionFailure(authorized.error));
|
||||
return provider === undefined
|
||||
): Result<JavaScriptRuntimeObservationPort, AnalysisError> =>
|
||||
provider === undefined
|
||||
? err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
"rea-v8-inspector",
|
||||
@@ -104,4 +67,3 @@ const prepare = async (
|
||||
),
|
||||
)
|
||||
: ok(provider);
|
||||
};
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { resolve } from "node:path";
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
@@ -32,19 +33,82 @@ export const reconcileJavaScriptRuntimeEvidence = (
|
||||
|
||||
/** Reconcile input already parsed by a trusted adapter boundary. */
|
||||
export const reconcileJavaScriptRuntimeEvidenceValidated = (
|
||||
input: z.output<typeof reconcileJavaScriptRuntimeInputSchema>,
|
||||
parsedInput: z.output<typeof reconcileJavaScriptRuntimeInputSchema>,
|
||||
): Result<Evidence, AnalysisError> => {
|
||||
try {
|
||||
const input = reconcileJavaScriptRuntimeInputSchema.parse(
|
||||
normalizeRuntimeMappingRoots(parsedInput),
|
||||
);
|
||||
const result = reconcileJavaScriptRuntime(input);
|
||||
return ok(createJavaScriptRuntimeReconciliationEvidence(input, result));
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof z.ZodError)
|
||||
return err(
|
||||
new AnalysisInputError(
|
||||
OPERATION,
|
||||
undefined,
|
||||
projectInputIssues(cause.issues, parsedInput),
|
||||
),
|
||||
);
|
||||
if (
|
||||
cause instanceof TypeError &&
|
||||
SAFE_RECONCILIATION_INPUT_CONSTRAINTS.has(cause.message)
|
||||
)
|
||||
return err(
|
||||
new AnalysisInputError(OPERATION, undefined, [
|
||||
{ path: [], reason: "invalid_value", message: cause.message },
|
||||
]),
|
||||
);
|
||||
return err(
|
||||
cause instanceof z.ZodError || cause instanceof TypeError
|
||||
? new AnalysisInputError(OPERATION)
|
||||
: new AnalysisProtocolError(
|
||||
"JavaScript runtime reconciliation produced an invalid result",
|
||||
{ cause },
|
||||
),
|
||||
new AnalysisProtocolError(
|
||||
"JavaScript runtime reconciliation produced an invalid result",
|
||||
{ cause },
|
||||
),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const normalizeRuntimeMappingRoots = (
|
||||
input: z.output<typeof reconcileJavaScriptRuntimeInputSchema>,
|
||||
): z.output<typeof reconcileJavaScriptRuntimeInputSchema> => ({
|
||||
...input,
|
||||
static_layers: input.static_layers.map((layer) => ({
|
||||
...layer,
|
||||
runtime_mappings: layer.runtime_mappings.map((mapping) =>
|
||||
mapping.kind === "file-root"
|
||||
? {
|
||||
...mapping,
|
||||
root: isPortableAbsolutePath(mapping.root)
|
||||
? mapping.root
|
||||
: resolve(mapping.root),
|
||||
}
|
||||
: mapping,
|
||||
),
|
||||
})),
|
||||
});
|
||||
|
||||
const isPortableAbsolutePath = (path: string): boolean =>
|
||||
path.startsWith("/") ||
|
||||
/^[a-z]:[\\/]/iu.test(path) ||
|
||||
/^(?:\\\\|\/\/)[^\\/]+[\\/][^\\/]+(?:[\\/]|$)/u.test(path);
|
||||
|
||||
const SAFE_RECONCILIATION_INPUT_CONSTRAINTS = new Set([
|
||||
"Evidence semantic identifier does not match its record",
|
||||
"JavaScript application Evidence subject disagrees with its result",
|
||||
"Runtime reconciliation requires inspect_web_page, inspect_electron_page, observe_javascript_runtime, or capture_electron_scenario Evidence",
|
||||
"Runtime Evidence target or declared role disagrees with its result",
|
||||
"Runtime Evidence contains an invalid builtin location",
|
||||
"Runtime Evidence target disagrees with its captured result",
|
||||
"Browser Evidence target is outside its recorded origin scope",
|
||||
"Runtime Evidence contains source without source-capture selection",
|
||||
"Active Electron Evidence application path disagrees with its configured root",
|
||||
...[
|
||||
"inspect_web_page",
|
||||
"inspect_electron_page",
|
||||
"observe_javascript_runtime",
|
||||
"capture_electron_scenario",
|
||||
].map(
|
||||
(operation) =>
|
||||
`Evidence does not match the supported ${operation} contract`,
|
||||
),
|
||||
]);
|
||||
|
||||
@@ -179,7 +179,8 @@ const handleHttpRequest = async (
|
||||
recorder.scenario.limits.protocol_body_bytes,
|
||||
);
|
||||
const method = request.method ?? "GET";
|
||||
const path = new URL(request.url ?? "/", "http://127.0.0.1").pathname;
|
||||
const requestUrl = new URL(request.url ?? "/", "http://127.0.0.1");
|
||||
const path = `${requestUrl.pathname}${requestUrl.search}`;
|
||||
if (body === undefined) {
|
||||
recorder.truncated = true;
|
||||
response.statusCode = 413;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFile } from "node:fs/promises";
|
||||
|
||||
import { z } from "zod";
|
||||
@@ -11,6 +12,7 @@ import {
|
||||
import {
|
||||
AnalysisInputError,
|
||||
AnalysisProtocolError,
|
||||
EvidenceIntegrityError,
|
||||
type AnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
import { createEvidence, type Evidence } from "../domain/evidence.js";
|
||||
@@ -41,16 +43,29 @@ export const compareManagedMembersEvidenceValidated = (
|
||||
}
|
||||
};
|
||||
|
||||
interface ManagedMemberComparisonPathDependencies {
|
||||
readonly resolveTarget: typeof parseBinaryTarget;
|
||||
readonly readBytes: (path: string) => Promise<Buffer>;
|
||||
}
|
||||
|
||||
const DEFAULT_PATH_DEPENDENCIES: ManagedMemberComparisonPathDependencies = {
|
||||
resolveTarget: parseBinaryTarget,
|
||||
readBytes: readFile,
|
||||
};
|
||||
|
||||
/** Inspect two local PE artifacts and return one derived comparison Evidence. */
|
||||
export const compareManagedMemberPaths = async (input: {
|
||||
readonly leftPath: string;
|
||||
readonly rightPath: string;
|
||||
}): Promise<Result<Evidence, AnalysisError>> => {
|
||||
export const compareManagedMemberPaths = async (
|
||||
input: {
|
||||
readonly leftPath: string;
|
||||
readonly rightPath: string;
|
||||
},
|
||||
dependencies: ManagedMemberComparisonPathDependencies = DEFAULT_PATH_DEPENDENCIES,
|
||||
): Promise<Result<Evidence, AnalysisError>> => {
|
||||
const operation = "compare_managed_members";
|
||||
try {
|
||||
const [leftTarget, rightTarget] = await Promise.all([
|
||||
parseBinaryTarget(input.leftPath),
|
||||
parseBinaryTarget(input.rightPath),
|
||||
dependencies.resolveTarget(input.leftPath),
|
||||
dependencies.resolveTarget(input.rightPath),
|
||||
]);
|
||||
if (!leftTarget.ok)
|
||||
return err(
|
||||
@@ -61,9 +76,21 @@ export const compareManagedMemberPaths = async (input: {
|
||||
new AnalysisInputError(operation, { cause: rightTarget.error }),
|
||||
);
|
||||
const [leftBytes, rightBytes] = await Promise.all([
|
||||
readFile(leftTarget.value.path),
|
||||
readFile(rightTarget.value.path),
|
||||
dependencies.readBytes(leftTarget.value.path),
|
||||
dependencies.readBytes(rightTarget.value.path),
|
||||
]);
|
||||
for (const [target, bytes] of [
|
||||
[leftTarget.value, leftBytes],
|
||||
[rightTarget.value, rightBytes],
|
||||
] as const) {
|
||||
const observedSha256 = createHash("sha256").update(bytes).digest("hex");
|
||||
if (observedSha256 !== target.sha256)
|
||||
return err(
|
||||
new EvidenceIntegrityError(
|
||||
`Managed artifact digest changed after open: expected ${target.sha256}, observed ${observedSha256} at ${target.path}`,
|
||||
),
|
||||
);
|
||||
}
|
||||
const leftInspection = inspectManagedMembersBytes(
|
||||
leftBytes,
|
||||
leftTarget.value,
|
||||
|
||||
@@ -1,15 +1,9 @@
|
||||
import { projectPermissionFailure } from "./PermissionFailure.js";
|
||||
import {
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisInputError,
|
||||
AnalysisProtocolError,
|
||||
type AnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
import {
|
||||
createEvidence,
|
||||
parseEvidence,
|
||||
type Evidence,
|
||||
} from "../domain/evidence.js";
|
||||
import { createEvidence, type Evidence } from "../domain/evidence.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import {
|
||||
managedRuntimeCorrelationInputSchema,
|
||||
@@ -17,33 +11,21 @@ import {
|
||||
type ManagedRuntimeCorrelationInput,
|
||||
} from "../domain/managedRuntimeCorrelation.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import type { PermissionAuthority } from "./PermissionAuthority.js";
|
||||
import { MANAGED_WORKFLOW_PROVIDER } from "./InvestigationProviders.js";
|
||||
import { digestJson } from "./JavaScriptReplayPlanning.js";
|
||||
|
||||
const OPERATION = "plan_managed_runtime_correlation" as const;
|
||||
|
||||
/** Parsed availability and authority scope for managed runtime correlation. */
|
||||
export type ManagedRuntimePolicy =
|
||||
| { readonly status: "disabled" }
|
||||
| {
|
||||
readonly status: "enabled";
|
||||
readonly roots: readonly [string, ...string[]];
|
||||
readonly executablePath: string;
|
||||
};
|
||||
|
||||
/** A managed-runtime policy that grants no runtime-correlation authority. */
|
||||
export const MANAGED_RUNTIME_DISABLED = {
|
||||
status: "disabled",
|
||||
} as const satisfies ManagedRuntimePolicy;
|
||||
|
||||
/** Live policy and authority dependencies for managed runtime correlation. */
|
||||
export interface ManagedRuntimeCorrelationDependencies {
|
||||
readonly policy: () => ManagedRuntimePolicy;
|
||||
readonly authority: PermissionAuthority | undefined;
|
||||
/** Configured local runtime executable used when preparing a correlation plan. */
|
||||
export interface ManagedRuntimeConfiguration {
|
||||
readonly executablePath: string | undefined;
|
||||
}
|
||||
|
||||
/** Create a separately authorized, non-executing managed runtime plan Evidence. */
|
||||
/** Live managed runtime configuration source, evaluated for each request. */
|
||||
export interface ManagedRuntimeCorrelationDependencies {
|
||||
readonly configuration: () => ManagedRuntimeConfiguration;
|
||||
}
|
||||
|
||||
/** Create a non-executing managed runtime correlation plan Evidence record. */
|
||||
export const planManagedRuntimeCorrelationEvidence = async (
|
||||
dependencies: ManagedRuntimeCorrelationDependencies,
|
||||
rawInput: unknown,
|
||||
@@ -62,50 +44,10 @@ export const planManagedRuntimeCorrelationEvidenceValidated = async (
|
||||
dependencies: ManagedRuntimeCorrelationDependencies,
|
||||
input: ManagedRuntimeCorrelationInput,
|
||||
): Promise<Result<Evidence, AnalysisError>> => {
|
||||
const policy = dependencies.policy();
|
||||
if (policy.status === "disabled")
|
||||
return err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
MANAGED_WORKFLOW_PROVIDER.id,
|
||||
OPERATION,
|
||||
"managed runtime correlation is disabled; configure exact roots and runtime executable before enabling it",
|
||||
),
|
||||
);
|
||||
if (dependencies.authority === undefined)
|
||||
return err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
MANAGED_WORKFLOW_PROVIDER.id,
|
||||
OPERATION,
|
||||
"managed runtime permission policy is not configured",
|
||||
),
|
||||
);
|
||||
let staticEvidence: Evidence, artifactPath: string;
|
||||
const executablePath =
|
||||
dependencies.configuration().executablePath ?? "dotnet";
|
||||
try {
|
||||
staticEvidence = parseEvidence(input.static_members);
|
||||
artifactPath = artifactPathFor(staticEvidence);
|
||||
} catch (cause: unknown) {
|
||||
return err(new AnalysisInputError(OPERATION, { cause }));
|
||||
}
|
||||
const authorized = await dependencies.authority.explain(
|
||||
{
|
||||
capability: "managed_runtime",
|
||||
roots: [artifactPath],
|
||||
executables: [policy.executablePath],
|
||||
environment_names: [],
|
||||
network: "none",
|
||||
mount: false,
|
||||
operation_identity: operationIdentity(input, staticEvidence),
|
||||
},
|
||||
"read",
|
||||
{ remediation: "restart" },
|
||||
);
|
||||
if (!authorized.ok) return err(projectPermissionFailure(authorized.error));
|
||||
try {
|
||||
const result = planManagedRuntimeCorrelation(
|
||||
input,
|
||||
policy.executablePath,
|
||||
authorized.value.grant_id,
|
||||
);
|
||||
const result = planManagedRuntimeCorrelation(input, executablePath);
|
||||
return ok(
|
||||
createEvidence(
|
||||
{
|
||||
@@ -118,7 +60,7 @@ export const planManagedRuntimeCorrelationEvidenceValidated = async (
|
||||
predicateType: "rea.managed-runtime-correlation-plan",
|
||||
operation: OPERATION,
|
||||
parameters: {
|
||||
static_members_evidence_id: staticEvidence.evidence_id,
|
||||
static_members_evidence_id: result.static_observation.evidence_id,
|
||||
method: jsonValueSchema.parse(input.method),
|
||||
requested_effect: input.requested_effect,
|
||||
host: jsonValueSchema.parse(input.host),
|
||||
@@ -151,34 +93,3 @@ export const planManagedRuntimeCorrelationEvidenceValidated = async (
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const artifactPathFor = (evidence: Evidence): string => {
|
||||
const result = evidence.normalized_result;
|
||||
if (
|
||||
typeof result === "object" &&
|
||||
result !== null &&
|
||||
"artifact" in result &&
|
||||
typeof result.artifact === "object" &&
|
||||
result.artifact !== null &&
|
||||
"path" in result.artifact &&
|
||||
typeof result.artifact.path === "string"
|
||||
)
|
||||
return result.artifact.path;
|
||||
throw new AnalysisInputError(OPERATION, {
|
||||
cause: new TypeError(
|
||||
"Managed member Evidence does not expose an artifact path",
|
||||
),
|
||||
});
|
||||
};
|
||||
|
||||
const operationIdentity = (
|
||||
input: ManagedRuntimeCorrelationInput,
|
||||
evidence: Evidence,
|
||||
): string =>
|
||||
`${OPERATION}:${digestJson({
|
||||
evidence_id: evidence.evidence_id,
|
||||
method: input.method,
|
||||
requested_effect: input.requested_effect,
|
||||
host: input.host,
|
||||
bounds: input.bounds,
|
||||
})}`;
|
||||
|
||||
@@ -65,7 +65,7 @@ export const prepareNodeCharacterization = async (
|
||||
: prepared;
|
||||
};
|
||||
|
||||
/** Execute only a freshly recomputed and separately approved characterization plan. */
|
||||
/** Execute only when the supplied plan hash matches freshly prepared content. */
|
||||
export const executeNodeCharacterization = async (
|
||||
dependencies: JavaScriptReplayDependencies,
|
||||
rawInput: unknown,
|
||||
@@ -82,10 +82,10 @@ export const executeNodeCharacterization = async (
|
||||
options,
|
||||
);
|
||||
if (!prepared.ok) return prepared;
|
||||
if (prepared.value.plan.plan_sha256 !== parsed.data.approved_plan_sha256)
|
||||
if (prepared.value.plan.plan_sha256 !== parsed.data.plan_sha256)
|
||||
return err(
|
||||
new ReplayPlanStaleError(
|
||||
parsed.data.approved_plan_sha256,
|
||||
parsed.data.plan_sha256,
|
||||
prepared.value.plan.plan_sha256,
|
||||
),
|
||||
);
|
||||
@@ -229,7 +229,7 @@ const createTransformationEvidence = (
|
||||
},
|
||||
],
|
||||
limitations: [
|
||||
"The transformation is deterministic derived evidence; execution authority is established only by a separately approved characterization run.",
|
||||
"The transformation is deterministic derived evidence; execution results are limited to the characterization plan whose content hash matched.",
|
||||
],
|
||||
},
|
||||
);
|
||||
@@ -266,7 +266,7 @@ const createCharacterizationEvidence = (
|
||||
authority: "controlled-replay",
|
||||
environment: replay.evidence.environment,
|
||||
limitations: [
|
||||
"This Evidence proves only the finite approved characterization plan and transformed controlled-replay authority, not unmodified shipped-runtime equivalence.",
|
||||
"This Evidence proves only the finite hash-matched characterization plan and transformed controlled-replay result, not unmodified shipped-runtime equivalence.",
|
||||
...replay.evidence.limitations,
|
||||
],
|
||||
evidenceLinks: [
|
||||
@@ -326,12 +326,6 @@ const createCharacterizationPlan = (
|
||||
identifiers: "deterministic",
|
||||
seed: replayPlan.determinism.random_seed,
|
||||
},
|
||||
authority: {
|
||||
preparation_approved: true,
|
||||
execution_approved: false,
|
||||
network: "none",
|
||||
provider_owned_process_only: true,
|
||||
},
|
||||
});
|
||||
|
||||
const digestPreparation = (
|
||||
|
||||
@@ -1,435 +0,0 @@
|
||||
import { realpath } from "node:fs/promises";
|
||||
import { basename, dirname, join, resolve } from "node:path";
|
||||
|
||||
import type {
|
||||
PermissionCeiling,
|
||||
PermissionDecision,
|
||||
PermissionGrant,
|
||||
PermissionPolicy,
|
||||
PermissionRequest,
|
||||
PermissionScope,
|
||||
} from "../domain/permissionPolicy.js";
|
||||
import {
|
||||
consumePermission,
|
||||
clearSessionPermissions,
|
||||
createPermissionPolicy,
|
||||
evaluatePermission,
|
||||
grantPermission,
|
||||
reloadPermissionCeilings,
|
||||
revokePermission,
|
||||
} from "../domain/permissionPolicy.js";
|
||||
import {
|
||||
PermissionRequiredError,
|
||||
type PermissionRemediation,
|
||||
} from "../domain/errors.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
|
||||
/** Failure to establish a filesystem object's canonical authorization identity. */
|
||||
export class PermissionPathError extends Error {
|
||||
readonly _tag = "PermissionPathError" as const;
|
||||
|
||||
constructor(
|
||||
readonly path: string,
|
||||
readonly reason: "not_found" | "io",
|
||||
options?: ErrorOptions,
|
||||
) {
|
||||
super(`Cannot canonicalize permission path: ${path}`, options);
|
||||
}
|
||||
}
|
||||
|
||||
/** Canonicalize administrator ceilings before they become authorization state. */
|
||||
export const canonicalizePermissionCeilings = async (
|
||||
ceilings: readonly PermissionCeiling[],
|
||||
): Promise<Result<readonly PermissionCeiling[], PermissionPathError>> => {
|
||||
const normalized: PermissionCeiling[] = [];
|
||||
for (const ceiling of ceilings) {
|
||||
const canonical = await canonicalizeScope(ceiling, "read");
|
||||
if (!canonical.ok) return canonical;
|
||||
normalized.push(canonical.value);
|
||||
}
|
||||
return ok(normalized);
|
||||
};
|
||||
|
||||
/** Canonicalize one exact operation request before subset evaluation. */
|
||||
export const canonicalizePermissionRequest = async (
|
||||
request: PermissionRequest,
|
||||
access: "read" | "write",
|
||||
): Promise<Result<PermissionRequest, PermissionPathError>> => {
|
||||
const canonical = await canonicalizeScope(request, access);
|
||||
return canonical.ok
|
||||
? ok({ ...canonical.value, operation_identity: request.operation_identity })
|
||||
: canonical;
|
||||
};
|
||||
|
||||
const canonicalizeScope = async (
|
||||
scope: PermissionScope,
|
||||
access: "read" | "write",
|
||||
): Promise<Result<PermissionScope, PermissionPathError>> => {
|
||||
const roots = await canonicalizePaths(scope.roots, access);
|
||||
if (!roots.ok) return roots;
|
||||
const executables = await canonicalizePaths(scope.executables, "read");
|
||||
if (!executables.ok) return executables;
|
||||
return ok({ ...scope, roots: roots.value, executables: executables.value });
|
||||
};
|
||||
|
||||
const canonicalizePaths = async (
|
||||
paths: readonly string[],
|
||||
access: "read" | "write",
|
||||
): Promise<Result<readonly string[], PermissionPathError>> => {
|
||||
const canonical: string[] = [];
|
||||
for (const path of paths) {
|
||||
const result = await canonicalizePath(path, access);
|
||||
if (!result.ok) return result;
|
||||
canonical.push(result.value);
|
||||
}
|
||||
return ok(canonical);
|
||||
};
|
||||
|
||||
const canonicalizePath = async (
|
||||
path: string,
|
||||
access: "read" | "write",
|
||||
): Promise<Result<string, PermissionPathError>> => {
|
||||
const requested = resolve(path);
|
||||
try {
|
||||
return ok(await realpath(requested));
|
||||
} catch (cause: unknown) {
|
||||
if (access !== "write" || !isNotFound(cause))
|
||||
return err(new PermissionPathError(path, errorReason(cause), { cause }));
|
||||
}
|
||||
try {
|
||||
const parent = await realpath(dirname(requested));
|
||||
return ok(join(parent, basename(requested)));
|
||||
} catch (cause: unknown) {
|
||||
return err(new PermissionPathError(path, errorReason(cause), { cause }));
|
||||
}
|
||||
};
|
||||
|
||||
const isNotFound = (error: unknown): boolean =>
|
||||
error instanceof Error && "code" in error && error.code === "ENOENT";
|
||||
|
||||
const errorReason = (error: unknown): PermissionPathError["reason"] =>
|
||||
isNotFound(error) ? "not_found" : "io";
|
||||
|
||||
interface PermissionEvaluationOptions {
|
||||
readonly remediation?: PermissionRemediation;
|
||||
}
|
||||
|
||||
interface CanonicalPermissionDecision {
|
||||
readonly decision: Extract<PermissionDecision, { readonly allowed: true }>;
|
||||
readonly owner: PermissionAuthority;
|
||||
readonly request: PermissionRequest;
|
||||
}
|
||||
|
||||
type AuthorizedPermission = PermissionDecision & {
|
||||
readonly allowed: true;
|
||||
readonly request: PermissionRequest;
|
||||
};
|
||||
|
||||
type PermissionAuthorizationResult = Promise<
|
||||
Result<AuthorizedPermission, PermissionPathError | PermissionRequiredError>
|
||||
>;
|
||||
|
||||
/** Stateful owner for permission evaluation, consumption, reload, and revoke. */
|
||||
export class PermissionAuthority {
|
||||
private policy: PermissionPolicy;
|
||||
private readonly configuredAuthority: PermissionAuthority | undefined;
|
||||
private readonly outsideCeilingRemediation: Exclude<
|
||||
PermissionRemediation,
|
||||
"elicit"
|
||||
>;
|
||||
|
||||
constructor(
|
||||
policy: PermissionPolicy,
|
||||
configuredAuthority?: PermissionAuthority,
|
||||
outsideCeilingRemediation: Exclude<
|
||||
PermissionRemediation,
|
||||
"elicit"
|
||||
> = "configure",
|
||||
) {
|
||||
this.policy = policy;
|
||||
this.configuredAuthority = configuredAuthority;
|
||||
this.outsideCeilingRemediation = outsideCeilingRemediation;
|
||||
}
|
||||
|
||||
/** Create a connection-owned overlay for once and session grants. */
|
||||
createConnectionAuthority(): PermissionAuthority {
|
||||
return new PermissionAuthority(
|
||||
createPermissionPolicy([]),
|
||||
this.configuredAuthority ?? this,
|
||||
"restart",
|
||||
);
|
||||
}
|
||||
|
||||
/** Canonicalize and authorize one exact operation before its side effect. */
|
||||
async authorize(
|
||||
request: PermissionRequest,
|
||||
access: "read" | "write",
|
||||
options: PermissionEvaluationOptions = {},
|
||||
): PermissionAuthorizationResult {
|
||||
const evaluated = await this.evaluateRequest(request, access, options);
|
||||
if (!evaluated.ok) return evaluated;
|
||||
const { decision, owner, request: canonicalRequest } = evaluated.value;
|
||||
owner.policy = consumePermission(owner.policy, decision);
|
||||
return ok({ ...decision, request: canonicalRequest });
|
||||
}
|
||||
|
||||
/** Dry-run the exact shared evaluation without consuming a once grant. */
|
||||
async explain(
|
||||
request: PermissionRequest,
|
||||
access: "read" | "write",
|
||||
options: PermissionEvaluationOptions = {},
|
||||
): PermissionAuthorizationResult {
|
||||
const evaluated = await this.evaluateRequest(request, access, options);
|
||||
return evaluated.ok
|
||||
? ok({
|
||||
...evaluated.value.decision,
|
||||
request: evaluated.value.request,
|
||||
})
|
||||
: evaluated;
|
||||
}
|
||||
|
||||
private async evaluateRequest(
|
||||
request: PermissionRequest,
|
||||
access: "read" | "write",
|
||||
options: PermissionEvaluationOptions,
|
||||
): Promise<
|
||||
Result<
|
||||
CanonicalPermissionDecision,
|
||||
PermissionPathError | PermissionRequiredError
|
||||
>
|
||||
> {
|
||||
const canonical = await canonicalizePermissionRequest(request, access);
|
||||
if (!canonical.ok) return canonical;
|
||||
const evaluated = this.evaluateCanonical(canonical.value, options);
|
||||
return evaluated.ok
|
||||
? ok({ ...evaluated.value, request: canonical.value })
|
||||
: evaluated;
|
||||
}
|
||||
|
||||
/** Add authority beneath the administrator ceiling. */
|
||||
grant(grant: PermissionGrant): ReturnType<typeof grantPermission> {
|
||||
const policy =
|
||||
this.configuredAuthority === undefined
|
||||
? this.policy
|
||||
: {
|
||||
...this.policy,
|
||||
ceilings: this.configuredAuthority.effectivePolicy().ceilings,
|
||||
};
|
||||
const result = grantPermission(policy, grant);
|
||||
if (result.ok) this.policy = result.value;
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Revoke authority immediately for subsequent operations. */
|
||||
revoke(grantId: string): void {
|
||||
this.policy = revokePermission(this.policy, grantId);
|
||||
}
|
||||
|
||||
/** Drop once/session authority when its owning connection ends. */
|
||||
clearSessionGrants(): void {
|
||||
this.policy = clearSessionPermissions(this.policy);
|
||||
}
|
||||
|
||||
private effectivePolicy(): PermissionPolicy {
|
||||
if (this.configuredAuthority === undefined) return this.policy;
|
||||
const configured = this.configuredAuthority.effectivePolicy();
|
||||
return {
|
||||
ceilings: configured.ceilings,
|
||||
grants: [...configured.grants, ...this.policy.grants],
|
||||
revoked_grant_ids: new Set([
|
||||
...configured.revoked_grant_ids,
|
||||
...this.policy.revoked_grant_ids,
|
||||
]),
|
||||
consumed_grant_ids: new Set([
|
||||
...configured.consumed_grant_ids,
|
||||
...this.policy.consumed_grant_ids,
|
||||
]),
|
||||
};
|
||||
}
|
||||
|
||||
private evaluateCanonical(
|
||||
request: PermissionRequest,
|
||||
options: PermissionEvaluationOptions,
|
||||
): Result<
|
||||
{
|
||||
readonly decision: Extract<
|
||||
PermissionDecision,
|
||||
{ readonly allowed: true }
|
||||
>;
|
||||
readonly owner: PermissionAuthority;
|
||||
},
|
||||
PermissionRequiredError
|
||||
> {
|
||||
const configured = this.configuredAuthority;
|
||||
if (configured !== undefined) {
|
||||
const configuredDecision = evaluatePermission(
|
||||
configured.effectivePolicy(),
|
||||
request,
|
||||
);
|
||||
if (configuredDecision.allowed)
|
||||
return ok({ decision: configuredDecision, owner: configured });
|
||||
}
|
||||
const localPolicy =
|
||||
configured === undefined
|
||||
? this.policy
|
||||
: { ...this.policy, ceilings: configured.effectivePolicy().ceilings };
|
||||
const localDecision = evaluatePermission(localPolicy, request);
|
||||
if (localDecision.allowed)
|
||||
return ok({ decision: localDecision, owner: this });
|
||||
const effective = this.effectivePolicy();
|
||||
const denied = evaluatePermission(effective, request);
|
||||
if (denied.allowed) return ok({ decision: denied, owner: this });
|
||||
const outsideAdministratorCeiling =
|
||||
denied.reason === "outside_administrator_ceiling";
|
||||
const requestedRemediation = options.remediation ?? "configure";
|
||||
// Only a genuine ceiling violation can be fixed by widening configuration.
|
||||
// When the scope is inside the ceiling but no grant was ever issued, the
|
||||
// `missing` payload describes what a *grant* must cover, so pointing the
|
||||
// caller at the ceiling sends them to edit configuration that already
|
||||
// permits the operation. An explicitly requested remediation is honoured.
|
||||
const remediation = outsideAdministratorCeiling
|
||||
? requestedRemediation === "restart"
|
||||
? requestedRemediation
|
||||
: this.outsideCeilingRemediation
|
||||
: requestedRemediation === "configure"
|
||||
? "grant"
|
||||
: requestedRemediation;
|
||||
return err(
|
||||
new PermissionRequiredError({
|
||||
requested: request,
|
||||
missing: denied.missing,
|
||||
ceiling: ceilingFor(effective, request.capability),
|
||||
remediation,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** Atomically replace optional persisted project grants. */
|
||||
async replaceProjectGrants(
|
||||
grants: readonly PermissionGrant[],
|
||||
): Promise<Result<null, PermissionPathError>> {
|
||||
return this.replaceGrants(grants, "project");
|
||||
}
|
||||
|
||||
/** Replace grants derived from the currently loaded administrator ceiling. */
|
||||
async replaceAdministratorGrants(
|
||||
grants: readonly PermissionGrant[],
|
||||
): Promise<Result<null, PermissionPathError>> {
|
||||
return this.replaceGrants(grants, "administrator");
|
||||
}
|
||||
|
||||
private async replaceGrants(
|
||||
grants: readonly PermissionGrant[],
|
||||
lifetime: "administrator" | "project",
|
||||
): Promise<Result<null, PermissionPathError>> {
|
||||
const canonical = await canonicalizeGrants(grants);
|
||||
if (!canonical.ok) return canonical;
|
||||
const replaced = addGrantsToPolicy(
|
||||
{
|
||||
...this.policy,
|
||||
grants: this.policy.grants.filter(
|
||||
(grant) => grant.lifetime !== lifetime,
|
||||
),
|
||||
},
|
||||
canonical.value,
|
||||
);
|
||||
if (!replaced.ok) return replaced;
|
||||
this.policy = replaced.value;
|
||||
return ok(null);
|
||||
}
|
||||
|
||||
/** Atomically replace reloadable ceilings and persisted grants. */
|
||||
async replaceConfiguredPolicy(configuration: {
|
||||
readonly ceilings: readonly PermissionCeiling[];
|
||||
readonly administratorGrants: readonly PermissionGrant[];
|
||||
readonly projectGrants: readonly PermissionGrant[];
|
||||
}): Promise<Result<null, PermissionPathError>> {
|
||||
const ceilings = await canonicalizePermissionCeilings(
|
||||
configuration.ceilings,
|
||||
);
|
||||
if (!ceilings.ok) return ceilings;
|
||||
const grants = await canonicalizeGrants([
|
||||
...configuration.administratorGrants,
|
||||
...configuration.projectGrants,
|
||||
]);
|
||||
if (!grants.ok) return grants;
|
||||
const candidate: PermissionPolicy = {
|
||||
...reloadPermissionCeilings(this.policy, ceilings.value),
|
||||
grants: this.policy.grants.filter(
|
||||
({ lifetime }) =>
|
||||
lifetime !== "administrator" && lifetime !== "project",
|
||||
),
|
||||
};
|
||||
const replaced = addGrantsToPolicy(candidate, grants.value);
|
||||
if (!replaced.ok) return replaced;
|
||||
this.policy = replaced.value;
|
||||
return ok(null);
|
||||
}
|
||||
|
||||
/** Replace ceilings without restarting the MCP process. */
|
||||
async reload(
|
||||
ceilings: readonly PermissionCeiling[],
|
||||
): Promise<Result<null, PermissionPathError>> {
|
||||
const canonical = await canonicalizePermissionCeilings(ceilings);
|
||||
if (!canonical.ok) return canonical;
|
||||
this.policy = reloadPermissionCeilings(this.policy, canonical.value);
|
||||
return ok(null);
|
||||
}
|
||||
}
|
||||
|
||||
/** Create one canonical policy and optional grants at the composition root. */
|
||||
export const createPermissionAuthority = async (
|
||||
ceilings: readonly PermissionCeiling[],
|
||||
grants: readonly PermissionGrant[] = [],
|
||||
): Promise<Result<PermissionAuthority, PermissionPathError>> => {
|
||||
const canonical = await canonicalizePermissionCeilings(ceilings);
|
||||
if (!canonical.ok) return canonical;
|
||||
const canonicalGrants = await canonicalizeGrants(grants);
|
||||
if (!canonicalGrants.ok) return canonicalGrants;
|
||||
const policy = addGrantsToPolicy(
|
||||
createPermissionPolicy(canonical.value),
|
||||
canonicalGrants.value,
|
||||
);
|
||||
return policy.ok ? ok(new PermissionAuthority(policy.value)) : policy;
|
||||
};
|
||||
|
||||
const canonicalizeGrants = async (
|
||||
grants: readonly PermissionGrant[],
|
||||
): Promise<Result<readonly PermissionGrant[], PermissionPathError>> => {
|
||||
const canonical: PermissionGrant[] = [];
|
||||
for (const grant of grants) {
|
||||
const canonicalGrant = await canonicalizeGrant(grant);
|
||||
if (!canonicalGrant.ok) return canonicalGrant;
|
||||
canonical.push(canonicalGrant.value);
|
||||
}
|
||||
return ok(canonical);
|
||||
};
|
||||
|
||||
const addGrantsToPolicy = (
|
||||
initial: PermissionPolicy,
|
||||
grants: readonly PermissionGrant[],
|
||||
): Result<PermissionPolicy, PermissionPathError> => {
|
||||
let policy = initial;
|
||||
for (const grant of grants) {
|
||||
const added = grantPermission(policy, grant);
|
||||
if (!added.ok)
|
||||
return err(
|
||||
new PermissionPathError(grant.grant_id, "io", { cause: added.error }),
|
||||
);
|
||||
policy = added.value;
|
||||
}
|
||||
return ok(policy);
|
||||
};
|
||||
|
||||
const canonicalizeGrant = async (
|
||||
grant: PermissionGrant,
|
||||
): Promise<Result<PermissionGrant, PermissionPathError>> => {
|
||||
const scope = await canonicalizeScope(grant, "read");
|
||||
return scope.ok ? ok({ ...grant, ...scope.value }) : scope;
|
||||
};
|
||||
|
||||
const ceilingFor = (
|
||||
policy: PermissionPolicy,
|
||||
capability: PermissionRequest["capability"],
|
||||
): PermissionScope | null =>
|
||||
policy.ceilings.find((ceiling) => ceiling.capability === capability) ?? null;
|
||||
@@ -1,99 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { PermissionAuthority } from "./PermissionAuthority.js";
|
||||
import type { PermissionRequiredError } from "../domain/errors.js";
|
||||
import {
|
||||
createPermissionPolicy,
|
||||
type PermissionRequest,
|
||||
type PermissionScope,
|
||||
} from "../domain/permissionPolicy.js";
|
||||
|
||||
// Ceiling paths must exist: the policy canonicalizes them with realpath.
|
||||
const ceilingScope: PermissionScope = {
|
||||
capability: "browser_automate",
|
||||
roots: [],
|
||||
executables: [process.execPath],
|
||||
origins: ["http://127.0.0.1:3000"],
|
||||
environment_names: [],
|
||||
network: "external",
|
||||
mount: false,
|
||||
};
|
||||
|
||||
/** A request the administrator ceiling already fully covers. */
|
||||
const coveredRequest = (
|
||||
overrides: Partial<PermissionScope> = {},
|
||||
): PermissionRequest => ({
|
||||
...ceilingScope,
|
||||
network: "loopback",
|
||||
operation_identity: "browser-scenario-1",
|
||||
...overrides,
|
||||
});
|
||||
|
||||
/** Narrow to the permission-denial error, failing the test on any other error. */
|
||||
const denied = async (
|
||||
authority: PermissionAuthority,
|
||||
request: PermissionRequest,
|
||||
remediation?: "elicit",
|
||||
): Promise<PermissionRequiredError> => {
|
||||
const result = await authority.authorize(
|
||||
request,
|
||||
"write",
|
||||
remediation === undefined ? {} : { remediation },
|
||||
);
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) throw new Error("expected a denial");
|
||||
if (result.error._tag !== "PermissionRequiredError")
|
||||
throw new Error(`expected a permission denial, got ${result.error._tag}`);
|
||||
return result.error;
|
||||
};
|
||||
|
||||
describe("permission denial remediation", () => {
|
||||
it("asks for a grant, not a wider ceiling, when the ceiling covers the scope", async () => {
|
||||
const authority = new PermissionAuthority(
|
||||
createPermissionPolicy([ceilingScope], []),
|
||||
);
|
||||
// The ceiling contains this scope, so widening it cannot help.
|
||||
expect(await denied(authority, coveredRequest())).toMatchObject({
|
||||
remediation: "grant",
|
||||
});
|
||||
});
|
||||
|
||||
it("denies an empty request as needing a grant, not a ceiling violation", async () => {
|
||||
const authority = new PermissionAuthority(
|
||||
createPermissionPolicy([ceilingScope], []),
|
||||
);
|
||||
expect(
|
||||
await denied(authority, {
|
||||
capability: "browser_automate",
|
||||
roots: [],
|
||||
executables: [],
|
||||
origins: [],
|
||||
environment_names: [],
|
||||
network: "none",
|
||||
mount: false,
|
||||
operation_identity: "browser-scenario-1",
|
||||
}),
|
||||
).toMatchObject({ remediation: "grant" });
|
||||
});
|
||||
|
||||
it("still points at configuration for a genuine ceiling violation", async () => {
|
||||
const authority = new PermissionAuthority(
|
||||
createPermissionPolicy([ceilingScope], []),
|
||||
);
|
||||
expect(
|
||||
await denied(
|
||||
authority,
|
||||
coveredRequest({ origins: ["https://not-configured.example"] }),
|
||||
),
|
||||
).toMatchObject({ remediation: "configure" });
|
||||
});
|
||||
|
||||
it("keeps an explicitly requested elicit remediation untouched", async () => {
|
||||
const authority = new PermissionAuthority(
|
||||
createPermissionPolicy([ceilingScope], []),
|
||||
);
|
||||
expect(await denied(authority, coveredRequest(), "elicit")).toMatchObject({
|
||||
remediation: "elicit",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,52 +0,0 @@
|
||||
import type { AppConfig } from "../config.js";
|
||||
import { ConfigurationError } from "../domain/errors.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
createPermissionAuthority,
|
||||
type PermissionAuthority,
|
||||
} from "./PermissionAuthority.js";
|
||||
import { readProjectPermissionStore } from "./ProjectPermissionStore.js";
|
||||
|
||||
/** Load the same administrator and optional project policy for CLI and MCP. */
|
||||
export const loadConfiguredPermissionAuthority = async (
|
||||
config: AppConfig,
|
||||
): Promise<Result<PermissionAuthority, ConfigurationError>> => {
|
||||
const authority = await createPermissionAuthority(
|
||||
config.permissionCeilings,
|
||||
config.administratorPermissionGrants,
|
||||
);
|
||||
if (!authority.ok)
|
||||
return err(
|
||||
new ConfigurationError("Permission policy could not be loaded", {
|
||||
cause: authority.error,
|
||||
}),
|
||||
);
|
||||
if (
|
||||
config.permissionProjectRoot === undefined ||
|
||||
config.permissionProjectStore === undefined
|
||||
)
|
||||
return ok(authority.value);
|
||||
const project = await readProjectPermissionStore(
|
||||
config.permissionProjectStore,
|
||||
config.permissionProjectRoot,
|
||||
);
|
||||
if (!project.ok)
|
||||
return err(
|
||||
new ConfigurationError("Project permission policy could not be loaded", {
|
||||
cause: project.error,
|
||||
}),
|
||||
);
|
||||
const replaced = await authority.value.replaceProjectGrants(
|
||||
project.value?.grants ?? [],
|
||||
);
|
||||
return replaced.ok
|
||||
? ok(authority.value)
|
||||
: err(
|
||||
new ConfigurationError(
|
||||
"Project permission policy could not be applied",
|
||||
{
|
||||
cause: replaced.error,
|
||||
},
|
||||
),
|
||||
);
|
||||
};
|
||||
@@ -1,13 +0,0 @@
|
||||
import {
|
||||
AnalysisProtocolError,
|
||||
PermissionRequiredError,
|
||||
} from "../domain/errors.js";
|
||||
import type { PermissionPathError } from "./PermissionAuthority.js";
|
||||
|
||||
/** Preserve permission denials and project failed path resolution for callers. */
|
||||
export const projectPermissionFailure = (
|
||||
error: PermissionRequiredError | PermissionPathError,
|
||||
): PermissionRequiredError | AnalysisProtocolError =>
|
||||
error instanceof PermissionRequiredError
|
||||
? error
|
||||
: new AnalysisProtocolError(error.message, { cause: error });
|
||||
@@ -1,46 +0,0 @@
|
||||
import { realpath } from "node:fs/promises";
|
||||
import { isPathWithinRoot } from "../domain/localPath.js";
|
||||
|
||||
import type {
|
||||
EnabledProcessExecutionPolicy,
|
||||
ProcessScenario,
|
||||
} from "../domain/processCapture.js";
|
||||
import {
|
||||
ProcessCaptureError,
|
||||
processCaptureCancelled,
|
||||
} from "./ProcessCaptureError.js";
|
||||
import { canonicalizeConfiguredRoots } from "./ConfiguredRoots.js";
|
||||
|
||||
export const assertRealPathAuthority = async (
|
||||
scenario: ProcessScenario,
|
||||
policy: EnabledProcessExecutionPolicy,
|
||||
): Promise<void> => {
|
||||
const executable = await realpath(scenario.executable);
|
||||
const executableRoots = await canonicalizeConfiguredRoots(
|
||||
policy.executableRoots,
|
||||
);
|
||||
if (!executableRoots.some((root) => isPathWithinRoot(root, executable)))
|
||||
throw new ProcessCaptureError(
|
||||
"resolved executable is outside approved roots",
|
||||
);
|
||||
const workingDirectory = await realpath(scenario.working_directory);
|
||||
const workingRoots = await canonicalizeConfiguredRoots(policy.workingRoots);
|
||||
if (!workingRoots.some((root) => isPathWithinRoot(root, workingDirectory)))
|
||||
throw new ProcessCaptureError(
|
||||
"resolved working directory is outside approved roots",
|
||||
);
|
||||
for (const root of scenario.filesystem_roots) {
|
||||
const resolvedRoot = await realpath(root);
|
||||
if (
|
||||
!workingRoots.some((approved) => isPathWithinRoot(approved, resolvedRoot))
|
||||
)
|
||||
throw new ProcessCaptureError(
|
||||
"resolved filesystem root is outside approved roots",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
/** Reject cancellation before a process capture operation begins. */
|
||||
export const assertNotCancelled = (signal: AbortSignal | undefined): void => {
|
||||
if (signal?.aborted === true) throw processCaptureCancelled();
|
||||
};
|
||||
@@ -8,9 +8,26 @@ export type ProcessCaptureCapability =
|
||||
readonly reason: string;
|
||||
};
|
||||
|
||||
/** Explain why process capture cannot claim owned-process cleanup on a host. */
|
||||
export const processCaptureOwnershipUnavailableReason = (
|
||||
platform: NodeJS.Platform,
|
||||
): string | undefined =>
|
||||
platform === "win32"
|
||||
? "Windows process-tree ownership and cleanup are unavailable; REA cannot verify that descendants have stopped."
|
||||
: undefined;
|
||||
|
||||
/** Probe the actual native PTY seam instead of inferring support from the OS name. */
|
||||
export const probeProcessCaptureCapability =
|
||||
async (): Promise<ProcessCaptureCapability> => {
|
||||
const ownershipReason = processCaptureOwnershipUnavailableReason(
|
||||
process.platform,
|
||||
);
|
||||
if (ownershipReason !== undefined)
|
||||
return {
|
||||
available: false,
|
||||
backend: "node-pty",
|
||||
reason: ownershipReason,
|
||||
};
|
||||
try {
|
||||
const { spawn } = await import("@lydell/node-pty");
|
||||
const terminal = spawn(
|
||||
|
||||
@@ -1,39 +1,38 @@
|
||||
import { delimiter } from "node:path";
|
||||
|
||||
import type { ProcessScenario } from "../domain/processCapture.js";
|
||||
import type { LoopbackReplay } from "./LoopbackReplay.js";
|
||||
import type { CommandShimReplay } from "./CommandShimReplay.js";
|
||||
|
||||
interface ProcessCaptureEnvironmentOptions {
|
||||
readonly scenario: ProcessScenario;
|
||||
readonly home: string;
|
||||
readonly replay: LoopbackReplay;
|
||||
readonly shimReplay: CommandShimReplay;
|
||||
readonly runId: string;
|
||||
readonly hostEnvironment: Readonly<Record<string, string | undefined>>;
|
||||
}
|
||||
|
||||
/** Build the explicitly admitted environment for a captured process. */
|
||||
/** Build the inherited environment with scenario overrides and replay instrumentation. */
|
||||
export const makeProcessCaptureEnvironment = (
|
||||
options: ProcessCaptureEnvironmentOptions,
|
||||
): Record<string, string> => {
|
||||
const { scenario, home, replay, shimReplay, runId } = options;
|
||||
const { scenario, replay, shimReplay, runId, hostEnvironment } = options;
|
||||
const environment: Record<string, string> = {
|
||||
...Object.fromEntries(
|
||||
Object.entries(hostEnvironment).filter(
|
||||
(entry): entry is [string, string] => entry[1] !== undefined,
|
||||
),
|
||||
),
|
||||
...scenario.environment,
|
||||
HOME: home,
|
||||
TERM: "xterm-256color",
|
||||
TERM: scenario.environment.TERM ?? hostEnvironment.TERM ?? "xterm-256color",
|
||||
REA_PROCESS_RUN_ID: runId,
|
||||
};
|
||||
for (const name of scenario.inherit_environment) {
|
||||
const value = process.env[name];
|
||||
if (value !== undefined) environment[name] = value;
|
||||
}
|
||||
environment.REA_REPLAY_HTTP_URL = replay.httpUrl;
|
||||
environment.REA_REPLAY_WEBSOCKET_URL = replay.websocketUrl;
|
||||
environment.REA_SHIM_LEDGER_URL = shimReplay.url;
|
||||
// PATH is evidence-producing input. Inheriting the host PATH here would let
|
||||
// the authority and reconstruction probe different tools without recording
|
||||
// that difference. Scenarios must opt in through environment or
|
||||
// inherit_environment; deterministic shims always take precedence.
|
||||
// Shims are instrumentation; all remaining executable lookup uses host PATH.
|
||||
environment.PATH = [shimReplay.binPath, environment.PATH ?? ""]
|
||||
.filter((part) => part.length > 0)
|
||||
.join(":");
|
||||
.join(delimiter);
|
||||
return environment;
|
||||
};
|
||||
|
||||
@@ -2,12 +2,8 @@ import { AnalysisError } from "../domain/errors.js";
|
||||
|
||||
interface ProcessCaptureErrorOptions extends ErrorOptions {
|
||||
readonly userMessage?: string;
|
||||
readonly userCategory?: "permission_required" | "cancelled";
|
||||
readonly reason?:
|
||||
| "capture_failed"
|
||||
| "cleanup_incomplete"
|
||||
| "permission_required"
|
||||
| "cancelled";
|
||||
readonly userCategory?: "cancelled";
|
||||
readonly reason?: "capture_failed" | "cleanup_incomplete" | "cancelled";
|
||||
readonly cleanupResources?: readonly string[];
|
||||
}
|
||||
|
||||
@@ -16,10 +12,7 @@ export class ProcessCaptureError extends AnalysisError {
|
||||
readonly _tag = "ProcessCaptureError";
|
||||
|
||||
override readonly userMessage: string | undefined;
|
||||
override readonly userCategory:
|
||||
| "permission_required"
|
||||
| "cancelled"
|
||||
| undefined;
|
||||
override readonly userCategory: "cancelled" | undefined;
|
||||
readonly reason: NonNullable<ProcessCaptureErrorOptions["reason"]>;
|
||||
override readonly cleanupIncomplete: boolean;
|
||||
override readonly cleanupResources: readonly string[];
|
||||
@@ -30,11 +23,7 @@ export class ProcessCaptureError extends AnalysisError {
|
||||
this.userCategory = options?.userCategory;
|
||||
this.reason =
|
||||
options?.reason ??
|
||||
(options?.userCategory === "permission_required"
|
||||
? "permission_required"
|
||||
: options?.userCategory === "cancelled"
|
||||
? "cancelled"
|
||||
: "capture_failed");
|
||||
(options?.userCategory === "cancelled" ? "cancelled" : "capture_failed");
|
||||
this.cleanupIncomplete = this.reason === "cleanup_incomplete";
|
||||
this.cleanupResources = options?.cleanupResources ?? [];
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { createReadStream } from "node:fs";
|
||||
import { mkdir, mkdtemp, rm } from "node:fs/promises";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import type { IPty } from "@lydell/node-pty";
|
||||
@@ -10,8 +10,6 @@ import type {
|
||||
InteractionEvent,
|
||||
ProcessCapture,
|
||||
UnverifiedProcessCapture,
|
||||
ProcessExecutionPolicy,
|
||||
ProcessPolicyDecision,
|
||||
ProcessSample,
|
||||
ProcessSettlement,
|
||||
ProcessScenario,
|
||||
@@ -20,7 +18,6 @@ import type {
|
||||
TerminalFrame,
|
||||
} from "../domain/processCapture.js";
|
||||
import {
|
||||
authorizeProcessScenario,
|
||||
digestProcessCommitment,
|
||||
processComparisonContract,
|
||||
processScenarioCommitment,
|
||||
@@ -38,15 +35,12 @@ import {
|
||||
ProcessCheckpoints,
|
||||
} from "./ProcessCheckpoints.js";
|
||||
import { ProcessCaptureError } from "./ProcessCaptureError.js";
|
||||
import {
|
||||
assertNotCancelled,
|
||||
assertRealPathAuthority,
|
||||
} from "./ProcessCaptureAuthority.js";
|
||||
import { assertNotCancelled } from "./ProcessScenarioRuntimeValidation.js";
|
||||
import {
|
||||
normalizeProcessElapsedTime,
|
||||
normalizeProcessSamples,
|
||||
normalizeProcessText,
|
||||
redactProtocolEvents,
|
||||
normalizeProtocolEvents,
|
||||
} from "./ProcessNormalization.js";
|
||||
import type { CommandShimReplay } from "./CommandShimReplay.js";
|
||||
import { PROCESS_PROVIDER } from "./ProcessEvidence.js";
|
||||
@@ -110,60 +104,91 @@ export type PendingProcessCapture = Omit<
|
||||
|
||||
export const buildCaptureResult = (
|
||||
options: CaptureResultOptions,
|
||||
): PendingProcessCapture => ({
|
||||
manifest: options.manifest,
|
||||
normalization: options.scenario.normalization,
|
||||
frames: options.frames,
|
||||
rendered_frames: options.renderedFrames,
|
||||
interaction_events: options.interactions,
|
||||
exit: {
|
||||
code:
|
||||
options.exit.reason === "exited" && options.exit.exitCode >= 0
|
||||
? options.exit.exitCode
|
||||
: null,
|
||||
signal: options.exit.signal ?? null,
|
||||
reason: options.exit.reason,
|
||||
},
|
||||
settlement: options.settlement,
|
||||
process_samples: normalizeProcessSamples(
|
||||
options.samples,
|
||||
options.scenario,
|
||||
options.rootPid,
|
||||
),
|
||||
filesystem_checkpoints: options.checkpoints,
|
||||
shim_events: options.shimEvents,
|
||||
protocol_events: redactProtocolEvents(
|
||||
): PendingProcessCapture => {
|
||||
const hasSensitiveScriptedInput = options.scenario.events.some(
|
||||
(event) => event.type === "input" && event.sensitive,
|
||||
);
|
||||
const sensitiveInputUnknown =
|
||||
"Sensitive scripted input values are redacted from process capture Evidence.";
|
||||
const filesystemObservationUnknown =
|
||||
"No filesystem observation paths were selected; filesystem effects remain unknown.";
|
||||
const protocolEvents = normalizeProtocolEvents(
|
||||
options.replay.events,
|
||||
options.scenario,
|
||||
),
|
||||
replay_transitions: options.replay.transitions,
|
||||
event_journal: options.eventJournal,
|
||||
files_before: options.before.files,
|
||||
files_after: options.after.files,
|
||||
filesystem_effects: classifyFilesystemEffects(
|
||||
options.before.files,
|
||||
options.after.files,
|
||||
),
|
||||
truncated: options.truncated,
|
||||
limitations: [
|
||||
"Process trees are sampled and may omit short-lived descendants.",
|
||||
...(options.samplingPartial
|
||||
? ["Process-tree sampling ended with an incomplete observation."]
|
||||
: []),
|
||||
"Filesystem observations are before/after snapshots, not syscall traces.",
|
||||
"The harness does not enforce external network isolation.",
|
||||
],
|
||||
residual_unknowns: [
|
||||
{
|
||||
scope: "process",
|
||||
reason: "Process trees are sampled and may omit short-lived descendants.",
|
||||
);
|
||||
const hasFilesystemObservations =
|
||||
options.scenario.filesystem_observation_paths.length > 0;
|
||||
return {
|
||||
manifest: options.manifest,
|
||||
normalization: options.scenario.normalization,
|
||||
frames: options.frames,
|
||||
rendered_frames: options.renderedFrames,
|
||||
interaction_events: options.interactions,
|
||||
exit: {
|
||||
code:
|
||||
options.exit.reason === "exited" && options.exit.exitCode >= 0
|
||||
? options.exit.exitCode
|
||||
: null,
|
||||
signal: options.exit.signal ?? null,
|
||||
reason: options.exit.reason,
|
||||
},
|
||||
{
|
||||
scope: "network",
|
||||
reason: "External network isolation is not enforced by this adapter.",
|
||||
},
|
||||
],
|
||||
});
|
||||
settlement: options.settlement,
|
||||
process_samples: normalizeProcessSamples(
|
||||
options.samples,
|
||||
options.scenario,
|
||||
options.rootPid,
|
||||
),
|
||||
filesystem_checkpoints: options.checkpoints,
|
||||
shim_events: options.shimEvents,
|
||||
protocol_events: protocolEvents,
|
||||
replay_transitions: options.replay.transitions,
|
||||
event_journal: options.eventJournal,
|
||||
files_before: options.before.files,
|
||||
files_after: options.after.files,
|
||||
filesystem_effects: classifyFilesystemEffects(
|
||||
options.before.files,
|
||||
options.after.files,
|
||||
),
|
||||
truncated: options.truncated,
|
||||
limitations: [
|
||||
"Process trees are sampled and may omit short-lived descendants.",
|
||||
...(options.samplingPartial
|
||||
? ["Process-tree sampling ended with an incomplete observation."]
|
||||
: []),
|
||||
"Filesystem observations are before/after snapshots, not syscall traces.",
|
||||
"The harness does not enforce external network isolation.",
|
||||
"Inherited host environment variables are not recorded and may affect results.",
|
||||
...(!hasFilesystemObservations ? [filesystemObservationUnknown] : []),
|
||||
...(hasSensitiveScriptedInput ? [sensitiveInputUnknown] : []),
|
||||
],
|
||||
residual_unknowns: [
|
||||
{
|
||||
scope: "process",
|
||||
reason:
|
||||
"Process trees are sampled and may omit short-lived descendants.",
|
||||
},
|
||||
{
|
||||
scope: "network",
|
||||
reason: "External network isolation is not enforced by this adapter.",
|
||||
},
|
||||
{
|
||||
scope: "environment",
|
||||
reason: "Inherited host environment variables are not recorded.",
|
||||
},
|
||||
...(!hasFilesystemObservations
|
||||
? [
|
||||
{
|
||||
scope: "filesystem" as const,
|
||||
reason: filesystemObservationUnknown,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(hasSensitiveScriptedInput
|
||||
? [{ scope: "interaction" as const, reason: sensitiveInputUnknown }]
|
||||
: []),
|
||||
],
|
||||
};
|
||||
};
|
||||
|
||||
const hashFile = async (path: string): Promise<string> => {
|
||||
const hash = createHash("sha256");
|
||||
@@ -306,6 +331,19 @@ export const awaitTerminalExit = async ({
|
||||
timers.add(timeout);
|
||||
});
|
||||
|
||||
/** Host operations used when releasing one captured process run. */
|
||||
export interface ProcessCaptureCleanupHost {
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly cleanupProcessGroup: typeof cleanupOwnedProcessGroup;
|
||||
readonly removeTemporaryRoot: (path: string) => Promise<void>;
|
||||
}
|
||||
|
||||
const processCaptureCleanupHost: ProcessCaptureCleanupHost = {
|
||||
platform: process.platform,
|
||||
cleanupProcessGroup: cleanupOwnedProcessGroup,
|
||||
removeTemporaryRoot: (path) => rm(path, { recursive: true, force: true }),
|
||||
};
|
||||
|
||||
export const releaseProcessResources = async (options: {
|
||||
readonly timers: ReadonlySet<ProcessTimer>;
|
||||
readonly replay: LoopbackReplay | undefined;
|
||||
@@ -316,7 +354,9 @@ export const releaseProcessResources = async (options: {
|
||||
readonly runId: string;
|
||||
readonly temporaryRoot: string;
|
||||
readonly capturedProcessGroupIds: readonly number[];
|
||||
readonly host?: ProcessCaptureCleanupHost;
|
||||
}): Promise<string | undefined> => {
|
||||
const host = options.host ?? processCaptureCleanupHost;
|
||||
for (const timer of options.timers) timer.cancel();
|
||||
let failure: string | undefined;
|
||||
try {
|
||||
@@ -339,9 +379,9 @@ export const releaseProcessResources = async (options: {
|
||||
} catch {
|
||||
failure ??= "filesystem checkpoint cleanup failed";
|
||||
}
|
||||
if (options.terminal !== undefined && process.platform !== "win32") {
|
||||
if (options.terminal !== undefined && host.platform !== "win32") {
|
||||
for (const processGroupId of new Set(options.capturedProcessGroupIds)) {
|
||||
const cleaned = await cleanupOwnedProcessGroup({
|
||||
const cleaned = await host.cleanupProcessGroup({
|
||||
runId: options.runId,
|
||||
leaderPid: processGroupId,
|
||||
processGroupId,
|
||||
@@ -350,7 +390,7 @@ export const releaseProcessResources = async (options: {
|
||||
}
|
||||
}
|
||||
try {
|
||||
await rm(options.temporaryRoot, { recursive: true, force: true });
|
||||
await host.removeTemporaryRoot(options.temporaryRoot);
|
||||
} catch {
|
||||
failure ??= "temporary process root cleanup failed";
|
||||
}
|
||||
@@ -424,70 +464,32 @@ export const resolveProcessResult = (
|
||||
|
||||
export const prepareProcessCapture = async (
|
||||
scenario: ProcessScenario,
|
||||
policy: ProcessExecutionPolicy,
|
||||
signal: AbortSignal | undefined,
|
||||
host: ProcessPreparationHost = systemProcessPreparationHost,
|
||||
): Promise<{
|
||||
readonly temporaryRoot: string;
|
||||
readonly runId: string;
|
||||
readonly home: string;
|
||||
readonly before: SnapshotResult;
|
||||
}> => {
|
||||
if (policy.status === "disabled")
|
||||
throw new ProcessCaptureError("process capture is disabled", {
|
||||
userCategory: "permission_required",
|
||||
userMessage: processPolicyMessage("process capture is disabled"),
|
||||
});
|
||||
const decision = authorizeProcessScenario(scenario, policy);
|
||||
if (!decision.allowed)
|
||||
throw new ProcessCaptureError(decision.reason, {
|
||||
userCategory: "permission_required",
|
||||
userMessage: processPolicyMessage(decision.reason),
|
||||
});
|
||||
await assertRealPathAuthority(scenario, policy);
|
||||
assertNotCancelled(signal);
|
||||
const before = await snapshotRoots(scenario, signal);
|
||||
const temporaryRoot = await host.createTemporaryRoot();
|
||||
try {
|
||||
const runId = randomUUID();
|
||||
const home = join(temporaryRoot, "home");
|
||||
await host.createHome(home);
|
||||
return { temporaryRoot, runId, home, before };
|
||||
return { temporaryRoot, runId, before };
|
||||
} catch (cause: unknown) {
|
||||
await host.cleanup(temporaryRoot);
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
/** Filesystem seam for allocating and cleaning a capture's private home. */
|
||||
/** Filesystem seam for allocating and cleaning a capture's temporary root. */
|
||||
export interface ProcessPreparationHost {
|
||||
createTemporaryRoot(): Promise<string>;
|
||||
createHome(path: string): Promise<void>;
|
||||
cleanup(path: string): Promise<void>;
|
||||
}
|
||||
|
||||
const systemProcessPreparationHost: ProcessPreparationHost = {
|
||||
createTemporaryRoot: () => mkdtemp(join(tmpdir(), "rea-process-")),
|
||||
createHome: (path) => mkdir(path),
|
||||
cleanup: (path) => rm(path, { recursive: true, force: true }),
|
||||
};
|
||||
|
||||
const processPolicyMessage = (
|
||||
reason: Exclude<ProcessPolicyDecision, { readonly allowed: true }>["reason"],
|
||||
): string => {
|
||||
if (reason === "process capture is disabled")
|
||||
return "Process capture is disabled. Set `REA_PROCESS_CAPTURE_ENABLED=true`, configure approved roots, then restart REA.";
|
||||
if (reason === "host network access is not approved by operator policy")
|
||||
return "This capture requests host network access, but policy does not allow it. Use replayed network access or ask the operator to enable external network capture.";
|
||||
if (reason === "executable is outside approved roots")
|
||||
return "The executable is outside the approved capture directories. Choose an approved executable or add its directory to `REA_PROCESS_EXECUTABLE_ROOTS_JSON`.";
|
||||
if (reason === "working directory is outside approved roots")
|
||||
return "The working directory is outside the approved capture directories. Choose an approved directory or add it to `REA_PROCESS_WORKING_ROOTS_JSON`.";
|
||||
if (reason === "filesystem root is outside approved roots")
|
||||
return "A requested filesystem root is outside the approved capture directories. Remove it or add its directory to `REA_PROCESS_WORKING_ROOTS_JSON`.";
|
||||
if (
|
||||
reason === "scenario requests an environment variable not allowed by policy"
|
||||
)
|
||||
return "The capture requests an environment variable that policy does not allow. Remove it or add its name to `REA_PROCESS_ALLOWED_ENV_JSON`.";
|
||||
return reason satisfies never;
|
||||
};
|
||||
|
||||
@@ -1,17 +1,12 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { snapshotRoots } from "./FilesystemSnapshot.js";
|
||||
import {
|
||||
buildCaptureResult,
|
||||
prepareProcessCapture,
|
||||
type ProcessPreparationHost,
|
||||
} from "./ProcessCaptureLifecycle.js";
|
||||
import { buildCaptureResult } from "./ProcessCaptureLifecycle.js";
|
||||
import { ProcessCheckpoints } from "./ProcessCheckpoints.js";
|
||||
import { normalizeProcessSamples } from "./ProcessNormalization.js";
|
||||
import { isInitializedPtyRoot, readLinuxChildren } from "./ProcessSampling.js";
|
||||
import { TerminalRenderer } from "./TerminalRenderer.js";
|
||||
import {
|
||||
authorizeProcessScenario,
|
||||
compareProcessCaptures,
|
||||
parseProcessCapture,
|
||||
parseProcessScenario,
|
||||
@@ -127,32 +122,55 @@ it("preserves rendered observation order instead of timestamp sorting", () => {
|
||||
expect(result.rendered_frames).toEqual(renderedFrames);
|
||||
});
|
||||
|
||||
it("cleans the temporary root when capture home creation fails", async () => {
|
||||
const cleaned: string[] = [];
|
||||
const host: ProcessPreparationHost = {
|
||||
createTemporaryRoot: () => Promise.resolve("/tmp/rea-process-fixture"),
|
||||
createHome: () => Promise.reject(new Error("mkdir failed")),
|
||||
cleanup: (path) => {
|
||||
cleaned.push(path);
|
||||
return Promise.resolve();
|
||||
it("marks redacted scripted input as an interaction unknown", () => {
|
||||
const capture = emptyCapture();
|
||||
const result = buildCaptureResult({
|
||||
frames: [],
|
||||
exit: { exitCode: 0, reason: "exited" },
|
||||
samples: [],
|
||||
replay: {
|
||||
httpUrl: "http://127.0.0.1",
|
||||
websocketUrl: "ws://127.0.0.1/ws",
|
||||
events: [],
|
||||
transitions: [],
|
||||
truncated: false,
|
||||
close: () => Promise.resolve(),
|
||||
},
|
||||
};
|
||||
|
||||
await expect(
|
||||
prepareProcessCapture(
|
||||
parseProcessScenario(base),
|
||||
before: { files: [], truncated: false },
|
||||
after: { files: [], truncated: false },
|
||||
truncated: false,
|
||||
scenario: parseProcessScenario({
|
||||
...base,
|
||||
events: [{ type: "input", at_ms: 0, data: "secret", sensitive: true }],
|
||||
}),
|
||||
rootPid: 1,
|
||||
samplingPartial: false,
|
||||
renderedFrames: [],
|
||||
interactions: [
|
||||
{
|
||||
status: "enabled",
|
||||
executableRoots: ["/bin"],
|
||||
workingRoots: ["/tmp"],
|
||||
allowedEnvironment: [],
|
||||
networkAccess: "external",
|
||||
sequence: 0,
|
||||
scheduled_at_ms: 0,
|
||||
dispatched_at_ms: 0,
|
||||
type: "input",
|
||||
data: "<redacted-input:6-bytes>",
|
||||
outcome: "dispatched",
|
||||
},
|
||||
undefined,
|
||||
host,
|
||||
),
|
||||
).rejects.toThrow("mkdir failed");
|
||||
expect(cleaned).toEqual(["/tmp/rea-process-fixture"]);
|
||||
],
|
||||
checkpoints: capture.filesystem_checkpoints,
|
||||
shimEvents: [],
|
||||
settlement: {
|
||||
state: capture.settlement.state,
|
||||
elapsed_ms: capture.settlement.elapsed_ms,
|
||||
},
|
||||
manifest: capture.manifest,
|
||||
eventJournal: [],
|
||||
});
|
||||
|
||||
expect(result.residual_unknowns).toContainEqual({
|
||||
scope: "interaction",
|
||||
reason:
|
||||
"Sensitive scripted input values are redacted from process capture Evidence.",
|
||||
});
|
||||
});
|
||||
|
||||
it("normalizes every sampled process identifier in command text", () => {
|
||||
@@ -275,7 +293,7 @@ it("cancels filesystem snapshots before traversing declared roots", async () =>
|
||||
snapshotRoots(
|
||||
parseProcessScenario({
|
||||
...base,
|
||||
filesystem_roots: ["/tmp"],
|
||||
filesystem_observation_paths: ["/tmp"],
|
||||
}),
|
||||
controller.signal,
|
||||
),
|
||||
@@ -293,12 +311,12 @@ it("parses bounded scenarios and rejects unordered events", () => {
|
||||
],
|
||||
}),
|
||||
).toThrow(/ordered/);
|
||||
expect(() =>
|
||||
expect(
|
||||
parseProcessScenario({
|
||||
...base,
|
||||
environment: { HOME: "/unsafe" },
|
||||
}),
|
||||
).toThrow(/reserved/);
|
||||
environment: { HOME: "/caller-selected-home" },
|
||||
}).environment.HOME,
|
||||
).toBe("/caller-selected-home");
|
||||
expect(() =>
|
||||
parseProcessScenario({
|
||||
...base,
|
||||
@@ -306,37 +324,3 @@ it("parses bounded scenarios and rejects unordered events", () => {
|
||||
}),
|
||||
).toThrow(/after the scenario timeout/);
|
||||
});
|
||||
|
||||
it("requires explicit operator approval for host network access", () => {
|
||||
expect(
|
||||
authorizeProcessScenario(parseProcessScenario(base), {
|
||||
status: "enabled",
|
||||
executableRoots: ["/bin"],
|
||||
workingRoots: ["/tmp"],
|
||||
allowedEnvironment: [],
|
||||
networkAccess: "none",
|
||||
}),
|
||||
).toEqual({
|
||||
allowed: false,
|
||||
reason: "host network access is not approved by operator policy",
|
||||
});
|
||||
});
|
||||
|
||||
it("refuses paths and environment outside operator policy", () => {
|
||||
const scenario = parseProcessScenario({
|
||||
...base,
|
||||
environment: { TOKEN: "secret" },
|
||||
});
|
||||
expect(
|
||||
authorizeProcessScenario(scenario, {
|
||||
status: "enabled",
|
||||
executableRoots: ["/bin"],
|
||||
workingRoots: ["/tmp"],
|
||||
allowedEnvironment: [],
|
||||
networkAccess: "external",
|
||||
}),
|
||||
).toEqual({
|
||||
allowed: false,
|
||||
reason: "scenario requests an environment variable not allowed by policy",
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { processCapturePermissionRequest } from "./ProcessCapturePermission.js";
|
||||
import { parseProcessScenario } from "../domain/processCapture.js";
|
||||
|
||||
describe("process capture permission request", () => {
|
||||
it("projects the complete adapter-neutral authority scope", () => {
|
||||
const scenario = parseProcessScenario({
|
||||
executable: "/bin/tool",
|
||||
arguments: ["--probe"],
|
||||
working_directory: "/workspace",
|
||||
environment: { FIXTURE_TOKEN: "secret" },
|
||||
inherit_environment: ["PATH"],
|
||||
filesystem_roots: ["/workspace/output"],
|
||||
network_access: "host",
|
||||
events: [],
|
||||
});
|
||||
|
||||
expect(processCapturePermissionRequest(scenario)).toEqual({
|
||||
capability: "process_capture",
|
||||
roots: ["/workspace", "/workspace/output"],
|
||||
executables: ["/bin/tool"],
|
||||
environment_names: ["FIXTURE_TOKEN", "PATH"],
|
||||
network: "external",
|
||||
mount: false,
|
||||
operation_identity: "capture_process_scenario:/bin/tool",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,18 +0,0 @@
|
||||
import type { PermissionRequest } from "../domain/permissionPolicy.js";
|
||||
import type { ProcessScenario } from "../domain/processCapture.js";
|
||||
|
||||
/** Build the exact permission request shared by process-capture adapters. */
|
||||
export const processCapturePermissionRequest = (
|
||||
scenario: ProcessScenario,
|
||||
): PermissionRequest => ({
|
||||
capability: "process_capture",
|
||||
roots: [scenario.working_directory, ...scenario.filesystem_roots],
|
||||
executables: [scenario.executable],
|
||||
environment_names: [
|
||||
...Object.keys(scenario.environment),
|
||||
...scenario.inherit_environment,
|
||||
],
|
||||
network: scenario.network_access === "host" ? "external" : "none",
|
||||
mount: false,
|
||||
operation_identity: `capture_process_scenario:${scenario.executable}`,
|
||||
});
|
||||
@@ -1,7 +1,5 @@
|
||||
import { projectPermissionFailure } from "./PermissionFailure.js";
|
||||
import { readFile } from "node:fs/promises";
|
||||
|
||||
import { parseConfig } from "../config.js";
|
||||
import {
|
||||
AnalysisError,
|
||||
AnalysisInputError,
|
||||
@@ -11,18 +9,16 @@ import { createEvidence, parseEvidence } from "../domain/evidence.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import { projectInputIssues } from "../domain/inputIssueProjection.js";
|
||||
import { processTraceSpecificationSchema } from "../domain/processTraceComparison.js";
|
||||
import { processScenarioSchema } from "../domain/processScenario.js";
|
||||
import {
|
||||
compareProcessCaptures,
|
||||
parseProcessScenario,
|
||||
parseProcessCapture,
|
||||
} from "../domain/processCapture.js";
|
||||
import { captureProcessScenario } from "./ProcessHarness.js";
|
||||
import { processCapturePermissionRequest } from "./ProcessCapturePermission.js";
|
||||
import {
|
||||
PROCESS_PROVIDER,
|
||||
createProcessCaptureEvidence,
|
||||
} from "./ProcessEvidence.js";
|
||||
import { loadConfiguredPermissionAuthority } from "./PermissionConfiguration.js";
|
||||
|
||||
/** Safe process-command failure returned to the CLI adapter. */
|
||||
export interface ProcessCliErrorOutput {
|
||||
@@ -31,38 +27,28 @@ export interface ProcessCliErrorOutput {
|
||||
readonly message: string;
|
||||
}
|
||||
|
||||
/** Capture one JSON scenario through the same policy and evidence contract as MCP. */
|
||||
/** Capture one JSON scenario through the shared process harness and Evidence contract. */
|
||||
export const captureProcessScenarioFile = async (
|
||||
path: string,
|
||||
environment: Readonly<Record<string, string | undefined>> = process.env,
|
||||
) => {
|
||||
try {
|
||||
const input = await readJson(path);
|
||||
let scenario;
|
||||
try {
|
||||
scenario = parseProcessScenario(input);
|
||||
} catch {
|
||||
throw new ProcessCliFailure(
|
||||
"invalid_input",
|
||||
"Process scenario is invalid. Check its required fields and limits, then try again.",
|
||||
const parsed = processScenarioSchema.safeParse(input);
|
||||
if (!parsed.success)
|
||||
throw new AnalysisInputError(
|
||||
"capture_process_scenario",
|
||||
{ cause: parsed.error },
|
||||
projectInputIssues(parsed.error.issues, input),
|
||||
);
|
||||
}
|
||||
const config = parseConfig(environment);
|
||||
if (!config.ok) return cliAnalysisError(config.error);
|
||||
const authority = await loadConfiguredPermissionAuthority(config.value);
|
||||
if (!authority.ok) return cliAnalysisError(authority.error);
|
||||
const authorized = await authority.value.authorize(
|
||||
processCapturePermissionRequest(scenario),
|
||||
"read",
|
||||
);
|
||||
if (!authorized.ok)
|
||||
return cliAnalysisError(projectPermissionFailure(authorized.error));
|
||||
const captured = await captureProcessScenario(
|
||||
scenario,
|
||||
config.value.processExecutionPolicy,
|
||||
parsed.data,
|
||||
undefined,
|
||||
process.platform,
|
||||
environment,
|
||||
);
|
||||
if (!captured.ok) return cliAnalysisError(captured.error);
|
||||
return createProcessCaptureEvidence(scenario, captured.value);
|
||||
return createProcessCaptureEvidence(parsed.data, captured.value);
|
||||
} catch (cause: unknown) {
|
||||
return projectProcessCliError(cause);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { createProcessCaptureEvidence } from "./ProcessEvidence.js";
|
||||
import { createRunManifest } from "./ProcessCaptureLifecycle.js";
|
||||
import { normalizeProtocolEvents } from "./ProcessNormalization.js";
|
||||
import { emptyUnverifiedProcessCapture } from "../domain/processCapture.fixture.js";
|
||||
import {
|
||||
compareProcessCaptures,
|
||||
parseProcessCapture,
|
||||
} from "../domain/processCapture.js";
|
||||
import {
|
||||
digestProcessCommitment,
|
||||
parseProcessScenario,
|
||||
processComparisonContract,
|
||||
processScenarioCommitment,
|
||||
} from "../domain/processScenario.js";
|
||||
|
||||
const captureEvidenceForSensitiveInput = (data: string) => {
|
||||
const scenario = parseProcessScenario({
|
||||
executable: "/bin/echo",
|
||||
working_directory: "/tmp",
|
||||
events: [{ type: "input", at_ms: 0, data, sensitive: true }],
|
||||
});
|
||||
const base = emptyUnverifiedProcessCapture();
|
||||
const executableSha256 = "0".repeat(64);
|
||||
const scenarioProjection = processScenarioCommitment(
|
||||
scenario,
|
||||
executableSha256,
|
||||
);
|
||||
const comparisonContract = processComparisonContract(scenario);
|
||||
const capture = parseProcessCapture({
|
||||
...base,
|
||||
normalization: scenario.normalization,
|
||||
residual_unknowns: [
|
||||
{
|
||||
scope: "interaction",
|
||||
reason:
|
||||
"Sensitive scripted input values are redacted from process capture Evidence.",
|
||||
},
|
||||
{
|
||||
scope: "environment",
|
||||
reason: "Inherited host environment variables are not recorded.",
|
||||
},
|
||||
],
|
||||
manifest: {
|
||||
...base.manifest,
|
||||
scenario: scenarioProjection,
|
||||
comparison_contract: comparisonContract,
|
||||
full_scenario_sha256: digestProcessCommitment(scenarioProjection),
|
||||
comparison_contract_sha256: digestProcessCommitment(comparisonContract),
|
||||
executable_sha256: executableSha256,
|
||||
normalization_sha256: digestProcessCommitment(scenario.normalization),
|
||||
},
|
||||
});
|
||||
return createProcessCaptureEvidence(scenario, capture);
|
||||
};
|
||||
|
||||
const captureEvidenceForEnvironmentSecret = async (value: string) => {
|
||||
const scenario = parseProcessScenario({
|
||||
executable: "/bin/echo",
|
||||
working_directory: "/tmp",
|
||||
environment: { API_TOKEN: value },
|
||||
events: [{ type: "input", at_ms: 0, data: value }],
|
||||
command_shims: [
|
||||
{
|
||||
name: "echo",
|
||||
routes: [
|
||||
{
|
||||
arguments: [],
|
||||
outputs: [{ at_ms: 0, stream: "stdout", data: value }],
|
||||
termination: { type: "exit", code: 0 },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
replay: {
|
||||
http: [
|
||||
{
|
||||
method: "GET",
|
||||
path: `/token?token=${value}`,
|
||||
status: 200,
|
||||
body: value,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
const base = emptyUnverifiedProcessCapture();
|
||||
const manifest = await createRunManifest(scenario, new Date(0), new Date(1));
|
||||
const scenarioManifest = {
|
||||
...manifest,
|
||||
normalization_sha256: digestProcessCommitment(scenario.normalization),
|
||||
};
|
||||
const capture = parseProcessCapture({
|
||||
...base,
|
||||
normalization: scenario.normalization,
|
||||
frames: [{ sequence: 0, at_ms: 0, data: "observed-output" }],
|
||||
protocol_events: normalizeProtocolEvents(
|
||||
[
|
||||
{
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
protocol: "http",
|
||||
direction: "request",
|
||||
method: "GET",
|
||||
path: `/token?token=${value}`,
|
||||
data: "",
|
||||
outcome: "matched",
|
||||
},
|
||||
],
|
||||
scenario,
|
||||
),
|
||||
residual_unknowns: [
|
||||
{
|
||||
scope: "environment",
|
||||
reason: "Inherited host environment variables are not recorded.",
|
||||
},
|
||||
],
|
||||
manifest: scenarioManifest,
|
||||
});
|
||||
return createProcessCaptureEvidence(scenario, capture);
|
||||
};
|
||||
|
||||
it("does not persist sensitive scripted input in process capture Evidence", () => {
|
||||
const secret = "top-secret-input";
|
||||
const evidence = captureEvidenceForSensitiveInput(secret);
|
||||
const serialized = JSON.stringify(evidence);
|
||||
const manifest = evidence.normalized_result;
|
||||
|
||||
expect(JSON.stringify(manifest)).not.toContain(secret);
|
||||
expect(JSON.stringify(evidence.parameters)).not.toContain(secret);
|
||||
expect(serialized).not.toContain(secret);
|
||||
});
|
||||
|
||||
it("does not treat captures with different redacted inputs as equivalent", () => {
|
||||
const left = captureEvidenceForSensitiveInput("secret-left");
|
||||
const right = captureEvidenceForSensitiveInput("secret-right");
|
||||
|
||||
expect(
|
||||
compareProcessCaptures(
|
||||
parseProcessCapture(left.normalized_result),
|
||||
parseProcessCapture(right.normalized_result),
|
||||
),
|
||||
).toMatchObject({ status: "unknown", interaction: "unknown" });
|
||||
});
|
||||
|
||||
it("preserves selected local environment, shim, replay, and protocol values", async () => {
|
||||
const left = await captureEvidenceForEnvironmentSecret("secret-left");
|
||||
const right = await captureEvidenceForEnvironmentSecret("secret-right");
|
||||
const serialized = JSON.stringify(left);
|
||||
const leftCapture = parseProcessCapture(left.normalized_result);
|
||||
const rightCapture = parseProcessCapture(right.normalized_result);
|
||||
|
||||
expect(serialized).toContain("secret-left");
|
||||
expect(serialized).toContain("/token?token=secret-left");
|
||||
expect(leftCapture.manifest.scenario).toMatchObject({
|
||||
environment: { API_TOKEN: "secret-left" },
|
||||
});
|
||||
expect(leftCapture.manifest.scenario).not.toHaveProperty("PATH");
|
||||
expect(leftCapture.manifest.comparison_contract_sha256).not.toBe(
|
||||
rightCapture.manifest.comparison_contract_sha256,
|
||||
);
|
||||
|
||||
const changedOutput = parseProcessCapture({
|
||||
...leftCapture,
|
||||
frames: [{ sequence: 0, at_ms: 0, data: "different-output" }],
|
||||
});
|
||||
expect(compareProcessCaptures(leftCapture, changedOutput)).toMatchObject({
|
||||
status: "changed",
|
||||
terminal: "changed",
|
||||
});
|
||||
});
|
||||
@@ -20,7 +20,8 @@ const processEvidenceParameters = (
|
||||
executable_name: scenario.executable.split("/").at(-1) ?? scenario.executable,
|
||||
argument_count: scenario.arguments.length,
|
||||
event_count: scenario.events.length,
|
||||
filesystem_root_count: scenario.filesystem_roots.length,
|
||||
filesystem_observation_path_count:
|
||||
scenario.filesystem_observation_paths.length,
|
||||
checkpoint_count: scenario.checkpoints.length,
|
||||
command_shim_count: scenario.command_shims.length,
|
||||
normalization: scenario.normalization,
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { processScenarioSchema } from "../domain/processScenario.js";
|
||||
import { AnalysisCapabilityUnavailableError } from "../domain/errors.js";
|
||||
import { captureProcessScenario } from "./ProcessHarness.js";
|
||||
|
||||
it("fails closed on Windows before resolving or launching scenario paths", async () => {
|
||||
const scenario = processScenarioSchema.parse({
|
||||
executable: "Z:/missing/should-never-be-resolved.exe",
|
||||
working_directory: "Z:/missing/working-directory",
|
||||
});
|
||||
const result = await captureProcessScenario(scenario, undefined, "win32");
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) throw new Error("expected Windows ownership refusal");
|
||||
expect(result.error).toBeInstanceOf(AnalysisCapabilityUnavailableError);
|
||||
expect(result.error).toMatchObject({
|
||||
operation: "capture_process_scenario",
|
||||
reason: expect.stringContaining("Windows process-tree ownership"),
|
||||
});
|
||||
});
|
||||
@@ -4,7 +4,6 @@ import type {
|
||||
ProcessCapture,
|
||||
UnverifiedProcessCapture,
|
||||
ProcessCaptureEventJournalEntry,
|
||||
ProcessExecutionPolicy,
|
||||
ProcessSample,
|
||||
ProcessScenario,
|
||||
RecordProcessCaptureEvent,
|
||||
@@ -12,6 +11,10 @@ import type {
|
||||
} from "../domain/processCapture.js";
|
||||
import { parseProcessCapture } from "../domain/processCapture.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
AnalysisCapabilityUnavailableError,
|
||||
type AnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
import {
|
||||
ProcessCaptureError,
|
||||
processCaptureCancelled,
|
||||
@@ -43,7 +46,10 @@ import {
|
||||
resolveProcessResult,
|
||||
type PendingProcessCapture,
|
||||
} from "./ProcessCaptureLifecycle.js";
|
||||
import { assertNotCancelled } from "./ProcessCaptureAuthority.js";
|
||||
import {
|
||||
assertNotCancelled,
|
||||
resolveProcessScenarioRuntimePaths,
|
||||
} from "./ProcessScenarioRuntimeValidation.js";
|
||||
import {
|
||||
createProcessCaptureJournal,
|
||||
scheduleScenarioInteractions,
|
||||
@@ -56,6 +62,7 @@ import {
|
||||
type ProcessReactiveHarness,
|
||||
} from "./ProcessReactiveHarness.js";
|
||||
import { makeProcessCaptureEnvironment } from "./ProcessCaptureEnvironment.js";
|
||||
import { processCaptureOwnershipUnavailableReason } from "./ProcessCaptureCapability.js";
|
||||
export { probeProcessCaptureCapability } from "./ProcessCaptureCapability.js";
|
||||
|
||||
interface StartedCaptureRuntime {
|
||||
@@ -115,7 +122,7 @@ const createTerminalRenderer = (
|
||||
|
||||
interface StartCaptureRuntimeOptions {
|
||||
readonly scenario: ProcessScenario;
|
||||
readonly home: string;
|
||||
readonly hostEnvironment: Readonly<Record<string, string | undefined>>;
|
||||
readonly temporaryRoot: string;
|
||||
readonly runId: string;
|
||||
readonly before: Awaited<ReturnType<typeof snapshotRoots>>;
|
||||
@@ -436,16 +443,15 @@ const completeCapture = async (options: {
|
||||
});
|
||||
};
|
||||
|
||||
/** Execute one authorized scenario and return bounded observations. */
|
||||
/** Execute one caller-selected scenario and return bounded observations. */
|
||||
const runProcessScenario = async (
|
||||
scenario: ProcessScenario,
|
||||
policy: ProcessExecutionPolicy,
|
||||
signal?: AbortSignal,
|
||||
hostEnvironment: Readonly<Record<string, string | undefined>> = process.env,
|
||||
): Promise<ProcessCapture> => {
|
||||
assertSupportedReactiveScenario(scenario);
|
||||
const { temporaryRoot, runId, home, before } = await prepareProcessCapture(
|
||||
const { temporaryRoot, runId, before } = await prepareProcessCapture(
|
||||
scenario,
|
||||
policy,
|
||||
signal,
|
||||
);
|
||||
const frames: TerminalFrame[] = [];
|
||||
@@ -463,7 +469,7 @@ const runProcessScenario = async (
|
||||
try {
|
||||
runtime = await startCaptureRuntime({
|
||||
scenario,
|
||||
home,
|
||||
hostEnvironment,
|
||||
temporaryRoot,
|
||||
runId,
|
||||
before,
|
||||
@@ -522,11 +528,26 @@ const runProcessScenario = async (
|
||||
/** Execute one scenario through a typed expected-failure channel. */
|
||||
export const captureProcessScenario = async (
|
||||
scenario: ProcessScenario,
|
||||
policy: ProcessExecutionPolicy,
|
||||
signal?: AbortSignal,
|
||||
): Promise<Result<ProcessCapture, ProcessCaptureError>> => {
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
environment: Readonly<Record<string, string | undefined>> = process.env,
|
||||
): Promise<Result<ProcessCapture, ProcessCaptureError | AnalysisError>> => {
|
||||
const ownershipReason = processCaptureOwnershipUnavailableReason(platform);
|
||||
if (ownershipReason !== undefined)
|
||||
return err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
"rea-process",
|
||||
"capture_process_scenario",
|
||||
ownershipReason,
|
||||
),
|
||||
);
|
||||
try {
|
||||
return ok(await runProcessScenario(scenario, policy, signal));
|
||||
assertNotCancelled(signal);
|
||||
const resolvedScenario = await resolveProcessScenarioRuntimePaths(
|
||||
scenario,
|
||||
environment,
|
||||
);
|
||||
return ok(await runProcessScenario(resolvedScenario, signal, environment));
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
cause instanceof ProcessCaptureError
|
||||
|
||||
@@ -11,7 +11,7 @@ export const normalizeProcessElapsedTime = (
|
||||
timeBucketMs: number,
|
||||
): number => Math.floor(elapsedMs / timeBucketMs) * timeBucketMs;
|
||||
|
||||
/** Normalize and redact one terminal/protocol payload under scenario rules. */
|
||||
/** Normalize one terminal/protocol payload under explicitly selected scenario rules. */
|
||||
export const normalizeProcessText = (
|
||||
value: string,
|
||||
scenario: ProcessScenario,
|
||||
@@ -19,11 +19,6 @@ export const normalizeProcessText = (
|
||||
pid: number,
|
||||
): string => {
|
||||
let normalized = value;
|
||||
for (const alias of scenario.secret_aliases) {
|
||||
const secret = scenario.environment[alias];
|
||||
if (secret !== undefined && secret.length > 0)
|
||||
normalized = normalized.replaceAll(secret, "<redacted>");
|
||||
}
|
||||
if (scenario.normalization.paths) {
|
||||
normalized = normalized.replaceAll(temporaryRoot, "<temporary-root>");
|
||||
normalized = normalized.replaceAll(
|
||||
@@ -31,7 +26,7 @@ export const normalizeProcessText = (
|
||||
"<working-directory>",
|
||||
);
|
||||
normalized = normalized.replaceAll(scenario.executable, "<executable>");
|
||||
for (const [index, root] of scenario.filesystem_roots.entries())
|
||||
for (const [index, root] of scenario.filesystem_observation_paths.entries())
|
||||
normalized = normalized.replaceAll(
|
||||
root,
|
||||
`<filesystem-root-${String(index)}>`,
|
||||
@@ -127,7 +122,7 @@ const normalizePidTokens = (
|
||||
);
|
||||
};
|
||||
|
||||
export const redactProtocolEvents = (
|
||||
export const normalizeProtocolEvents = (
|
||||
events: readonly ProcessCapture["protocol_events"][number][],
|
||||
scenario: ProcessScenario,
|
||||
): readonly ProcessCapture["protocol_events"][number][] =>
|
||||
|
||||
@@ -11,17 +11,14 @@ import type {
|
||||
InteractionEvent,
|
||||
TerminalFrame,
|
||||
} from "../domain/processCapture.js";
|
||||
import { parseProcessScenario } from "../domain/processScenario.js";
|
||||
import {
|
||||
processReactiveScenarioSchema,
|
||||
type ProcessReactiveScenario,
|
||||
} from "../domain/processReactiveScenario.js";
|
||||
const terminalTrigger = () => ({
|
||||
kind: "terminal_text" as const,
|
||||
view: "decoded" as const,
|
||||
encoding: "utf8" as const,
|
||||
literal: "Ready",
|
||||
case_sensitive: true,
|
||||
control_sequences: "include" as const,
|
||||
occurrence: 1,
|
||||
since: { kind: "scenario_start" as const },
|
||||
consume: true,
|
||||
@@ -56,7 +53,7 @@ const twoStateScenario = (): ProcessReactiveScenario =>
|
||||
priority: 1,
|
||||
max_uses: 1,
|
||||
when: terminalTrigger(),
|
||||
actions: [{ type: "send_input", data: "go", sensitive: false }],
|
||||
actions: [{ type: "send_input", data: "go" }],
|
||||
target: { kind: "goto", state: "sent" },
|
||||
},
|
||||
],
|
||||
@@ -84,7 +81,7 @@ const twoStateScenario = (): ProcessReactiveScenario =>
|
||||
cardinality: { min: 1, max: 1 },
|
||||
},
|
||||
actions: [],
|
||||
target: { kind: "finish", outcome: "passed" },
|
||||
target: { kind: "finish" },
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -99,6 +96,7 @@ const createHarness = (scenario: ProcessReactiveScenario) => {
|
||||
const timers = timerHost();
|
||||
let now = 100;
|
||||
const effectHost = {
|
||||
scenario: parseProcessScenario({ executable: "node" }),
|
||||
terminal: () => ({
|
||||
write: (data: string) => terminalCalls.push(`write:${data}`),
|
||||
resize: (columns: number, rows: number) =>
|
||||
@@ -219,7 +217,7 @@ describe("process reactive coordinator ordering", () => {
|
||||
},
|
||||
{ type: "checkpoint", name: "stopped" },
|
||||
],
|
||||
target: { kind: "finish", outcome: "passed" },
|
||||
target: { kind: "finish" },
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
@@ -6,11 +6,7 @@ import {
|
||||
|
||||
export const terminalTrigger = () => ({
|
||||
kind: "terminal_text" as const,
|
||||
view: "decoded" as const,
|
||||
encoding: "utf8" as const,
|
||||
literal: "Ready",
|
||||
case_sensitive: true,
|
||||
control_sequences: "include" as const,
|
||||
occurrence: 1,
|
||||
since: { kind: "scenario_start" as const },
|
||||
consume: true,
|
||||
@@ -45,7 +41,7 @@ export const twoStateScenario = (): ProcessReactiveScenario =>
|
||||
priority: 1,
|
||||
max_uses: 1,
|
||||
when: terminalTrigger(),
|
||||
actions: [{ type: "send_input", data: "go", sensitive: false }],
|
||||
actions: [{ type: "send_input", data: "go" }],
|
||||
target: { kind: "goto", state: "sent" },
|
||||
},
|
||||
],
|
||||
@@ -73,7 +69,7 @@ export const twoStateScenario = (): ProcessReactiveScenario =>
|
||||
cardinality: { min: 1, max: 1 },
|
||||
},
|
||||
actions: [],
|
||||
target: { kind: "finish", outcome: "passed" },
|
||||
target: { kind: "finish" },
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
@@ -8,8 +8,12 @@ import type {
|
||||
ProcessReactiveAction,
|
||||
ProcessReactiveScenario,
|
||||
} from "../domain/processReactiveScenario.js";
|
||||
import type { ProcessScenario } from "../domain/processScenario.js";
|
||||
import type { ProcessCaptureJournal } from "./ProcessCaptureJournal.js";
|
||||
import { normalizeProcessElapsedTime } from "./ProcessNormalization.js";
|
||||
import {
|
||||
normalizeProcessElapsedTime,
|
||||
normalizeProcessText,
|
||||
} from "./ProcessNormalization.js";
|
||||
|
||||
/** Minimal PTY authority used by the admitted reactive action slice. */
|
||||
export interface ProcessReactiveTerminal {
|
||||
@@ -37,6 +41,7 @@ export interface ProcessReactiveCheckpoints {
|
||||
|
||||
/** Host dependencies for journal-backed reactive process actions. */
|
||||
export interface ProcessReactiveEffectHost {
|
||||
readonly scenario: ProcessScenario;
|
||||
readonly terminal: () => ProcessReactiveTerminal | undefined;
|
||||
readonly renderer: ProcessReactiveRenderer;
|
||||
readonly checkpoints: ProcessReactiveCheckpoints;
|
||||
@@ -53,11 +58,12 @@ const elapsed = (host: ProcessReactiveEffectHost): number =>
|
||||
|
||||
const interactionData = (
|
||||
action: Exclude<ProcessReactiveAction, { readonly type: "checkpoint" }>,
|
||||
scenario: ProcessScenario,
|
||||
): string => {
|
||||
if (action.type === "send_input")
|
||||
return action.sensitive
|
||||
? `<redacted-input:${String(Buffer.byteLength(action.data))}-bytes>`
|
||||
: action.data;
|
||||
: normalizeProcessText(action.data, scenario, "<no-temporary-root>", -1);
|
||||
if (action.type === "resize")
|
||||
return `${String(action.columns)}x${String(action.rows)}`;
|
||||
if (action.type === "close_stdin") return "";
|
||||
@@ -108,7 +114,7 @@ const recordInteraction = (
|
||||
scheduled_at_ms: atMs,
|
||||
dispatched_at_ms: atMs,
|
||||
type: interactionType(action),
|
||||
data: interactionData(action),
|
||||
data: interactionData(action, host.scenario),
|
||||
outcome,
|
||||
};
|
||||
host.interactions.push(event);
|
||||
|
||||
@@ -24,7 +24,7 @@ import { subscribeProcessReactiveObservations } from "./ProcessReactiveObservati
|
||||
import {
|
||||
normalizeProcessSamples,
|
||||
normalizeProcessShimEvent,
|
||||
redactProtocolEvents,
|
||||
normalizeProtocolEvents,
|
||||
} from "./ProcessNormalization.js";
|
||||
import type { TerminalRenderer } from "./TerminalRenderer.js";
|
||||
|
||||
@@ -101,6 +101,7 @@ export const startProcessReactiveHarness = (options: {
|
||||
execute: (actions, signal) =>
|
||||
executeProcessReactiveEffects(
|
||||
{
|
||||
scenario: options.scenario,
|
||||
terminal: () => reactiveTerminalFor(options.terminal()),
|
||||
renderer: options.renderer,
|
||||
checkpoints: options.checkpoints,
|
||||
@@ -144,7 +145,7 @@ export const startProcessReactiveHarness = (options: {
|
||||
)[index];
|
||||
},
|
||||
protocolEventAt: (index) =>
|
||||
redactProtocolEvents(
|
||||
normalizeProtocolEvents(
|
||||
options.capture.protocolEvents().slice(index, index + 1),
|
||||
options.scenario,
|
||||
)[0],
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { mkdtemp, rm, symlink } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
resolveExecutable,
|
||||
resolveProcessScenarioRuntimePaths,
|
||||
} from "./ProcessScenarioRuntimeValidation.js";
|
||||
import { parseProcessScenario } from "../domain/processCapture.js";
|
||||
|
||||
it("preserves the caller-selected executable symlink for process invocation", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-process-executable-alias-"));
|
||||
try {
|
||||
const alias = join(root, "chosen-node");
|
||||
await symlink(process.execPath, alias);
|
||||
|
||||
await expect(resolveExecutable(alias, root, "")).resolves.toBe(alias);
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("retains the selected missing working directory and OS reason", async () => {
|
||||
const selected = join(tmpdir(), "rea-process-missing-cwd-unique");
|
||||
const scenario = parseProcessScenario({
|
||||
executable: process.execPath,
|
||||
working_directory: selected,
|
||||
});
|
||||
|
||||
await expect(resolveProcessScenarioRuntimePaths(scenario)).rejects.toThrow(
|
||||
`working directory could not be resolved: ${selected} (ENOENT)`,
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
import { access, realpath, stat } from "node:fs/promises";
|
||||
import { constants as fsConstants } from "node:fs";
|
||||
import { delimiter, isAbsolute, join, resolve } from "node:path";
|
||||
|
||||
import type { ProcessScenario } from "../domain/processCapture.js";
|
||||
import {
|
||||
ProcessCaptureError,
|
||||
processCaptureCancelled,
|
||||
} from "./ProcessCaptureError.js";
|
||||
|
||||
/** Resolve caller-selected executable and observation paths for this execution. */
|
||||
export const resolveProcessScenarioRuntimePaths = async (
|
||||
scenario: ProcessScenario,
|
||||
environment: Readonly<Record<string, string | undefined>> = process.env,
|
||||
): Promise<ProcessScenario> => {
|
||||
const selectedWorkingDirectory = resolve(scenario.working_directory);
|
||||
let workingDirectory: string;
|
||||
try {
|
||||
workingDirectory = await realpath(selectedWorkingDirectory);
|
||||
} catch (cause: unknown) {
|
||||
throw new ProcessCaptureError(
|
||||
`working directory could not be resolved: ${selectedWorkingDirectory}${osFailure(cause)}`,
|
||||
{ cause },
|
||||
);
|
||||
}
|
||||
let workingDirectoryStat;
|
||||
try {
|
||||
workingDirectoryStat = await stat(workingDirectory);
|
||||
} catch (cause: unknown) {
|
||||
throw new ProcessCaptureError(
|
||||
`working directory could not be inspected: ${workingDirectory}${osFailure(cause)}`,
|
||||
{ cause },
|
||||
);
|
||||
}
|
||||
if (!workingDirectoryStat.isDirectory())
|
||||
throw new ProcessCaptureError(
|
||||
`working directory is not a directory: ${workingDirectory}`,
|
||||
);
|
||||
const executable = await resolveExecutable(
|
||||
scenario.executable,
|
||||
workingDirectory,
|
||||
scenario.environment.PATH ?? environment.PATH ?? "",
|
||||
);
|
||||
const observationPaths = scenario.filesystem_observation_paths.map((path) =>
|
||||
resolve(workingDirectory, path),
|
||||
);
|
||||
return {
|
||||
...scenario,
|
||||
executable,
|
||||
working_directory: workingDirectory,
|
||||
filesystem_observation_paths: observationPaths,
|
||||
};
|
||||
};
|
||||
|
||||
/** Resolve a selected executable through the caller's effective PATH. */
|
||||
export const resolveExecutable = async (
|
||||
command: string,
|
||||
workingDirectory: string,
|
||||
searchPath: string,
|
||||
): Promise<string> => {
|
||||
const directories = searchPath
|
||||
.split(delimiter)
|
||||
.map((directory) =>
|
||||
directory === ""
|
||||
? workingDirectory
|
||||
: resolve(workingDirectory, directory),
|
||||
);
|
||||
const candidates =
|
||||
isAbsolute(command) || command.includes("/") || command.includes("\\")
|
||||
? [resolve(workingDirectory, command)]
|
||||
: directories.map((directory) => join(directory, command));
|
||||
const failures: string[] = [];
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
await access(candidate, fsConstants.X_OK);
|
||||
if ((await stat(candidate)).isFile()) return candidate;
|
||||
failures.push(`${candidate} (not a regular file)`);
|
||||
} catch (cause: unknown) {
|
||||
const code = osErrorCode(cause);
|
||||
if (code !== "ENOENT" && code !== "ENOTDIR")
|
||||
failures.push(`${candidate}${osFailure(cause)}`);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
throw new ProcessCaptureError(
|
||||
failures.length === 0
|
||||
? `executable could not be resolved: ${command}`
|
||||
: `executable could not be resolved: ${command}; checked ${failures.join("; ")}`,
|
||||
);
|
||||
};
|
||||
|
||||
const osErrorCode = (cause: unknown): string | undefined =>
|
||||
typeof cause === "object" &&
|
||||
cause !== null &&
|
||||
"code" in cause &&
|
||||
typeof cause.code === "string"
|
||||
? cause.code
|
||||
: undefined;
|
||||
|
||||
const osFailure = (cause: unknown): string => {
|
||||
const code = osErrorCode(cause);
|
||||
return code === undefined ? "" : ` (${code})`;
|
||||
};
|
||||
|
||||
/** Reject cancellation before a process capture operation begins. */
|
||||
export const assertNotCancelled = (signal: AbortSignal | undefined): void => {
|
||||
if (signal?.aborted === true) throw processCaptureCancelled();
|
||||
};
|
||||
@@ -1,272 +0,0 @@
|
||||
import {
|
||||
createStoreFileLock,
|
||||
removeStaleStoreFileLock,
|
||||
type StoreFileLock,
|
||||
} from "./StoreFileLock.js";
|
||||
import { createHash } from "node:crypto";
|
||||
import { constants } from "node:fs";
|
||||
import {
|
||||
lstat,
|
||||
mkdir,
|
||||
open,
|
||||
realpath,
|
||||
type FileHandle,
|
||||
} from "node:fs/promises";
|
||||
import { dirname } from "node:path";
|
||||
import { setTimeout as delay } from "node:timers/promises";
|
||||
|
||||
import writeFileAtomic from "write-file-atomic";
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
PERMISSION_CAPABILITIES,
|
||||
type PermissionGrant,
|
||||
} from "../domain/permissionPolicy.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { prefixedDigestSchema } from "./../domain/digests.js";
|
||||
|
||||
const grantSchema = z.object({
|
||||
grant_id: z.string().min(1),
|
||||
capability: z.enum(PERMISSION_CAPABILITIES),
|
||||
roots: z.array(z.string()),
|
||||
executables: z.array(z.string()),
|
||||
environment_names: z.array(z.string()),
|
||||
origins: z.array(z.string()).optional(),
|
||||
network: z.enum(["none", "loopback", "external"]),
|
||||
mount: z.boolean(),
|
||||
lifetime: z.literal("project"),
|
||||
operation_identity: z.string().nullable(),
|
||||
expires_at: z.iso.datetime().nullable(),
|
||||
});
|
||||
|
||||
const storeSchema = z.object({
|
||||
project_id: prefixedDigestSchema("project"),
|
||||
project_root: z.string(),
|
||||
grants: z.array(grantSchema),
|
||||
});
|
||||
|
||||
export type ProjectPermissionStore = z.infer<typeof storeSchema>;
|
||||
|
||||
/** Owner-only project policy persistence failure. */
|
||||
export class ProjectPermissionStoreError extends Error {
|
||||
readonly _tag = "ProjectPermissionStoreError" as const;
|
||||
|
||||
constructor(
|
||||
readonly reason:
|
||||
| "project_not_found"
|
||||
| "not_owner_only"
|
||||
| "invalid"
|
||||
| "locked"
|
||||
| "io",
|
||||
options?: ErrorOptions,
|
||||
) {
|
||||
super(`Project permission store failed: ${reason}`, options);
|
||||
}
|
||||
}
|
||||
|
||||
/** Derive relocation-explicit project identity from its canonical root. */
|
||||
const identifyPermissionProject = async (
|
||||
projectRoot: string,
|
||||
): Promise<
|
||||
Result<
|
||||
{ readonly id: string; readonly root: string },
|
||||
ProjectPermissionStoreError
|
||||
>
|
||||
> => {
|
||||
try {
|
||||
const root = await realpath(projectRoot);
|
||||
return ok({
|
||||
id: `project_${createHash("sha256").update(root).digest("hex")}`,
|
||||
root,
|
||||
});
|
||||
} catch (cause: unknown) {
|
||||
return err(new ProjectPermissionStoreError("project_not_found", { cause }));
|
||||
}
|
||||
};
|
||||
|
||||
/** Read and validate an owner-only store bound to the requested project. */
|
||||
export const readProjectPermissionStore = async (
|
||||
path: string,
|
||||
projectRoot: string,
|
||||
): Promise<
|
||||
Result<ProjectPermissionStore | null, ProjectPermissionStoreError>
|
||||
> => {
|
||||
const project = await identifyPermissionProject(projectRoot);
|
||||
if (!project.ok) return project;
|
||||
if (process.getuid === undefined)
|
||||
return err(new ProjectPermissionStoreError("not_owner_only"));
|
||||
let handle: FileHandle | undefined;
|
||||
try {
|
||||
const opened = await openPrivateStore(path);
|
||||
if (!opened.ok) return opened;
|
||||
if (opened.value === null) return ok(null);
|
||||
handle = opened.value;
|
||||
const encoded = await handle.readFile("utf8");
|
||||
let decoded: unknown;
|
||||
try {
|
||||
decoded = JSON.parse(encoded);
|
||||
} catch (cause: unknown) {
|
||||
return err(new ProjectPermissionStoreError("invalid", { cause }));
|
||||
}
|
||||
const parsed = storeSchema.safeParse(decoded);
|
||||
if (
|
||||
!parsed.success ||
|
||||
parsed.data.project_id !== project.value.id ||
|
||||
parsed.data.project_root !== project.value.root
|
||||
)
|
||||
return err(new ProjectPermissionStoreError("invalid"));
|
||||
return ok(parsed.data);
|
||||
} catch (cause: unknown) {
|
||||
if (isNotFound(cause)) return ok(null);
|
||||
return err(new ProjectPermissionStoreError("io", { cause }));
|
||||
} finally {
|
||||
await handle?.close().catch(() => undefined);
|
||||
}
|
||||
};
|
||||
|
||||
/** Atomically replace explicit project grants with owner-only permissions. */
|
||||
export const writeProjectPermissionStore = async (
|
||||
path: string,
|
||||
projectRoot: string,
|
||||
grants: readonly PermissionGrant[],
|
||||
): Promise<Result<ProjectPermissionStore, ProjectPermissionStoreError>> => {
|
||||
const project = await identifyPermissionProject(projectRoot);
|
||||
if (!project.ok) return project;
|
||||
const candidate = storeSchema.safeParse({
|
||||
project_id: project.value.id,
|
||||
project_root: project.value.root,
|
||||
grants,
|
||||
});
|
||||
if (!candidate.success)
|
||||
return err(
|
||||
new ProjectPermissionStoreError("invalid", { cause: candidate.error }),
|
||||
);
|
||||
if (process.getuid === undefined)
|
||||
return err(new ProjectPermissionStoreError("not_owner_only"));
|
||||
return withPermissionStoreLock(path, () =>
|
||||
writePreparedPermissionStore(path, projectRoot, candidate.data),
|
||||
);
|
||||
};
|
||||
|
||||
const writePreparedPermissionStore = async (
|
||||
path: string,
|
||||
projectRoot: string,
|
||||
candidate: ProjectPermissionStore,
|
||||
): Promise<Result<ProjectPermissionStore, ProjectPermissionStoreError>> => {
|
||||
await writeFileAtomic(path, `${JSON.stringify(candidate, null, 2)}\n`, {
|
||||
encoding: "utf8",
|
||||
mode: 0o600,
|
||||
});
|
||||
const verified = await readProjectPermissionStore(path, projectRoot);
|
||||
if (!verified.ok) return verified;
|
||||
if (
|
||||
verified.value === null ||
|
||||
JSON.stringify(verified.value) !== JSON.stringify(candidate)
|
||||
)
|
||||
return err(new ProjectPermissionStoreError("invalid"));
|
||||
return ok(candidate);
|
||||
};
|
||||
|
||||
/** Revoke one grant while serializing the complete read-modify-write cycle. */
|
||||
export const revokeProjectPermissionGrant = async (
|
||||
path: string,
|
||||
projectRoot: string,
|
||||
grantId: string,
|
||||
): Promise<Result<boolean, ProjectPermissionStoreError>> =>
|
||||
withPermissionStoreLock(path, async () => {
|
||||
const current = await readProjectPermissionStore(path, projectRoot);
|
||||
if (!current.ok) return current;
|
||||
if (current.value === null) return ok(false);
|
||||
const retained = current.value.grants.filter(
|
||||
({ grant_id }) => grant_id !== grantId,
|
||||
);
|
||||
if (retained.length === current.value.grants.length) return ok(false);
|
||||
const written = await writePreparedPermissionStore(path, projectRoot, {
|
||||
...current.value,
|
||||
grants: retained,
|
||||
});
|
||||
return written.ok ? ok(true) : written;
|
||||
});
|
||||
|
||||
const withPermissionStoreLock = async <Value>(
|
||||
path: string,
|
||||
action: () => Promise<Result<Value, ProjectPermissionStoreError>>,
|
||||
): Promise<Result<Value, ProjectPermissionStoreError>> => {
|
||||
let lock: StoreFileLock | undefined;
|
||||
try {
|
||||
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
||||
const acquired = await acquirePermissionStoreLock(path);
|
||||
if (!acquired.ok) return acquired;
|
||||
lock = acquired.value;
|
||||
return await action();
|
||||
} catch (cause: unknown) {
|
||||
return err(new ProjectPermissionStoreError("io", { cause }));
|
||||
} finally {
|
||||
if (lock !== undefined) await lock.release();
|
||||
}
|
||||
};
|
||||
|
||||
const acquirePermissionStoreLock = async (
|
||||
destination: string,
|
||||
): Promise<Result<StoreFileLock, ProjectPermissionStoreError>> => {
|
||||
const path = `${destination}.lock`;
|
||||
for (let attempt = 0; attempt < 100; attempt += 1) {
|
||||
try {
|
||||
return ok(await createStoreFileLock(path));
|
||||
} catch (cause: unknown) {
|
||||
if (!isAlreadyExists(cause))
|
||||
return err(new ProjectPermissionStoreError("io", { cause }));
|
||||
if (await removeStaleStoreFileLock(path)) continue;
|
||||
if (attempt === 99)
|
||||
return err(new ProjectPermissionStoreError("locked", { cause }));
|
||||
await delay(10);
|
||||
}
|
||||
}
|
||||
return err(new ProjectPermissionStoreError("locked"));
|
||||
};
|
||||
|
||||
const isNotFound = (cause: unknown): boolean => errorCode(cause) === "ENOENT";
|
||||
|
||||
const openPrivateStore = async (
|
||||
path: string,
|
||||
): Promise<Result<FileHandle | null, ProjectPermissionStoreError>> => {
|
||||
let handle: FileHandle | undefined;
|
||||
try {
|
||||
handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
||||
const metadata = await handle.stat();
|
||||
if (!privateRegularFile(metadata)) {
|
||||
await handle.close();
|
||||
return err(new ProjectPermissionStoreError("not_owner_only"));
|
||||
}
|
||||
return ok(handle);
|
||||
} catch (cause: unknown) {
|
||||
await handle?.close().catch(() => undefined);
|
||||
if (isNotFound(cause)) return ok(null);
|
||||
return err(
|
||||
new ProjectPermissionStoreError(
|
||||
isSymlinkRefusal(cause) ? "not_owner_only" : "io",
|
||||
{ cause },
|
||||
),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const privateRegularFile = (
|
||||
metadata: Awaited<ReturnType<typeof lstat>>,
|
||||
): boolean =>
|
||||
metadata.isFile() &&
|
||||
!metadata.isSymbolicLink() &&
|
||||
(Number(metadata.mode) & 0o077) === 0 &&
|
||||
process.getuid !== undefined &&
|
||||
metadata.uid === process.getuid();
|
||||
|
||||
const isAlreadyExists = (cause: unknown): boolean =>
|
||||
errorCode(cause) === "EEXIST";
|
||||
|
||||
const errorCode = (cause: unknown): unknown =>
|
||||
typeof cause === "object" && cause !== null && "code" in cause
|
||||
? cause.code
|
||||
: undefined;
|
||||
|
||||
const isSymlinkRefusal = (cause: unknown): boolean =>
|
||||
errorCode(cause) === "ELOOP" || errorCode(cause) === "EMLINK";
|
||||
@@ -1,5 +1,4 @@
|
||||
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
|
||||
import { isSecretLikePath } from "../domain/referenceSourceClassification.js";
|
||||
import {
|
||||
createHistoricalSourceGraph,
|
||||
historicalSourceLanguages,
|
||||
@@ -128,8 +127,8 @@ const sortExclusions = (
|
||||
* Import a reference source directory into a committed historical source graph.
|
||||
*
|
||||
* The import is deterministic, parallel-safe, and never executes source, hooks,
|
||||
* git subprocesses, or network requests. Secret-like paths are redacted before
|
||||
* they are committed to the graph.
|
||||
* git subprocesses, or network requests. Paths explicitly excluded by the
|
||||
* caller's reference-source policy are omitted from the graph.
|
||||
*/
|
||||
export const importReferenceSource = async (
|
||||
options: ReferenceSourceImportOptions,
|
||||
@@ -142,7 +141,7 @@ export const importReferenceSource = async (
|
||||
|
||||
const exclusions: HistoricalSourceGraphInput["exclusions"] = [];
|
||||
const shouldExclude = (path: string): boolean => {
|
||||
if (isSecretLikePath(path) || secrets.ignores(path)) {
|
||||
if (secrets.ignores(path)) {
|
||||
exclusions.push({ path, reason: "configured-secret" });
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -46,10 +46,7 @@ export const createBinarySession = (
|
||||
const { ArtifactProvider } = await import(
|
||||
"../artifacts/ArtifactProvider.js"
|
||||
);
|
||||
return new ArtifactProvider(
|
||||
config.artifactNativeMountEnabled,
|
||||
config.artifactIntegrityContinueEnabled,
|
||||
);
|
||||
return new ArtifactProvider();
|
||||
}),
|
||||
lazyProvider("native-macos", async () => {
|
||||
const { NativeMacOSProvider } = await import(
|
||||
|
||||
Reference in New Issue
Block a user