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:
morluto
2026-08-11 18:34:32 +08:00
committed by GitHub
parent d65730c4c2
commit d4dc940bd8
117 changed files with 1519 additions and 2419 deletions
@@ -0,0 +1,379 @@
import {
copyFile,
lstat,
mkdir,
readFile,
realpath,
rm,
symlink,
writeFile,
} from "node:fs/promises";
import { dirname, join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
configureTomlClient,
detectClients,
} from "../../../src/application/Setup.js";
import {
runUninstall,
systemUninstallHost,
type UninstallFileSystem,
} from "../../../src/application/Uninstall.js";
const roots: string[] = [];
afterEach(async () => {
await Promise.all(
roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
);
});
describe("client configuration filesystem lifecycle", () => {
it("detects every supported client and skips absent clients", async () => {
const home = await createTestTempDirectory("rea-detect-");
roots.push(home);
for (const marker of [
".claude",
"Library/Application Support/Claude",
".codex",
".cursor",
".gemini",
".codeium/windsurf",
".devin",
])
await mkdir(join(home, marker), { recursive: true });
const detected = await detectClients(home);
expect(detected.map(({ name }) => name)).toEqual([
"claude_code",
"claude_desktop",
"codex",
"cursor",
"gemini_cli",
"windsurf",
"devin",
]);
expect(
detected.find(({ name }) => name === "claude_code")?.configPath,
).toBe(join(home, ".claude.json"));
expect(detected.find(({ name }) => name === "devin")?.format).toBe(
"unsupported",
);
const emptyHome = await createTestTempDirectory("rea-empty-");
roots.push(emptyHome);
expect(await detectClients(emptyHome)).toEqual([]);
});
it("preserves unrelated Codex TOML and supports an installed command", async () => {
const home = await createTestTempDirectory("rea-toml-");
roots.push(home);
const configPath = join(home, ".codex/config.toml");
await mkdir(dirname(configPath), { recursive: true });
await writeFile(
configPath,
'model = "gpt-5"\n[mcp_servers.other]\ncommand = "other"\n',
);
expect(
await configureTomlClient(
{ name: "codex", configPath, format: "toml" },
{
HOPPER_LAUNCHER_PATH: "/Hopper Path",
GHIDRA_INSTALL_DIR: "/opt/ghidra",
JAVA_HOME: "/opt/jdk-21",
},
["rea", "mcp"],
),
).toMatchObject({ status: "configured" });
const configured = await readFile(configPath, "utf8");
expect(configured).toContain('model = "gpt-5"');
expect(configured).toContain("[mcp_servers.rea]");
expect(configured).toContain('command = "rea"');
expect(configured).toContain("startup_timeout_sec = 30");
expect(configured).toContain('GHIDRA_INSTALL_DIR = "/opt/ghidra"');
expect(configured).toContain('JAVA_HOME = "/opt/jdk-21"');
expect(
await configureTomlClient(
{ name: "codex", configPath, format: "toml" },
{
HOPPER_LAUNCHER_PATH: "/Hopper Path",
GHIDRA_INSTALL_DIR: "/opt/ghidra",
JAVA_HOME: "/opt/jdk-21",
},
["rea", "mcp"],
),
).toEqual({ status: "unchanged" });
});
it("does not rewrite an equivalent Codex registration with reordered environment keys", async () => {
const home = await createTestTempDirectory("rea-toml-");
roots.push(home);
const configPath = join(home, ".codex/config.toml");
await mkdir(dirname(configPath), { recursive: true });
await writeFile(
configPath,
`[mcp_servers.rea]\ncommand = "rea"\nargs = ["mcp"]\nstartup_timeout_sec = 30\n\n[mcp_servers.rea.env]\nJAVA_HOME = "/opt/jdk-21"\nHOPPER_LAUNCHER_PATH = "/Hopper Path"\nGHIDRA_INSTALL_DIR = "/opt/ghidra"\n`,
);
expect(
await configureTomlClient(
{ name: "codex", configPath, format: "toml" },
{
HOPPER_LAUNCHER_PATH: "/Hopper Path",
GHIDRA_INSTALL_DIR: "/opt/ghidra",
JAVA_HOME: "/opt/jdk-21",
},
["rea", "mcp"],
),
).toEqual({ status: "unchanged" });
await expect(
readFile(`${configPath}.rea.backup`, "utf8"),
).rejects.toThrow();
});
it("updates a symlink target without replacing the TOML config symlink", async () => {
const home = await createTestTempDirectory("rea-toml-symlink-");
roots.push(home);
const configPath = join(home, ".codex/config.toml");
const targetPath = join(home, "managed-config.toml");
const original = 'model = "gpt-5"\n';
await mkdir(dirname(configPath), { recursive: true });
await writeFile(targetPath, original);
await symlink(targetPath, configPath);
expect(
await configureTomlClient(
{ name: "codex", configPath, format: "toml" },
undefined,
["rea", "mcp"],
),
).toMatchObject({ status: "configured" });
expect((await lstat(configPath)).isSymbolicLink()).toBe(true);
expect(await readFile(`${configPath}.rea.backup`, "utf8")).toBe(original);
expect(await readFile(targetPath, "utf8")).toContain("[mcp_servers.rea]");
});
it("fails before mutation when a TOML config symlink is dangling", async () => {
const home = await createTestTempDirectory("rea-toml-symlink-");
roots.push(home);
const configPath = join(home, ".codex/config.toml");
await mkdir(dirname(configPath), { recursive: true });
await symlink(join(home, "missing-config.toml"), configPath);
expect(
await configureTomlClient({ name: "codex", configPath, format: "toml" }),
).toEqual({ status: "failed", reason: "path" });
expect((await lstat(configPath)).isSymbolicLink()).toBe(true);
await expect(
readFile(`${configPath}.rea.backup`, "utf8"),
).rejects.toThrow();
});
});
describe("client configuration filesystem removal", () => {
it("uninstalls only owned entries and refuses purge symlinks", async () => {
const home = await createTestTempDirectory("rea-uninstall-");
roots.push(home);
const cursor = join(home, ".cursor/mcp.json");
const skill = join(
home,
".agents/skills/reverse-engineer-anything/SKILL.md",
);
await mkdir(dirname(cursor), { recursive: true });
await mkdir(dirname(skill), { recursive: true });
await writeFile(
cursor,
JSON.stringify({
mcpServers: {
rea: { command: "/isolated prefix/bin/rea", args: ["mcp"] },
other: { command: "other" },
},
}),
);
await writeFile(skill, "managed");
await mkdir(join(home, ".rea"), { recursive: true });
await import("node:fs/promises").then(({ symlink }) =>
symlink(home, join(home, ".rea/cache")),
);
const first = await runUninstall(true, systemUninstallHost(home));
expect(first.status).toBe("complete");
expect(JSON.parse(await readFile(cursor, "utf8"))).toEqual({
mcpServers: { other: { command: "other" } },
});
await expect(readFile(skill, "utf8")).rejects.toThrow();
expect(first.items).toContainEqual(
expect.objectContaining({
name: "cache",
status: "retained",
detail:
"REA did not remove this item because its managed path is a symbolic link. Verify the link target before removing it manually.",
}),
);
expect((await runUninstall(true, systemUninstallHost(home))).status).toBe(
"complete",
);
});
it("removes an owned entry through a symlink without replacing it", async () => {
const home = await createTestTempDirectory("rea-uninstall-symlink-");
roots.push(home);
const configPath = join(home, ".cursor/mcp.json");
const targetPath = join(home, "managed-mcp.json");
const original = JSON.stringify({
mcpServers: {
rea: { command: "rea", args: ["mcp"] },
other: { command: "other" },
},
});
await mkdir(dirname(configPath), { recursive: true });
await writeFile(targetPath, original);
await symlink(targetPath, configPath);
expect((await runUninstall(false, systemUninstallHost(home))).status).toBe(
"complete",
);
expect((await lstat(configPath)).isSymbolicLink()).toBe(true);
expect(await readFile(`${configPath}.rea.backup`, "utf8")).toBe(original);
expect(JSON.parse(await readFile(targetPath, "utf8"))).toEqual({
mcpServers: { other: { command: "other" } },
});
});
it("fails before mutation when an uninstall config symlink is dangling", async () => {
const home = await createTestTempDirectory("rea-uninstall-symlink-");
roots.push(home);
const configPath = join(home, ".cursor/mcp.json");
await mkdir(dirname(configPath), { recursive: true });
await symlink(join(home, "missing-mcp.json"), configPath);
const result = await runUninstall(false, systemUninstallHost(home));
expect(result.status).toBe("failed");
expect(result.items).toContainEqual({
name: "cursor",
status: "failed",
detail:
"Configuration path could not be safely verified. Check its permissions and, if it is a symbolic link, verify that the link resolves to a regular file owned by the current user, then rerun uninstall.",
});
expect((await lstat(configPath)).isSymbolicLink()).toBe(true);
await expect(
readFile(`${configPath}.rea.backup`, "utf8"),
).rejects.toThrow();
});
it("fails closed on malformed client configuration", async () => {
const home = await createTestTempDirectory("rea-uninstall-bad-");
roots.push(home);
const config = join(home, ".cursor/mcp.json");
await mkdir(dirname(config), { recursive: true });
await writeFile(config, "not-json");
const result = await runUninstall(false, systemUninstallHost(home));
expect(result.status).toBe("failed");
expect(result.items).toContainEqual(
expect.objectContaining({
name: "cursor",
status: "failed",
detail:
"Configuration is not valid JSON and was not changed. Repair it, then rerun uninstall.",
}),
);
expect(await readFile(config, "utf8")).toBe("not-json");
});
});
describe("client configuration filesystem failure reporting", () => {
it.each([
[
"read",
"Configuration could not be read. Check file permissions, then rerun uninstall.",
],
[
"backup",
"Configuration could not be backed up, so no change was made. Check file permissions, then rerun uninstall.",
],
[
"update",
"Configuration could not be updated. The original was restored and its `.rea.backup` was retained. Repair the configuration or restore the backup, then rerun uninstall.",
],
[
"restore",
"Configuration could not be updated or restored. Restore its `.rea.backup` manually, then rerun uninstall.",
],
] as const)(
"reports an actionable client %s failure",
async (failure, detail) => {
const { home, config } = await uninstallFixture();
let writes = 0;
const fileSystem: UninstallFileSystem = {
...testFileSystem,
readText: (path) =>
failure === "read" && path === config
? Promise.reject(new Error("SECRET read failure"))
: readFile(path, "utf8"),
copy: (source, destination) =>
failure === "backup"
? Promise.reject(new Error("SECRET backup failure"))
: copyFile(source, destination),
writeText: async (path, contents) => {
writes += 1;
if ((failure === "update" && writes === 1) || failure === "restore")
throw new Error("SECRET write failure");
await writeFile(path, contents);
},
};
const result = await runUninstall(
false,
systemUninstallHost(home, fileSystem),
);
expect(result.status).toBe("failed");
expect(result.items).toContainEqual(
expect.objectContaining({ name: "cursor", status: "failed", detail }),
);
expect(JSON.stringify(result)).not.toContain("SECRET");
},
);
it("reports a managed-path removal failure", async () => {
const home = await createTestTempDirectory("rea-uninstall-remove-");
roots.push(home);
const skillRoot = join(home, ".agents/skills/reverse-engineer-anything");
await mkdir(skillRoot, { recursive: true });
const result = await runUninstall(
false,
systemUninstallHost(home, {
...testFileSystem,
remove: () => Promise.reject(new Error("SECRET removal failure")),
}),
);
expect(result.items).toContainEqual({
name: "skill",
status: "failed",
detail:
"This item could not be removed. Check file permissions, then rerun uninstall.",
});
expect(JSON.stringify(result)).not.toContain("SECRET");
});
});
const testFileSystem: UninstallFileSystem = {
readText: (path) => readFile(path, "utf8"),
copy: (source, destination) => copyFile(source, destination),
writeText: (path, contents) => writeFile(path, contents),
stat: (path) => lstat(path),
realpath: (path) => realpath(path),
remove: (path) => rm(path, { recursive: true }),
};
const uninstallFixture = async (): Promise<{
readonly home: string;
readonly config: string;
}> => {
const home = await createTestTempDirectory("rea-uninstall-failure-");
roots.push(home);
const config = join(home, ".cursor/mcp.json");
await mkdir(dirname(config), { recursive: true });
await writeFile(
config,
JSON.stringify({ mcpServers: { rea: { command: "rea", args: ["mcp"] } } }),
);
return { home, config };
};
@@ -1,94 +0,0 @@
import { describe, expect, it } from "vitest";
import { parseConfig } from "../../../src/config.js";
describe("configuration parsing integration", () => {
it("returns defaults when no environment variables are set", () => {
const result = parseConfig({});
expect(result.ok).toBe(true);
if (!result.ok) throw new Error("unreachable");
expect(result.value.hopperLauncherPath).toBe(
process.platform === "linux"
? "/opt/hopper/bin/Hopper"
: "/Applications/Hopper Disassembler.app/Contents/MacOS/hopper",
);
expect(result.value.hopperTargetPath).toBeUndefined();
expect(result.value.hopperTargetKind).toBe("executable");
expect(result.value.hopperLoaderArgs).toEqual([]);
expect(result.value.analysisProvider).toBe("auto");
});
it("parses a complete target-bound configuration", () => {
const result = parseConfig({
HOPPER_TARGET_PATH: "/usr/bin/true",
HOPPER_TARGET_KIND: "executable",
HOPPER_LOADER_ARGS_JSON: '["-l","Mach-O","--aarch64"]',
REA_ANALYSIS_PROVIDER: "hopper",
REA_EVIDENCE_ROOTS_JSON: '["/tmp/evidence"]',
REA_INVESTIGATION_INPUT_ROOTS_JSON: '["/tmp/releases"]',
REA_ANALYSIS_SNAPSHOT_ROOTS_JSON: '["/tmp/analysis"]',
});
expect(result.ok).toBe(true);
if (!result.ok) throw new Error("unreachable");
expect(result.value.hopperTargetPath).toBe("/usr/bin/true");
expect(result.value.hopperTargetKind).toBe("executable");
expect(result.value.analysisProvider).toBe("hopper");
expect(result.value.hopperLoaderArgs).toEqual([
"-l",
"Mach-O",
"--aarch64",
]);
expect(result.value.evidenceFilePolicy.roots).toEqual(["/tmp/evidence"]);
expect(result.value.investigationInputRoots).toEqual(["/tmp/releases"]);
expect(result.value.analysisSnapshotFilePolicy.roots).toEqual([
"/tmp/analysis",
]);
});
it("rejects target kind values outside the enum", () => {
const result = parseConfig({
HOPPER_TARGET_KIND: "archive",
});
expect(result.ok).toBe(false);
if (result.ok) throw new Error("unreachable");
expect(result.error.message).toContain("Invalid REA environment");
});
it("rejects invalid JSON in loader arguments", () => {
const result = parseConfig({
HOPPER_LOADER_ARGS_JSON: "not json",
});
expect(result.ok).toBe(false);
if (result.ok) throw new Error("unreachable");
expect(result.error.message).toContain("valid JSON");
});
it("rejects non-array types in loader arguments JSON", () => {
const result = parseConfig({
HOPPER_LOADER_ARGS_JSON: '"just a string"',
});
expect(result.ok).toBe(false);
if (result.ok) throw new Error("unreachable");
expect(result.error.message).toContain("array of strings");
});
it("allows overriding the launcher path while keeping other defaults", () => {
const result = parseConfig({
HOPPER_LAUNCHER_PATH: "/custom/hopper",
});
expect(result.ok).toBe(true);
if (!result.ok) throw new Error("unreachable");
expect(result.value.hopperLauncherPath).toBe("/custom/hopper");
expect(result.value.hopperTargetPath).toBeUndefined();
});
it("parses database target kind correctly", () => {
const result = parseConfig({
HOPPER_TARGET_PATH: "/path/to/file.hop",
HOPPER_TARGET_KIND: "database",
});
expect(result.ok).toBe(true);
if (!result.ok) throw new Error("unreachable");
expect(result.value.hopperTargetKind).toBe("database");
});
});
@@ -0,0 +1,118 @@
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 filesystem 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,4 +1,3 @@
import { createHash } from "node:crypto";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
@@ -15,29 +14,13 @@ import { MANAGED_STATIC_PROVIDER } from "../../../src/application/InvestigationP
import { createPermissionAuthority } from "../../../src/application/PermissionAuthority.js";
import { createEvidence } from "../../../src/domain/evidence.js";
import { managedRuntimeCorrelationResultSchema } from "../../../src/domain/managedRuntimeCorrelation.js";
import type { BinaryTarget } from "../../../src/domain/binaryTarget.js";
import type { PermissionCeiling } from "../../../src/domain/permissionPolicy.js";
import { inspectManagedMembersBytes } from "../../../src/dotnet/ManagedMemberInspector.js";
import { buildManagedPeFixture } from "../../fixtures/managedPe.js";
const memberLimits = {
typeOffset: 0,
typeLimit: 100,
methodOffset: 0,
methodLimit: 100,
fieldOffset: 0,
fieldLimit: 100,
memberRefOffset: 0,
memberRefLimit: 100,
edgeOffset: 0,
edgeLimit: 100,
instructionAnchorLimit: 100,
maxMetadataBytes: 1024 * 1024,
maxTableRows: 1_000,
maxHeapItemBytes: 1024 * 1024,
maxMethodBodyBytes: 1024 * 1024,
maxMethodInstructions: 1_000,
};
import {
buildManagedPeFixture,
managedPeFixtureTarget,
MANAGED_MEMBER_FIXTURE_LIMITS,
} from "../../../src/dotnet/ManagedPe.fixture.js";
describe("managed runtime correlation planning", () => {
it("fails closed while the managed runtime authority is disabled", async () => {
@@ -157,7 +140,7 @@ describe("managed runtime correlation planning", () => {
await writeFile(artifactPath, bytes);
await writeFile(executablePath, "#!/bin/sh\n");
const fixture = inspect(bytes, artifactPath, {
...memberLimits,
...MANAGED_MEMBER_FIXTURE_LIMITS,
maxMethodInstructions: 1,
});
const authority = await authorityFor(directory, executablePath, true);
@@ -247,18 +230,9 @@ const inputFor = (
const inspect = (
bytes: Buffer,
path: string,
limits: typeof memberLimits = memberLimits,
limits: typeof MANAGED_MEMBER_FIXTURE_LIMITS = MANAGED_MEMBER_FIXTURE_LIMITS,
) => {
const target: BinaryTarget = {
path,
sha256: hash(bytes),
kind: "executable",
format: "pe",
architecture: "x86",
availableArchitectures: ["x86"],
executableRole: "application",
managed: true,
};
const target = managedPeFixtureTarget(bytes, path);
const result = inspectManagedMembersBytes(bytes, target, limits);
const method = result.methods.items[0];
if (method === undefined) throw new Error("fixture has no method");
@@ -274,6 +248,3 @@ const inspect = (
}),
};
};
const hash = (bytes: Buffer): string =>
createHash("sha256").update(bytes).digest("hex");
@@ -0,0 +1,350 @@
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 filesystem boundaries", () => {
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;