refactor(test): keep coverage at behavioral boundaries (#474)
* refactor(test): keep coverage at behavioral boundaries * fix(ci): restore package workflow temp-root classification
This commit is contained in:
@@ -1,421 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
AnalysisProviderRegistry,
|
||||
type AnalysisProviderBinding,
|
||||
} from "../../../src/application/AnalysisProviderRegistry.js";
|
||||
import {
|
||||
createAnalysisExecution,
|
||||
type AnalysisClient,
|
||||
type AnalysisProviderCandidate,
|
||||
type CapabilityDescriptor,
|
||||
type ProviderAvailability,
|
||||
type ProviderIdentity,
|
||||
type ProviderTargetSupport,
|
||||
} from "../../../src/application/AnalysisProvider.js";
|
||||
import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js";
|
||||
import type { BinaryTarget } from "../../../src/domain/binaryTarget.js";
|
||||
import {
|
||||
ProviderAdapterError,
|
||||
ProviderSelectionError,
|
||||
projectAnalysisError,
|
||||
} from "../../../src/domain/errors.js";
|
||||
import { err, ok } from "../../../src/domain/result.js";
|
||||
|
||||
const DATABASE_TARGET: BinaryTarget = {
|
||||
path: "/tmp/fixture.hop",
|
||||
sha256: "a".repeat(64),
|
||||
kind: "database",
|
||||
format: "analysis-database",
|
||||
};
|
||||
const ARTIFACT_TARGET: BinaryTarget = {
|
||||
path: "/tmp/app.asar",
|
||||
sha256: "b".repeat(64),
|
||||
kind: "archive",
|
||||
format: "asar",
|
||||
};
|
||||
|
||||
describe("analysis provider registry: discovery and selection", () => {
|
||||
it("admits overlapping operations, sorts discovery, and rejects duplicate IDs", () => {
|
||||
const alpha = candidate("alpha");
|
||||
const beta = candidate("beta");
|
||||
const registry = new AnalysisProviderRegistry([
|
||||
beta.provider,
|
||||
alpha.provider,
|
||||
]);
|
||||
|
||||
expect(registry.identities().map(({ id }) => id)).toEqual([
|
||||
"alpha",
|
||||
"beta",
|
||||
]);
|
||||
expect(
|
||||
registry.candidates().map(({ provider, targetSupport }) => ({
|
||||
id: provider.id,
|
||||
support: targetSupport.status,
|
||||
})),
|
||||
).toEqual([
|
||||
{ id: "alpha", support: "unknown" },
|
||||
{ id: "beta", support: "unknown" },
|
||||
]);
|
||||
expect(alpha.created).toEqual([]);
|
||||
expect(beta.created).toEqual([]);
|
||||
expect(
|
||||
() => new AnalysisProviderRegistry([alpha.provider, alpha.provider]),
|
||||
).toThrow(/Duplicate analysis provider ID: alpha/u);
|
||||
expect(
|
||||
() =>
|
||||
new AnalysisProviderRegistry([
|
||||
{
|
||||
...alpha.provider,
|
||||
capabilities: () => {
|
||||
const descriptor = capability(alpha.provider.identity());
|
||||
return [descriptor, descriptor];
|
||||
},
|
||||
},
|
||||
]),
|
||||
).toThrow(/declares operation address_name more than once/u);
|
||||
expect(
|
||||
() =>
|
||||
new AnalysisProviderRegistry([
|
||||
{
|
||||
...alpha.provider,
|
||||
capabilities: () => [
|
||||
capability({
|
||||
...alpha.provider.identity(),
|
||||
name: "mismatched provider",
|
||||
}),
|
||||
],
|
||||
},
|
||||
]),
|
||||
).toThrow(/published mismatched capability provenance/u);
|
||||
expect(
|
||||
() => new AnalysisProviderRegistry([candidate("auto").provider]),
|
||||
).toThrow(/Invalid analysis provider ID: auto/u);
|
||||
});
|
||||
|
||||
it("selects the sole usable candidate without creating a client", async () => {
|
||||
const alpha = candidate("alpha");
|
||||
const beta = candidate("beta", { available: false });
|
||||
const registry = new AnalysisProviderRegistry([
|
||||
beta.provider,
|
||||
alpha.provider,
|
||||
]);
|
||||
|
||||
const selected = await registry.select(DATABASE_TARGET);
|
||||
expect(selected.ok).toBe(true);
|
||||
if (!selected.ok || selected.value.binding === null) return;
|
||||
expect(bindingProjection(selected.value.binding)).toEqual({
|
||||
id: "alpha",
|
||||
source: "auto-single-candidate",
|
||||
version: "1",
|
||||
});
|
||||
expect(selected.value.candidates).toMatchObject([
|
||||
{ provider: { id: "alpha", version: "1" }, selected: true },
|
||||
{
|
||||
provider: { id: "beta" },
|
||||
selected: false,
|
||||
availability: { status: "unavailable", code: "runtime_missing" },
|
||||
},
|
||||
]);
|
||||
expect(alpha.created).toEqual([]);
|
||||
expect(beta.created).toEqual([]);
|
||||
});
|
||||
|
||||
it("makes auto ambiguity explicit and honors request over environment", async () => {
|
||||
const alpha = candidate("alpha");
|
||||
const beta = candidate("beta");
|
||||
const registry = new AnalysisProviderRegistry(
|
||||
[alpha.provider, beta.provider],
|
||||
"beta",
|
||||
);
|
||||
|
||||
const environment = await registry.select(DATABASE_TARGET);
|
||||
expect(environment.ok).toBe(true);
|
||||
if (environment.ok)
|
||||
expect(environment.value.binding?.selectionSource).toBe("environment");
|
||||
expect(environment.ok && environment.value.binding?.identity.id).toBe(
|
||||
"beta",
|
||||
);
|
||||
|
||||
const request = await registry.select(DATABASE_TARGET, "alpha");
|
||||
expect(request.ok && request.value.binding?.identity.id).toBe("alpha");
|
||||
if (request.ok)
|
||||
expect(request.value.binding?.selectionSource).toBe("request");
|
||||
|
||||
const automatic = await registry.select(DATABASE_TARGET, "auto");
|
||||
expect(automatic.ok).toBe(false);
|
||||
if (automatic.ok) return;
|
||||
expect(automatic.error).toMatchObject({
|
||||
reason: "ambiguous",
|
||||
requestedProviderId: "auto",
|
||||
candidateIds: ["alpha", "beta"],
|
||||
});
|
||||
expect(projectAnalysisError(automatic.error)).toMatchObject({
|
||||
code: "capability_unavailable",
|
||||
details: {
|
||||
selection_reason: "ambiguous",
|
||||
candidate_ids: ["alpha", "beta"],
|
||||
},
|
||||
});
|
||||
expect(alpha.created).toEqual([]);
|
||||
expect(beta.created).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("analysis provider registry: binding failures and cancellation", () => {
|
||||
it("returns actionable unknown, unavailable, and unsupported failures", async () => {
|
||||
const unavailable = candidate("alpha", { available: false });
|
||||
const registry = new AnalysisProviderRegistry([unavailable.provider]);
|
||||
|
||||
const unknown = await registry.select(DATABASE_TARGET, "missing");
|
||||
expect(unknown.ok).toBe(false);
|
||||
if (!unknown.ok)
|
||||
expect(projectAnalysisError(unknown.error)).toMatchObject({
|
||||
details: {
|
||||
selection_reason: "unknown_provider",
|
||||
requested_provider_id: "missing",
|
||||
candidate_ids: ["alpha"],
|
||||
},
|
||||
});
|
||||
|
||||
const rejected = await registry.select(DATABASE_TARGET, "alpha");
|
||||
expect(rejected.ok).toBe(false);
|
||||
if (!rejected.ok)
|
||||
expect(projectAnalysisError(rejected.error)).toMatchObject({
|
||||
code: "provider_unavailable",
|
||||
details: {
|
||||
rejections: [
|
||||
{
|
||||
provider_id: "alpha",
|
||||
code: "runtime_missing",
|
||||
diagnostics: { executable_path: "/opt/alpha/bin/analyze" },
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const unsupported = await new AnalysisProviderRegistry([
|
||||
candidate("alpha", { available: false }).provider,
|
||||
]).select(ARTIFACT_TARGET, "alpha");
|
||||
expect(unsupported.ok).toBe(false);
|
||||
if (
|
||||
!unsupported.ok &&
|
||||
unsupported.error instanceof ProviderSelectionError
|
||||
) {
|
||||
expect(unsupported.error).toMatchObject({
|
||||
reason: "target_unsupported",
|
||||
});
|
||||
expect(unsupported.error.rejections.map(({ code }) => code)).toEqual([
|
||||
"runtime_missing",
|
||||
"target_kind_unsupported",
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps artifact-only targets unbound under auto or environment preference", async () => {
|
||||
const alpha = candidate("alpha");
|
||||
const environment = new AnalysisProviderRegistry([alpha.provider], "alpha");
|
||||
const automatic = new AnalysisProviderRegistry([alpha.provider]);
|
||||
|
||||
for (const registry of [environment, automatic]) {
|
||||
const selected = await registry.select(ARTIFACT_TARGET);
|
||||
expect(selected).toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
binding: null,
|
||||
candidates: [
|
||||
{
|
||||
selected: false,
|
||||
targetSupport: {
|
||||
status: "unsupported",
|
||||
code: "target_kind_unsupported",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
const explicit = await automatic.select(ARTIFACT_TARGET, "alpha");
|
||||
expect(explicit.ok).toBe(false);
|
||||
if (!explicit.ok && explicit.error instanceof ProviderSelectionError)
|
||||
expect(explicit.error.reason).toBe("target_unsupported");
|
||||
});
|
||||
|
||||
it("does not bind a profile with unresolved version or adapter failure", async () => {
|
||||
const unresolved = candidate("unresolved", { profile: "missing" });
|
||||
const failed = candidate("failed", { profile: "error" });
|
||||
|
||||
const automatic = await new AnalysisProviderRegistry([
|
||||
unresolved.provider,
|
||||
]).select(DATABASE_TARGET);
|
||||
expect(automatic).toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
binding: null,
|
||||
candidates: [
|
||||
{
|
||||
availability: {
|
||||
status: "unavailable",
|
||||
code: "version_unresolved",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const explicit = await new AnalysisProviderRegistry([
|
||||
failed.provider,
|
||||
]).select(DATABASE_TARGET, "failed");
|
||||
expect(explicit.ok).toBe(false);
|
||||
if (!explicit.ok && explicit.error instanceof ProviderSelectionError)
|
||||
expect(explicit.error.rejections).toMatchObject([
|
||||
{
|
||||
providerId: "failed",
|
||||
code: "version_unresolved",
|
||||
diagnostics: { error_tag: "ProviderAdapterError" },
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("cancels a pending profile probe even when the adapter ignores its signal", async () => {
|
||||
const alpha = candidate("alpha");
|
||||
let observedSignal: AbortSignal | undefined;
|
||||
const ignoresCancellation: AnalysisProviderCandidate = {
|
||||
...alpha.provider,
|
||||
resolveAnalysisProfile: (_target, options) => {
|
||||
observedSignal = options?.signal;
|
||||
return new Promise<never>(() => undefined);
|
||||
},
|
||||
};
|
||||
const controller = new AbortController();
|
||||
const selecting = new AnalysisProviderRegistry([
|
||||
ignoresCancellation,
|
||||
]).select(DATABASE_TARGET, "alpha", { signal: controller.signal });
|
||||
expect(observedSignal).toBe(controller.signal);
|
||||
|
||||
controller.abort();
|
||||
|
||||
await expect(selecting).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisCancelledError", operation: "open_binary" },
|
||||
});
|
||||
expect(alpha.created).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
interface CandidateFixture {
|
||||
readonly provider: AnalysisProviderCandidate;
|
||||
readonly created: string[];
|
||||
}
|
||||
|
||||
const candidate = (
|
||||
id: string,
|
||||
options: {
|
||||
readonly available?: boolean;
|
||||
readonly profile?: "resolved" | "missing" | "error";
|
||||
} = {},
|
||||
): CandidateFixture => {
|
||||
const identity: ProviderIdentity = {
|
||||
id,
|
||||
name: `${id} provider`,
|
||||
version: null,
|
||||
};
|
||||
const created: string[] = [];
|
||||
const available = options.available ?? true;
|
||||
const provider: AnalysisProviderCandidate = {
|
||||
identity: () => identity,
|
||||
capabilities: () => [capability(identity)],
|
||||
inspectAvailability: (): ProviderAvailability =>
|
||||
available
|
||||
? {
|
||||
status: "available",
|
||||
code: null,
|
||||
reason: null,
|
||||
diagnostics: { executable_path: `/opt/${id}/bin/analyze` },
|
||||
}
|
||||
: {
|
||||
status: "unavailable",
|
||||
code: "runtime_missing",
|
||||
reason: `${id} runtime is unavailable`,
|
||||
diagnostics: { executable_path: `/opt/${id}/bin/analyze` },
|
||||
},
|
||||
inspectTargetSupport: (target): ProviderTargetSupport =>
|
||||
target.kind === "database"
|
||||
? {
|
||||
status: "supported",
|
||||
code: null,
|
||||
reason: null,
|
||||
diagnostics: { target_kind: target.kind },
|
||||
}
|
||||
: {
|
||||
status: "unsupported",
|
||||
code: "target_kind_unsupported",
|
||||
reason: `${id} only accepts analysis databases in this fixture`,
|
||||
diagnostics: { target_kind: target.kind },
|
||||
},
|
||||
resolveAnalysisProfile: () => {
|
||||
if (options.profile === "error")
|
||||
return Promise.resolve(
|
||||
err(new ProviderAdapterError(id, "resolve_analysis_profile")),
|
||||
);
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
profile:
|
||||
options.profile === "missing"
|
||||
? null
|
||||
: createAnalysisProfile(
|
||||
{ id, name: identity.name, version: "1" },
|
||||
1,
|
||||
{ fixture: id },
|
||||
),
|
||||
compatibility: {},
|
||||
}),
|
||||
);
|
||||
},
|
||||
createClient: (_target, profile): AnalysisClient => {
|
||||
created.push(id);
|
||||
const executionIdentity = profile?.provider ?? identity;
|
||||
return {
|
||||
execute: (operation) =>
|
||||
Promise.resolve(
|
||||
ok(
|
||||
createAnalysisExecution(
|
||||
operation === "health" ? null : `${id}:${operation}`,
|
||||
executionIdentity,
|
||||
),
|
||||
),
|
||||
),
|
||||
close: () => Promise.resolve(),
|
||||
};
|
||||
},
|
||||
};
|
||||
return { provider, created };
|
||||
};
|
||||
|
||||
const capability = (provider: ProviderIdentity): CapabilityDescriptor => ({
|
||||
provider,
|
||||
operation: "address_name",
|
||||
inputContractVersion: 1,
|
||||
outputContractVersion: 1,
|
||||
available: true,
|
||||
reason: null,
|
||||
pagination: "none",
|
||||
exhaustive: true,
|
||||
effects: {
|
||||
mutatesArtifact: false,
|
||||
launchesProcess: true,
|
||||
mayShowUi: false,
|
||||
mayAccessNetwork: false,
|
||||
mayWriteFilesystem: false,
|
||||
changesPermissions: false,
|
||||
requiresRoot: false,
|
||||
},
|
||||
limits: { maxResults: null, maxPayloadBytes: 1_000, timeoutMs: 1_000 },
|
||||
limitations: [],
|
||||
});
|
||||
|
||||
const bindingProjection = (binding: AnalysisProviderBinding) => ({
|
||||
id: binding.identity.id,
|
||||
source: binding.selectionSource,
|
||||
version: binding.identity.version,
|
||||
});
|
||||
+7
-86
@@ -1,96 +1,17 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import type {
|
||||
AnalysisProvider,
|
||||
CapabilityDescriptor,
|
||||
} from "../../../src/application/AnalysisProvider.js";
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js";
|
||||
import {
|
||||
createBinarySessionTargets,
|
||||
createCacheProvider,
|
||||
createTestBinarySession,
|
||||
} from "../../fixtures/binarySession.js";
|
||||
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
|
||||
import { createInvestigationWorkspace } from "../../../src/domain/investigationWorkspace.js";
|
||||
import { ok as resultOk } from "../../../src/domain/result.js";
|
||||
import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
|
||||
const cacheProvider = (
|
||||
calls: string[],
|
||||
mayWriteFilesystem = false,
|
||||
): AnalysisProvider => {
|
||||
const identity = {
|
||||
id: "fixture",
|
||||
name: "Fixture analysis provider",
|
||||
version: "1",
|
||||
} as const;
|
||||
return {
|
||||
identity: () => identity,
|
||||
resolveAnalysisProfile: () =>
|
||||
Promise.resolve(
|
||||
resultOk({
|
||||
profile: createAnalysisProfile(identity, 1, { fixture: true }),
|
||||
compatibility: {},
|
||||
}),
|
||||
),
|
||||
capabilities: () => [
|
||||
cacheCapability(identity, "address_name", false, mayWriteFilesystem),
|
||||
cacheCapability(identity, "set_address_name", true),
|
||||
],
|
||||
createClient: () => ({
|
||||
execute: (operation) => {
|
||||
calls.push(operation);
|
||||
return Promise.resolve(ok(operation));
|
||||
},
|
||||
close: () => Promise.resolve(),
|
||||
}),
|
||||
};
|
||||
};
|
||||
|
||||
const cacheCapability = (
|
||||
provider: CapabilityDescriptor["provider"],
|
||||
operation: "address_name" | "set_address_name",
|
||||
mutatesArtifact: boolean,
|
||||
mayWriteFilesystem = false,
|
||||
): CapabilityDescriptor => ({
|
||||
provider,
|
||||
operation,
|
||||
inputContractVersion: 1,
|
||||
outputContractVersion: 1,
|
||||
available: true,
|
||||
reason: null,
|
||||
pagination: "none",
|
||||
exhaustive: true,
|
||||
effects: {
|
||||
mutatesArtifact,
|
||||
launchesProcess: false,
|
||||
mayShowUi: false,
|
||||
mayAccessNetwork: false,
|
||||
mayWriteFilesystem,
|
||||
changesPermissions: false,
|
||||
requiresRoot: false,
|
||||
},
|
||||
limits: {
|
||||
maxResults: null,
|
||||
maxPayloadBytes: null,
|
||||
timeoutMs: null,
|
||||
},
|
||||
limitations: [],
|
||||
});
|
||||
|
||||
const targets = async (): Promise<readonly [string, string]> => {
|
||||
const directory = await createTestTempDirectory("bb-session-");
|
||||
const first = join(directory, "first.hop");
|
||||
const second = join(directory, "second.hop");
|
||||
await writeFile(first, "one");
|
||||
await writeFile(second, "two");
|
||||
return [first, second];
|
||||
};
|
||||
|
||||
describe("binary session", () => {
|
||||
it("returns detached provider, target, and workspace metadata", async () => {
|
||||
const [first] = await targets();
|
||||
const session = createTestBinarySession(cacheProvider([]));
|
||||
const [first] = await createBinarySessionTargets();
|
||||
const session = createTestBinarySession(createCacheProvider([]));
|
||||
expect((await session.open(first)).ok).toBe(true);
|
||||
expect(session.status()).toMatchObject({
|
||||
analysis_run: {
|
||||
|
||||
+5
-15
@@ -1,22 +1,12 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import type { AnalysisProvider } from "../../../src/application/AnalysisProvider.js";
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import {
|
||||
createBinarySessionTargets,
|
||||
createTestBinarySession,
|
||||
} from "../../fixtures/binarySession.js";
|
||||
import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
|
||||
const targets = async (): Promise<readonly [string, string]> => {
|
||||
const directory = await createTestTempDirectory("bb-session-");
|
||||
const first = join(directory, "first.hop");
|
||||
const second = join(directory, "second.hop");
|
||||
await writeFile(first, "one");
|
||||
await writeFile(second, "two");
|
||||
return [first, second];
|
||||
};
|
||||
|
||||
const nonHopperProvider = (operations: string[]): AnalysisProvider => {
|
||||
const provider: AnalysisProvider = {
|
||||
identity: () => ({ id: "fixture", name: "Fixture", version: "1" }),
|
||||
@@ -96,7 +86,7 @@ const nonHopperProvider = (operations: string[]): AnalysisProvider => {
|
||||
|
||||
describe("binary session", () => {
|
||||
it("runs through a non-Hopper analysis provider", async () => {
|
||||
const [first] = await targets();
|
||||
const [first] = await createBinarySessionTargets();
|
||||
const operations: string[] = [];
|
||||
const provider = nonHopperProvider(operations);
|
||||
const session = createTestBinarySession(provider);
|
||||
|
||||
+7
-86
@@ -1,94 +1,15 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import type {
|
||||
AnalysisProvider,
|
||||
CapabilityDescriptor,
|
||||
} from "../../../src/application/AnalysisProvider.js";
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js";
|
||||
import { ok as resultOk } from "../../../src/domain/result.js";
|
||||
import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
|
||||
const cacheProvider = (
|
||||
calls: string[],
|
||||
mayWriteFilesystem = false,
|
||||
): AnalysisProvider => {
|
||||
const identity = {
|
||||
id: "fixture",
|
||||
name: "Fixture analysis provider",
|
||||
version: "1",
|
||||
} as const;
|
||||
return {
|
||||
identity: () => identity,
|
||||
resolveAnalysisProfile: () =>
|
||||
Promise.resolve(
|
||||
resultOk({
|
||||
profile: createAnalysisProfile(identity, 1, { fixture: true }),
|
||||
compatibility: {},
|
||||
}),
|
||||
),
|
||||
capabilities: () => [
|
||||
cacheCapability(identity, "address_name", false, mayWriteFilesystem),
|
||||
cacheCapability(identity, "set_address_name", true),
|
||||
],
|
||||
createClient: () => ({
|
||||
execute: (operation) => {
|
||||
calls.push(operation);
|
||||
return Promise.resolve(ok(operation));
|
||||
},
|
||||
close: () => Promise.resolve(),
|
||||
}),
|
||||
};
|
||||
};
|
||||
|
||||
const cacheCapability = (
|
||||
provider: CapabilityDescriptor["provider"],
|
||||
operation: "address_name" | "set_address_name",
|
||||
mutatesArtifact: boolean,
|
||||
mayWriteFilesystem = false,
|
||||
): CapabilityDescriptor => ({
|
||||
provider,
|
||||
operation,
|
||||
inputContractVersion: 1,
|
||||
outputContractVersion: 1,
|
||||
available: true,
|
||||
reason: null,
|
||||
pagination: "none",
|
||||
exhaustive: true,
|
||||
effects: {
|
||||
mutatesArtifact,
|
||||
launchesProcess: false,
|
||||
mayShowUi: false,
|
||||
mayAccessNetwork: false,
|
||||
mayWriteFilesystem,
|
||||
changesPermissions: false,
|
||||
requiresRoot: false,
|
||||
},
|
||||
limits: {
|
||||
maxResults: null,
|
||||
maxPayloadBytes: null,
|
||||
timeoutMs: null,
|
||||
},
|
||||
limitations: [],
|
||||
});
|
||||
|
||||
const targets = async (): Promise<readonly [string, string]> => {
|
||||
const directory = await createTestTempDirectory("bb-session-");
|
||||
const first = join(directory, "first.hop");
|
||||
const second = join(directory, "second.hop");
|
||||
await writeFile(first, "one");
|
||||
await writeFile(second, "two");
|
||||
return [first, second];
|
||||
};
|
||||
import {
|
||||
createBinarySessionTargets,
|
||||
createCacheProvider,
|
||||
createTestBinarySession,
|
||||
} from "../../fixtures/binarySession.js";
|
||||
|
||||
describe("binary session", () => {
|
||||
it("allocates one fresh run identity per provider client lifetime", async () => {
|
||||
const [first, second] = await targets();
|
||||
const provider = cacheProvider([]);
|
||||
const [first, second] = await createBinarySessionTargets();
|
||||
const provider = createCacheProvider([]);
|
||||
const createClient = provider.createClient.bind(provider);
|
||||
const runIds: string[] = [];
|
||||
provider.createClient = (target, profile, context) => {
|
||||
|
||||
+12
-89
@@ -1,95 +1,18 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import type {
|
||||
AnalysisProvider,
|
||||
CapabilityDescriptor,
|
||||
} from "../../../src/application/AnalysisProvider.js";
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import {
|
||||
createBinarySessionTargets,
|
||||
createCacheProvider,
|
||||
createTestBinarySession,
|
||||
} from "../../fixtures/binarySession.js";
|
||||
import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js";
|
||||
import { ok as resultOk } from "../../../src/domain/result.js";
|
||||
import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
|
||||
const cacheProvider = (
|
||||
calls: string[],
|
||||
mayWriteFilesystem = false,
|
||||
): AnalysisProvider => {
|
||||
const identity = {
|
||||
id: "fixture",
|
||||
name: "Fixture analysis provider",
|
||||
version: "1",
|
||||
} as const;
|
||||
return {
|
||||
identity: () => identity,
|
||||
resolveAnalysisProfile: () =>
|
||||
Promise.resolve(
|
||||
resultOk({
|
||||
profile: createAnalysisProfile(identity, 1, { fixture: true }),
|
||||
compatibility: {},
|
||||
}),
|
||||
),
|
||||
capabilities: () => [
|
||||
cacheCapability(identity, "address_name", false, mayWriteFilesystem),
|
||||
cacheCapability(identity, "set_address_name", true),
|
||||
],
|
||||
createClient: () => ({
|
||||
execute: (operation) => {
|
||||
calls.push(operation);
|
||||
return Promise.resolve(ok(operation));
|
||||
},
|
||||
close: () => Promise.resolve(),
|
||||
}),
|
||||
};
|
||||
};
|
||||
|
||||
const cacheCapability = (
|
||||
provider: CapabilityDescriptor["provider"],
|
||||
operation: "address_name" | "set_address_name",
|
||||
mutatesArtifact: boolean,
|
||||
mayWriteFilesystem = false,
|
||||
): CapabilityDescriptor => ({
|
||||
provider,
|
||||
operation,
|
||||
inputContractVersion: 1,
|
||||
outputContractVersion: 1,
|
||||
available: true,
|
||||
reason: null,
|
||||
pagination: "none",
|
||||
exhaustive: true,
|
||||
effects: {
|
||||
mutatesArtifact,
|
||||
launchesProcess: false,
|
||||
mayShowUi: false,
|
||||
mayAccessNetwork: false,
|
||||
mayWriteFilesystem,
|
||||
changesPermissions: false,
|
||||
requiresRoot: false,
|
||||
},
|
||||
limits: {
|
||||
maxResults: null,
|
||||
maxPayloadBytes: null,
|
||||
timeoutMs: null,
|
||||
},
|
||||
limitations: [],
|
||||
});
|
||||
|
||||
const targets = async (): Promise<readonly [string, string]> => {
|
||||
const directory = await createTestTempDirectory("bb-session-");
|
||||
const first = join(directory, "first.hop");
|
||||
const second = join(directory, "second.hop");
|
||||
await writeFile(first, "one");
|
||||
await writeFile(second, "two");
|
||||
return [first, second];
|
||||
};
|
||||
|
||||
describe("binary session", () => {
|
||||
it("replays exact immutable calls from a matching provider-neutral snapshot", async () => {
|
||||
const [first, second] = await targets();
|
||||
const [first, second] = await createBinarySessionTargets();
|
||||
const initialCalls: string[] = [];
|
||||
const initial = createTestBinarySession(cacheProvider(initialCalls));
|
||||
const initial = createTestBinarySession(createCacheProvider(initialCalls));
|
||||
expect((await initial.open(first)).ok).toBe(true);
|
||||
expect(
|
||||
(
|
||||
@@ -106,7 +29,7 @@ describe("binary session", () => {
|
||||
await initial.close();
|
||||
|
||||
const replayCalls: string[] = [];
|
||||
const replay = createTestBinarySession(cacheProvider(replayCalls));
|
||||
const replay = createTestBinarySession(createCacheProvider(replayCalls));
|
||||
expect(replay.importAnalysisSnapshot(snapshot.value)).toEqual({
|
||||
ok: true,
|
||||
value: 1,
|
||||
@@ -147,7 +70,7 @@ describe("binary session", () => {
|
||||
});
|
||||
await replay.close();
|
||||
|
||||
const mismatch = createTestBinarySession(cacheProvider([]));
|
||||
const mismatch = createTestBinarySession(createCacheProvider([]));
|
||||
expect(mismatch.importAnalysisSnapshot(snapshot.value).ok).toBe(true);
|
||||
const opened = await mismatch.open(second);
|
||||
expect(opened.ok).toBe(false);
|
||||
@@ -155,7 +78,7 @@ describe("binary session", () => {
|
||||
await mismatch.close();
|
||||
|
||||
const profileMismatchCalls: string[] = [];
|
||||
const profileMismatchProvider = cacheProvider(profileMismatchCalls);
|
||||
const profileMismatchProvider = createCacheProvider(profileMismatchCalls);
|
||||
const identity = profileMismatchProvider.identity();
|
||||
profileMismatchProvider.resolveAnalysisProfile = () =>
|
||||
Promise.resolve(
|
||||
@@ -199,9 +122,9 @@ describe("binary session", () => {
|
||||
});
|
||||
|
||||
it("does not snapshot reads that depend on the provider cursor", async () => {
|
||||
const [first] = await targets();
|
||||
const [first] = await createBinarySessionTargets();
|
||||
const calls: string[] = [];
|
||||
const session = createTestBinarySession(cacheProvider(calls));
|
||||
const session = createTestBinarySession(createCacheProvider(calls));
|
||||
expect((await session.open(first)).ok).toBe(true);
|
||||
expect((await session.execute("address_name", {})).ok).toBe(true);
|
||||
expect((await session.execute("address_name", {})).ok).toBe(true);
|
||||
|
||||
+12
-89
@@ -1,95 +1,18 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import type {
|
||||
AnalysisProvider,
|
||||
CapabilityDescriptor,
|
||||
} from "../../../src/application/AnalysisProvider.js";
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js";
|
||||
import { ProviderAdapterError } from "../../../src/domain/errors.js";
|
||||
import { err, ok as resultOk } from "../../../src/domain/result.js";
|
||||
import { err } from "../../../src/domain/result.js";
|
||||
import {
|
||||
createBinarySessionTargets,
|
||||
createCacheProvider,
|
||||
createTestBinarySession,
|
||||
} from "../../fixtures/binarySession.js";
|
||||
import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
|
||||
const cacheProvider = (
|
||||
calls: string[],
|
||||
mayWriteFilesystem = false,
|
||||
): AnalysisProvider => {
|
||||
const identity = {
|
||||
id: "fixture",
|
||||
name: "Fixture analysis provider",
|
||||
version: "1",
|
||||
} as const;
|
||||
return {
|
||||
identity: () => identity,
|
||||
resolveAnalysisProfile: () =>
|
||||
Promise.resolve(
|
||||
resultOk({
|
||||
profile: createAnalysisProfile(identity, 1, { fixture: true }),
|
||||
compatibility: {},
|
||||
}),
|
||||
),
|
||||
capabilities: () => [
|
||||
cacheCapability(identity, "address_name", false, mayWriteFilesystem),
|
||||
cacheCapability(identity, "set_address_name", true),
|
||||
],
|
||||
createClient: () => ({
|
||||
execute: (operation) => {
|
||||
calls.push(operation);
|
||||
return Promise.resolve(ok(operation));
|
||||
},
|
||||
close: () => Promise.resolve(),
|
||||
}),
|
||||
};
|
||||
};
|
||||
|
||||
const cacheCapability = (
|
||||
provider: CapabilityDescriptor["provider"],
|
||||
operation: "address_name" | "set_address_name",
|
||||
mutatesArtifact: boolean,
|
||||
mayWriteFilesystem = false,
|
||||
): CapabilityDescriptor => ({
|
||||
provider,
|
||||
operation,
|
||||
inputContractVersion: 1,
|
||||
outputContractVersion: 1,
|
||||
available: true,
|
||||
reason: null,
|
||||
pagination: "none",
|
||||
exhaustive: true,
|
||||
effects: {
|
||||
mutatesArtifact,
|
||||
launchesProcess: false,
|
||||
mayShowUi: false,
|
||||
mayAccessNetwork: false,
|
||||
mayWriteFilesystem,
|
||||
changesPermissions: false,
|
||||
requiresRoot: false,
|
||||
},
|
||||
limits: {
|
||||
maxResults: null,
|
||||
maxPayloadBytes: null,
|
||||
timeoutMs: null,
|
||||
},
|
||||
limitations: [],
|
||||
});
|
||||
|
||||
const targets = async (): Promise<readonly [string, string]> => {
|
||||
const directory = await createTestTempDirectory("bb-session-");
|
||||
const first = join(directory, "first.hop");
|
||||
const second = join(directory, "second.hop");
|
||||
await writeFile(first, "one");
|
||||
await writeFile(second, "two");
|
||||
return [first, second];
|
||||
};
|
||||
|
||||
describe("binary session", () => {
|
||||
it("publishes provider-health availability changes and resets on target switch", async () => {
|
||||
const [first, second] = await targets();
|
||||
const provider = cacheProvider([]);
|
||||
const [first, second] = await createBinarySessionTargets();
|
||||
const provider = createCacheProvider([]);
|
||||
provider.createClient = () => ({
|
||||
execute: (operation) =>
|
||||
Promise.resolve(
|
||||
@@ -130,8 +53,8 @@ describe("binary session", () => {
|
||||
});
|
||||
|
||||
it("isolates availability observers from execution results and session state", async () => {
|
||||
const [first] = await targets();
|
||||
const provider = cacheProvider([]);
|
||||
const [first] = await createBinarySessionTargets();
|
||||
const provider = createCacheProvider([]);
|
||||
let providerCalls = 0;
|
||||
provider.createClient = () => ({
|
||||
execute: (operation) => {
|
||||
@@ -179,9 +102,9 @@ describe("binary session", () => {
|
||||
});
|
||||
|
||||
it("does not replay operations with filesystem side effects", async () => {
|
||||
const [first] = await targets();
|
||||
const [first] = await createBinarySessionTargets();
|
||||
const calls: string[] = [];
|
||||
const session = createTestBinarySession(cacheProvider(calls, true));
|
||||
const session = createTestBinarySession(createCacheProvider(calls, true));
|
||||
expect((await session.open(first)).ok).toBe(true);
|
||||
const input = { address: "0x1000", document: "first" };
|
||||
expect((await session.execute("address_name", input)).ok).toBe(true);
|
||||
|
||||
+10
-43
@@ -1,14 +1,14 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import type {
|
||||
AnalysisClient,
|
||||
AnalysisProvider,
|
||||
} from "../../../src/application/AnalysisProvider.js";
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import {
|
||||
ControllableAnalysisClient,
|
||||
createBinarySessionTargets,
|
||||
createTestBinarySession,
|
||||
} from "../../fixtures/binarySession.js";
|
||||
import { HopperStartError } from "../../../src/domain/errors.js";
|
||||
import { err } from "../../../src/domain/result.js";
|
||||
import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
@@ -18,38 +18,9 @@ const client = (fail = false): AnalysisClient => ({
|
||||
close: () => Promise.resolve(),
|
||||
});
|
||||
|
||||
class TestClient implements AnalysisClient {
|
||||
closed = 0;
|
||||
constructor(
|
||||
readonly pendingHealth?: Promise<ReturnType<typeof ok>>,
|
||||
readonly failHealth = false,
|
||||
readonly pendingCall?: Promise<ReturnType<typeof ok>>,
|
||||
) {}
|
||||
execute(name: string) {
|
||||
if (name === "health")
|
||||
return this.failHealth
|
||||
? Promise.resolve(err(new HopperStartError()))
|
||||
: (this.pendingHealth ?? Promise.resolve(ok(null)));
|
||||
return this.pendingCall ?? Promise.resolve(ok(null));
|
||||
}
|
||||
close(): Promise<void> {
|
||||
this.closed += 1;
|
||||
return Promise.resolve();
|
||||
}
|
||||
}
|
||||
|
||||
const targets = async (): Promise<readonly [string, string]> => {
|
||||
const directory = await createTestTempDirectory("bb-session-");
|
||||
const first = join(directory, "first.hop");
|
||||
const second = join(directory, "second.hop");
|
||||
await writeFile(first, "one");
|
||||
await writeFile(second, "two");
|
||||
return [first, second];
|
||||
};
|
||||
|
||||
describe("binary session", () => {
|
||||
it("returns typed unavailability without dispatching a partial provider", async () => {
|
||||
const [first] = await targets();
|
||||
const [first] = await createBinarySessionTargets();
|
||||
const operations: string[] = [];
|
||||
const provider: AnalysisProvider = {
|
||||
identity: () => ({ id: "partial", name: "Partial", version: "1" }),
|
||||
@@ -111,11 +82,7 @@ describe("binary session", () => {
|
||||
});
|
||||
|
||||
it("keeps the active client when a switch fails", async () => {
|
||||
const directory = await createTestTempDirectory("bb-session-");
|
||||
const first = join(directory, "first.hop");
|
||||
const second = join(directory, "second.hop");
|
||||
await writeFile(first, "one");
|
||||
await writeFile(second, "two");
|
||||
const [first, second] = await createBinarySessionTargets();
|
||||
let created = 0;
|
||||
const session = createTestBinarySession(() => client(created++ === 1));
|
||||
expect((await session.open(first)).ok).toBe(true);
|
||||
@@ -131,10 +98,10 @@ describe("binary session", () => {
|
||||
});
|
||||
|
||||
it("serializes concurrent opens and leaves the last target active", async () => {
|
||||
const [first, second] = await targets();
|
||||
const clients: TestClient[] = [];
|
||||
const [first, second] = await createBinarySessionTargets();
|
||||
const clients: ControllableAnalysisClient[] = [];
|
||||
const session = createTestBinarySession(() => {
|
||||
const value = new TestClient();
|
||||
const value = new ControllableAnalysisClient();
|
||||
clients.push(value);
|
||||
return value;
|
||||
});
|
||||
|
||||
+15
-56
@@ -4,57 +4,14 @@ import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import type { AnalysisClient } from "../../../src/application/AnalysisProvider.js";
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import { HopperStartError } from "../../../src/domain/errors.js";
|
||||
import { err } from "../../../src/domain/result.js";
|
||||
import {
|
||||
ControllableAnalysisClient,
|
||||
createBinarySessionTargets,
|
||||
createDeferred,
|
||||
createTestBinarySession,
|
||||
} from "../../fixtures/binarySession.js";
|
||||
import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
|
||||
class TestClient implements AnalysisClient {
|
||||
closed = 0;
|
||||
constructor(
|
||||
readonly pendingHealth?: Promise<ReturnType<typeof ok>>,
|
||||
readonly failHealth = false,
|
||||
readonly pendingCall?: Promise<ReturnType<typeof ok>>,
|
||||
) {}
|
||||
execute(name: string) {
|
||||
if (name === "health")
|
||||
return this.failHealth
|
||||
? Promise.resolve(err(new HopperStartError()))
|
||||
: (this.pendingHealth ?? Promise.resolve(ok(null)));
|
||||
return this.pendingCall ?? Promise.resolve(ok(null));
|
||||
}
|
||||
close(): Promise<void> {
|
||||
this.closed += 1;
|
||||
return Promise.resolve();
|
||||
}
|
||||
}
|
||||
|
||||
const targets = async (): Promise<readonly [string, string]> => {
|
||||
const directory = await createTestTempDirectory("bb-session-");
|
||||
const first = join(directory, "first.hop");
|
||||
const second = join(directory, "second.hop");
|
||||
await writeFile(first, "one");
|
||||
await writeFile(second, "two");
|
||||
return [first, second];
|
||||
};
|
||||
|
||||
const deferred = <T>(): {
|
||||
readonly promise: Promise<T>;
|
||||
resolve(value: T): void;
|
||||
} => {
|
||||
let resolvePromise: ((value: T) => void) | undefined;
|
||||
const promise = new Promise<T>((resolve) => {
|
||||
resolvePromise = resolve;
|
||||
});
|
||||
return {
|
||||
promise,
|
||||
resolve(value) {
|
||||
resolvePromise?.(value);
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
describe("binary session", () => {
|
||||
it("replaces the active client when a canonical path changes contents", async () => {
|
||||
const directory = await createTestTempDirectory("bb-session-");
|
||||
@@ -115,11 +72,11 @@ describe("binary session", () => {
|
||||
});
|
||||
|
||||
it("waits for an active call before closing its client during a switch", async () => {
|
||||
const [first, second] = await targets();
|
||||
const active = deferred<ReturnType<typeof ok>>();
|
||||
const clients: TestClient[] = [];
|
||||
const [first, second] = await createBinarySessionTargets();
|
||||
const active = createDeferred<ReturnType<typeof ok>>();
|
||||
const clients: ControllableAnalysisClient[] = [];
|
||||
const session = createTestBinarySession(() => {
|
||||
const value = new TestClient(
|
||||
const value = new ControllableAnalysisClient(
|
||||
undefined,
|
||||
false,
|
||||
clients.length === 0 ? active.promise : undefined,
|
||||
@@ -139,12 +96,14 @@ describe("binary session", () => {
|
||||
});
|
||||
|
||||
it("cancels an open queued behind another transition without creating a client", async () => {
|
||||
const [first, second] = await targets();
|
||||
const health = deferred<ReturnType<typeof ok>>();
|
||||
const [first, second] = await createBinarySessionTargets();
|
||||
const health = createDeferred<ReturnType<typeof ok>>();
|
||||
let created = 0;
|
||||
const session = createTestBinarySession(() => {
|
||||
created += 1;
|
||||
return new TestClient(created === 1 ? health.promise : undefined);
|
||||
return new ControllableAnalysisClient(
|
||||
created === 1 ? health.promise : undefined,
|
||||
);
|
||||
});
|
||||
const opening = session.open(first);
|
||||
const controller = new AbortController();
|
||||
|
||||
+22
-132
@@ -1,133 +1,20 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import type {
|
||||
AnalysisClient,
|
||||
AnalysisProvider,
|
||||
CapabilityDescriptor,
|
||||
} from "../../../src/application/AnalysisProvider.js";
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js";
|
||||
import { HopperStartError } from "../../../src/domain/errors.js";
|
||||
import {
|
||||
ControllableAnalysisClient,
|
||||
createBinarySessionTargets,
|
||||
createCacheProvider,
|
||||
createDeferred,
|
||||
createTestBinarySession,
|
||||
} from "../../fixtures/binarySession.js";
|
||||
import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js";
|
||||
import { err, ok as resultOk } from "../../../src/domain/result.js";
|
||||
import { err } from "../../../src/domain/result.js";
|
||||
import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
|
||||
const cacheProvider = (
|
||||
calls: string[],
|
||||
mayWriteFilesystem = false,
|
||||
): AnalysisProvider => {
|
||||
const identity = {
|
||||
id: "fixture",
|
||||
name: "Fixture analysis provider",
|
||||
version: "1",
|
||||
} as const;
|
||||
return {
|
||||
identity: () => identity,
|
||||
resolveAnalysisProfile: () =>
|
||||
Promise.resolve(
|
||||
resultOk({
|
||||
profile: createAnalysisProfile(identity, 1, { fixture: true }),
|
||||
compatibility: {},
|
||||
}),
|
||||
),
|
||||
capabilities: () => [
|
||||
cacheCapability(identity, "address_name", false, mayWriteFilesystem),
|
||||
cacheCapability(identity, "set_address_name", true),
|
||||
],
|
||||
createClient: () => ({
|
||||
execute: (operation) => {
|
||||
calls.push(operation);
|
||||
return Promise.resolve(ok(operation));
|
||||
},
|
||||
close: () => Promise.resolve(),
|
||||
}),
|
||||
};
|
||||
};
|
||||
|
||||
const cacheCapability = (
|
||||
provider: CapabilityDescriptor["provider"],
|
||||
operation: "address_name" | "set_address_name",
|
||||
mutatesArtifact: boolean,
|
||||
mayWriteFilesystem = false,
|
||||
): CapabilityDescriptor => ({
|
||||
provider,
|
||||
operation,
|
||||
inputContractVersion: 1,
|
||||
outputContractVersion: 1,
|
||||
available: true,
|
||||
reason: null,
|
||||
pagination: "none",
|
||||
exhaustive: true,
|
||||
effects: {
|
||||
mutatesArtifact,
|
||||
launchesProcess: false,
|
||||
mayShowUi: false,
|
||||
mayAccessNetwork: false,
|
||||
mayWriteFilesystem,
|
||||
changesPermissions: false,
|
||||
requiresRoot: false,
|
||||
},
|
||||
limits: {
|
||||
maxResults: null,
|
||||
maxPayloadBytes: null,
|
||||
timeoutMs: null,
|
||||
},
|
||||
limitations: [],
|
||||
});
|
||||
|
||||
class TestClient implements AnalysisClient {
|
||||
closed = 0;
|
||||
constructor(
|
||||
readonly pendingHealth?: Promise<ReturnType<typeof ok>>,
|
||||
readonly failHealth = false,
|
||||
readonly pendingCall?: Promise<ReturnType<typeof ok>>,
|
||||
) {}
|
||||
execute(name: string) {
|
||||
if (name === "health")
|
||||
return this.failHealth
|
||||
? Promise.resolve(err(new HopperStartError()))
|
||||
: (this.pendingHealth ?? Promise.resolve(ok(null)));
|
||||
return this.pendingCall ?? Promise.resolve(ok(null));
|
||||
}
|
||||
close(): Promise<void> {
|
||||
this.closed += 1;
|
||||
return Promise.resolve();
|
||||
}
|
||||
}
|
||||
|
||||
const targets = async (): Promise<readonly [string, string]> => {
|
||||
const directory = await createTestTempDirectory("bb-session-");
|
||||
const first = join(directory, "first.hop");
|
||||
const second = join(directory, "second.hop");
|
||||
await writeFile(first, "one");
|
||||
await writeFile(second, "two");
|
||||
return [first, second];
|
||||
};
|
||||
|
||||
const deferred = <T>(): {
|
||||
readonly promise: Promise<T>;
|
||||
resolve(value: T): void;
|
||||
} => {
|
||||
let resolvePromise: ((value: T) => void) | undefined;
|
||||
const promise = new Promise<T>((resolve) => {
|
||||
resolvePromise = resolve;
|
||||
});
|
||||
return {
|
||||
promise,
|
||||
resolve(value) {
|
||||
resolvePromise?.(value);
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
describe("binary session", () => {
|
||||
it("cancels legacy profile resolution even when the provider ignores its signal", async () => {
|
||||
const [first] = await targets();
|
||||
const provider = cacheProvider([]);
|
||||
const [first] = await createBinarySessionTargets();
|
||||
const provider = createCacheProvider([]);
|
||||
let observedSignal: AbortSignal | undefined;
|
||||
let created = 0;
|
||||
provider.resolveAnalysisProfile = (_target, options) => {
|
||||
@@ -136,7 +23,7 @@ describe("binary session", () => {
|
||||
};
|
||||
provider.createClient = () => {
|
||||
created += 1;
|
||||
return new TestClient();
|
||||
return new ControllableAnalysisClient();
|
||||
};
|
||||
const session = createTestBinarySession(provider);
|
||||
const controller = new AbortController();
|
||||
@@ -155,10 +42,10 @@ describe("binary session", () => {
|
||||
});
|
||||
|
||||
it("cancels a call while it waits for a transition", async () => {
|
||||
const [first] = await targets();
|
||||
const health = deferred<ReturnType<typeof ok>>();
|
||||
const [first] = await createBinarySessionTargets();
|
||||
const health = createDeferred<ReturnType<typeof ok>>();
|
||||
const session = createTestBinarySession(
|
||||
() => new TestClient(health.promise),
|
||||
() => new ControllableAnalysisClient(health.promise),
|
||||
);
|
||||
const opening = session.open(first);
|
||||
const controller = new AbortController();
|
||||
@@ -178,10 +65,13 @@ describe("binary session", () => {
|
||||
});
|
||||
|
||||
it("closes a failed candidate and reopens the previous target", async () => {
|
||||
const [first, second] = await targets();
|
||||
const clients: TestClient[] = [];
|
||||
const [first, second] = await createBinarySessionTargets();
|
||||
const clients: ControllableAnalysisClient[] = [];
|
||||
const session = createTestBinarySession(() => {
|
||||
const value = new TestClient(undefined, clients.length === 1);
|
||||
const value = new ControllableAnalysisClient(
|
||||
undefined,
|
||||
clients.length === 1,
|
||||
);
|
||||
clients.push(value);
|
||||
return value;
|
||||
});
|
||||
@@ -197,7 +87,7 @@ describe("binary session", () => {
|
||||
});
|
||||
|
||||
it("closes the active bridge before starting a replacement", async () => {
|
||||
const [first, second] = await targets();
|
||||
const [first, second] = await createBinarySessionTargets();
|
||||
let liveClients = 0;
|
||||
let overlapped = false;
|
||||
const session = createTestBinarySession(() => ({
|
||||
@@ -218,7 +108,7 @@ describe("binary session", () => {
|
||||
});
|
||||
|
||||
it("clears session state while preserving a typed provider cleanup failure", async () => {
|
||||
const [first] = await targets();
|
||||
const [first] = await createBinarySessionTargets();
|
||||
const cleanupError = new ProviderCleanupError(
|
||||
"fixture",
|
||||
["fixture-document"],
|
||||
|
||||
+5
-15
@@ -1,26 +1,16 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import {
|
||||
createBinarySessionTargets,
|
||||
createTestBinarySession,
|
||||
} from "../../fixtures/binarySession.js";
|
||||
import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js";
|
||||
import { err } from "../../../src/domain/result.js";
|
||||
import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
|
||||
const targets = async (): Promise<readonly [string, string]> => {
|
||||
const directory = await createTestTempDirectory("bb-session-");
|
||||
const first = join(directory, "first.hop");
|
||||
const second = join(directory, "second.hop");
|
||||
await writeFile(first, "one");
|
||||
await writeFile(second, "two");
|
||||
return [first, second];
|
||||
};
|
||||
|
||||
describe("binary session", () => {
|
||||
it("does not start a replacement after the active provider cleanup is unconfirmed", async () => {
|
||||
const [first, second] = await targets();
|
||||
const [first, second] = await createBinarySessionTargets();
|
||||
const cleanupError = new ProviderCleanupError(
|
||||
"fixture",
|
||||
["fixture-document"],
|
||||
|
||||
@@ -1,439 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisInputError,
|
||||
AnalysisOutputError,
|
||||
AnalysisProtocolError,
|
||||
AnalysisTimeoutError,
|
||||
ArtifactOperationError,
|
||||
BinaryTargetError,
|
||||
BrowserObservationError,
|
||||
ConfigurationError,
|
||||
EvidenceFileError,
|
||||
EvidenceIntegrityError,
|
||||
EvidenceLimitError,
|
||||
HopperCancelledError,
|
||||
HopperProcessError,
|
||||
HopperProtocolError,
|
||||
HopperRemoteError,
|
||||
HopperStartError,
|
||||
HopperTimeoutError,
|
||||
InvestigationWorkspaceError,
|
||||
NoBinaryOpenError,
|
||||
ProviderAdapterError,
|
||||
ProviderSelectionError,
|
||||
PermissionRequiredError,
|
||||
ReplayPlanStaleError,
|
||||
UnknownRegistryError,
|
||||
projectAnalysisError,
|
||||
type AnalysisError,
|
||||
type AnalysisErrorTag,
|
||||
} from "../../../src/domain/errors.js";
|
||||
import { ProcessCaptureError } from "../../../src/application/ProcessHarness.js";
|
||||
import {
|
||||
analysisErrorJsonSchema,
|
||||
analysisErrorProjectionSchema,
|
||||
} from "../../../src/contracts/errorSchemas.js";
|
||||
|
||||
const expectSecretsHidden = (serialized: string): void => {
|
||||
for (const hidden of [
|
||||
"secret-token",
|
||||
"AnalysisCapabilityUnavailableError",
|
||||
"declaredSha256",
|
||||
])
|
||||
expect(serialized).not.toContain(hidden);
|
||||
};
|
||||
|
||||
describe("analysis error projection: provider failures", () => {
|
||||
it("uses the correct provider-neutral protocol tag", () => {
|
||||
expect(new AnalysisProtocolError("invalid")._tag).toBe(
|
||||
"AnalysisProtocolError",
|
||||
);
|
||||
});
|
||||
|
||||
it("projects bounded provider diagnostics without dropping local coordinates", () => {
|
||||
const diagnostics = {
|
||||
runtime_root: "/tmp/rea-ghidra-fixture",
|
||||
profile_digest: "a".repeat(64),
|
||||
exit_code: 1,
|
||||
};
|
||||
const error = new ProviderAdapterError("ghidra", "health", {
|
||||
diagnostics,
|
||||
});
|
||||
|
||||
expect(error.diagnostics).not.toBe(diagnostics);
|
||||
expect(projectAnalysisError(error)).toMatchObject({
|
||||
details: {
|
||||
provider_id: "ghidra",
|
||||
operation: "health",
|
||||
diagnostics,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("projects stable, safe Linux startup failure codes", () => {
|
||||
const expected = [
|
||||
[70, "private_display_unavailable"],
|
||||
[71, "x11_authorization_failed"],
|
||||
[72, "unsupported_hopper_build"],
|
||||
[73, "invalid_launch_command"],
|
||||
[74, "process_ownership_mismatch"],
|
||||
[75, "hopper_exited_during_startup"],
|
||||
[76, "unsupported_demo_dialog"],
|
||||
[77, "unexpected_display_geometry"],
|
||||
[78, "x11_input_failed"],
|
||||
[79, "runtime_dependency_unavailable"],
|
||||
[80, "x11_socket_directory_unusable"],
|
||||
] as const;
|
||||
for (const [exitCode, code] of expected) {
|
||||
const projected = projectAnalysisError(new HopperProcessError(exitCode));
|
||||
expect(projected).toMatchObject({
|
||||
code: "provider_unavailable",
|
||||
details: { failure_code: code, exit_code: exitCode },
|
||||
});
|
||||
expect(projected.message.length).toBeGreaterThan(20);
|
||||
expect(JSON.stringify(projected)).not.toContain("/proc/");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("analysis error projection: typed failures", () => {
|
||||
it("projects every typed failure without secrets", () => {
|
||||
const secretCause = new Error("secret-token");
|
||||
const byTag = {
|
||||
AnalysisProtocolError: new AnalysisProtocolError("protocol failed"),
|
||||
AnalysisInputError: new AnalysisInputError("overview", {
|
||||
cause: secretCause,
|
||||
}),
|
||||
AnalysisOutputError: new AnalysisOutputError(
|
||||
"overview",
|
||||
"invalid shape",
|
||||
{
|
||||
cause: secretCause,
|
||||
},
|
||||
),
|
||||
AnalysisCapabilityUnavailableError:
|
||||
new AnalysisCapabilityUnavailableError("fixture", "overview", "absent"),
|
||||
AnalysisCancelledError: new AnalysisCancelledError("overview"),
|
||||
AnalysisTimeoutError: new AnalysisTimeoutError("overview", 50),
|
||||
ProviderSelectionError: new ProviderSelectionError("overview"),
|
||||
ProviderAdapterError: new ProviderAdapterError("fixture", "overview", {
|
||||
cause: secretCause,
|
||||
}),
|
||||
BrowserObservationError: new BrowserObservationError(
|
||||
"inspect_web_page",
|
||||
"endpoint_unreachable",
|
||||
{ cause: secretCause },
|
||||
),
|
||||
ArtifactOperationError: new ArtifactOperationError(
|
||||
"inventory_artifact",
|
||||
"integrity",
|
||||
),
|
||||
ProcessCaptureError: new ProcessCaptureError("capture failed", {
|
||||
cause: secretCause,
|
||||
}),
|
||||
EvidenceIntegrityError: new EvidenceIntegrityError("integrity failed", {
|
||||
cause: secretCause,
|
||||
}),
|
||||
EvidenceLimitError: new EvidenceLimitError("records", 10),
|
||||
EvidenceFileError: new EvidenceFileError("read", "outside-root", {
|
||||
cause: secretCause,
|
||||
}),
|
||||
InvestigationWorkspaceError: new InvestigationWorkspaceError(
|
||||
"update",
|
||||
"revision-conflict",
|
||||
{ cause: secretCause },
|
||||
),
|
||||
UnknownRegistryError: new UnknownRegistryError("revision-conflict", {
|
||||
cause: secretCause,
|
||||
}),
|
||||
HopperTimeoutError: new HopperTimeoutError(100),
|
||||
HopperCancelledError: new HopperCancelledError(),
|
||||
HopperProtocolError: new HopperProtocolError("wire failed", {
|
||||
cause: secretCause,
|
||||
}),
|
||||
HopperRemoteError: new HopperRemoteError(7, "safe"),
|
||||
HopperProcessError: new HopperProcessError(1),
|
||||
HopperStartError: new HopperStartError({ cause: secretCause }),
|
||||
ConfigurationError: new ConfigurationError("configuration failed", {
|
||||
cause: secretCause,
|
||||
}),
|
||||
NoBinaryOpenError: new NoBinaryOpenError(),
|
||||
BinaryTargetError: new BinaryTargetError(
|
||||
"/secret/local/path",
|
||||
"invalid",
|
||||
{
|
||||
cause: secretCause,
|
||||
},
|
||||
),
|
||||
PermissionRequiredError: new PermissionRequiredError({
|
||||
requested: {
|
||||
capability: "evidence_read",
|
||||
roots: ["/workspace/evidence.json"],
|
||||
executables: [],
|
||||
environment_names: ["TOKEN_NAME"],
|
||||
network: "none",
|
||||
mount: false,
|
||||
operation_identity: "read:evidence",
|
||||
},
|
||||
missing: { environment_names: ["TOKEN_NAME"] },
|
||||
ceiling: null,
|
||||
remediation: "restart",
|
||||
}),
|
||||
ReplayPlanStaleError: new ReplayPlanStaleError(
|
||||
"a".repeat(64),
|
||||
"b".repeat(64),
|
||||
),
|
||||
} satisfies Readonly<Record<AnalysisErrorTag, AnalysisError>>;
|
||||
const errors = Object.values(byTag);
|
||||
const projected = errors.map(projectAnalysisError);
|
||||
expect(projected).toHaveLength(27);
|
||||
const serialized = JSON.stringify(projected);
|
||||
expectSecretsHidden(serialized);
|
||||
expect(serialized).toContain("/secret/local/path");
|
||||
expect(serialized).toContain('"environment_names":["TOKEN_NAME"]');
|
||||
expect(
|
||||
projectAnalysisError(byTag.AnalysisCapabilityUnavailableError),
|
||||
).toMatchObject({
|
||||
category: "unsupported_provider",
|
||||
});
|
||||
expect(
|
||||
projectAnalysisError(
|
||||
new ArtifactOperationError("inventory_artifact", "integrity", {
|
||||
logicalPath: "main.js",
|
||||
declaredSha256: "a".repeat(64),
|
||||
calculatedSha256: "b".repeat(64),
|
||||
unpacked: true,
|
||||
}),
|
||||
),
|
||||
).toMatchObject({
|
||||
category: "integrity_mismatch",
|
||||
details: {
|
||||
logical_path: "main.js",
|
||||
declared_sha256: "a".repeat(64),
|
||||
calculated_sha256: "b".repeat(64),
|
||||
unpacked: true,
|
||||
},
|
||||
});
|
||||
expect(projected.every(({ message }) => message.length > 0)).toBe(true);
|
||||
expect(
|
||||
projected.every(
|
||||
(value) => analysisErrorProjectionSchema.safeParse(value).success,
|
||||
),
|
||||
).toBe(true);
|
||||
expect(analysisErrorJsonSchema).toMatchObject({ oneOf: expect.any(Array) });
|
||||
expect(
|
||||
projectAnalysisError(
|
||||
new ProcessCaptureError("terminal cleanup failed", {
|
||||
reason: "cleanup_incomplete",
|
||||
cleanupResources: ["process_group"],
|
||||
}),
|
||||
),
|
||||
).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: { cleanup: "incomplete", resources: ["process_group"] },
|
||||
});
|
||||
expect(
|
||||
projected
|
||||
.map(({ message }) => message)
|
||||
.filter(
|
||||
(message) =>
|
||||
!/try again|run `rea doctor`|current target|when ready|smaller request|smaller artifact|fresh copy|re-import|reduce|inline evidence|configured evidence directory|evidence file|allow overwrite|refresh the current state|reported setting|call open_binary|supported file|review capture policy|review the requested scope/iu.test(
|
||||
message,
|
||||
),
|
||||
),
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("analysis error projection: remediation", () => {
|
||||
it.each([
|
||||
[
|
||||
"configure",
|
||||
false,
|
||||
false,
|
||||
"Add the exact missing scope beneath the administrator ceiling, then retry.",
|
||||
],
|
||||
[
|
||||
"elicit",
|
||||
false,
|
||||
true,
|
||||
"Approve the exact missing scope, then retry the operation.",
|
||||
],
|
||||
[
|
||||
"restart",
|
||||
true,
|
||||
false,
|
||||
"Add the exact missing scope to the administrator configuration, then restart the registered MCP server or client.",
|
||||
],
|
||||
] as const)(
|
||||
"projects %s permission remediation into the stable protocol fields",
|
||||
(remediation, restartRequired, elicitationSupported, action) => {
|
||||
const projected = projectAnalysisError(
|
||||
new PermissionRequiredError({
|
||||
requested: {
|
||||
capability: "evidence_read",
|
||||
roots: ["/workspace/evidence.json"],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
network: "none",
|
||||
mount: false,
|
||||
operation_identity: "read:evidence",
|
||||
},
|
||||
missing: { roots: ["/workspace/evidence.json"] },
|
||||
ceiling: null,
|
||||
remediation,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(projected.remediation).toEqual({
|
||||
action,
|
||||
restart_required: restartRequired,
|
||||
elicitation_supported: elicitationSupported,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("gives missing residual unknowns a lookup-specific remediation", () => {
|
||||
expect(
|
||||
projectAnalysisError(new UnknownRegistryError("not-found")),
|
||||
).toMatchObject({
|
||||
code: "execution_failure",
|
||||
message:
|
||||
"The requested residual unknown does not exist in this session. Check the unknown_id and try again.",
|
||||
remediation: {
|
||||
action:
|
||||
"Check that the unknown_id belongs to this session, then retry.",
|
||||
},
|
||||
details: { reason: "not-found" },
|
||||
});
|
||||
});
|
||||
|
||||
it("retains custom input guidance in the projected error details", () => {
|
||||
expect(
|
||||
projectAnalysisError(
|
||||
new AnalysisInputError("find_changed_behavior", undefined, [
|
||||
{
|
||||
path: [],
|
||||
reason: "invalid_value",
|
||||
message:
|
||||
"Supply either existing comparisons or one investigation_run",
|
||||
},
|
||||
]),
|
||||
),
|
||||
).toMatchObject({
|
||||
details: {
|
||||
issues: [
|
||||
{
|
||||
path: [],
|
||||
reason: "invalid_value",
|
||||
message:
|
||||
"Supply either existing comparisons or one investigation_run",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("distinguishes disabled integrity continuation from format support", () => {
|
||||
expect(
|
||||
projectAnalysisError(
|
||||
new ArtifactOperationError("inventory_artifact", "policy"),
|
||||
),
|
||||
).toMatchObject({
|
||||
code: "artifact_operation_failed",
|
||||
category: "unavailable",
|
||||
message: expect.stringContaining(
|
||||
"REA_ARTIFACT_INTEGRITY_CONTINUE_ENABLED=true",
|
||||
),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("analysis error projection: contract variants", () => {
|
||||
it("validates every closed error-reason variant against the generated contract", () => {
|
||||
const variants: AnalysisError[] = [
|
||||
...(
|
||||
[
|
||||
"cancelled",
|
||||
"format",
|
||||
"integrity",
|
||||
"limit",
|
||||
"path",
|
||||
"policy",
|
||||
"unavailable",
|
||||
"io",
|
||||
] as const
|
||||
).map(
|
||||
(reason) => new ArtifactOperationError("inventory_artifact", reason),
|
||||
),
|
||||
...(
|
||||
[
|
||||
"disabled",
|
||||
"outside-root",
|
||||
"not-file",
|
||||
"too-large",
|
||||
"exists",
|
||||
"invalid-json",
|
||||
"io",
|
||||
] as const
|
||||
).map((reason) => new EvidenceFileError("read", reason)),
|
||||
...(
|
||||
[
|
||||
"disabled",
|
||||
"outside-root",
|
||||
"not-file",
|
||||
"too-large",
|
||||
"invalid-json",
|
||||
"integrity",
|
||||
"locked",
|
||||
"revision-conflict",
|
||||
"name-conflict",
|
||||
"io",
|
||||
] as const
|
||||
).map((reason) => new InvestigationWorkspaceError("update", reason)),
|
||||
...(
|
||||
[
|
||||
"not-found",
|
||||
"already-exists",
|
||||
"revision-conflict",
|
||||
"invalid-transition",
|
||||
"integrity",
|
||||
"limit",
|
||||
] as const
|
||||
).map((reason) => new UnknownRegistryError(reason)),
|
||||
...(
|
||||
[
|
||||
"capture_failed",
|
||||
"cleanup_incomplete",
|
||||
"permission_required",
|
||||
"cancelled",
|
||||
] as const
|
||||
).map(
|
||||
(reason) =>
|
||||
new ProcessCaptureError("SECRET capture diagnostic", { reason }),
|
||||
),
|
||||
...(
|
||||
[
|
||||
"remote",
|
||||
"authorization",
|
||||
"invalid_request",
|
||||
"bridge_exception",
|
||||
] as const
|
||||
).map((diagnostic) => new HopperRemoteError(9, "safe", diagnostic)),
|
||||
];
|
||||
|
||||
expect(variants).toHaveLength(39);
|
||||
for (const variant of variants) {
|
||||
const projected = projectAnalysisError(variant);
|
||||
const parsed = analysisErrorProjectionSchema.safeParse(projected);
|
||||
expect(parsed, JSON.stringify({ variant, projected })).toMatchObject({
|
||||
success: true,
|
||||
});
|
||||
expect(projected.code).toMatch(/^[a-z][a-z0-9_]*$/u);
|
||||
expect(JSON.stringify(projected)).not.toContain("SECRET");
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,111 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { parseConfig } from "../../../src/config.js";
|
||||
import type { BinaryTarget } from "../../../src/domain/binaryTarget.js";
|
||||
import { HopperProvider } from "../../../src/hopper/HopperProvider.js";
|
||||
import { silentLogger } from "../../../src/logger.js";
|
||||
|
||||
describe("Hopper provider discovery", () => {
|
||||
it("reports bounded launcher availability without starting Hopper", () => {
|
||||
const available = provider(process.execPath).inspectAvailability();
|
||||
expect(available).toEqual({
|
||||
status: "available",
|
||||
code: null,
|
||||
reason: null,
|
||||
diagnostics: {
|
||||
launcher_path: process.execPath,
|
||||
platform: process.platform,
|
||||
},
|
||||
});
|
||||
|
||||
const missingPath = "/missing/rea-hopper-launcher";
|
||||
expect(provider(missingPath).inspectAvailability()).toEqual({
|
||||
status: "unavailable",
|
||||
code: "executable_missing",
|
||||
reason: `Hopper launcher is missing or not executable: ${missingPath}`,
|
||||
diagnostics: {
|
||||
launcher_path: missingPath,
|
||||
platform: process.platform,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("separates target kind, format, and architecture support", () => {
|
||||
const hopper = provider(process.execPath);
|
||||
expect(hopper.inspectTargetSupport(databaseTarget())).toMatchObject({
|
||||
status: "supported",
|
||||
});
|
||||
expect(
|
||||
hopper.inspectTargetSupport(executableTarget("elf", "x86_64")),
|
||||
).toMatchObject({ status: "supported" });
|
||||
expect(hopper.inspectTargetSupport(artifactTarget())).toMatchObject({
|
||||
status: "unsupported",
|
||||
code: "target_kind_unsupported",
|
||||
diagnostics: { target_kind: "archive", target_format: "asar" },
|
||||
});
|
||||
});
|
||||
|
||||
it("advertises the exact bounded byte-read limit", () => {
|
||||
const capabilities = provider(process.execPath).capabilities();
|
||||
expect(
|
||||
capabilities.find(({ operation }) => operation === "read_bytes"),
|
||||
).toMatchObject({
|
||||
available: true,
|
||||
pagination: "none",
|
||||
limits: {
|
||||
maxResults: null,
|
||||
maxPayloadBytes: 4_096,
|
||||
timeoutMs: null,
|
||||
},
|
||||
});
|
||||
expect(
|
||||
capabilities.find(
|
||||
({ operation }) => operation === "address_to_file_offset",
|
||||
),
|
||||
).toMatchObject({ available: true, pagination: "none" });
|
||||
});
|
||||
});
|
||||
|
||||
const provider = (launcherPath: string): HopperProvider => {
|
||||
const config = parseConfig({ HOPPER_LAUNCHER_PATH: launcherPath });
|
||||
if (!config.ok) throw config.error;
|
||||
return new HopperProvider(config.value, silentLogger);
|
||||
};
|
||||
|
||||
const databaseTarget = (): BinaryTarget => ({
|
||||
path: "/tmp/fixture.hop",
|
||||
sha256: "a".repeat(64),
|
||||
kind: "database",
|
||||
format: "analysis-database",
|
||||
});
|
||||
|
||||
const executableTarget = (
|
||||
format: "mach-o" | "elf" | "pe",
|
||||
architecture: "x86" | "x86_64" | "arm" | "arm64",
|
||||
): BinaryTarget =>
|
||||
format === "pe"
|
||||
? {
|
||||
path: "/tmp/fixture",
|
||||
sha256: "b".repeat(64),
|
||||
kind: "executable",
|
||||
format,
|
||||
architecture,
|
||||
availableArchitectures: [architecture],
|
||||
executableRole: "application",
|
||||
managed: false,
|
||||
}
|
||||
: {
|
||||
path: "/tmp/fixture",
|
||||
sha256: "b".repeat(64),
|
||||
kind: "executable",
|
||||
format,
|
||||
architecture,
|
||||
availableArchitectures: [architecture],
|
||||
};
|
||||
|
||||
const artifactTarget = (): BinaryTarget => ({
|
||||
path: "/tmp/app.asar",
|
||||
sha256: "c".repeat(64),
|
||||
kind: "archive",
|
||||
format: "asar",
|
||||
});
|
||||
@@ -0,0 +1,304 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { projectManagedApplicationGraphEvidence } from "../../../src/application/ManagedApplicationGraphService.js";
|
||||
import { traceApplicationFeatureEvidence } from "../../../src/application/JavaScriptApplicationWorkflowService.js";
|
||||
import { MANAGED_STATIC_PROVIDER } from "../../../src/application/InvestigationProviders.js";
|
||||
import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { parseJavaScriptApplicationGraph } from "../../../src/domain/javascriptApplicationGraph.js";
|
||||
import { managedApplicationGraphResultSchema } from "../../../src/domain/managedApplicationGraph.js";
|
||||
import { inspectManagedArtifactBytes } from "../../../src/dotnet/ManagedArtifactInspector.js";
|
||||
import { inspectManagedMembersBytes } from "../../../src/dotnet/ManagedMemberInspector.js";
|
||||
import { inspectManagedNativeBoundariesBytes } from "../../../src/dotnet/ManagedNativeBoundaryInspector.js";
|
||||
import {
|
||||
buildManagedPeFixture,
|
||||
managedPeFixtureTarget,
|
||||
MANAGED_ARTIFACT_FIXTURE_LIMITS,
|
||||
MANAGED_MEMBER_FIXTURE_LIMITS,
|
||||
MANAGED_NATIVE_BOUNDARY_FIXTURE_LIMITS,
|
||||
} from "../../../src/dotnet/ManagedPe.fixture.js";
|
||||
|
||||
describe("managed application graph projection", () => {
|
||||
it("projects managed metadata and native declarations into authenticated graph Evidence", () => {
|
||||
const bytes = buildManagedPeFixture({
|
||||
pinvoke: {
|
||||
moduleName: "user32.dll",
|
||||
importName: "MessageBoxW",
|
||||
mappingFlags: 0x0345,
|
||||
},
|
||||
});
|
||||
const binary = managedPeFixtureTarget(bytes, "/fixture/ManagedInterop.exe");
|
||||
const managedArtifact = inspectManagedArtifactBytes(
|
||||
bytes,
|
||||
binary,
|
||||
MANAGED_ARTIFACT_FIXTURE_LIMITS,
|
||||
);
|
||||
const members = inspectManagedMembersBytes(
|
||||
bytes,
|
||||
binary,
|
||||
MANAGED_MEMBER_FIXTURE_LIMITS,
|
||||
);
|
||||
const boundaries = inspectManagedNativeBoundariesBytes(
|
||||
bytes,
|
||||
binary,
|
||||
MANAGED_NATIVE_BOUNDARY_FIXTURE_LIMITS,
|
||||
);
|
||||
const artifactEvidence = createEvidence(binary, MANAGED_STATIC_PROVIDER, {
|
||||
operation: "inspect_managed_artifact",
|
||||
parameters: {},
|
||||
result: managedArtifact,
|
||||
rawResult: null,
|
||||
limitations: managedArtifact.limitations,
|
||||
locations: [{ kind: "artifact-path", path: binary.path }],
|
||||
});
|
||||
const memberEvidence = createEvidence(binary, MANAGED_STATIC_PROVIDER, {
|
||||
operation: "inspect_managed_members",
|
||||
parameters: {},
|
||||
result: members,
|
||||
rawResult: null,
|
||||
limitations: members.limitations,
|
||||
locations: [{ kind: "artifact-path", path: binary.path }],
|
||||
});
|
||||
const boundaryEvidence = createEvidence(binary, MANAGED_STATIC_PROVIDER, {
|
||||
operation: "inspect_managed_native_boundaries",
|
||||
parameters: {},
|
||||
result: boundaries,
|
||||
rawResult: null,
|
||||
limitations: boundaries.limitations,
|
||||
locations: [{ kind: "artifact-path", path: binary.path }],
|
||||
});
|
||||
|
||||
const evidence = projectManagedApplicationGraphEvidence({
|
||||
managed_artifact: artifactEvidence,
|
||||
managed_members: memberEvidence,
|
||||
managed_native_boundaries: boundaryEvidence,
|
||||
limits: {
|
||||
max_types: 100,
|
||||
max_methods: 100,
|
||||
max_fields: 100,
|
||||
max_pinvoke_imports: 100,
|
||||
max_native_implementations: 100,
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
evidence.ok,
|
||||
evidence.ok
|
||||
? undefined
|
||||
: `${JSON.stringify(evidence.error)} cause=${String(evidence.error.cause)}`,
|
||||
).toBe(true);
|
||||
if (!evidence.ok) throw new Error("projection failed");
|
||||
const parsed = parseEvidence(evidence.value);
|
||||
expect(parsed).toMatchObject({
|
||||
operation: "project_managed_application_graph",
|
||||
predicate_type: "rea.managed-application-graph/v1",
|
||||
provider: { id: "rea-dotnet-workflows" },
|
||||
confidence: "inferred",
|
||||
authority: "analyst-inference",
|
||||
evidence_links: [
|
||||
artifactEvidence.evidence_id,
|
||||
memberEvidence.evidence_id,
|
||||
boundaryEvidence.evidence_id,
|
||||
],
|
||||
});
|
||||
const result = managedApplicationGraphResultSchema.parse(
|
||||
parsed.normalized_result,
|
||||
);
|
||||
const graph = parseJavaScriptApplicationGraph(result.graph);
|
||||
expect(result.summary).toMatchObject({
|
||||
assemblies: 1,
|
||||
modules: 1,
|
||||
types: 1,
|
||||
methods: 1,
|
||||
fields: 1,
|
||||
pinvoke_imports: 1,
|
||||
});
|
||||
expect(graph.nodes.map(({ kind }) => kind)).toEqual(
|
||||
expect.arrayContaining([
|
||||
"artifact",
|
||||
"managed-assembly",
|
||||
"managed-module",
|
||||
"managed-type",
|
||||
"managed-method",
|
||||
"managed-field",
|
||||
"managed-pinvoke-import",
|
||||
]),
|
||||
);
|
||||
const method = graph.nodes.find(
|
||||
({ kind, observations }) =>
|
||||
kind === "managed-method" &&
|
||||
observations[0]?.label === "Fixture.Program.Main",
|
||||
);
|
||||
expect(method).toBeDefined();
|
||||
expect(
|
||||
graph.edges.some(
|
||||
({ source_node_id, relation, target_node_id }) =>
|
||||
source_node_id === method?.node_id &&
|
||||
relation === "imports" &&
|
||||
graph.nodes.find(({ node_id: id }) => id === target_node_id)?.kind ===
|
||||
"managed-pinvoke-import",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
graph.nodes.flatMap(({ observations }) =>
|
||||
observations.map(({ evidence }) => evidence.authority),
|
||||
),
|
||||
).toContain("managed-static-analysis");
|
||||
|
||||
const trace = traceApplicationFeatureEvidence({
|
||||
application: parsed,
|
||||
native_observations: [],
|
||||
seed: {
|
||||
kind: "string",
|
||||
value: "MessageBoxW",
|
||||
match: "exact",
|
||||
case_sensitive: true,
|
||||
},
|
||||
direction: "incoming",
|
||||
limits: {
|
||||
max_seed_matches: 5,
|
||||
max_depth: 4,
|
||||
max_nodes: 50,
|
||||
max_edges: 100,
|
||||
max_paths: 10,
|
||||
},
|
||||
});
|
||||
expect(trace.ok).toBe(true);
|
||||
if (!trace.ok) throw new Error("trace failed");
|
||||
expect(trace.value.normalized_result).toMatchObject({
|
||||
source_evidence_id: parsed.evidence_id,
|
||||
summary: { matched_seeds: 1 },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("managed application graph coverage", () => {
|
||||
it("preserves source-page omissions in graph and per-fact coverage", () => {
|
||||
const bytes = buildManagedPeFixture();
|
||||
const binary = managedPeFixtureTarget(bytes, "/fixture/ManagedInterop.exe");
|
||||
const members = inspectManagedMembersBytes(
|
||||
bytes,
|
||||
binary,
|
||||
MANAGED_MEMBER_FIXTURE_LIMITS,
|
||||
);
|
||||
const partialMembers = {
|
||||
...members,
|
||||
methods: {
|
||||
...members.methods,
|
||||
total: 2,
|
||||
returned: 1,
|
||||
dropped: 1,
|
||||
complete: false,
|
||||
},
|
||||
};
|
||||
const memberEvidence = createEvidence(binary, MANAGED_STATIC_PROVIDER, {
|
||||
operation: "inspect_managed_members",
|
||||
parameters: {},
|
||||
result: partialMembers,
|
||||
rawResult: null,
|
||||
limitations: partialMembers.limitations,
|
||||
locations: [{ kind: "artifact-path", path: binary.path }],
|
||||
});
|
||||
|
||||
const evidence = projectManagedApplicationGraphEvidence({
|
||||
managed_members: memberEvidence,
|
||||
limits: {
|
||||
max_types: 100,
|
||||
max_methods: 100,
|
||||
max_fields: 100,
|
||||
max_pinvoke_imports: 100,
|
||||
max_native_implementations: 100,
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
evidence.ok,
|
||||
evidence.ok
|
||||
? undefined
|
||||
: `${JSON.stringify(evidence.error)} cause=${String(evidence.error.cause)}`,
|
||||
).toBe(true);
|
||||
if (!evidence.ok) throw new Error("projection failed");
|
||||
const result = managedApplicationGraphResultSchema.parse(
|
||||
parseEvidence(evidence.value).normalized_result,
|
||||
);
|
||||
const graph = parseJavaScriptApplicationGraph(result.graph);
|
||||
expect(result.coverage).toMatchObject({
|
||||
status: "truncated",
|
||||
omitted_types: 0,
|
||||
omitted_methods: 1,
|
||||
omitted_fields: 0,
|
||||
});
|
||||
expect(graph.coverage).toMatchObject({
|
||||
status: "partial",
|
||||
truncated: true,
|
||||
omitted_count: 1,
|
||||
});
|
||||
const method = graph.nodes.find(({ kind }) => kind === "managed-method");
|
||||
expect(method?.observations[0]?.evidence.coverage).toMatchObject({
|
||||
status: "partial",
|
||||
truncated: true,
|
||||
omitted_count: 1,
|
||||
});
|
||||
expect(
|
||||
graph.edges.find(
|
||||
({ target_node_id }) => target_node_id === method?.node_id,
|
||||
)?.evidence.coverage,
|
||||
).toMatchObject({
|
||||
status: "partial",
|
||||
truncated: true,
|
||||
omitted_count: 1,
|
||||
});
|
||||
|
||||
const parserPartialMembers = {
|
||||
...partialMembers,
|
||||
coverage: {
|
||||
state: "partial" as const,
|
||||
issues: [
|
||||
{
|
||||
code: "limit-exceeded" as const,
|
||||
scope: "method.0x06000001.body.instructions",
|
||||
offset: 0x0a00,
|
||||
detail: "instruction limit reached",
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
const parserPartialEvidence = createEvidence(
|
||||
binary,
|
||||
MANAGED_STATIC_PROVIDER,
|
||||
{
|
||||
operation: "inspect_managed_members",
|
||||
parameters: {},
|
||||
result: parserPartialMembers,
|
||||
rawResult: null,
|
||||
limitations: parserPartialMembers.limitations,
|
||||
},
|
||||
);
|
||||
const parserPartialProjection = projectManagedApplicationGraphEvidence({
|
||||
managed_members: parserPartialEvidence,
|
||||
limits: {
|
||||
max_types: 100,
|
||||
max_methods: 100,
|
||||
max_fields: 100,
|
||||
max_pinvoke_imports: 100,
|
||||
max_native_implementations: 100,
|
||||
},
|
||||
});
|
||||
|
||||
expect(parserPartialProjection.ok).toBe(true);
|
||||
if (!parserPartialProjection.ok)
|
||||
throw new Error("partial projection failed");
|
||||
const parserPartialResult = managedApplicationGraphResultSchema.parse(
|
||||
parseEvidence(parserPartialProjection.value).normalized_result,
|
||||
);
|
||||
expect(parserPartialResult.coverage).toMatchObject({
|
||||
status: "partial",
|
||||
omitted_methods: 1,
|
||||
});
|
||||
expect(parserPartialResult.graph.coverage).toEqual({
|
||||
status: "partial",
|
||||
truncated: false,
|
||||
omitted_count: null,
|
||||
limits: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -14,7 +14,7 @@ import { electronActiveObservationInputSchema } from "../../../src/domain/electr
|
||||
import { inspectElectronPageInputSchema } from "../../../src/domain/electronObservation.js";
|
||||
import { createWebTextArtifact } from "../../../src/domain/webContentArtifact.js";
|
||||
import { permissionAuthorityForRoot } from "../../fixtures/permissionAuthority.js";
|
||||
import { createElectronActiveObservationFixtureResult } from "../../fixtures/electronActiveObservationResult.js";
|
||||
import { createElectronActiveObservationFixtureResult } from "../../../src/domain/electronActiveObservation.fixture.js";
|
||||
|
||||
const SOURCE = `const worker = new Worker("./worker.js");\nexport const observed = worker;\n`;
|
||||
|
||||
|
||||
@@ -1,118 +0,0 @@
|
||||
import { chmod, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { writeAnalysisSnapshot } from "../../../src/application/AnalysisSnapshotFiles.js";
|
||||
import { runDirectAnalysis } from "../../../src/application/DirectAnalysis.js";
|
||||
import type { AnalysisSnapshot } from "../../../src/domain/analysisSnapshot.js";
|
||||
import {
|
||||
snapshotBinding,
|
||||
snapshotTarget,
|
||||
} from "../../../src/domain/analysisSnapshot.js";
|
||||
import { parseBinaryTarget } from "../../../src/domain/binaryTarget.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
|
||||
import { permissionAuthorityForRoot } from "../../fixtures/permissionAuthority.js";
|
||||
import {
|
||||
REA_WORKFLOW_PROVIDER,
|
||||
workflowAnalysisProfile,
|
||||
} from "../../../src/application/InvestigationProviders.js";
|
||||
import { HOPPER_PROVIDER_IDENTITY } from "../../../src/hopper/HopperProvider.js";
|
||||
import { resolveHopperAnalysisProfile } from "../../../src/hopper/HopperAnalysisProfile.js";
|
||||
|
||||
afterEach(async () => {
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
describe("direct analysis snapshot permissions", () => {
|
||||
it("forwards the CLI provider selector ahead of the environment preference", async () => {
|
||||
const directory = await createTestTempDirectory("rea-direct-provider-");
|
||||
const targetPath = join(directory, "fixture.hop");
|
||||
await writeFile(targetPath, "fixture");
|
||||
vi.stubEnv("HOPPER_LAUNCHER_PATH", process.execPath);
|
||||
vi.stubEnv("REA_ANALYSIS_PROVIDER", "environment-provider");
|
||||
|
||||
await expect(
|
||||
runDirectAnalysis(
|
||||
targetPath,
|
||||
"binary_overview",
|
||||
{},
|
||||
{
|
||||
providerId: "request-provider",
|
||||
},
|
||||
),
|
||||
).resolves.toMatchObject({
|
||||
error: "Analysis failed",
|
||||
code: "capability_unavailable",
|
||||
details: {
|
||||
selection_reason: "unknown_provider",
|
||||
requested_provider_id: "request-provider",
|
||||
candidate_ids: ["ghidra", "hopper"],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("replays a cache hit with snapshot read authority only", async () => {
|
||||
const directory = await createTestTempDirectory("rea-direct-snapshot-");
|
||||
const snapshotPath = join(directory, "analysis.json");
|
||||
const launcherPath = join(directory, "hopper-launcher");
|
||||
await writeFile(launcherPath, "fixture Hopper launcher");
|
||||
await chmod(launcherPath, 0o755);
|
||||
const target = await parseBinaryTarget(process.execPath);
|
||||
if (!target.ok) throw target.error;
|
||||
const resolved = await resolveHopperAnalysisProfile(target.value, {
|
||||
launcherPath,
|
||||
loaderArgsOverride: [],
|
||||
provider: HOPPER_PROVIDER_IDENTITY,
|
||||
});
|
||||
if (!resolved.ok || resolved.value.profile === null)
|
||||
throw new Error("fixture Hopper profile did not resolve");
|
||||
const profile = resolved.value.profile;
|
||||
const workflowProfile = workflowAnalysisProfile(profile);
|
||||
const evidence = createEvidence(target.value, REA_WORKFLOW_PROVIDER, {
|
||||
operation: "binary_overview",
|
||||
parameters: {},
|
||||
result: { cached: true },
|
||||
analysisProfile: workflowProfile,
|
||||
});
|
||||
const snapshot: AnalysisSnapshot = {
|
||||
snapshot_version: 2,
|
||||
target: snapshotTarget(target.value),
|
||||
binding: snapshotBinding(profile),
|
||||
entries: [],
|
||||
evidence_bundle: createEvidenceBundle([evidence]),
|
||||
};
|
||||
const policy = {
|
||||
roots: [directory],
|
||||
maxBytes: 1024 * 1024,
|
||||
maxDepth: 64,
|
||||
maxStringLength: 1024,
|
||||
maxNodes: 10_000,
|
||||
};
|
||||
expect(
|
||||
(await writeAnalysisSnapshot(snapshot, snapshotPath, false, policy)).ok,
|
||||
).toBe(true);
|
||||
const authority = await permissionAuthorityForRoot(
|
||||
directory,
|
||||
["snapshot_read", "snapshot_write"],
|
||||
["snapshot_read"],
|
||||
);
|
||||
vi.stubEnv("REA_ANALYSIS_SNAPSHOT_ROOTS_JSON", JSON.stringify([directory]));
|
||||
vi.stubEnv("HOPPER_LAUNCHER_PATH", launcherPath);
|
||||
|
||||
await expect(
|
||||
runDirectAnalysis(
|
||||
process.execPath,
|
||||
"binary_overview",
|
||||
{},
|
||||
{
|
||||
snapshotPath,
|
||||
permissionAuthority: authority,
|
||||
},
|
||||
),
|
||||
).resolves.toEqual(evidence);
|
||||
});
|
||||
});
|
||||
@@ -1,350 +0,0 @@
|
||||
import { mkdir, symlink, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import {
|
||||
canonicalizePermissionCeilings,
|
||||
canonicalizePermissionRequest,
|
||||
createPermissionAuthority,
|
||||
type PermissionAuthority,
|
||||
} from "../../../src/application/PermissionAuthority.js";
|
||||
import {
|
||||
createPermissionPolicy,
|
||||
evaluatePermission,
|
||||
type PermissionGrant,
|
||||
type PermissionScope,
|
||||
} from "../../../src/domain/permissionPolicy.js";
|
||||
|
||||
describe("permission authority", () => {
|
||||
it("distinguishes an elicitable grant from administrator reconfiguration", async () => {
|
||||
const sandbox = await createTestTempDirectory(
|
||||
"rea-permission-remediation-",
|
||||
);
|
||||
const allowedRoot = join(sandbox, "allowed");
|
||||
const outsideRoot = join(sandbox, "outside");
|
||||
await Promise.all([mkdir(allowedRoot), mkdir(outsideRoot)]);
|
||||
const authority = await createPermissionAuthority([
|
||||
evidenceScope(allowedRoot),
|
||||
]);
|
||||
expect(authority.ok).toBe(true);
|
||||
if (!authority.ok) return;
|
||||
|
||||
const inside = await authority.value.authorize(
|
||||
{
|
||||
...evidenceScope(allowedRoot),
|
||||
operation_identity: "read:inside-ceiling",
|
||||
},
|
||||
"read",
|
||||
{ remediation: "elicit" },
|
||||
);
|
||||
expect(inside).toMatchObject({
|
||||
ok: false,
|
||||
error: { remediation: "elicit" },
|
||||
});
|
||||
|
||||
const outside = await authority.value.createConnectionAuthority().authorize(
|
||||
{
|
||||
...evidenceScope(outsideRoot),
|
||||
operation_identity: "read:outside-ceiling",
|
||||
},
|
||||
"read",
|
||||
{ remediation: "elicit" },
|
||||
);
|
||||
expect(outside).toMatchObject({
|
||||
ok: false,
|
||||
error: { remediation: "restart" },
|
||||
});
|
||||
});
|
||||
|
||||
it("accepts canonical aliases but rejects a symlink escape", async () => {
|
||||
const sandbox = await createTestTempDirectory("rea-permission-");
|
||||
const root = join(sandbox, "root");
|
||||
const outside = join(sandbox, "outside");
|
||||
await Promise.all([mkdir(root), mkdir(outside)]);
|
||||
await writeFile(join(root, "inside"), "inside");
|
||||
await writeFile(join(outside, "secret"), "secret");
|
||||
await symlink(root, join(sandbox, "root-alias"));
|
||||
await symlink(join(outside, "secret"), join(root, "escape"));
|
||||
const ceiling = await canonicalizePermissionCeilings([
|
||||
{
|
||||
capability: "evidence_read",
|
||||
roots: [join(sandbox, "root-alias")],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
network: "none",
|
||||
mount: false,
|
||||
},
|
||||
]);
|
||||
expect(ceiling.ok).toBe(true);
|
||||
if (!ceiling.ok) return;
|
||||
const policy = createPermissionPolicy(ceiling.value, [
|
||||
{
|
||||
...ceiling.value[0]!,
|
||||
grant_id: "administrator:evidence-read",
|
||||
lifetime: "administrator",
|
||||
operation_identity: null,
|
||||
expires_at: null,
|
||||
},
|
||||
]);
|
||||
const inside = await canonicalizePermissionRequest(
|
||||
{
|
||||
capability: "evidence_read",
|
||||
roots: [join(root, "inside")],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
network: "none",
|
||||
mount: false,
|
||||
operation_identity: "read:inside",
|
||||
},
|
||||
"read",
|
||||
);
|
||||
const escaped = await canonicalizePermissionRequest(
|
||||
{
|
||||
capability: "evidence_read",
|
||||
roots: [join(root, "escape")],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
network: "none",
|
||||
mount: false,
|
||||
operation_identity: "read:escape",
|
||||
},
|
||||
"read",
|
||||
);
|
||||
expect(inside.ok).toBe(true);
|
||||
expect(escaped.ok).toBe(true);
|
||||
if (!inside.ok || !escaped.ok) return;
|
||||
expect(evaluatePermission(policy, inside.value)).toMatchObject({
|
||||
allowed: true,
|
||||
});
|
||||
expect(evaluatePermission(policy, escaped.value)).toMatchObject({
|
||||
allowed: false,
|
||||
reason: "outside_administrator_ceiling",
|
||||
});
|
||||
});
|
||||
|
||||
it("canonicalizes a new write through its existing parent", async () => {
|
||||
const sandbox = await createTestTempDirectory("rea-permission-write-");
|
||||
const result = await canonicalizePermissionRequest(
|
||||
{
|
||||
capability: "evidence_write",
|
||||
roots: [join(sandbox, "new.json")],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
network: "none",
|
||||
mount: false,
|
||||
operation_identity: "write:new.json",
|
||||
},
|
||||
"write",
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({ ok: true });
|
||||
if (result.ok)
|
||||
expect(result.value.roots).toEqual([join(sandbox, "new.json")]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("permission authority policy and connection lifecycle", () => {
|
||||
it("commits a configured policy only after every grant validates", async () => {
|
||||
const sandbox = await createTestTempDirectory("rea-permission-reload-");
|
||||
const oldRoot = join(sandbox, "old");
|
||||
const newRoot = join(sandbox, "new");
|
||||
const outsideRoot = join(sandbox, "outside");
|
||||
await Promise.all([mkdir(oldRoot), mkdir(newRoot), mkdir(outsideRoot)]);
|
||||
const oldScope = evidenceScope(oldRoot);
|
||||
const newScope = evidenceScope(newRoot);
|
||||
const authority = await createPermissionAuthority(
|
||||
[oldScope],
|
||||
[administratorGrant(oldScope)],
|
||||
);
|
||||
expect(authority.ok).toBe(true);
|
||||
if (!authority.ok) return;
|
||||
|
||||
const reloaded = await authority.value.replaceConfiguredPolicy({
|
||||
ceilings: [newScope],
|
||||
administratorGrants: [administratorGrant(newScope)],
|
||||
projectGrants: [
|
||||
{
|
||||
...evidenceScope(outsideRoot),
|
||||
grant_id: "project:outside-ceiling",
|
||||
lifetime: "project",
|
||||
operation_identity: null,
|
||||
expires_at: null,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(reloaded.ok).toBe(false);
|
||||
expect(await canRead(authority.value, oldRoot)).toBe(true);
|
||||
expect(await canRead(authority.value, newRoot)).toBe(false);
|
||||
|
||||
expect(
|
||||
await authority.value.replaceConfiguredPolicy({
|
||||
ceilings: [newScope],
|
||||
administratorGrants: [administratorGrant(newScope)],
|
||||
projectGrants: [],
|
||||
}),
|
||||
).toEqual({ ok: true, value: null });
|
||||
expect(await canRead(authority.value, oldRoot)).toBe(false);
|
||||
expect(await canRead(authority.value, newRoot)).toBe(true);
|
||||
});
|
||||
|
||||
it("isolates transient grants and consumption between live connections", async () => {
|
||||
const sandbox = await createTestTempDirectory("rea-permission-session-");
|
||||
const scope = evidenceScope(sandbox);
|
||||
const configured = await createPermissionAuthority([scope]);
|
||||
expect(configured.ok).toBe(true);
|
||||
if (!configured.ok) return;
|
||||
const connectionA = configured.value.createConnectionAuthority();
|
||||
const connectionB = configured.value.createConnectionAuthority();
|
||||
const request = {
|
||||
...scope,
|
||||
operation_identity: "read:connection-owned",
|
||||
};
|
||||
|
||||
expect(
|
||||
connectionA.grant({
|
||||
...request,
|
||||
grant_id: "session:a",
|
||||
lifetime: "session",
|
||||
operation_identity: null,
|
||||
expires_at: null,
|
||||
}),
|
||||
).toMatchObject({ ok: true });
|
||||
expect(await connectionA.authorize(request, "read")).toMatchObject({
|
||||
ok: true,
|
||||
});
|
||||
expect(await connectionB.authorize(request, "read")).toMatchObject({
|
||||
ok: false,
|
||||
});
|
||||
|
||||
connectionB.clearSessionGrants();
|
||||
expect(await connectionA.authorize(request, "read")).toMatchObject({
|
||||
ok: true,
|
||||
});
|
||||
|
||||
connectionA.clearSessionGrants();
|
||||
const onceRequest = {
|
||||
...request,
|
||||
operation_identity: "read:once-on-a",
|
||||
};
|
||||
expect(
|
||||
connectionA.grant({
|
||||
...onceRequest,
|
||||
grant_id: "once:a",
|
||||
lifetime: "once",
|
||||
expires_at: null,
|
||||
}),
|
||||
).toMatchObject({ ok: true });
|
||||
expect(
|
||||
connectionB.grant({
|
||||
...onceRequest,
|
||||
grant_id: "once:a",
|
||||
lifetime: "once",
|
||||
expires_at: null,
|
||||
}),
|
||||
).toMatchObject({ ok: true });
|
||||
const concurrent = await Promise.all([
|
||||
connectionA.authorize(onceRequest, "read"),
|
||||
connectionA.authorize(onceRequest, "read"),
|
||||
]);
|
||||
expect(concurrent.filter(({ ok }) => ok)).toHaveLength(1);
|
||||
expect(await connectionB.authorize(onceRequest, "read")).toMatchObject({
|
||||
ok: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("permission authority policy reload", () => {
|
||||
it("applies configured policy reloads to existing connections", async () => {
|
||||
const sandbox = await createTestTempDirectory(
|
||||
"rea-permission-live-reload-",
|
||||
);
|
||||
const allowedRoot = join(sandbox, "allowed");
|
||||
const replacementRoot = join(sandbox, "replacement");
|
||||
await Promise.all([mkdir(allowedRoot), mkdir(replacementRoot)]);
|
||||
const configured = await createPermissionAuthority([
|
||||
evidenceScope(allowedRoot),
|
||||
]);
|
||||
expect(configured.ok).toBe(true);
|
||||
if (!configured.ok) return;
|
||||
const connection = configured.value.createConnectionAuthority();
|
||||
expect(
|
||||
connection.grant({
|
||||
...evidenceScope(allowedRoot),
|
||||
grant_id: "session:before-reload",
|
||||
lifetime: "session",
|
||||
operation_identity: null,
|
||||
expires_at: null,
|
||||
}),
|
||||
).toMatchObject({ ok: true });
|
||||
expect(await canRead(connection, allowedRoot)).toBe(true);
|
||||
|
||||
const collisionRequest = {
|
||||
...evidenceScope(allowedRoot),
|
||||
operation_identity: "read:reload-collision",
|
||||
};
|
||||
expect(
|
||||
connection.grant({
|
||||
...collisionRequest,
|
||||
grant_id: "shared-id",
|
||||
lifetime: "once",
|
||||
expires_at: null,
|
||||
}),
|
||||
).toMatchObject({ ok: true });
|
||||
expect(await connection.authorize(collisionRequest, "read")).toMatchObject({
|
||||
ok: true,
|
||||
});
|
||||
expect(
|
||||
await configured.value.replaceAdministratorGrants([
|
||||
{
|
||||
...evidenceScope(allowedRoot),
|
||||
grant_id: "shared-id",
|
||||
lifetime: "administrator",
|
||||
operation_identity: null,
|
||||
expires_at: null,
|
||||
},
|
||||
]),
|
||||
).toEqual({ ok: true, value: null });
|
||||
expect(await connection.authorize(collisionRequest, "read")).toMatchObject({
|
||||
ok: true,
|
||||
});
|
||||
|
||||
expect(
|
||||
await configured.value.reload([evidenceScope(replacementRoot)]),
|
||||
).toEqual({ ok: true, value: null });
|
||||
expect(await canRead(connection, allowedRoot)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
const evidenceScope = (root: string): PermissionScope => ({
|
||||
capability: "evidence_read",
|
||||
roots: [root],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
network: "none",
|
||||
mount: false,
|
||||
});
|
||||
|
||||
const administratorGrant = (scope: PermissionScope): PermissionGrant => ({
|
||||
...scope,
|
||||
grant_id: "administrator:evidence_read",
|
||||
lifetime: "administrator",
|
||||
operation_identity: null,
|
||||
expires_at: null,
|
||||
});
|
||||
|
||||
const canRead = async (
|
||||
authority: PermissionAuthority,
|
||||
root: string,
|
||||
): Promise<boolean> =>
|
||||
(
|
||||
await authority.explain(
|
||||
{
|
||||
...evidenceScope(root),
|
||||
operation_identity: `read:${root}`,
|
||||
},
|
||||
"read",
|
||||
)
|
||||
).ok;
|
||||
Reference in New Issue
Block a user