fix: consolidate boundary ownership and cleanup failure paths (#477)
This commit is contained in:
+7
-295
@@ -1,249 +1,10 @@
|
||||
import { constants } from "node:fs";
|
||||
import { createHash } from "node:crypto";
|
||||
import {
|
||||
access,
|
||||
open,
|
||||
readFile,
|
||||
realpath,
|
||||
stat,
|
||||
type FileHandle,
|
||||
} from "node:fs/promises";
|
||||
import { execFile } from "node:child_process";
|
||||
import { extname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { BinaryTargetError } from "./errors.js";
|
||||
import type { BinaryArchitecture, BinaryTarget } from "./binaryTargetTypes.js";
|
||||
import type { BinaryArchitecture } from "./binaryTargetTypes.js";
|
||||
import { err, ok, type Result } from "./result.js";
|
||||
import { zipPackageFormatForPath } from "./zipPackageFormat.js";
|
||||
|
||||
export type { BinaryArchitecture, BinaryTarget } from "./binaryTargetTypes.js";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
/**
|
||||
* Resolve and classify a readable local target before a provider is selected.
|
||||
* FAT Mach-O inputs select only a host-compatible architecture so setup remains
|
||||
* non-interactive; unsupported or ambiguous inputs are returned as typed errors.
|
||||
*/
|
||||
export const parseBinaryTarget = async (
|
||||
input: string,
|
||||
cwd = process.cwd(),
|
||||
hostArchitecture: NodeJS.Architecture = process.arch,
|
||||
targetKind?: BinaryTarget["kind"],
|
||||
): Promise<Result<BinaryTarget, BinaryTargetError>> => {
|
||||
const candidate = isAbsolute(input) ? input : resolve(cwd, input);
|
||||
try {
|
||||
await access(candidate, constants.R_OK);
|
||||
const canonical = await realpath(candidate);
|
||||
const resolved = await resolveAppBundle(canonical);
|
||||
if (!resolved.ok) return err(resolved.error);
|
||||
const path = resolved.value;
|
||||
const handle = await open(path, "r");
|
||||
try {
|
||||
if (!(await handle.stat()).isFile())
|
||||
return err(new BinaryTargetError(path, "target is not a regular file"));
|
||||
if (
|
||||
targetKind === "database" ||
|
||||
(targetKind === undefined && path.toLowerCase().endsWith(".hop"))
|
||||
)
|
||||
return ok({
|
||||
path,
|
||||
sourcePath: canonical,
|
||||
sha256: await sha256Handle(handle),
|
||||
kind: "database",
|
||||
format: "analysis-database",
|
||||
});
|
||||
const artifactFormat = await detectArtifactFormat(path, handle);
|
||||
if (artifactFormat !== undefined) {
|
||||
const identity = {
|
||||
path,
|
||||
sourcePath: canonical,
|
||||
sha256: await sha256Handle(handle),
|
||||
};
|
||||
return isArchiveFormat(artifactFormat)
|
||||
? ok({ ...identity, kind: "archive", format: artifactFormat })
|
||||
: ok({ ...identity, kind: "artifact", format: artifactFormat });
|
||||
}
|
||||
const detected = await readExecutableMetadata(handle, hostArchitecture);
|
||||
if (!detected.ok) return err(new BinaryTargetError(path, detected.error));
|
||||
return ok({
|
||||
path,
|
||||
sourcePath: canonical,
|
||||
sha256: await sha256Handle(handle),
|
||||
kind: "executable",
|
||||
...detected.value,
|
||||
});
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new BinaryTargetError(candidate, "path is not readable", { cause }),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const detectArtifactFormat = async (
|
||||
path: string,
|
||||
handle: FileHandle,
|
||||
): Promise<
|
||||
| Exclude<
|
||||
BinaryTarget["format"],
|
||||
"analysis-database" | "mach-o" | "elf" | "pe"
|
||||
>
|
||||
| undefined
|
||||
> => {
|
||||
const lower = path.toLowerCase();
|
||||
const magic = Buffer.alloc(8);
|
||||
const observed = await handle.read(magic, 0, magic.length, 0);
|
||||
if (
|
||||
observed.bytesRead >= 4 &&
|
||||
magic[0] === 0x50 &&
|
||||
magic[1] === 0x4b &&
|
||||
[0x03, 0x05, 0x07].includes(magic[2] ?? -1) &&
|
||||
[0x04, 0x06, 0x08].includes(magic[3] ?? -1)
|
||||
) {
|
||||
return zipPackageFormatForPath(lower) ?? "zip";
|
||||
}
|
||||
const named = namedArtifactFormat(lower);
|
||||
if (named !== undefined) return named;
|
||||
if (
|
||||
lower.endsWith(".pkg") &&
|
||||
observed.bytesRead >= 4 &&
|
||||
magic.subarray(0, 4).toString("ascii") === "xar!"
|
||||
)
|
||||
return "pkg";
|
||||
if (lower.endsWith(".dmg")) {
|
||||
const size = (await handle.stat()).size;
|
||||
if (size >= 512) {
|
||||
const trailer = Buffer.alloc(4);
|
||||
const read = await handle.read(trailer, 0, trailer.length, size - 512);
|
||||
if (read.bytesRead === 4 && trailer.toString("ascii") === "koly")
|
||||
return "dmg";
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const namedArtifactFormat = (
|
||||
lowerPath: string,
|
||||
): "asar" | "plist" | "source-map" | "javascript" | undefined => {
|
||||
if (lowerPath.endsWith(".asar")) return "asar";
|
||||
if (lowerPath.endsWith(".plist")) return "plist";
|
||||
if (lowerPath.endsWith(".map")) return "source-map";
|
||||
return /\.(?:m?js|cjs)$/u.test(lowerPath) ? "javascript" : undefined;
|
||||
};
|
||||
|
||||
const isArchiveFormat = (
|
||||
format: Exclude<
|
||||
BinaryTarget["format"],
|
||||
"analysis-database" | "mach-o" | "elf" | "pe"
|
||||
>,
|
||||
): format is Extract<BinaryTarget, { kind: "archive" }>["format"] =>
|
||||
["zip", "ipa", "apk", "msix", "appx", "asar", "dmg", "pkg"].includes(format);
|
||||
|
||||
const sha256Handle = async (handle: FileHandle): Promise<string> => {
|
||||
const hash = createHash("sha256");
|
||||
const chunk = Buffer.allocUnsafe(64 * 1024);
|
||||
let position = 0;
|
||||
while (true) {
|
||||
const observed = await handle.read(chunk, 0, chunk.length, position);
|
||||
if (observed.bytesRead === 0) break;
|
||||
hash.update(chunk.subarray(0, observed.bytesRead));
|
||||
position += observed.bytesRead;
|
||||
}
|
||||
return hash.digest("hex");
|
||||
};
|
||||
|
||||
const resolveAppBundle = async (
|
||||
path: string,
|
||||
): Promise<Result<string, BinaryTargetError>> => {
|
||||
const metadata = await stat(path);
|
||||
if (!metadata.isDirectory()) return ok(path);
|
||||
if (extname(path).toLowerCase() !== ".app")
|
||||
return err(new BinaryTargetError(path, "target is not an app or file"));
|
||||
const plistPath = join(path, "Contents", "Info.plist");
|
||||
let name: string;
|
||||
try {
|
||||
const plist = await readFile(plistPath);
|
||||
name =
|
||||
plist.subarray(0, 6).toString("ascii") === "bplist"
|
||||
? await readBinaryPlistExecutable(plistPath)
|
||||
: parseXmlPlistExecutable(plist.toString("utf8"));
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new BinaryTargetError(path, "app has no readable CFBundleExecutable", {
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (!isSafeExecutableName(name))
|
||||
return err(
|
||||
new BinaryTargetError(path, "app has an unsafe CFBundleExecutable"),
|
||||
);
|
||||
const programs = join(path, "Contents", "MacOS");
|
||||
const executable = join(programs, name);
|
||||
try {
|
||||
const [canonicalPrograms, canonicalExecutable] = await Promise.all([
|
||||
realpath(programs),
|
||||
realpath(executable),
|
||||
]);
|
||||
const location = relative(canonicalPrograms, canonicalExecutable);
|
||||
if (
|
||||
location === ".." ||
|
||||
location.startsWith(`..${sep}`) ||
|
||||
isAbsolute(location)
|
||||
)
|
||||
return err(
|
||||
new BinaryTargetError(path, "app program file leaves Contents/MacOS"),
|
||||
);
|
||||
return ok(canonicalExecutable);
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new BinaryTargetError(path, "app program file is missing", { cause }),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const parseXmlPlistExecutable = (plist: string): string => {
|
||||
const match =
|
||||
/<key>\s*CFBundleExecutable\s*<\/key>\s*<string>([^<]+)<\/string>/u.exec(
|
||||
plist,
|
||||
);
|
||||
if (match?.[1] === undefined)
|
||||
throw new Error("CFBundleExecutable is missing");
|
||||
return decodeXml(match[1].trim());
|
||||
};
|
||||
|
||||
const readBinaryPlistExecutable = async (plistPath: string): Promise<string> =>
|
||||
(
|
||||
await execFileAsync("/usr/bin/plutil", [
|
||||
"-extract",
|
||||
"CFBundleExecutable",
|
||||
"raw",
|
||||
"-o",
|
||||
"-",
|
||||
plistPath,
|
||||
])
|
||||
).stdout.trim();
|
||||
|
||||
const isSafeExecutableName = (name: string): boolean =>
|
||||
name.length > 0 &&
|
||||
name !== "." &&
|
||||
name !== ".." &&
|
||||
!name.includes("\0") &&
|
||||
!/[/\\]/u.test(name);
|
||||
|
||||
const decodeXml = (value: string): string =>
|
||||
value
|
||||
.replaceAll("&", "&")
|
||||
.replaceAll("<", "<")
|
||||
.replaceAll(">", ">")
|
||||
.replaceAll(""", '"')
|
||||
.replaceAll("'", "'");
|
||||
|
||||
type ExecutableMetadata =
|
||||
/** Format and architecture facts recovered from an executable header. */
|
||||
export type ExecutableMetadata =
|
||||
| {
|
||||
readonly format: "mach-o" | "elf";
|
||||
readonly architecture: BinaryArchitecture;
|
||||
@@ -260,58 +21,6 @@ type ExecutableMetadata =
|
||||
readonly managed: boolean;
|
||||
};
|
||||
|
||||
const readExecutableMetadata = async (
|
||||
handle: FileHandle,
|
||||
hostArchitecture: NodeJS.Architecture,
|
||||
): Promise<Result<ExecutableMetadata, string>> => {
|
||||
const prefix = Buffer.alloc(4096);
|
||||
const prefixRead = await handle.read(prefix, 0, prefix.length, 0);
|
||||
const bytes = prefix.subarray(0, prefixRead.bytesRead);
|
||||
if (bytes.length >= 64 && bytes[0] === 0x4d && bytes[1] === 0x5a) {
|
||||
const offset = bytes.readUInt32LE(0x3c);
|
||||
return readPeMetadata(handle, offset);
|
||||
}
|
||||
if (bytes.length >= 8) {
|
||||
const magic = bytes.readUInt32BE(0);
|
||||
if ([0xcafebabf, 0xbfbafeca].includes(magic)) {
|
||||
const little = magic === 0xbfbafeca;
|
||||
const count = little ? bytes.readUInt32LE(4) : bytes.readUInt32BE(4);
|
||||
const required = 8 + count * 32;
|
||||
if (count <= 128 && required > bytes.length) {
|
||||
const header = Buffer.alloc(required);
|
||||
const headerRead = await handle.read(header, 0, header.length, 0);
|
||||
return parseExecutableHeader(
|
||||
header.subarray(0, headerRead.bytesRead),
|
||||
hostArchitecture,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
return parseExecutableHeader(bytes, hostArchitecture);
|
||||
};
|
||||
|
||||
const readPeMetadata = async (
|
||||
handle: FileHandle,
|
||||
offset: number,
|
||||
): Promise<Result<ExecutableMetadata, string>> => {
|
||||
const fileHeader = Buffer.alloc(24);
|
||||
const fileHeaderRead = await handle.read(
|
||||
fileHeader,
|
||||
0,
|
||||
fileHeader.length,
|
||||
offset,
|
||||
);
|
||||
if (fileHeaderRead.bytesRead !== fileHeader.length)
|
||||
return err("invalid or truncated PE header");
|
||||
const optionalHeaderSize = fileHeader.readUInt16LE(20);
|
||||
if (optionalHeaderSize > 4096) return err("invalid PE optional header size");
|
||||
const record = Buffer.alloc(24 + optionalHeaderSize);
|
||||
const recordRead = await handle.read(record, 0, record.length, offset);
|
||||
return recordRead.bytesRead === record.length
|
||||
? parsePeRecord(record)
|
||||
: err("invalid or truncated PE header");
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse supported executable headers without I/O. The caller supplies the host
|
||||
* architecture used for deterministic FAT Mach-O slice selection.
|
||||
@@ -414,7 +123,10 @@ const parsePe = (bytes: Buffer): Result<ExecutableMetadata, string> => {
|
||||
return parsePeRecord(bytes.subarray(offset));
|
||||
};
|
||||
|
||||
const parsePeRecord = (record: Buffer): Result<ExecutableMetadata, string> => {
|
||||
/** Parse a bounded PE signature, COFF record, and optional header without I/O. */
|
||||
export const parsePeRecord = (
|
||||
record: Buffer,
|
||||
): Result<ExecutableMetadata, string> => {
|
||||
if (
|
||||
record.length < 24 ||
|
||||
record.toString("binary", 0, 4) !== "PE\u0000\u0000"
|
||||
|
||||
@@ -380,3 +380,17 @@ export const sanitizeBrowserUrl = (value: string): SanitizedBrowserUrl => {
|
||||
redacted: wasTruncated || hadCredentials || hadFragment || names.length > 0,
|
||||
};
|
||||
};
|
||||
|
||||
/** Remove credentials, fragments, and query values from endpoint candidates. */
|
||||
export const sanitizeEndpointCandidate = (value: string): string => {
|
||||
const bounded = value.slice(0, 4_096);
|
||||
try {
|
||||
const parsed = new URL(bounded, "https://rea.invalid");
|
||||
const sanitized = sanitizeBrowserUrl(parsed.href).url;
|
||||
return parsed.origin === "https://rea.invalid"
|
||||
? sanitized.replace("https://rea.invalid", "")
|
||||
: sanitized;
|
||||
} catch {
|
||||
return bounded.split("#", 1)[0]?.split("?", 1)[0] ?? "";
|
||||
}
|
||||
};
|
||||
|
||||
+2
-15
@@ -190,22 +190,9 @@ export class ProviderSelectionError extends AnalysisError {
|
||||
readonly rejections: readonly ProviderSelectionRejection[];
|
||||
override readonly userMessage: string;
|
||||
|
||||
constructor(input: string | ProviderSelectionErrorOptions) {
|
||||
const legacy = typeof input === "string";
|
||||
const options: ProviderSelectionErrorOptions = legacy
|
||||
? {
|
||||
operation: input,
|
||||
reason: "provider_unavailable",
|
||||
requestedProviderId: "auto",
|
||||
candidateIds: [],
|
||||
}
|
||||
: input;
|
||||
constructor(options: ProviderSelectionErrorOptions) {
|
||||
const operation = options.operation ?? "open_binary";
|
||||
super(
|
||||
legacy
|
||||
? `No configured provider can execute ${operation}`
|
||||
: providerSelectionDiagnostic(options),
|
||||
);
|
||||
super(providerSelectionDiagnostic(options));
|
||||
this.operation = operation;
|
||||
this.reason = options.reason;
|
||||
this.requestedProviderId = options.requestedProviderId;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { isAbsolute, relative } from "node:path";
|
||||
import { isAbsolute } from "node:path";
|
||||
|
||||
import { isPathWithinRoot } from "./localPath.js";
|
||||
import canonicalize from "canonicalize";
|
||||
import { z } from "zod";
|
||||
|
||||
@@ -33,7 +34,7 @@ export const parseActiveElectronCapture = (
|
||||
.parse(evidence.parameters);
|
||||
if (
|
||||
result.application.application_path !== parameters.application_path ||
|
||||
!isWithinRoot(
|
||||
!isPathWithinRoot(
|
||||
parameters.application_root,
|
||||
result.application.application_path,
|
||||
)
|
||||
@@ -129,10 +130,3 @@ const digestCanonical = (value: unknown): string => {
|
||||
throw new TypeError("Runtime reconciliation could not canonicalize input");
|
||||
return createHash("sha256").update(encoded).digest("hex");
|
||||
};
|
||||
|
||||
const isWithinRoot = (root: string, path: string): boolean => {
|
||||
const remainder = relative(root, path);
|
||||
return (
|
||||
remainder === "" || (!remainder.startsWith("..") && !isAbsolute(remainder))
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { isAbsolute, relative } from "node:path";
|
||||
import { isAbsolute } from "node:path";
|
||||
|
||||
import { isPathWithinRoot } from "./localPath.js";
|
||||
import canonicalize from "canonicalize";
|
||||
import { z } from "zod";
|
||||
|
||||
@@ -310,7 +311,7 @@ const assertV8RuntimeParameters = (
|
||||
if (
|
||||
(location.kind === "file" &&
|
||||
!parameters.allowed_file_roots.some((root) =>
|
||||
isWithinRoot(root, location.file_path),
|
||||
isPathWithinRoot(root, location.file_path),
|
||||
)) ||
|
||||
(location.kind === "url" &&
|
||||
!parameters.allowed_origins.includes(location.origin)) ||
|
||||
@@ -321,13 +322,6 @@ const assertV8RuntimeParameters = (
|
||||
);
|
||||
};
|
||||
|
||||
const isWithinRoot = (root: string, path: string): boolean => {
|
||||
const remainder = relative(root, path);
|
||||
return (
|
||||
remainder === "" || (!remainder.startsWith("..") && !isAbsolute(remainder))
|
||||
);
|
||||
};
|
||||
|
||||
const normalizeV8Inspection = (
|
||||
result: JavaScriptRuntimeObservation,
|
||||
): NormalizedV8Inspection => ({
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { isAbsolute, posix, relative } from "node:path";
|
||||
import { posix, relative } from "node:path";
|
||||
|
||||
import { isPathWithinRoot } from "./localPath.js";
|
||||
import {
|
||||
compareCodePoints,
|
||||
type ApplicationNode,
|
||||
@@ -210,8 +211,7 @@ const pathBelowRoot = (root: string, value: string): string | null => {
|
||||
const remainder = relative(root, value);
|
||||
if (
|
||||
remainder === "" ||
|
||||
remainder.startsWith("..") ||
|
||||
isAbsolute(remainder) ||
|
||||
!isPathWithinRoot(root, value) ||
|
||||
remainder.includes("\\")
|
||||
)
|
||||
return null;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import * as t from "@babel/types";
|
||||
|
||||
import { sanitizeEndpointCandidate } from "./browserObservation.js";
|
||||
import {
|
||||
addBoundedFinding,
|
||||
addLocatedFinding,
|
||||
@@ -14,7 +15,6 @@ import {
|
||||
propertyName,
|
||||
range,
|
||||
rangeForOffsets,
|
||||
sanitizeCandidate,
|
||||
sourceSlice,
|
||||
staticPath,
|
||||
staticPathResolutionContext,
|
||||
@@ -264,7 +264,7 @@ const addEndpoint = (context: FindingContext, input: EndpointInput): void =>
|
||||
node: input.node,
|
||||
value: {
|
||||
kind: input.kind,
|
||||
value: sanitizeCandidate(input.value),
|
||||
value: sanitizeEndpointCandidate(input.value),
|
||||
mechanism: input.mechanism,
|
||||
module_key: null,
|
||||
location: range(input.node),
|
||||
|
||||
@@ -3,7 +3,6 @@ import { posix } from "node:path";
|
||||
|
||||
import * as t from "@babel/types";
|
||||
|
||||
import { sanitizeBrowserUrl } from "./browserObservation.js";
|
||||
import type {
|
||||
JavaScriptBundlerRegistration,
|
||||
JavaScriptSourceRange,
|
||||
@@ -411,20 +410,6 @@ export const detectVendors = (source: string): string[] =>
|
||||
patterns.some((pattern) => source.includes(pattern)) ? [name] : [],
|
||||
);
|
||||
|
||||
/** Remove credentials, fragments, and query values from endpoint candidates. */
|
||||
export const sanitizeCandidate = (value: string): string => {
|
||||
const bounded = value.slice(0, 4_096);
|
||||
try {
|
||||
const parsed = new URL(bounded, "https://rea.invalid");
|
||||
const sanitized = sanitizeBrowserUrl(parsed.href).url;
|
||||
return parsed.origin === "https://rea.invalid"
|
||||
? sanitized.replace("https://rea.invalid", "")
|
||||
: sanitized;
|
||||
} catch {
|
||||
return bounded.split("#", 1)[0]?.split("?", 1)[0] ?? "";
|
||||
}
|
||||
};
|
||||
|
||||
/** Commit the static semantic content used to deduplicate registrations. */
|
||||
export const registrationKey = (
|
||||
registration: JavaScriptBundlerRegistration,
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import { isAbsolute, relative, sep } from "node:path";
|
||||
|
||||
/** Test lexical containment on the host platform; callers must resolve symlinks first. */
|
||||
export const isPathWithinRoot = (root: string, path: string): boolean => {
|
||||
const value = relative(root, path);
|
||||
return (
|
||||
value === "" ||
|
||||
(value !== ".." && !value.startsWith(`..${sep}`) && !isAbsolute(value))
|
||||
);
|
||||
};
|
||||
@@ -2,26 +2,30 @@ import { isAbsolute, relative, resolve, sep } from "node:path";
|
||||
|
||||
import { err, ok, type Result } from "./result.js";
|
||||
|
||||
/** Local capabilities governed by the shared REA permission policy. */
|
||||
export type PermissionCapability =
|
||||
| "process_capture"
|
||||
| "browser_observe"
|
||||
| "browser_automate"
|
||||
| "electron_observe"
|
||||
| "electron_automate"
|
||||
| "v8_inspector_observe"
|
||||
| "evidence_read"
|
||||
| "evidence_write"
|
||||
| "investigation_input"
|
||||
| "investigation_workspace_read"
|
||||
| "investigation_workspace_write"
|
||||
| "snapshot_read"
|
||||
| "snapshot_write"
|
||||
| "artifact_extract"
|
||||
| "native_mount"
|
||||
| "reference_read"
|
||||
| "javascript_replay"
|
||||
| "managed_runtime";
|
||||
/** Canonical local capabilities governed by the shared REA permission policy. */
|
||||
export const PERMISSION_CAPABILITIES = [
|
||||
"process_capture",
|
||||
"browser_observe",
|
||||
"browser_automate",
|
||||
"electron_observe",
|
||||
"electron_automate",
|
||||
"v8_inspector_observe",
|
||||
"evidence_read",
|
||||
"evidence_write",
|
||||
"investigation_input",
|
||||
"investigation_workspace_read",
|
||||
"investigation_workspace_write",
|
||||
"snapshot_read",
|
||||
"snapshot_write",
|
||||
"artifact_extract",
|
||||
"native_mount",
|
||||
"reference_read",
|
||||
"javascript_replay",
|
||||
"managed_runtime",
|
||||
] as const;
|
||||
|
||||
/** One capability from the canonical local permission inventory. */
|
||||
export type PermissionCapability = (typeof PERMISSION_CAPABILITIES)[number];
|
||||
|
||||
/** Ordered network authority; each mode includes the modes before it. */
|
||||
type PermissionNetwork = "none" | "loopback" | "external";
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { resolve } from "node:path";
|
||||
import { isPathWithinRoot } from "./localPath.js";
|
||||
import canonicalize from "canonicalize";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
@@ -451,12 +451,6 @@ export type ProcessPolicyDecision =
|
||||
| "filesystem root is outside approved roots";
|
||||
};
|
||||
|
||||
const isWithin = (candidate: string, root: string): boolean =>
|
||||
resolve(candidate) === resolve(root) ||
|
||||
resolve(candidate).startsWith(
|
||||
`${resolve(root)}${resolve(root).endsWith("/") ? "" : "/"}`,
|
||||
);
|
||||
|
||||
/** Evaluate scenario authority before any process or filesystem side effect occurs. */
|
||||
export const authorizeProcessScenario = (
|
||||
scenario: ProcessScenario,
|
||||
@@ -470,13 +464,15 @@ export const authorizeProcessScenario = (
|
||||
reason: "host network access is not approved by operator policy",
|
||||
};
|
||||
if (
|
||||
!policy.executableRoots.some((root) => isWithin(scenario.executable, root))
|
||||
!policy.executableRoots.some((root) =>
|
||||
isPathWithinRoot(root, scenario.executable),
|
||||
)
|
||||
) {
|
||||
return { allowed: false, reason: "executable is outside approved roots" };
|
||||
}
|
||||
if (
|
||||
!policy.workingRoots.some((root) =>
|
||||
isWithin(scenario.working_directory, root),
|
||||
isPathWithinRoot(root, scenario.working_directory),
|
||||
)
|
||||
) {
|
||||
return {
|
||||
@@ -498,7 +494,8 @@ export const authorizeProcessScenario = (
|
||||
}
|
||||
if (
|
||||
scenario.filesystem_roots.some(
|
||||
(path) => !policy.workingRoots.some((root) => isWithin(path, root)),
|
||||
(path) =>
|
||||
!policy.workingRoots.some((root) => isPathWithinRoot(root, path)),
|
||||
)
|
||||
) {
|
||||
return {
|
||||
|
||||
@@ -100,6 +100,33 @@ const graphInput = (): HistoricalSourceGraphInput => ({
|
||||
});
|
||||
|
||||
describe("historical source graph", () => {
|
||||
it("validates supplementary paths and derived indexes by code point", () => {
|
||||
const paths = ["a", "aa", "\uE000", "\u{10000}"];
|
||||
const input: HistoricalSourceGraphInput = {
|
||||
...graphInput(),
|
||||
entries: paths.map((path) =>
|
||||
fileEntry({
|
||||
path,
|
||||
language: path,
|
||||
classifications: ["manifest"],
|
||||
}),
|
||||
),
|
||||
relationships: [],
|
||||
languages: paths,
|
||||
manifests: paths,
|
||||
};
|
||||
const graph = createHistoricalSourceGraph(input);
|
||||
expect(parseHistoricalSourceGraph(graph)).toEqual(graph);
|
||||
expect(() =>
|
||||
createHistoricalSourceGraph({
|
||||
...input,
|
||||
entries: [...input.entries].sort((left, right) =>
|
||||
left.path < right.path ? -1 : left.path > right.path ? 1 : 0,
|
||||
),
|
||||
}),
|
||||
).toThrow(/Unicode code point/u);
|
||||
});
|
||||
|
||||
it("builds and verifies internal root and manifest commitments", () => {
|
||||
const graph = createHistoricalSourceGraph(graphInput());
|
||||
const first = createHistoricalSourceManifest(graph);
|
||||
|
||||
@@ -4,6 +4,7 @@ import { posix } from "node:path";
|
||||
import canonicalize from "canonicalize";
|
||||
import { z } from "zod";
|
||||
|
||||
import { compareUnicodeCodePoints } from "./unicodeCodePointOrder.js";
|
||||
const MAX_PATH = 4_096;
|
||||
const digestSchema = z.string().regex(/^[a-f0-9]{64}$/u);
|
||||
const boundedTextSchema = z.string().min(1).max(1_024);
|
||||
@@ -240,16 +241,16 @@ const relationshipKey = (
|
||||
): string =>
|
||||
`${relationship.from_path}\u0000${relationship.to}\u0000${relationship.kind}\u0000${relationship.resolution}\u0000${relationship.parse_state}`;
|
||||
|
||||
const compareCodePoints = (left: string, right: string): number =>
|
||||
left < right ? -1 : left > right ? 1 : 0;
|
||||
|
||||
const checkSortedUnique = (
|
||||
values: readonly string[],
|
||||
field: string,
|
||||
context: z.RefinementCtx,
|
||||
): void => {
|
||||
for (let index = 1; index < values.length; index += 1)
|
||||
if (compareCodePoints(values[index - 1] ?? "", values[index] ?? "") >= 0) {
|
||||
if (
|
||||
compareUnicodeCodePoints(values[index - 1] ?? "", values[index] ?? "") >=
|
||||
0
|
||||
) {
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: `${field} must be sorted and unique by Unicode code point`,
|
||||
@@ -270,7 +271,7 @@ const expectedLanguages = (
|
||||
: [],
|
||||
),
|
||||
),
|
||||
].sort(compareCodePoints);
|
||||
].sort(compareUnicodeCodePoints);
|
||||
|
||||
const expectedManifests = (
|
||||
entries: readonly z.infer<typeof sourceEntrySchema>[],
|
||||
@@ -281,7 +282,7 @@ const expectedManifests = (
|
||||
? [entry.path]
|
||||
: [],
|
||||
)
|
||||
.sort(compareCodePoints);
|
||||
.sort(compareUnicodeCodePoints);
|
||||
|
||||
type GraphStructure = z.infer<typeof historicalSourceGraphStructureSchema>;
|
||||
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
/** Compare strings lexicographically by Unicode code point, independent of locale. */
|
||||
export const compareUnicodeCodePoints = (
|
||||
left: string,
|
||||
right: string,
|
||||
): number => {
|
||||
const leftPoints = [...left].map((value) => value.codePointAt(0) ?? 0);
|
||||
const rightPoints = [...right].map((value) => value.codePointAt(0) ?? 0);
|
||||
const length = Math.min(leftPoints.length, rightPoints.length);
|
||||
for (let index = 0; index < length; index += 1) {
|
||||
const difference = (leftPoints[index] ?? 0) - (rightPoints[index] ?? 0);
|
||||
if (difference !== 0) return difference;
|
||||
}
|
||||
return leftPoints.length - rightPoints.length;
|
||||
};
|
||||
@@ -58,19 +58,6 @@ export const resolveSpecifier = (
|
||||
}
|
||||
};
|
||||
|
||||
export const sanitizeCandidate = (value: string): string => {
|
||||
const bounded = value.slice(0, 4_096);
|
||||
try {
|
||||
const parsed = new URL(bounded, "https://rea.invalid");
|
||||
const sanitized = sanitizeBrowserUrl(parsed.href).url;
|
||||
return parsed.origin === "https://rea.invalid"
|
||||
? sanitized.replace("https://rea.invalid", "")
|
||||
: sanitized;
|
||||
} catch {
|
||||
return bounded.split("#", 1)[0]?.split("?", 1)[0] ?? "";
|
||||
}
|
||||
};
|
||||
|
||||
export const location = (scriptKey: string, node: t.Node) => ({
|
||||
script_key: scriptKey,
|
||||
...locationFields(node),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { parse } from "@babel/parser";
|
||||
import * as t from "@babel/types";
|
||||
|
||||
import { sanitizeEndpointCandidate } from "./browserObservation.js";
|
||||
import type { WebPageInspection } from "./browserObservation.js";
|
||||
import type {
|
||||
AnalyzeWebBundleInput,
|
||||
@@ -15,7 +16,6 @@ import {
|
||||
objectValue,
|
||||
propertyName,
|
||||
resolveSpecifier,
|
||||
sanitizeCandidate,
|
||||
stringArgument,
|
||||
} from "./webBundleAnalyzerAst.js";
|
||||
|
||||
@@ -242,7 +242,7 @@ interface AddFindingContext {
|
||||
}
|
||||
|
||||
const addFinding = (context: AddFindingContext): void => {
|
||||
const value = sanitizeCandidate(context.rawValue);
|
||||
const value = sanitizeEndpointCandidate(context.rawValue);
|
||||
const key = `finding\0${context.mechanism}\0${context.script.script_key}\0${value}`;
|
||||
addBounded(context.accumulator, key, context.maximumFindings, () =>
|
||||
context.collection.push({
|
||||
|
||||
@@ -1,6 +1,15 @@
|
||||
/** ZIP-backed application package families that share the hardened archive reader. */
|
||||
export type ZipPackageFormat = "zip" | "ipa" | "apk" | "msix" | "appx";
|
||||
|
||||
/** Recognize local-header, empty-archive, or split-archive ZIP signatures, not archive validity. */
|
||||
export const hasZipSignature = (bytes: Uint8Array): boolean =>
|
||||
bytes.length >= 4 &&
|
||||
bytes[0] === 0x50 &&
|
||||
bytes[1] === 0x4b &&
|
||||
((bytes[2] === 0x03 && bytes[3] === 0x04) ||
|
||||
(bytes[2] === 0x05 && bytes[3] === 0x06) ||
|
||||
(bytes[2] === 0x07 && bytes[3] === 0x08));
|
||||
|
||||
/**
|
||||
* Classify a ZIP-backed package by its complete lower-cased path suffix.
|
||||
*
|
||||
|
||||
Reference in New Issue
Block a user