mirror of
https://github.com/morluto/rea.git
synced 2026-11-18 04:34:13 +00:00
fix(contracts): keep recorded local-path schemas portable
This commit is contained in:
1 parent
a88c0a5554
commit
954979b7ff
8 files changed
+168
-29
No files matched your search
@@ -121,17 +121,7 @@ export const UNIT_LAYERS = Object.freeze(
|
||||
* a deliberate decision, not a baseline debt: it is not counted, and any other
|
||||
* import between the same units still is. Keep the list short and say why.
|
||||
*/
|
||||
export const LAYER_EXCEPTIONS = Object.freeze([
|
||||
Object.freeze({
|
||||
file: "src/domain/localPath.ts",
|
||||
target: "src/platform/HostPlatform.ts",
|
||||
// `absoluteLocalPathStringSchema` states which paths are absolute on the
|
||||
// host running REA; that is a fact about the host's path rules, and
|
||||
// HostPlatform is its only reader (maintainer decision, W8).
|
||||
reason:
|
||||
"the absolute local path schema follows the running host's path rules",
|
||||
}),
|
||||
]);
|
||||
export const LAYER_EXCEPTIONS = Object.freeze([]);
|
||||
|
||||
const sourcePath = (path) => path.replace(/\.js$/u, ".ts");
|
||||
/** Whether one resolved import is a declared layer exception. */
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { isAbsolute, win32 } from "node:path";
|
||||
import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import { z } from "zod";
|
||||
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
@@ -20,6 +22,20 @@ const PATHS = [
|
||||
"file:///absolute/path",
|
||||
];
|
||||
|
||||
it("serializes portable path constraints for catalogs shipped to another host", () => {
|
||||
const ajv = new Ajv2020({ strict: false });
|
||||
for (const io of ["input", "output"] as const) {
|
||||
const schema = JSON.parse(
|
||||
JSON.stringify(z.toJSONSchema(absoluteLocalPathStringSchema, { io })),
|
||||
);
|
||||
const validate = ajv.compile(schema);
|
||||
for (const path of PATHS.filter((path) => win32.isAbsolute(path)))
|
||||
expect(validate(path), `${io}: ${path}`).toBe(true);
|
||||
for (const path of ["", "relative/path", "C:relative/path", "/tmp/\0"])
|
||||
expect(validate(path), `${io}: ${path}`).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("matches the host path module for absolute local paths", () => {
|
||||
const checked: string[] = [];
|
||||
for (const path of PATHS) {
|
||||
|
||||
+22
-10
@@ -1,10 +1,6 @@
|
||||
import { isAbsolute, relative, sep } from "node:path";
|
||||
import { z } from "zod";
|
||||
|
||||
// Declared layer exception (scripts/lib/module-layers.mjs LAYER_EXCEPTIONS):
|
||||
// which paths are absolute is a fact about the running host's path rules.
|
||||
import { HOST_PLATFORM } from "../platform/HostPlatform.js";
|
||||
|
||||
import { rejectUnpairedSurrogates } from "./stringPatterns.js";
|
||||
|
||||
/**
|
||||
@@ -35,16 +31,32 @@ export const localPathStringSchema = rejectUnpairedSurrogates(
|
||||
/**
|
||||
* A Windows absolute path: rooted, UNC, or drive-qualified. The classes spell
|
||||
* backslash and slash as `\x5C` and `\x2F` because `v` mode rejects an
|
||||
* unescaped `/` inside a class, and Windows hosts advertise this pattern.
|
||||
* unescaped `/` inside a class. This also admits every POSIX absolute path,
|
||||
* so it is a portable envelope for catalogs built once and shipped to any host.
|
||||
*/
|
||||
export const windowsAbsolutePathPattern =
|
||||
/^(?:[\x5C\x2F]|[A-Za-z]:[\x5C\x2F])/u;
|
||||
|
||||
/** A caller-selected path that is absolute on the host running REA. */
|
||||
export const absoluteLocalPathStringSchema = localPathStringSchema.regex(
|
||||
HOST_PLATFORM.platform === "win32" ? windowsAbsolutePathPattern : /^\//u,
|
||||
"must be an absolute local filesystem path",
|
||||
);
|
||||
/**
|
||||
* A caller-selected path that is absolute on the host running REA.
|
||||
* Advertise the host-independent envelope: choosing a regex on the build host
|
||||
* bakes that host's rules into the recorded CLI/MCP catalogs. Runtime admission
|
||||
* still uses the executing host's path rules, without serializing that choice.
|
||||
*/
|
||||
export const absoluteLocalPathStringSchema = localPathStringSchema
|
||||
.regex(windowsAbsolutePathPattern, {
|
||||
message: "must be an absolute local filesystem path",
|
||||
abort: true,
|
||||
})
|
||||
.superRefine((value, context) => {
|
||||
if (!isAbsolute(value))
|
||||
context.addIssue({
|
||||
code: "invalid_format",
|
||||
format: "regex",
|
||||
message: "must be an absolute local filesystem path",
|
||||
input: value,
|
||||
});
|
||||
});
|
||||
|
||||
/** Test lexical containment on the host platform; callers must resolve symlinks first. */
|
||||
export const isPathWithinRoot = (root: string, path: string): boolean => {
|
||||
|
||||
@@ -247,7 +247,7 @@ const inputCases = (
|
||||
];
|
||||
};
|
||||
|
||||
it("advertises full host-absolute path constraints after SDK schema conversion", async () => {
|
||||
it("advertises portable absolute-path constraints after SDK schema conversion", async () => {
|
||||
const firmwareCalls: string[] = [];
|
||||
const { client, close } = await createMcp(firmwareCalls, "compact");
|
||||
try {
|
||||
@@ -289,7 +289,8 @@ it("advertises full host-absolute path constraints after SDK schema conversion",
|
||||
for (const { name, field, valid, invalid } of schemaCases) {
|
||||
if (!listed.tools.some((tool) => tool.name === name))
|
||||
throw new Error(`Missing advertised tool ${name}`);
|
||||
// Path rules belong to the canonical input contract.
|
||||
// The canonical projection keeps portable constraints; handlers enforce
|
||||
// the executing host's stricter path rules.
|
||||
const validate = ajv.compile(canonicalInputSchema(name));
|
||||
expect(validate(invalid), `${name}.${field}`).toBe(false);
|
||||
expect(
|
||||
|
||||
@@ -2,16 +2,84 @@ import { withCanonicalOutputSchema } from "../../fixtures/canonicalOutputSchema.
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { expect } from "vitest";
|
||||
import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import type { AnySchema } from "ajv";
|
||||
import type { RecordedMcpCatalog } from "../../../src/recordedMcpCatalog.js";
|
||||
import { toolContract } from "../../../src/contracts/toolContracts.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import {
|
||||
elfHardeningFixture,
|
||||
machoHardeningFixture,
|
||||
peHardeningImage,
|
||||
} from "../../../src/native/hardening/BinaryHardening.fixture.js";
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { mcpTest } from "../../support/mcp/mcpFixture.js";
|
||||
|
||||
mcpTest(
|
||||
"ships a recorded hardening schema that validates Windows and POSIX result paths",
|
||||
async ({ mcp }) => {
|
||||
const catalog: RecordedMcpCatalog = JSON.parse(
|
||||
await readFile("dist/mcp-catalog.json", "utf8"),
|
||||
);
|
||||
const definition = catalog.tools.find(
|
||||
({ name }) => name === "inspect_binary_hardening",
|
||||
);
|
||||
if (definition?.outputSchema === undefined)
|
||||
throw new Error("Missing recorded hardening output schema");
|
||||
const validate = new Ajv2020({
|
||||
strict: false,
|
||||
validateFormats: false,
|
||||
}).compile(definition.outputSchema as AnySchema);
|
||||
const session = createTestBinarySession(() => {
|
||||
throw new Error("Hardening inspection must not acquire a provider");
|
||||
});
|
||||
const client = await mcp.connect(
|
||||
createServer({ kind: "session", session }),
|
||||
);
|
||||
try {
|
||||
const root = await createTestTempDirectory(
|
||||
"rea-portable-hardening-schema-",
|
||||
);
|
||||
const path = join(root, "app.exe");
|
||||
const bytes = peHardeningImage();
|
||||
await writeFile(path, bytes);
|
||||
const response = await client.callTool({
|
||||
name: "inspect_binary_hardening",
|
||||
arguments: { path },
|
||||
});
|
||||
expect(response.isError).not.toBe(true);
|
||||
const evidence = toolContract(
|
||||
"inspect_binary_hardening",
|
||||
).outputSchema.parse(response.structuredContent);
|
||||
expect(validate(evidence), JSON.stringify(validate.errors)).toBe(true);
|
||||
// The producer ran on this host. Only the path is substituted to test the
|
||||
// shipped contract independently; this is not a Windows filesystem run.
|
||||
for (const foreignPath of [
|
||||
"C:\\Windows\\System32\\cmd.exe",
|
||||
"c:/tools/app.exe",
|
||||
"\\\\server\\share\\app.exe",
|
||||
"/opt/tools/app",
|
||||
]) {
|
||||
const projected = structuredClone(evidence);
|
||||
projected.normalized_result.artifact.path = foreignPath;
|
||||
expect(
|
||||
validate(projected),
|
||||
`${foreignPath}: ${JSON.stringify(validate.errors)}`,
|
||||
).toBe(true);
|
||||
}
|
||||
for (const invalid of ["", "relative/app.exe", "C:app.exe", "/tmp/\0"]) {
|
||||
const projected = structuredClone(evidence);
|
||||
projected.normalized_result.artifact.path = invalid;
|
||||
expect(validate(projected), invalid).toBe(false);
|
||||
}
|
||||
expect((await readFile(path)).equals(bytes)).toBe(true);
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
mcpTest(
|
||||
"advertises and reads binary hardening without executing or changing the image",
|
||||
async ({ mcp }) => {
|
||||
|
||||
@@ -385,15 +385,14 @@ describe("module import syntax and source discovery", () => {
|
||||
'import { value } from "../domain/../android/Provider.js";',
|
||||
'const loaded = import("../%61ndroid/Provider.js?view=one#fragment");',
|
||||
])("checks the resolved owner in %s", (source) => {
|
||||
// Only the declared localPath -> HostPlatform import is exempt (see
|
||||
// LAYER_EXCEPTIONS); the same import from another domain file is not.
|
||||
// Host path admission uses node:path without a domain-to-platform exception.
|
||||
expect(
|
||||
inspectModuleBoundaries(
|
||||
"src/domain/localPath.ts",
|
||||
'import { HOST_PLATFORM } from "../platform/HostPlatform.js";',
|
||||
process.cwd(),
|
||||
),
|
||||
).toEqual([]);
|
||||
).toEqual([expect.objectContaining({ boundary: "pure-layer" })]);
|
||||
expect(
|
||||
inspectModuleBoundaries(
|
||||
"src/domain/probe.ts",
|
||||
|
||||
@@ -207,18 +207,18 @@ describe("provider boundaries", () => {
|
||||
).toEqual({ "providers -> ghidra": 1 });
|
||||
});
|
||||
|
||||
it("skips only the exact declared file-to-file exception", () => {
|
||||
it("counts domain-to-platform imports without a local-path exception", () => {
|
||||
expect(
|
||||
layerGraphFacts([
|
||||
edge("src/domain/localPath.ts", "src/platform/HostPlatform.js"),
|
||||
]).upward,
|
||||
).toEqual({});
|
||||
).toEqual({ "domain -> platform": 1 });
|
||||
expect(
|
||||
layerGraphFacts([
|
||||
edge("src/domain/localPath.ts", "src/platform/HostPlatform.js"),
|
||||
edge("src/domain/other.ts", "src/platform/HostPlatform.js"),
|
||||
edge("src/domain/localPath.ts", "src/platform/Other.js"),
|
||||
]).upward,
|
||||
).toEqual({ "domain -> platform": 2 });
|
||||
).toEqual({ "domain -> platform": 3 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
import { posix, win32 } from "node:path";
|
||||
import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import { expect, it, vi } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
const host = vi.hoisted(() => ({ pathStyle: "posix" as "posix" | "win32" }));
|
||||
vi.mock("node:path", async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import("node:path")>();
|
||||
return {
|
||||
...original,
|
||||
isAbsolute: (value: string) => original[host.pathStyle].isAbsolute(value),
|
||||
};
|
||||
});
|
||||
|
||||
import { absoluteLocalPathStringSchema } from "../../src/domain/localPath.js";
|
||||
|
||||
it("keeps the serialized contract fixed while enforcing the executing host's path rules", () => {
|
||||
const paths = [
|
||||
"/absolute/path",
|
||||
"C:\\absolute\\path",
|
||||
"c:/absolute/path",
|
||||
"\\\\server\\share\\path",
|
||||
"\\rooted\\path",
|
||||
"C:relative",
|
||||
"relative/path",
|
||||
"file:///absolute/path",
|
||||
];
|
||||
const serialized = JSON.stringify(
|
||||
z.toJSONSchema(absoluteLocalPathStringSchema),
|
||||
);
|
||||
const validate = new Ajv2020({ strict: false }).compile(
|
||||
JSON.parse(serialized),
|
||||
);
|
||||
for (const pathStyle of ["posix", "win32"] as const) {
|
||||
host.pathStyle = pathStyle;
|
||||
const rules = pathStyle === "posix" ? posix : win32;
|
||||
for (const path of paths) {
|
||||
const parsed = absoluteLocalPathStringSchema.safeParse(path);
|
||||
expect(parsed.success, `${pathStyle}: ${path}`).toBe(
|
||||
rules.isAbsolute(path),
|
||||
);
|
||||
if (!parsed.success)
|
||||
expect(parsed.error.issues).toEqual([
|
||||
expect.objectContaining({ code: "invalid_format", format: "regex" }),
|
||||
]);
|
||||
if (posix.isAbsolute(path) || win32.isAbsolute(path))
|
||||
expect(validate(path), path).toBe(true);
|
||||
}
|
||||
expect(JSON.stringify(z.toJSONSchema(absoluteLocalPathStringSchema))).toBe(
|
||||
serialized,
|
||||
);
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user