Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions scripts/macos-release-trust.d.mts
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,9 @@ export function macReleasePolicy(
env?: Record<string, string | undefined>,
): MacReleasePolicy;
export function assertPublicMacTrust<T>(proof: T): T;
/** Native binaries in the bundled `dist-*` folders, other than Node, to sign for public release. */
export function bundledLibrariesToSign(root: string): Promise<string[]>;
/** Records signed files' fingerprints in their folder's provenance.json, keeping the unsigned ones. */
export function recordSignedFiles(root: string, signed: string[]): Promise<void>;
/** Whether Apple notarized a standalone program; Gatekeeper's app assessment cannot tell. */
export function isNotarizedExecutable(binary: string): boolean;
88 changes: 83 additions & 5 deletions scripts/macos-release-trust.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { execFileSync } from "node:child_process";
import { execFileSync, spawnSync } from "node:child_process";
import { randomBytes, createHash } from "node:crypto";
import {
mkdir,
Expand All @@ -12,7 +12,7 @@ import {
chmod,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { join, relative, sep } from "node:path";

const appleKeys = [
"APPLE_CERTIFICATE",
Expand Down Expand Up @@ -245,6 +245,24 @@ export async function prepareMacSigning(root, inherited = process.env) {
node,
]);
run("/usr/bin/codesign", ["--verify", "--strict", node]);
// Native libraries in the other bundled folders, such as onnxruntime for local
// search, are loaded by that Node. Apple rejects the app while any is unsigned.
const libraries = await bundledLibrariesToSign(root);
for (const library of libraries) {
run("/usr/bin/codesign", [
"--force",
"--timestamp",
"--options",
"runtime",
"--sign",
policy.identity,
"--keychain",
keychain,
library,
]);
run("/usr/bin/codesign", ["--verify", "--strict", library]);
}
await recordSignedFiles(root, libraries);
const signedRuntime = {
originalExecutableSha256: provenance.executableSha256,
signedExecutableSha256: digest(await readFile(node)),
Expand All @@ -258,6 +276,67 @@ export async function prepareMacSigning(root, inherited = process.env) {
}
}

/**
* Whether Apple notarized a standalone program, such as the engine's command-line
* tools. Gatekeeper's app assessment rejects anything that is not an app bundle
* ("does not seem to be an app"), so it cannot answer this; codesign can.
*/
export function isNotarizedExecutable(binary) {
return (
spawnSync(
"/usr/bin/codesign",
["--verify", "--strict", "--test-requirement==notarized", binary],
{ stdio: "ignore" },
).status === 0
);
}

/**
* Writes the fingerprint of each signed file into the provenance.json of the bundled
* folder it is in, keeping the unsigned one, since the app checks those files
* against it before it loads them.
*/
export async function recordSignedFiles(root, signed) {
const byFolder = new Map();
for (const path of signed) {
const [folder, ...rest] = relative(root, path).split(sep);
byFolder.set(folder, [...(byFolder.get(folder) ?? []), rest.join("/")]);
}
for (const [folder, names] of byFolder) {
const manifest = join(root, folder, "provenance.json");
let provenance;
try {
provenance = JSON.parse(await readFile(manifest, "utf8"));
} catch {
continue;
}
if (!Array.isArray(provenance.files)) continue;
for (const entry of provenance.files) {
if (!names.includes(entry.name)) continue;
const bytes = await readFile(join(root, folder, entry.name));
entry.unsignedSha256 ??= entry.sha256;
entry.bytes = bytes.length;
entry.sha256 = digest(bytes);
}
await writeFile(manifest, JSON.stringify(provenance, null, 2) + "\n");
}
}

/**
* The native binaries in the folders packaging copies into the app as resources
* (`dist-*` at the root), other than Node, which is signed with its own entitlement.
*/
export async function bundledLibrariesToSign(root) {
const node = join(root, "dist-desktop-runtime/node");
const folders = (await readdir(root, { withFileTypes: true })).filter(
(entry) => entry.isDirectory() && entry.name.startsWith("dist-"),
);
const found = await Promise.all(
folders.map((folder) => machoFiles(join(root, folder.name))),
);
return found.flat().filter((path) => path !== node);
}

export async function machoFiles(directory) {
const files = [];
for (const entry of await readdir(directory, { withFileTypes: true })) {
Expand Down Expand Up @@ -353,7 +432,6 @@ export async function verifyMacRelease(root, signing) {
try {
run("/usr/bin/ditto", ["-x", "-k", engineArchive, engineTemp]);
const names = ["memtrace", "memcore-server", "memcortex-daemon", "memcortex-mcp"];
const { spawnSync } = await import("node:child_process");
for (const name of names) {
const binary = join(engineTemp, name);
const expected = engineManifest.files.find(file => file.name === name);
Expand All @@ -366,7 +444,8 @@ export async function verifyMacRelease(root, signing) {
const details = display.stdout + display.stderr;
if (display.status !== 0 || !details.includes("Authority=Developer ID Application:") || !details.includes("TeamIdentifier=" + proof.teamId) || !/flags=.*runtime/.test(details))
throw Error("Public Mac distribution requires separately Developer ID signed, hardened and notarized engine executables. This bundled engine has not established that trust; use an explicitly labelled manual-approval beta until a trusted engine release is pinned.");
run("/usr/sbin/spctl", ["--assess", "--type", "execute", "--verbose=4", binary]);
if (!isNotarizedExecutable(binary))
throw Error(`Apple has not notarized the bundled engine program ${name}.`);
}
proof.bundledEngineNativeTrust = { developerIdSigned: true, gatekeeper: "accepted", nativeExecutables: names.length, archiveSha256: engineManifest.sha256 };
} finally {
Expand Down Expand Up @@ -395,7 +474,6 @@ export async function verifyMacRelease(root, signing) {
run("/usr/bin/codesign", ["--verify", "--strict", binary]);
// codesign writes metadata to stderr even on success.
// Collect both streams without printing any content.
const { spawnSync } = await import("node:child_process");
const display = spawnSync(
"/usr/bin/codesign",
["--display", "--verbose=4", binary],
Expand Down
89 changes: 89 additions & 0 deletions tests/macos-release-trust.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,3 +164,92 @@ test("the installer background is genuinely 2x at the configured logical size",
height: 508,
});
});

test("public packaging signs the native libraries bundled beside the app, which Apple otherwise rejects", async () => {
const { mkdtemp, mkdir, writeFile, rm } = await import("node:fs/promises");
const { tmpdir } = await import("node:os");
const { join } = await import("node:path");
const { bundledLibrariesToSign } = await import("../scripts/macos-release-trust.mjs");
const root = await mkdtemp(join(tmpdir(), "memcode-mac-resources-"));
const macho = Buffer.from("cffaedfe0000000000000000", "hex");
const place = async (path: string, bytes: Buffer | string) => {
await mkdir(join(root, path, ".."), { recursive: true });
await writeFile(join(root, path), bytes);
};
try {
const onnx = "dist-retriever-runtime/node_modules/onnxruntime-node/bin/napi-v6/darwin/arm64";
await place(`${onnx}/onnxruntime_binding.node`, macho);
await place(`${onnx}/libonnxruntime.1.23.2.dylib`, macho);
await place("dist-retriever-runtime/node_modules/onnxruntime-node/README.md", "# docs");
// Node is signed on its own, with the JIT entitlement it needs.
await place("dist-desktop-runtime/node", macho);
await place("src-tauri/target/release/memcode", macho);
assert.deepEqual(
(await bundledLibrariesToSign(root)).map((path: string) => path.slice(root.length + 1)).sort(),
[`${onnx}/libonnxruntime.1.23.2.dylib`, `${onnx}/onnxruntime_binding.node`],
);
} finally {
await rm(root, { recursive: true, force: true });
}
});

test("a signed library's new fingerprint is recorded, so the app's own check still accepts it", async () => {
const { mkdtemp, mkdir, writeFile, readFile: read, rm } = await import("node:fs/promises");
const { tmpdir } = await import("node:os");
const { join } = await import("node:path");
const { createHash } = await import("node:crypto");
const { recordSignedFiles } = await import("../scripts/macos-release-trust.mjs");
const sha = (bytes: Buffer | string) => createHash("sha256").update(bytes).digest("hex");
const root = await mkdtemp(join(tmpdir(), "memcode-mac-provenance-"));
const folder = join(root, "dist-retriever-runtime");
const library = "node_modules/onnxruntime-node/bin/napi-v6/darwin/arm64/onnxruntime_binding.node";
try {
await mkdir(join(folder, library, ".."), { recursive: true });
await writeFile(join(folder, library), "signed bytes, longer than before");
await writeFile(
join(folder, "provenance.json"),
JSON.stringify({
schema: 1,
files: [
{ name: library, bytes: 8, sha256: sha("unsigned") },
{ name: "package.json", bytes: 2, sha256: sha("{}") },
],
}),
);
await recordSignedFiles(root, [join(folder, library)]);
const { files } = JSON.parse(await read(join(folder, "provenance.json"), "utf8"));
assert.deepEqual(files[0], {
name: library,
bytes: "signed bytes, longer than before".length,
sha256: sha("signed bytes, longer than before"),
unsignedSha256: sha("unsigned"),
});
assert.deepEqual(files[1], { name: "package.json", bytes: 2, sha256: sha("{}") });
} finally {
await rm(root, { recursive: true, force: true });
}
});

test("a command-line program counts as notarized only when Apple notarized it", { skip: process.platform !== "darwin" }, async () => {
const { mkdtemp, copyFile, rm } = await import("node:fs/promises");
const { existsSync } = await import("node:fs");
const { tmpdir } = await import("node:os");
const { join } = await import("node:path");
const { execFileSync } = await import("node:child_process");
const { isNotarizedExecutable } = await import("../scripts/macos-release-trust.mjs");
const folder = await mkdtemp(join(tmpdir(), "memcode-notarized-"));
try {
const local = join(folder, "echo");
await copyFile("/bin/echo", local);
execFileSync("/usr/bin/codesign", ["--force", "--sign", "-", local], { stdio: "ignore" });
assert.equal(isNotarizedExecutable(local), false);
// The engine packaging staged, Developer ID signed and notarized, when this computer has one.
const engine = new URL("../dist-memtrace-engine/engine.zip", import.meta.url).pathname;
if (existsSync(engine)) {
execFileSync("/usr/bin/ditto", ["-x", "-k", engine, folder]);
assert.equal(isNotarizedExecutable(join(folder, "memtrace")), true);
}
} finally {
await rm(folder, { recursive: true, force: true });
}
});