Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(local-vm): update a desktop whose workspace folders an older desktop owns

AdityaUmale1cd2ae457a6b
diff --git a/server/container-computer.test.ts b/server/container-computer.test.ts
index 2fd2d04e70..09935b90d4 100644
--- a/server/container-computer.test.ts
+++ b/server/container-computer.test.ts
@@ -1274,6 +1274,11 @@ describe("setupCommands", () => {
const script = tail[2];
expect(script.indexOf("find / -xdev"), "files move before /etc/passwd, so an interrupted start resumes")
.toBeLessThan(script.indexOf("sed -i"));
+ // The workspace is a bind mount, which -xdev from / skips: an older desktop's files there must change owner too.
+ for (const step of [`find ${VM_WORKSPACE_GUEST} -xdev -uid "$old_uid" -exec chown -h "$uid" {} +`, `find ${VM_WORKSPACE_GUEST} -xdev -gid "$old_gid" -exec chgrp -h "$gid" {} +`]) {
+ expect(script).toContain(step);
+ expect(script.indexOf(step)).toBeLessThan(script.indexOf("sed -i"));
+ }
expect(script).toMatch(/\|\| \{ echo "cua did not take uid \$uid gid \$gid" >&2; exit 1; \}\nfi\nexec /);
});
diff --git a/server/container-isolation.ts b/server/container-isolation.ts
index b66c4ebb5e..2600835480 100644
--- a/server/container-isolation.ts
+++ b/server/container-isolation.ts
@@ -22,6 +22,10 @@ const GUEST_IDS_SCRIPT = [
"set -eu",
'uid="$1"; gid="$2"; old_uid="$(id -u cua)"; old_gid="$(id -g cua)"',
'if [ "$old_uid:$old_gid" != "$uid:$gid" ]; then',
+ // The bind-mounted workspace is another filesystem, so -xdev from / skips it: an older desktop's files there move too.
+ // Best effort: a share that refuses chown must not keep the desktop from starting.
+ ' [ ! -d /home/cua/workspace ] || find /home/cua/workspace -xdev -uid "$old_uid" -exec chown -h "$uid" {} + || echo "some workspace files kept uid $old_uid" >&2',
+ ' [ ! -d /home/cua/workspace ] || find /home/cua/workspace -xdev -gid "$old_gid" -exec chgrp -h "$gid" {} + || echo "some workspace files kept gid $old_gid" >&2',
' find / -xdev -uid "$old_uid" -exec chown -h "$uid" {} +',
' find / -xdev -gid "$old_gid" -exec chgrp -h "$gid" {} +',
' sed -i "s/^cua:x:$old_uid:$old_gid:/cua:x:$uid:$gid:/" /etc/passwd',
diff --git a/server/local-vm-browser-profiles.test.ts b/server/local-vm-browser-profiles.test.ts
index 3208310574..44072a3e12 100644
--- a/server/local-vm-browser-profiles.test.ts
+++ b/server/local-vm-browser-profiles.test.ts
@@ -7,7 +7,7 @@ import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { VM_WORKSPACE_GUEST, managedImageDockerfile, type LocalVmTarget } from "./container-computer.ts";
-import { rescueFirefoxProfile, rescueInstalledApps } from "./local-vm-profiles.ts";
+import { keepFirefoxProfileBeforeRemove, rescueFirefoxProfile, rescueInstalledApps } from "./local-vm-profiles.ts";
const temporary: string[] = [];
afterEach(() => {
@@ -182,9 +182,10 @@ describe.skipIf(process.platform === "win32")("rescueFirefoxProfile", () => {
expect(await rescueFirefoxProfile(runtime, target(workspace))).toBe("rescued");
expect(readFileSync(join(workspace, ".browser-profiles", "mozilla", "firefox", "abc.default-esr", "cookies.sqlite"), "utf8")).toBe("signed in");
const [copy] = readFileSync(log, "utf8").trim().split("\n");
- expect(copy).toMatch(/^cp openmausbot-computer-x:\/home\/cua\/\.mozilla \S+\/\.browser-profiles\/\.mozilla-rescue-[0-9a-f]+$/);
- expect(copy.startsWith(`cp openmausbot-computer-x:/home/cua/.mozilla ${join(workspace, ".browser-profiles")}/`)).toBe(true);
+ expect(copy).toMatch(/^cp openmausbot-computer-x:\/home\/cua\/\.mozilla \S+\/\.mozilla-rescue-[0-9a-f]+$/);
+ expect(copy.startsWith(`cp openmausbot-computer-x:/home/cua/.mozilla ${workspace}/.mozilla-rescue-`)).toBe(true);
expect(readdirSync(join(workspace, ".browser-profiles"))).toEqual(["mozilla"]);
+ expect(readdirSync(workspace)).toEqual([".browser-profiles"]);
});
it("never overwrites a profile already in the workspace, and leaves a desktop whose ~/.mozilla is already a link alone", async () => {
@@ -216,4 +217,49 @@ describe.skipIf(process.platform === "win32")("rescueFirefoxProfile", () => {
.rejects.toThrow(/permission denied/);
expect(readdirSync(join(workspace, ".browser-profiles"))).toEqual([]);
});
+
+ // A desktop from before cua took the host's ids (uid 1000) leaves these folders owned by that uid; the server cannot
+ // write in them, yet a desktop whose ~/.mozilla and ~/.local already link into the workspace has nothing to copy.
+ it.skipIf(process.getuid?.() === 0)("updates a desktop whose profile folders an older desktop owns when there is nothing to copy", async () => {
+ const dir = scratch();
+ const container = join(dir, "container");
+ mkdirSync(join(container, "home", "cua"), { recursive: true });
+ symlinkSync("/home/cua/workspace/.browser-profiles/mozilla", join(container, "home", "cua", ".mozilla"));
+ symlinkSync("/home/cua/workspace/.desktop-apps/local", join(container, "home", "cua", ".local"));
+ const workspace = join(dir, "workspace");
+ mkdirSync(join(workspace, ".browser-profiles"), { recursive: true });
+ mkdirSync(join(workspace, ".desktop-apps", "local", "share"), { recursive: true });
+ chmodSync(join(workspace, ".browser-profiles"), 0o500);
+ chmodSync(join(workspace, ".desktop-apps"), 0o500);
+ try {
+ const { runtime } = fakeRuntime(dir, container);
+ expect(await rescueFirefoxProfile(runtime, target(workspace))).toBe("none");
+ expect(await rescueInstalledApps(runtime, target(workspace))).toBe("none");
+ } finally {
+ chmodSync(join(workspace, ".browser-profiles"), 0o700);
+ chmodSync(join(workspace, ".desktop-apps"), 0o700);
+ }
+ expect(readdirSync(workspace).sort()).toEqual([".browser-profiles", ".desktop-apps"]);
+ });
+
+ it.skipIf(process.getuid?.() === 0)("names the command that hands an older desktop's folders back when it must write in them", async () => {
+ const dir = scratch();
+ const container = join(dir, "container");
+ mkdirSync(join(container, "home", "cua", ".mozilla", "firefox"), { recursive: true });
+ writeFileSync(join(container, "home", "cua", ".mozilla", "firefox", "profiles.ini"), "old desktop");
+ const workspace = join(dir, "workspace");
+ mkdirSync(join(workspace, ".browser-profiles"), { recursive: true });
+ chmodSync(join(workspace, ".browser-profiles"), 0o500);
+ // The fake runtime is a path; the update itself only ever passes "docker" or "podman" through to the same spawn.
+ const status = { runtime: fakeRuntime(dir, container).runtime as "docker", container: "stopped", managed: true, imageMatches: false } as const;
+ let failure: unknown;
+ try {
+ failure = await keepFirefoxProfileBeforeRemove(target(workspace), status, async () => {}).catch((error: unknown) => error);
+ } finally {
+ chmodSync(join(workspace, ".browser-profiles"), 0o700);
+ }
+ expect(failure).toBeInstanceOf(Error);
+ expect((failure as Error).message).toContain(`sudo chown -R ${process.getuid?.()}:${process.getgid?.()} '${workspace}'`);
+ expect(readdirSync(workspace)).toEqual([".browser-profiles"]);
+ });
});
diff --git a/server/local-vm-profiles.ts b/server/local-vm-profiles.ts
index 9a0594c607..abb22b5d46 100644
--- a/server/local-vm-profiles.ts
+++ b/server/local-vm-profiles.ts
@@ -15,6 +15,17 @@ const PROFILE_IN_CONTAINER = "/home/cua/.mozilla";
const APPS_IN_CONTAINER = "/home/cua/.local";
// docker: "Could not find the file … in container"; podman: "… could not be found on container …: no such file or directory".
const NOT_IN_CONTAINER = /could not (?:be )?f(?:ou|i)nd|no such file/iu;
+const PERMISSION_DENIED = /EACCES|EPERM|permission denied|operation not permitted/iu;
+
+/** A desktop made before cua took the host's ids ran as uid 1000 and may have left folders this server cannot change.
+ * The update then names the one command that hands them back instead of a bare EACCES. */
+function withOwnershipStep(error: unknown, workspaceDir: string): Error {
+ const message = error instanceof Error ? error.message : String(error);
+ if (!PERMISSION_DENIED.test(message) || !process.getuid || !process.getgid) return error instanceof Error ? error : new Error(message);
+ return new Error(
+ `an older desktop left files this app (uid ${process.getuid()}) cannot change; run sudo chown -R ${process.getuid()}:${process.getgid()} '${workspaceDir}' and it retries on its own (${message.slice(0, 80)})`,
+ );
+}
async function isEmptyDirectory(path: string): Promise<boolean> {
try {
@@ -32,7 +43,9 @@ export async function rescueFirefoxProfile(runtime: string, target: LocalVmTarge
await mkdir(profiles, { recursive: true, mode: 0o700 });
const existing = await lstat(durable).catch(() => null);
if (existing && !(existing.isDirectory() && await isEmptyDirectory(durable))) return "kept";
- const staging = join(profiles, `.mozilla-rescue-${randomBytes(6).toString("hex")}`);
+ // Staged in the workspace root, which this server made: an older desktop may own .browser-profiles, and a desktop whose
+ // ~/.mozilla is already a link into the workspace must update without writing there.
+ const staging = join(target.workspaceDir, `.mozilla-rescue-${randomBytes(6).toString("hex")}`);
try {
const { command, args } = resolveCliSpawn(runtime, ["cp", `${target.containerName}:${PROFILE_IN_CONTAINER}`, staging]);
try {
@@ -62,7 +75,7 @@ export async function keepFirefoxProfileBeforeRemove(
): Promise<"rescued" | "kept" | "none"> {
if (!status.runtime || status.container === "missing" || !status.managed || status.imageMatches) return "none";
if (status.container === "running") await stop();
- return rescueFirefoxProfile(status.runtime, target);
+ return rescueFirefoxProfile(status.runtime, target).catch((error: unknown) => { throw withOwnershipStep(error, target.workspaceDir); });
}
/** User-installed desktop applications conventionally live in ~/.local. Rescue that directory before replacing a legacy
@@ -72,7 +85,7 @@ export async function rescueInstalledApps(runtime: string, target: LocalVmTarget
const durable = join(apps, "local");
await mkdir(apps, { recursive: true, mode: 0o700 });
const existing = await lstat(durable).catch(() => null);
- const staging = join(apps, `.local-rescue-${randomBytes(6).toString("hex")}`);
+ const staging = join(target.workspaceDir, `.local-rescue-${randomBytes(6).toString("hex")}`); // the root, as for Firefox
try {
const { command, args } = resolveCliSpawn(runtime, ["cp", `${target.containerName}:${APPS_IN_CONTAINER}`, staging]);
try {
@@ -107,5 +120,5 @@ export async function keepInstalledAppsBeforeRemove(
): Promise<"rescued" | "kept" | "none"> {
if (!status.runtime || status.container === "missing" || !status.managed || status.imageMatches) return "none";
if (status.container === "running") await stop();
- return rescueInstalledApps(status.runtime, target);
+ return rescueInstalledApps(status.runtime, target).catch((error: unknown) => { throw withOwnershipStep(error, target.workspaceDir); });
}