Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(ios-simulator): close release validation gaps

JiangJiahao8f612ec7131d
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-release-gate.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-release-gate.test.ts
index b3cb59db91..82a21e0e09 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-release-gate.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-release-gate.test.ts
@@ -5,6 +5,7 @@ import type {
IOSSimulatorSidecarArtifactDescriptor,
} from '@cindy/ios-simulator-runtime';
import {
+ finalizeIOSSimulatorReleaseGateProbe,
parseIOSSimulatorReleaseGateArgs,
runIOSSimulatorReleaseGate,
type IOSSimulatorReleaseGateDependencies,
@@ -76,6 +77,43 @@ function dependencies(
}
describe('packaged iOS Simulator release gate', () => {
+ it.each([0, 1, 2])(
+ 'fails a successful native probe when cleanup step %i fails and still runs later cleanup',
+ async (failingStep) => {
+ const cleanup = [0, 1, 2].map((index) =>
+ vi.fn(async () => {
+ if (index === failingStep) throw new Error(`cleanup-${index}`);
+ }),
+ );
+
+ await expect(finalizeIOSSimulatorReleaseGateProbe(true, cleanup)).rejects.toMatchObject({
+ message: 'IOS_SIMULATOR_RELEASE_CLEANUP_FAILED',
+ cause: expect.objectContaining({ message: `cleanup-${failingStep}` }),
+ });
+ expect(cleanup.every((step) => step.mock.calls.length === 1)).toBe(true);
+ },
+ );
+
+ it('preserves the original probe failure while still attempting every cleanup step', async () => {
+ const probeError = new Error('IOS_SIMULATOR_RELEASE_H264_INVALID');
+ const cleanup = [0, 1, 2].map((index) =>
+ vi.fn(async () => {
+ throw new Error(`cleanup-${index}`);
+ }),
+ );
+ const probe = (async () => {
+ let probeSucceeded = false;
+ try {
+ throw probeError;
+ } finally {
+ await finalizeIOSSimulatorReleaseGateProbe(probeSucceeded, cleanup);
+ }
+ })();
+
+ await expect(probe).rejects.toBe(probeError);
+ expect(cleanup.every((step) => step.mock.calls.length === 1)).toBe(true);
+ });
+
it('qualifies an exact verified combination without leaking Host paths', async () => {
const deps = dependencies();
const report = await runIOSSimulatorReleaseGate(OPTIONS, deps.value);
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts
index b30e9e5d50..ec70cf6d92 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator.test.ts
@@ -2523,6 +2523,7 @@ describe('iOS Simulator host', () => {
inspectArtifact: vi.fn(async () => ({
artifactId: 'artifact-xcresult',
worktreeRoot: '/tmp/force-quit-xcresult-session',
+ authorizedRoot: '/tmp/force-quit-xcresult-session',
appPath: '/tmp/force-quit-xcresult-session/Demo.app',
bundleId: 'com.example.demo',
createdAt: '2026-08-08T00:00:00.000Z',
@@ -7303,6 +7304,7 @@ describe('iOS Simulator host', () => {
const artifact = {
artifactId: 'artifact-a',
worktreeRoot: '/tmp/session-a',
+ authorizedRoot: '/tmp/session-a',
appPath: '/tmp/session-a/build/Demo.app',
bundleId: 'com.example.demo',
createdAt: '2026-07-23T00:00:00.000Z',
diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator-release-gate.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator-release-gate.ts
index 58951dec58..8c273fe251 100644
--- a/apps/desktop/src/main/mcp-integrations/ios-simulator-release-gate.ts
+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator-release-gate.ts
@@ -129,6 +129,28 @@ function sameArtifact(
);
}
+/** @internal Exported only so cleanup error precedence stays covered by unit tests. */
+export async function finalizeIOSSimulatorReleaseGateProbe(
+ probeSucceeded: boolean,
+ cleanupSteps: readonly (() => Promise<void>)[],
+): Promise<void> {
+ let firstCleanupError: unknown;
+ let cleanupFailed = false;
+ for (const cleanup of cleanupSteps) {
+ try {
+ await cleanup();
+ } catch (error) {
+ if (!cleanupFailed) firstCleanupError = error;
+ cleanupFailed = true;
+ }
+ }
+ if (probeSucceeded && cleanupFailed) {
+ throw new Error('IOS_SIMULATOR_RELEASE_CLEANUP_FAILED', {
+ cause: firstCleanupError,
+ });
+ }
+}
+
async function runNativeProbe(
input: IOSSimulatorReleaseGateNativeProbeInput,
): Promise<IOSSimulatorReleaseGateNativeResult> {
@@ -146,6 +168,7 @@ async function runNativeProbe(
const lifecycle = createIOSSimulatorSimctlLifecycle();
let simulatorUdid: string | null = null;
+ let probeSucceeded = false;
const manager = new IOSSimulatorNativeSidecarProcessManager({
binaryPath: input.artifact.executablePath,
admissionPolicy: input.resolvePolicy,
@@ -241,6 +264,7 @@ async function runNativeProbe(
throw new Error('IOS_SIMULATOR_RELEASE_RESTART_INCOMPLETE');
}
+ probeSucceeded = true;
return {
h264Frames,
keyFrames,
@@ -249,11 +273,15 @@ async function runNativeProbe(
cleanRestartReady,
};
} finally {
- await manager.stop(input.start.instanceId).catch(() => undefined);
- if (simulatorUdid) {
- await lifecycle.shutdownExact(simulatorUdid).catch(() => undefined);
- await lifecycle.deleteExact(simulatorUdid).catch(() => undefined);
+ const cleanupSteps: Array<() => Promise<void>> = [() => manager.stop(input.start.instanceId)];
+ const cleanupUdid = simulatorUdid;
+ if (cleanupUdid) {
+ cleanupSteps.push(
+ () => lifecycle.shutdownExact(cleanupUdid),
+ () => lifecycle.deleteExact(cleanupUdid),
+ );
}
+ await finalizeIOSSimulatorReleaseGateProbe(probeSucceeded, cleanupSteps);
}
}
diff --git a/packages/ios-simulator-runtime/src/app-lifecycle.test.ts b/packages/ios-simulator-runtime/src/app-lifecycle.test.ts
index 750062778a..f038aabd6c 100644
--- a/packages/ios-simulator-runtime/src/app-lifecycle.test.ts
+++ b/packages/ios-simulator-runtime/src/app-lifecycle.test.ts
@@ -1,4 +1,11 @@
-import { mkdir, mkdtemp, realpath, rm, writeFile } from "node:fs/promises";
+import {
+ mkdir,
+ mkdtemp,
+ realpath,
+ rm,
+ symlink,
+ writeFile,
+} from "node:fs/promises";
import os from "node:os";
import path from "node:path";
@@ -38,6 +45,7 @@ describe("IOSSimulatorAppLifecycle", () => {
expect(artifact).toMatchObject({
bundleId: "com.example.app",
appPath: resolvedAppPath,
+ authorizedRoot: await realpath(root),
});
expect(run).toHaveBeenCalledWith(
"xcrun",
@@ -67,25 +75,26 @@ describe("IOSSimulatorAppLifecycle", () => {
});
it("reports cancellation when a simctl app operation is aborted", async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-ios-cancel-"));
+ roots.push(root);
+ const appPath = path.join(root, "Demo.app");
+ await mkdir(appPath);
+ await writeFile(path.join(appPath, "Info.plist"), "plist");
const controller = new AbortController();
- const run = vi.fn(async () => {
- controller.abort();
+ let abortInstall = false;
+ const run = vi.fn(async (command: string) => {
+ if (command === "/usr/bin/plutil") {
+ return { stdout: "com.example.demo\n", stderr: "", exitCode: 0 };
+ }
+ if (abortInstall) controller.abort();
return { stdout: "", stderr: "", exitCode: null };
});
const lifecycle = new IOSSimulatorAppLifecycle({ commandRunner: { run } });
+ const artifact = await lifecycle.inspectArtifact(root, appPath);
+ abortInstall = true;
await expect(
- lifecycle.installExact(
- "EXACT-UDID",
- {
- artifactId: "artifact-a",
- worktreeRoot: "/tmp/worktree",
- appPath: "/tmp/worktree/Demo.app",
- bundleId: "com.example.demo",
- createdAt: "2026-08-08T00:00:00.000Z",
- },
- controller.signal,
- ),
+ lifecycle.installExact("EXACT-UDID", artifact, controller.signal),
).rejects.toMatchObject({ code: "MUTATION_CANCELLED" });
expect(run).toHaveBeenCalledWith(
"xcrun",
@@ -94,6 +103,88 @@ describe("IOSSimulatorAppLifecycle", () => {
);
});
+ it("revalidates and installs an app inside the Host-authorized build root", async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-ios-worktree-"));
+ const buildRoot = await mkdtemp(path.join(os.tmpdir(), "cindy-ios-derived-data-"));
+ roots.push(root, buildRoot);
+ const appPath = path.join(buildRoot, "Build", "Demo.app");
+ await mkdir(appPath, { recursive: true });
+ await writeFile(path.join(appPath, "Info.plist"), "plist");
+ const run = vi.fn(async (command: string) => ({
+ stdout: command === "/usr/bin/plutil" ? "com.example.demo\n" : "",
+ stderr: "",
+ exitCode: 0,
+ }));
+ const lifecycle = new IOSSimulatorAppLifecycle({ commandRunner: { run } });
+ const artifact = await lifecycle.inspectArtifact(root, appPath, buildRoot);
+
+ await lifecycle.installExact("EXACT-UDID", artifact);
+
+ expect(artifact.authorizedRoot).toBe(await realpath(buildRoot));
+ expect(run.mock.calls.filter(([command]) => command === "/usr/bin/plutil")).toHaveLength(2);
+ expect(run).toHaveBeenCalledWith(
+ "xcrun",
+ ["simctl", "install", "EXACT-UDID", await realpath(appPath)],
+ expect.any(Object),
+ );
+ });
+
+ it("rejects an app whose bundle identity changed after inspection", async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-ios-identity-"));
+ roots.push(root);
+ const appPath = path.join(root, "Demo.app");
+ await mkdir(appPath);
+ await writeFile(path.join(appPath, "Info.plist"), "plist");
+ let bundleId = "com.example.original";
+ const run = vi.fn(async (command: string) => ({
+ stdout: command === "/usr/bin/plutil" ? `${bundleId}\n` : "",
+ stderr: "",
+ exitCode: 0,
+ }));
+ const lifecycle = new IOSSimulatorAppLifecycle({ commandRunner: { run } });
+ const artifact = await lifecycle.inspectArtifact(root, appPath);
+ bundleId = "com.example.replaced";
+
+ await expect(lifecycle.installExact("EXACT-UDID", artifact)).rejects.toMatchObject({
+ code: "APP_ARTIFACT_INVALID",
+ });
+ expect(run).not.toHaveBeenCalledWith(
+ "xcrun",
+ expect.arrayContaining(["simctl", "install"]),
+ expect.anything(),
+ );
+ });
+
+ it("rejects an app path redirected outside its authorized roots after inspection", async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), "cindy-ios-redirect-root-"));
+ const outside = await mkdtemp(path.join(os.tmpdir(), "cindy-ios-redirect-outside-"));
+ roots.push(root, outside);
+ const appPath = path.join(root, "Demo.app");
+ const outsideAppPath = path.join(outside, "Demo.app");
+ await mkdir(appPath);
+ await mkdir(outsideAppPath);
+ await writeFile(path.join(appPath, "Info.plist"), "plist");
+ await writeFile(path.join(outsideAppPath, "Info.plist"), "plist");
+ const run = vi.fn(async (command: string) => ({
+ stdout: command === "/usr/bin/plutil" ? "com.example.demo\n" : "",
+ stderr: "",
+ exitCode: 0,
+ }));
+ const lifecycle = new IOSSimulatorAppLifecycle({ commandRunner: { run } });
+ const artifact = await lifecycle.inspectArtifact(root, appPath);
+ await rm(appPath, { recursive: true });
+ await symlink(outsideAppPath, appPath, process.platform === "win32" ? "junction" : "dir");
+
+ await expect(lifecycle.installExact("EXACT-UDID", artifact)).rejects.toMatchObject({
+ code: "APP_ARTIFACT_INVALID",
+ });
+ expect(run).not.toHaveBeenCalledWith(
+ "xcrun",
+ expect.arrayContaining(["simctl", "install"]),
+ expect.anything(),
+ );
+ });
+
it("rejects app artifacts outside the worktree", async () => {
const root = await mkdtemp(path.join(os.tmpdir(), "cindy-ios-root-"));
const outside = await mkdtemp(path.join(os.tmpdir(), "cindy-ios-outside-"));
diff --git a/packages/ios-simulator-runtime/src/app-lifecycle.ts b/packages/ios-simulator-runtime/src/app-lifecycle.ts
index 9912485cf7..072e8a1da5 100644
--- a/packages/ios-simulator-runtime/src/app-lifecycle.ts
+++ b/packages/ios-simulator-runtime/src/app-lifecycle.ts
@@ -9,6 +9,7 @@ import type { IOSSimulatorCommandRunner } from "./types.js";
export interface IOSSimulatorAppArtifact {
artifactId: string;
worktreeRoot: string;
+ authorizedRoot: string;
appPath: string;
bundleId: string;
createdAt: string;
@@ -51,30 +52,38 @@ export class IOSSimulatorAppLifecycle {
options.commandRunner ?? createNodeIOSSimulatorCommandRunner();
}
- async inspectArtifact(
- worktreeRoot: string,
+ async #inspectArtifactAtAuthorizedRoot(
+ authorizedRoot: string,
appPath: string,
- trustedBuildRoot?: string,
signal?: AbortSignal,
- ): Promise<IOSSimulatorAppArtifact> {
+ ): Promise<{ appPath: string; bundleId: string }> {
throwIfAborted(signal);
- const root = await realpath(worktreeRoot);
- const resolvedApp = await realpath(appPath);
- const resolvedBuildRoot = trustedBuildRoot
- ? await realpath(trustedBuildRoot)
- : null;
+ let resolvedApp: string;
+ try {
+ resolvedApp = await realpath(appPath);
+ } catch {
+ throw new IOSSimulatorInstanceError(
+ "APP_ARTIFACT_INVALID",
+ "The app artifact no longer exists.",
+ );
+ }
if (
- (!isInside(root, resolvedApp) &&
- (!resolvedBuildRoot || !isInside(resolvedBuildRoot, resolvedApp))) ||
+ !path.isAbsolute(authorizedRoot) ||
+ !isInside(authorizedRoot, resolvedApp) ||
path.extname(resolvedApp).toLowerCase() !== ".app"
) {
throw new IOSSimulatorInstanceError(
"APP_ARTIFACT_INVALID",
- "The app artifact must be a .app directory inside the current worktree.",
+ "The app artifact must remain inside its authorized build root.",
);
}
- const info = await stat(resolvedApp);
- if (!info.isDirectory()) {
+ let isDirectory = false;
+ try {
+ isDirectory = (await stat(resolvedApp)).isDirectory();
+ } catch {
+ // Normalize file races into the same fail-closed artifact result.
+ }
+ if (!isDirectory) {
throw new IOSSimulatorInstanceError(
"APP_ARTIFACT_INVALID",
"The app artifact is not a directory.",
@@ -94,10 +103,45 @@ export class IOSSimulatorAppLifecycle {
);
}
return {
- artifactId: randomUUID(),
- worktreeRoot: root,
appPath: resolvedApp,
bundleId: requireBundleId(result.stdout),
+ };
+ }
+
+ async inspectArtifact(
+ worktreeRoot: string,
+ appPath: string,
+ trustedBuildRoot?: string,
+ signal?: AbortSignal,
+ ): Promise<IOSSimulatorAppArtifact> {
+ throwIfAborted(signal);
+ const root = await realpath(worktreeRoot);
+ const resolvedApp = await realpath(appPath);
+ const resolvedBuildRoot = trustedBuildRoot
+ ? await realpath(trustedBuildRoot)
+ : null;
+ const authorizedRoot = isInside(root, resolvedApp)
+ ? root
+ : resolvedBuildRoot && isInside(resolvedBuildRoot, resolvedApp)
+ ? resolvedBuildRoot
+ : null;
+ if (!authorizedRoot) {
+ throw new IOSSimulatorInstanceError(
+ "APP_ARTIFACT_INVALID",
+ "The app artifact must be a .app directory inside the current worktree.",
+ );
+ }
+ const identity = await this.#inspectArtifactAtAuthorizedRoot(
+ authorizedRoot,
+ resolvedApp,
+ signal,
+ );
+ return {
+ artifactId: randomUUID(),
+ worktreeRoot: root,
+ authorizedRoot,
+ appPath: identity.appPath,
+ bundleId: identity.bundleId,
createdAt: new Date().toISOString(),
};
}
@@ -107,10 +151,25 @@ export class IOSSimulatorAppLifecycle {
artifact: IOSSimulatorAppArtifact,
signal?: AbortSignal,
): Promise<void> {
+ throwIfAborted(signal);
+ const revalidated = await this.#inspectArtifactAtAuthorizedRoot(
+ artifact.authorizedRoot,
+ artifact.appPath,
+ signal,
+ );
+ if (
+ revalidated.appPath !== artifact.appPath ||
+ revalidated.bundleId !== artifact.bundleId
+ ) {
+ throw new IOSSimulatorInstanceError(
+ "APP_ARTIFACT_INVALID",
+ "The app artifact changed after it was built.",
+ );
+ }
throwIfAborted(signal);
const result = await this.#runner.run(
"xcrun",
- ["simctl", "install", simulatorUdid, artifact.appPath],
+ ["simctl", "install", simulatorUdid, revalidated.appPath],
{
timeoutMs: 120_000,
signal,