feat(core): add typed policy and integrity contracts
This commit is contained in:
@@ -124,6 +124,17 @@ describe("artifact graph provider", () => {
|
||||
provider: { id: "rea-artifact-graph" },
|
||||
subject: { format: "apk" },
|
||||
});
|
||||
const cancellation = new AbortController();
|
||||
cancellation.abort();
|
||||
await expect(
|
||||
runProviderAnalysis(
|
||||
zipPath,
|
||||
"inventory_artifact",
|
||||
{},
|
||||
undefined,
|
||||
cancellation.signal,
|
||||
),
|
||||
).resolves.toMatchObject({ code: "cancelled" });
|
||||
|
||||
const source = join(root, "asar-source");
|
||||
await mkdir(source);
|
||||
|
||||
@@ -9,7 +9,10 @@ import type {
|
||||
AnalysisProvider,
|
||||
CapabilityDescriptor,
|
||||
} from "../src/application/AnalysisProvider.js";
|
||||
import { HopperStartError } from "../src/domain/errors.js";
|
||||
import {
|
||||
HopperStartError,
|
||||
ProviderAdapterError,
|
||||
} from "../src/domain/errors.js";
|
||||
import { err } from "../src/domain/result.js";
|
||||
import { observed as ok } from "./fixtures/analysisExecution.js";
|
||||
|
||||
@@ -178,6 +181,48 @@ describe("binary session", () => {
|
||||
await session.close();
|
||||
});
|
||||
|
||||
it("publishes provider-health availability changes and resets on target switch", async () => {
|
||||
const [first, second] = await targets();
|
||||
const provider = cacheProvider([]);
|
||||
provider.createClient = () => ({
|
||||
execute: (operation) =>
|
||||
Promise.resolve(
|
||||
operation === "health"
|
||||
? ok(null)
|
||||
: err(new ProviderAdapterError("fixture", operation)),
|
||||
),
|
||||
close: () => Promise.resolve(),
|
||||
});
|
||||
const session = new BinarySession(provider);
|
||||
let changes = 0;
|
||||
session.onAvailabilityChanged(() => {
|
||||
changes += 1;
|
||||
});
|
||||
expect((await session.open(first)).ok).toBe(true);
|
||||
expect((await session.execute("address_name", {})).ok).toBe(false);
|
||||
expect(session.status()).toMatchObject({
|
||||
capabilities: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
operation: "address_name",
|
||||
available: false,
|
||||
reason: "Provider became unavailable during this session.",
|
||||
}),
|
||||
]),
|
||||
});
|
||||
expect(changes).toBe(1);
|
||||
expect((await session.open(second)).ok).toBe(true);
|
||||
expect(session.status()).toMatchObject({
|
||||
capabilities: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
operation: "address_name",
|
||||
available: true,
|
||||
reason: null,
|
||||
}),
|
||||
]),
|
||||
});
|
||||
expect(changes).toBe(2);
|
||||
});
|
||||
|
||||
it("does not replay operations with filesystem side effects", async () => {
|
||||
const [first] = await targets();
|
||||
const calls: string[] = [];
|
||||
|
||||
@@ -36,7 +36,7 @@ describe("runtime configuration", () => {
|
||||
HOPPER_TARGET_KIND: "database",
|
||||
HOPPER_LOADER_ARGS_JSON: '["-l","FAT","--aarch64","-l","Mach-O"]',
|
||||
}),
|
||||
).toEqual({
|
||||
).toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
hopperLauncherPath:
|
||||
|
||||
+134
-9
@@ -23,12 +23,17 @@ import {
|
||||
NoBinaryOpenError,
|
||||
ProviderAdapterError,
|
||||
ProviderSelectionError,
|
||||
PermissionRequiredError,
|
||||
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";
|
||||
|
||||
describe("analysis error projection", () => {
|
||||
it("uses the correct provider-neutral protocol tag", () => {
|
||||
@@ -52,7 +57,10 @@ describe("analysis error projection", () => {
|
||||
] as const;
|
||||
for (const [exitCode, code] of expected) {
|
||||
const projected = projectAnalysisError(new HopperProcessError(exitCode));
|
||||
expect(projected.code).toBe(code);
|
||||
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/");
|
||||
}
|
||||
@@ -121,20 +129,34 @@ describe("analysis error projection", () => {
|
||||
cause: secretCause,
|
||||
},
|
||||
),
|
||||
PermissionRequiredError: new PermissionRequiredError(
|
||||
{
|
||||
capability: "evidence_read",
|
||||
roots: ["/workspace/evidence.json"],
|
||||
executables: [],
|
||||
environment_names: ["TOKEN_NAME"],
|
||||
network: "none",
|
||||
mount: false,
|
||||
operation_identity: "read:evidence",
|
||||
},
|
||||
{ environment_names: ["TOKEN_NAME"] },
|
||||
null,
|
||||
false,
|
||||
true,
|
||||
),
|
||||
} satisfies Readonly<Record<AnalysisErrorTag, AnalysisError>>;
|
||||
const errors = Object.values(byTag);
|
||||
const projected = errors.map(projectAnalysisError);
|
||||
expect(projected).toHaveLength(24);
|
||||
expect(projected).toHaveLength(25);
|
||||
const serialized = JSON.stringify(projected);
|
||||
for (const hidden of [
|
||||
"secret-token",
|
||||
"/secret/local/path",
|
||||
"fixture",
|
||||
"overview",
|
||||
"AnalysisCapabilityUnavailableError",
|
||||
"declaredSha256",
|
||||
])
|
||||
expect(serialized).not.toContain(hidden);
|
||||
expect(serialized).toContain("/secret/local/path");
|
||||
expect(serialized).toContain('"environment_names":["TOKEN_NAME"]');
|
||||
expect(
|
||||
projectAnalysisError(byTag.AnalysisCapabilityUnavailableError),
|
||||
).toMatchObject({
|
||||
@@ -160,11 +182,114 @@ describe("analysis error projection", () => {
|
||||
});
|
||||
expect(projected.every(({ message }) => message.length > 0)).toBe(true);
|
||||
expect(
|
||||
projected.every(({ 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/u.test(
|
||||
message,
|
||||
),
|
||||
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([]);
|
||||
});
|
||||
|
||||
it("validates every closed error-reason variant against the generated contract", () => {
|
||||
const variants: AnalysisError[] = [
|
||||
...(
|
||||
[
|
||||
"cancelled",
|
||||
"format",
|
||||
"integrity",
|
||||
"limit",
|
||||
"path",
|
||||
"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(38);
|
||||
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");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -12,6 +12,7 @@ import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { createPackageWithOptions } from "@electron/asar";
|
||||
|
||||
import { runCrossVersionInvestigation } from "../src/application/CrossVersionInvestigation.js";
|
||||
import {
|
||||
@@ -211,6 +212,86 @@ describe("persistent cross-version investigation workspace", () => {
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("checkpoints bounded integrity contradictions and safely reuses them", async () => {
|
||||
directory = await mkdtemp(join(tmpdir(), "rea-workspace-integrity-"));
|
||||
const source = join(directory, "source");
|
||||
await mkdir(source);
|
||||
await writeFile(join(source, "addon.node"), "verified native addon\n");
|
||||
const left = join(directory, "left.asar");
|
||||
const right = join(directory, "right.asar");
|
||||
await Promise.all([
|
||||
createPackageWithOptions(source, left, { unpack: "*.node" }),
|
||||
createPackageWithOptions(source, right, { unpack: "*.node" }),
|
||||
]);
|
||||
await writeFile(join(`${right}.unpacked`, "addon.node"), "tampered\n");
|
||||
const base = {
|
||||
approved: true as const,
|
||||
workspace_path: join(directory, "strict.json"),
|
||||
workspace_name: "integrity-diff",
|
||||
left_path: left,
|
||||
right_path: right,
|
||||
options: { page_size: 500, change_limit: 100 },
|
||||
};
|
||||
const strict = await runCrossVersionInvestigation(
|
||||
crossVersionInvestigationInputSchema.parse(base),
|
||||
policy(directory),
|
||||
{ inputRoots: [directory] },
|
||||
);
|
||||
expect(strict).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "ArtifactOperationError", reason: "integrity" },
|
||||
});
|
||||
|
||||
const continuedInput = crossVersionInvestigationInputSchema.parse({
|
||||
...base,
|
||||
workspace_path: join(directory, "continued.json"),
|
||||
integrity_policy: "record-and-continue",
|
||||
integrity_continue_approved: true,
|
||||
max_integrity_mismatches: 2,
|
||||
});
|
||||
const continued = await runCrossVersionInvestigation(
|
||||
continuedInput,
|
||||
policy(directory),
|
||||
{ inputRoots: [directory], integrityContinueEnabled: true },
|
||||
);
|
||||
expect(continued).toMatchObject({
|
||||
ok: true,
|
||||
value: { reused: false, workspace: { revision: 3 } },
|
||||
});
|
||||
if (!continued.ok) throw continued.error;
|
||||
expect(
|
||||
continued.value.workspace.bundle.records.some((record) =>
|
||||
JSON.stringify(record.normalized_result).includes(
|
||||
'"integrity_contradictions":[{',
|
||||
),
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
continued.value.workspace.bundle.records.find(
|
||||
({ operation }) => operation === "compare_artifacts",
|
||||
)?.normalized_result,
|
||||
).toMatchObject({ status: "contradiction" });
|
||||
await expect(
|
||||
runCrossVersionInvestigation(continuedInput, policy(directory), {
|
||||
inputRoots: [directory],
|
||||
integrityContinueEnabled: true,
|
||||
}),
|
||||
).resolves.toMatchObject({ ok: true, value: { reused: true } });
|
||||
|
||||
const strictAfterContinuation = crossVersionInvestigationInputSchema.parse({
|
||||
...base,
|
||||
workspace_path: continuedInput.workspace_path,
|
||||
});
|
||||
await expect(
|
||||
runCrossVersionInvestigation(strictAfterContinuation, policy(directory), {
|
||||
inputRoots: [directory],
|
||||
}),
|
||||
).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "ArtifactOperationError", reason: "integrity" },
|
||||
});
|
||||
});
|
||||
|
||||
it("fails closed on locks, CAS conflicts, tampering, and cancellation", async () => {
|
||||
const { path, input } = await fixture();
|
||||
if (directory === undefined) throw new Error("missing fixture root");
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import { mkdtemp, mkdir, symlink, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
canonicalizePermissionCeilings,
|
||||
canonicalizePermissionRequest,
|
||||
} from "../src/application/PermissionAuthority.js";
|
||||
import {
|
||||
createPermissionPolicy,
|
||||
evaluatePermission,
|
||||
} from "../src/domain/permissionPolicy.js";
|
||||
|
||||
describe("permission authority", () => {
|
||||
it("accepts canonical aliases but rejects a symlink escape", async () => {
|
||||
const sandbox = await mkdtemp(join(tmpdir(), "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 mkdtemp(join(tmpdir(), "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")]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,206 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { win32 } from "node:path";
|
||||
|
||||
import {
|
||||
consumePermission,
|
||||
clearSessionPermissions,
|
||||
createPermissionPolicy,
|
||||
evaluatePermission,
|
||||
grantPermission,
|
||||
isPathContained,
|
||||
reloadPermissionCeilings,
|
||||
revokePermission,
|
||||
} from "../src/domain/permissionPolicy.js";
|
||||
|
||||
describe("permission policy", () => {
|
||||
it("rejects sibling escapes for both POSIX and Windows path separators", () => {
|
||||
expect(isPathContained("/allowed", "/secret")).toBe(false);
|
||||
expect(
|
||||
isPathContained("C:\\allowed", "C:\\secret", {
|
||||
relative: win32.relative,
|
||||
isAbsolute: win32.isAbsolute,
|
||||
sep: win32.sep,
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isPathContained("C:\\allowed", "C:\\allowed\\nested", {
|
||||
relative: win32.relative,
|
||||
isAbsolute: win32.isAbsolute,
|
||||
sep: win32.sep,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("never lets a session grant exceed the administrator ceiling", () => {
|
||||
const policy = createPermissionPolicy([
|
||||
{
|
||||
capability: "process_capture",
|
||||
roots: ["/workspace/project"],
|
||||
executables: ["/workspace/project/bin/tool"],
|
||||
environment_names: ["LANG"],
|
||||
network: "loopback",
|
||||
mount: false,
|
||||
},
|
||||
]);
|
||||
const granted = grantPermission(policy, {
|
||||
grant_id: "grant_session_1",
|
||||
capability: "process_capture",
|
||||
roots: ["/workspace/project"],
|
||||
executables: ["/workspace/project/bin/tool"],
|
||||
environment_names: ["LANG"],
|
||||
network: "loopback",
|
||||
mount: false,
|
||||
lifetime: "session",
|
||||
operation_identity: null,
|
||||
expires_at: null,
|
||||
});
|
||||
|
||||
expect(granted.ok).toBe(true);
|
||||
if (!granted.ok) return;
|
||||
expect(
|
||||
evaluatePermission(granted.value, {
|
||||
capability: "process_capture",
|
||||
roots: ["/workspace/project/data"],
|
||||
executables: ["/workspace/project/bin/tool"],
|
||||
environment_names: ["LANG"],
|
||||
network: "loopback",
|
||||
mount: false,
|
||||
operation_identity: "capture-1",
|
||||
}),
|
||||
).toMatchObject({ allowed: true });
|
||||
expect(
|
||||
evaluatePermission(granted.value, {
|
||||
capability: "process_capture",
|
||||
roots: ["/workspace/project/data"],
|
||||
executables: ["/workspace/project/bin/tool"],
|
||||
environment_names: ["LANG", "TOKEN"],
|
||||
network: "external",
|
||||
mount: false,
|
||||
operation_identity: "capture-2",
|
||||
}),
|
||||
).toMatchObject({
|
||||
allowed: false,
|
||||
reason: "outside_administrator_ceiling",
|
||||
missing: {
|
||||
environment_names: ["TOKEN"],
|
||||
network: "external",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("consumes once grants and applies revocation and ceiling reload immediately", () => {
|
||||
const ceiling = {
|
||||
capability: "evidence_write" as const,
|
||||
roots: ["/workspace/evidence"],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
network: "none" as const,
|
||||
mount: false,
|
||||
};
|
||||
const granted = grantPermission(createPermissionPolicy([ceiling]), {
|
||||
...ceiling,
|
||||
grant_id: "grant_once_1",
|
||||
lifetime: "once",
|
||||
operation_identity: "write:report.json",
|
||||
expires_at: null,
|
||||
});
|
||||
expect(granted.ok).toBe(true);
|
||||
if (!granted.ok) return;
|
||||
const request = {
|
||||
...ceiling,
|
||||
roots: ["/workspace/evidence/report.json"],
|
||||
operation_identity: "write:report.json",
|
||||
};
|
||||
const decision = evaluatePermission(granted.value, request);
|
||||
expect(decision).toMatchObject({ allowed: true });
|
||||
if (!decision.allowed) return;
|
||||
|
||||
const consumed = consumePermission(granted.value, decision);
|
||||
expect(evaluatePermission(consumed, request)).toMatchObject({
|
||||
allowed: false,
|
||||
reason: "grant_revoked_or_consumed",
|
||||
});
|
||||
expect(
|
||||
evaluatePermission(
|
||||
revokePermission(granted.value, "grant_once_1"),
|
||||
request,
|
||||
),
|
||||
).toMatchObject({
|
||||
allowed: false,
|
||||
reason: "grant_revoked_or_consumed",
|
||||
});
|
||||
expect(
|
||||
evaluatePermission(reloadPermissionCeilings(granted.value, []), request),
|
||||
).toMatchObject({
|
||||
allowed: false,
|
||||
reason: "outside_administrator_ceiling",
|
||||
});
|
||||
});
|
||||
|
||||
it("expires grants, removes session authority on disconnect, and never combines partial grants", () => {
|
||||
const ceiling = {
|
||||
capability: "process_capture" as const,
|
||||
roots: ["/workspace"],
|
||||
executables: ["/bin/tool"],
|
||||
environment_names: ["LANG"],
|
||||
network: "loopback" as const,
|
||||
mount: false,
|
||||
};
|
||||
const base = createPermissionPolicy([ceiling]);
|
||||
const rootOnly = grantPermission(base, {
|
||||
...ceiling,
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
network: "none",
|
||||
grant_id: "root-only",
|
||||
lifetime: "project",
|
||||
operation_identity: null,
|
||||
expires_at: null,
|
||||
});
|
||||
expect(rootOnly.ok).toBe(true);
|
||||
if (!rootOnly.ok) return;
|
||||
const executableOnly = grantPermission(rootOnly.value, {
|
||||
...ceiling,
|
||||
roots: [],
|
||||
grant_id: "exec-only",
|
||||
lifetime: "session",
|
||||
operation_identity: null,
|
||||
expires_at: "2026-07-14T00:00:00.000Z",
|
||||
});
|
||||
expect(executableOnly.ok).toBe(true);
|
||||
if (!executableOnly.ok) return;
|
||||
const request = {
|
||||
...ceiling,
|
||||
operation_identity: "capture",
|
||||
};
|
||||
|
||||
expect(
|
||||
evaluatePermission(
|
||||
executableOnly.value,
|
||||
request,
|
||||
new Date("2026-07-13T00:00:00.000Z"),
|
||||
),
|
||||
).toMatchObject({ allowed: false, reason: "grant_required" });
|
||||
const expiring = grantPermission(base, {
|
||||
...ceiling,
|
||||
grant_id: "expiring",
|
||||
lifetime: "session",
|
||||
operation_identity: null,
|
||||
expires_at: "2026-07-14T00:00:00.000Z",
|
||||
});
|
||||
expect(expiring.ok).toBe(true);
|
||||
if (!expiring.ok) return;
|
||||
expect(
|
||||
evaluatePermission(
|
||||
expiring.value,
|
||||
request,
|
||||
new Date("2026-07-15T00:00:00.000Z"),
|
||||
),
|
||||
).toMatchObject({ allowed: false, reason: "grant_expired" });
|
||||
expect(
|
||||
clearSessionPermissions(executableOnly.value).grants.map(
|
||||
({ grant_id }) => grant_id,
|
||||
),
|
||||
).toEqual(["root-only"]);
|
||||
});
|
||||
});
|
||||
@@ -97,11 +97,20 @@ describe("process CLI errors", () => {
|
||||
working_directory: "/tmp",
|
||||
}),
|
||||
);
|
||||
expect(await captureProcessScenarioFile(scenario)).toEqual({
|
||||
expect(await captureProcessScenarioFile(scenario)).toMatchObject({
|
||||
error: "Process command failed",
|
||||
code: "permission_required",
|
||||
category: "permission_required",
|
||||
message:
|
||||
"Process capture is disabled. Set `REA_PROCESS_CAPTURE_ENABLED=true`, configure approved roots, then restart REA.",
|
||||
"This operation needs additional local permission. Review the requested scope and remediation.",
|
||||
details: {
|
||||
capability: "process_capture",
|
||||
ceiling: null,
|
||||
},
|
||||
remediation: {
|
||||
restart_required: false,
|
||||
elicitation_supported: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createProgressReporter } from "../src/application/ProgressReporter.js";
|
||||
|
||||
describe("progress reporter", () => {
|
||||
it("preserves monotonic order, rate bounds intermediate updates, and always emits terminal state", async () => {
|
||||
let now = 0;
|
||||
const observed: unknown[] = [];
|
||||
const reporter = createProgressReporter(
|
||||
(update) => {
|
||||
observed.push(update);
|
||||
return Promise.resolve();
|
||||
},
|
||||
{ minimumIntervalMs: 100, now: () => now },
|
||||
);
|
||||
await reporter.report({
|
||||
phase: "scan",
|
||||
completed: 0,
|
||||
total: 3,
|
||||
message: "start",
|
||||
});
|
||||
now = 10;
|
||||
await reporter.report({
|
||||
phase: "scan",
|
||||
completed: 1,
|
||||
total: 3,
|
||||
message: "one",
|
||||
});
|
||||
now = 20;
|
||||
await reporter.report({
|
||||
phase: "scan",
|
||||
completed: 3,
|
||||
total: 3,
|
||||
message: "done",
|
||||
terminal: true,
|
||||
});
|
||||
|
||||
expect(observed).toEqual([
|
||||
expect.objectContaining({ sequence: 1, completed: 0 }),
|
||||
expect.objectContaining({ sequence: 2, completed: 3, terminal: true }),
|
||||
]);
|
||||
await expect(
|
||||
reporter.report({
|
||||
phase: "scan",
|
||||
completed: 2,
|
||||
total: 3,
|
||||
message: "back",
|
||||
}),
|
||||
).rejects.toThrow(/backwards/u);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,63 @@
|
||||
import { chmod, mkdtemp, stat } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
readProjectPermissionStore,
|
||||
writeProjectPermissionStore,
|
||||
} from "../src/application/ProjectPermissionStore.js";
|
||||
|
||||
describe("project permission store", () => {
|
||||
it("persists explicit project grants atomically with owner-only permissions", async () => {
|
||||
const project = await mkdtemp(join(tmpdir(), "rea-policy-project-"));
|
||||
const path = join(project, ".rea", "permissions.json");
|
||||
const grant = {
|
||||
grant_id: "project:evidence-read",
|
||||
capability: "evidence_read" as const,
|
||||
roots: [project],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
network: "none" as const,
|
||||
mount: false,
|
||||
lifetime: "project" as const,
|
||||
operation_identity: null,
|
||||
expires_at: null,
|
||||
};
|
||||
|
||||
const written = await writeProjectPermissionStore(path, project, [grant]);
|
||||
expect(written.ok).toBe(true);
|
||||
expect((await stat(path)).mode & 0o077).toBe(0);
|
||||
const loaded = await readProjectPermissionStore(path, project);
|
||||
expect(loaded).toMatchObject({
|
||||
ok: true,
|
||||
value: { grants: [grant] },
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects stores readable by another user class", async () => {
|
||||
const project = await mkdtemp(join(tmpdir(), "rea-policy-mode-"));
|
||||
const path = join(project, "permissions.json");
|
||||
const written = await writeProjectPermissionStore(path, project, []);
|
||||
expect(written.ok).toBe(true);
|
||||
await chmod(path, 0o644);
|
||||
|
||||
expect(await readProjectPermissionStore(path, project)).toMatchObject({
|
||||
ok: false,
|
||||
error: { reason: "not_owner_only" },
|
||||
});
|
||||
});
|
||||
|
||||
it("binds grants to canonical project identity", async () => {
|
||||
const first = await mkdtemp(join(tmpdir(), "rea-policy-first-"));
|
||||
const second = await mkdtemp(join(tmpdir(), "rea-policy-second-"));
|
||||
const path = join(first, "permissions.json");
|
||||
expect((await writeProjectPermissionStore(path, first, [])).ok).toBe(true);
|
||||
|
||||
expect(await readProjectPermissionStore(path, second)).toMatchObject({
|
||||
ok: false,
|
||||
error: { reason: "invalid" },
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user