refactor(native): bound nested path checks and verify real ticket coverage

This commit is contained in:
morluto
2026-10-08 19:35:56 +08:00
parent 670b657d0e
commit 38e2a342d1
6 changed files with 162 additions and 87 deletions
+7
View File
@@ -105,6 +105,13 @@ flags. It checks that `inspect-signature` decodes those flags and derives the
expected security facets. It also checks a platform binary, which must report a
platform identifier and pass the `anchor apple` origin check, and bundles with an added unsealed file, at the top level
and inside a nested XPC service, which must fail deep strict verification. CLI and stdio MCP results must match.
The default lane explicitly reports real stapled-ticket coverage as unverified:
its source-built ad hoc fixtures cannot receive genuine Apple notarization tickets.
To verify ticket producer output through CLI and MCP, supply an existing stapled app:
`npm run verify:code-signature -- --stapled-app "/Applications/Firefox.app"`.
This optional subcase preflights `xcrun stapler`, validates the selected app with
Apple's tool, and checks that both REA surfaces return the same ticket digest and
`present` framing observation. It does not install an app or submit anything for notarization.
`verify:macos-bundle` needs only macOS with Command Line Tools. It compiles a
source-owned app with `clang`: a versioned framework, XPC services, an app
extension, a login item, a privileged helper, launchd plists, and a helper tool,
+49
View File
@@ -24,6 +24,20 @@ import {
const exec = promisify(execFile);
const args = process.argv.slice(2);
if (args.length !== 0 && (args.length !== 2 || args[0] !== "--stapled-app"))
throw new Error("Usage: verify:code-signature [--stapled-app PATH]");
const stapledApp = args[1];
if (stapledApp !== undefined) {
try {
await exec("/usr/bin/xcrun", ["--find", "stapler"]);
} catch (cause) {
throw new Error("Real stapled-ticket verification requires xcrun stapler", {
cause,
});
}
}
await preflightMacosBundleFixture();
const root = await mkdtemp(join(tmpdir(), "rea-code-signature-"));
@@ -59,6 +73,40 @@ const ENTITLEMENTS = `<?xml version="1.0" encoding="UTF-8"?>
try {
const { app } = await buildMacosBundleFixture(root);
let realTicket = {
status: "unverified",
reason:
"No known stapled app supplied; use --stapled-app PATH to exercise producer output.",
};
if (stapledApp !== undefined) {
const appPath = await realpath(stapledApp);
const oracle = await exec("/usr/bin/xcrun", [
"stapler",
"validate",
appPath,
]);
const observed = await artifactCli("inspect-signature", appPath);
assert.equal(
observed.stapled_ticket.status,
"present",
JSON.stringify(observed.stapled_ticket),
);
assert.equal(observed.stapled_ticket.reason, null);
assert.match(observed.stapled_ticket.sha256, /^[a-f0-9]{64}$/u);
await withArtifactMcp(appPath, async (client) => {
const viaMcp = await artifactMcpResult(client, "inspect_signature");
assert.deepEqual(viaMcp.stapled_ticket, observed.stapled_ticket);
});
realTicket = {
status: "verified",
selected_app: stapledApp,
ticket_sha256: observed.stapled_ticket.sha256,
size: observed.stapled_ticket.size,
oracle: "xcrun stapler validate",
stdout: oracle.stdout,
stderr: oracle.stderr,
};
}
const plain = await artifactCli("inspect-signature", app);
assert.deepEqual(plain.code_directory.flags.names, ["adhoc"]);
assert.equal(plain.verification.status, "valid");
@@ -185,6 +233,7 @@ try {
platform_identifier: platform.code_directory.platform_identifier,
tampered_verification: tampered.verification.status,
nested_tamper_verification: nestedTamper.verification.status,
real_stapled_ticket: realTicket,
})}\n`,
);
} finally {
+27
View File
@@ -0,0 +1,27 @@
import { expect, it } from "vitest";
import { unconfirmedNestedCode } from "./NativeNestedCode.js";
it("observes cancellation between nested filesystem lookups", async () => {
const controller = new AbortController();
const paths: string[] = [];
await expect(
unconfirmedNestedCode(
{
path: "/app",
status: "valid",
exit_code: 0,
diagnostics: [],
validated_nested_code: ["/app/first", "/app/second"],
},
controller.signal,
{
lookup: async (path) => {
paths.push(path);
controller.abort();
},
names: async () => [],
},
),
).rejects.toMatchObject({ name: "AbortError" });
expect(paths).toEqual(["/app/first"]);
});
+75
View File
@@ -0,0 +1,75 @@
import { lstat, readdir } from "node:fs/promises";
import { dirname } from "node:path";
import type { InspectSignature } from "../domain/native/nativeInspection.js";
/** Filesystem seam for path-completeness checks and cancellation regressions. */
export interface NativeNestedPathView {
lookup(path: string): Promise<void>;
names(directory: string): Promise<string[]>;
}
const FILE_SYSTEM: NativeNestedPathView = {
lookup: async (path) => {
await lstat(path);
},
names: (path) => readdir(path),
};
const errorCode = (cause: unknown) =>
cause instanceof Error && "code" in cause ? cause.code : undefined;
/** Preserve reported paths, but qualify missing, denied or newline-ambiguous records. */
export const unconfirmedNestedCode = async (
verification: NonNullable<InspectSignature["verification"]>,
signal?: AbortSignal,
view: NativeNestedPathView = FILE_SYSTEM,
): Promise<string[]> => {
signal?.throwIfAborted();
const limitations: string[] = [];
const directories = new Map<string, Promise<boolean>>();
for (const path of verification.validated_nested_code) {
signal?.throwIfAborted();
try {
await view.lookup(path);
} catch (cause: unknown) {
signal?.throwIfAborted();
const code = errorCode(cause);
if (code === "EACCES" || code === "EPERM") {
limitations.push(
`Could not confirm completeness of codesign nested path ${JSON.stringify(path)}: permission denied (${code}); the reported path may be a fragment.`,
);
continue;
}
if (code !== "ENOENT" && code !== "ENOTDIR") throw cause;
limitations.push(
`codesign reported validated nested code at ${JSON.stringify(path)}, which does not exist; a nested path probably contains a newline, so validated_nested_code and diagnostics hold fragments of it.`,
);
continue;
}
signal?.throwIfAborted();
const parent = dirname(path);
let names = directories.get(parent);
if (names === undefined) {
names = view
.names(parent)
.then((entries) => entries.some((name) => name.includes("\n")));
directories.set(parent, names);
}
try {
const ambiguous = await names;
signal?.throwIfAborted();
if (ambiguous)
limitations.push(
`codesign reported validated nested code at ${JSON.stringify(path)}, which exists but could be the first line of a nested path containing a newline; validated_nested_code is ambiguous and should not be trusted as complete.`,
);
} catch (cause: unknown) {
signal?.throwIfAborted();
if (!(cause instanceof Error) || !("code" in cause)) throw cause;
limitations.push(
`Could not confirm completeness of codesign nested path ${JSON.stringify(path)} from parent directory ${JSON.stringify(parent)}: ${cause.message}`,
);
}
}
signal?.throwIfAborted();
return limitations;
};
+2 -2
View File
@@ -32,8 +32,8 @@ import {
SIGNATURE_POSTURE_LIMITATIONS,
signedCodePath,
stapledTicket,
unconfirmedNestedCode,
} from "./NativeSignaturePosture.js";
import { unconfirmedNestedCode } from "./NativeNestedCode.js";
interface SignatureDisplays {
readonly display: NativeCommandCapture;
@@ -143,7 +143,7 @@ export const inspectNativeSignature = async (options: {
...parsed.limitations,
...SIGNATURE_POSTURE_LIMITATIONS,
...slices.value.limitations,
...(await unconfirmedNestedCode(verification)),
...(await unconfirmedNestedCode(verification, signal)),
];
if (entitlementValue.omittedPrototypeKeys !== 0)
limitations.push(
+2 -85
View File
@@ -1,7 +1,7 @@
import { createHash } from "node:crypto";
import { constants } from "node:fs";
import { lstat, open, readdir } from "node:fs/promises";
import { dirname, join } from "node:path";
import { lstat, open } from "node:fs/promises";
import { join } from "node:path";
import type { InspectSignature } from "../domain/native/nativeInspection.js";
import { ticketStructureIssue } from "./NotarizationTicket.js";
@@ -238,86 +238,3 @@ export const SIGNATURE_POSTURE_LIMITATIONS = [
"Security facets are derived from CodeDirectory flags and entitlements; runtime policy such as System Integrity Protection, AMFI, and setuid bits can further restrict a process.",
"Ticket presence requires recognized local s8ch/g8tk container and DER framing; certificate authenticity, ticket signature validity, and ticket-to-code binding are not verified.",
];
/**
* codesign prints one nested path per line, so a path that contains a newline
* is split into fragments. A reported path that does not exist on disk is
* named in a limitation instead of being trusted as complete. An existing
* reported path is still ambiguous when it could be the first line of a
* longer newline-containing path: either a diagnostic fragment completes it,
* or its parent directory holds an entry with an embedded newline.
*/
export const unconfirmedNestedCode = async (
verification: NonNullable<InspectSignature["verification"]>,
): Promise<string[]> => {
const missing: string[] = [];
const ambiguous: string[] = [];
const denied: string[] = [];
for (const validatedPath of verification.validated_nested_code) {
try {
await lstat(validatedPath);
} catch (cause: unknown) {
const code = errorCode(cause);
// A denied lookup cannot confirm the path, but is no sign of a split one.
if (code === "EACCES" || code === "EPERM") {
denied.push(
`Could not confirm completeness of codesign nested path ${JSON.stringify(validatedPath)}: permission denied (${code}); the reported path may be a fragment.`,
);
continue;
}
if (code !== "ENOENT" && code !== "ENOTDIR") throw cause;
missing.push(validatedPath);
continue;
}
if (await isNewlineFragment(validatedPath, verification.diagnostics)) {
ambiguous.push(validatedPath);
}
}
return [
...denied,
...missing.map(
(path) =>
`codesign reported validated nested code at ${JSON.stringify(path)}, which does not exist; a nested path probably contains a newline, so validated_nested_code and diagnostics hold fragments of it.`,
),
...ambiguous.map(
(path) =>
`codesign reported validated nested code at ${JSON.stringify(path)}, which exists but could be the first line of a nested path containing a newline; validated_nested_code is ambiguous and should not be trusted as complete.`,
),
];
};
/**
* Whether an existing validated path could be a newline-split fragment: a
* diagnostic line completes it to an existing path, or its parent directory
* contains an entry with an embedded newline whose first line matches it.
*/
const isNewlineFragment = async (
validated: string,
diagnostics: readonly string[],
): Promise<boolean> => {
for (const fragment of diagnostics) {
if (fragment.length === 0 || fragment.includes("\n")) continue;
// A continuation line is a bare fragment, not a `key: value` diagnostic.
if (fragment.includes(":") || fragment.includes(" ")) continue;
try {
await lstat(`${validated}\n${fragment}`);
return true;
} catch {
// Not completed by this diagnostic line; check directory entries below.
}
}
try {
const entries = await readdir(dirname(validated));
const base = validated.slice(dirname(validated).length + 1);
for (const entry of entries) {
if (!entry.includes("\n")) continue;
if (entry.split("\n")[0] === base) return true;
// A suffix beginning with `--validated:` can inject a second record;
// any newline entry in the same directory makes each record suspect.
return true;
}
} catch {
return false;
}
return false;
};