Ask the user before a bot deletes anything in a host directory

A folder mounted from the host machine is the user's own data, and what
is removed there can't be undone, so a delete now stops at the tool.

computer_bash reads the command's plain spellings before running it
(rm/rmdir/unlink/shred, find -delete, >, tee, dd of=, mv, rsync --delete,
git clean, git rm). A path inside a read-write, gated mount that the run
reaches holds the whole command: the bot is told nothing ran and to ask
with ask_user, naming the exact path and what would go. The newest user
message carries the answer, so an ask_user answer counts and an old
approval never does; it must name the path and agree.

Once approved, each named path is copied into the bot's own folder
(recovered/<stamp>/) before the command runs, up to
HostDirectoryRecoverMaxBytes; past that the delete goes ahead without a
copy and the result says so. A path already gone is skipped.

gate_deletes on each link (on by default, toggled in Settings > Host
directories) turns this off per place, and a read-only link is never
gated since nothing can be removed there. Both are a heuristic at the
tool's edge: a script a bot writes and runs still deletes what its
account may, which is why the copy is taken.
This commit is contained in:
2026-11-18 12:54:16 +01:00
parent 9d2dcc73d0
commit 5b268828e2
22 changed files with 1152 additions and 8 deletions
+1 -1
View File
@@ -160,7 +160,7 @@ A worker reaches another bot **only through the coordinator's gate**: `ask_bot`
### Host directories (`host_directories`)
A folder on the host machine shared with bots (super admin, Settings > Host directories). `host_directories` (`name`, `source` as the docker daemon sees it, `slug`, `created_by`), linked to computers (`host_directory_computers`) or workspaces (`host_directory_workspaces`), each link `read-write` (default) or `read-only`. **Where it shows:** a computer link is mounted for every bot reaching that computer at `bots/<bot>/hosts/<slug>` (the worker sees `/home/cb-<bot>/workspace/hosts/<slug>`), a workspace link at `workspaces/<wid>/<slug>` (in the workspace's shared folder). Both sit inside `computerRunDirs`' roots, so no agent path rule had to change; the mount points are made by `prepareHostDirectoryMounts` and docker's `CreateMountpoint: false` (`HostConfig.Mounts`, never `Binds`), so a missing source fails the setup instead of docker making a root-owned folder (the folders belong to the run accounts, so a dev app running as a plain user gets `EACCES` and makes them with a throwaway root container over the computer's folder instead). **Mounts only exist at container creation**, so `reconcileComputerHostDirectories` (after every link change, and from `sync-computers`) reprovisions a computer whose `metadata.host_mounts` (`hostDirectoryMountEntry` entries) differ, skipping a busy one (`isComputerBusy`; the cron retries) and `MAIN_COMPUTER_URL` ones. **A link is all it takes: Cobble gives every bot that sees the folder access to it itself.** `applyHostDirectoryGrant` computes the uids the live crew implies, runs `grantHostDirectory` (a throwaway container of the computer's image as root, `setfacl -R -m u:<uid>:rwX` on the folder and default entries on its folders) and records them in `host_directory_grants` (`uids`, `granted_at`, `error`). It is ACL entries only: ownership, group and mode are never touched, so the folder stays the host owner's exactly as it was. It runs on link and unlink, on a source change, when a bot joins a computer or a workspace, from `sync-computers` (`retry: false`, so a folder the user hasn't fixed doesn't start a container every five minutes), and from Give access (`api/admin/host-directories/grant-host-directory`) when it failed; a check refreshes after it. Unlinking a place takes the entries back from the uids no remaining link needs (removing the last link removes them all, so deleting a directory leaves the folder as it was). Check (`probeHostDirectory`: one throwaway container, each account through `setpriv --reuid/--regid/--groups`, `test -r`/`test -w`; mounted read and write, since a read-only mount answers no to every write test) stores `host_directory_checks` per computer, and the page shows `hostDirectoryPermissionCommand` only when the grant couldn't run (a host without ACLs, a folder the daemon can't reach), for the user to run by hand. **Every bot that sees the folder must be able to read and write it,** so the command names the uid of each of them, from the live crew and not from the stored check: `hostDirectoryLinkUids` over `bots`/`bot_computers`/`workspace_bots` (a computer link: every bot reaching it; a workspace link: its bots plus the coordinator), `hostDirectoryAccount` mapping a bot to its uid (coordinator 1000, a worker `100000 + bot_id`). A check that misses a uid now seeing the folder is flagged `hostDirectoryCheckStale`, so the page says to check again rather than showing an old result. The agent's `shareFolder` walk prunes every mount point found in `/proc/self/mountinfo` (`computer/agent/mount-points.ts`) and runs `find -xdev`, so setting up a bot never chowns or chmods through a mount into the host. The app container itself does not mount a source, so Files shows the mount point empty and sizes are not counted.
A folder on the host machine shared with bots (super admin, Settings > Host directories). `host_directories` (`name`, `source` as the docker daemon sees it, `slug`, `created_by`), linked to computers (`host_directory_computers`) or workspaces (`host_directory_workspaces`), each link `read-write` (default) or `read-only`. **Where it shows:** a computer link is mounted for every bot reaching that computer at `bots/<bot>/hosts/<slug>` (the worker sees `/home/cb-<bot>/workspace/hosts/<slug>`), a workspace link at `workspaces/<wid>/<slug>` (in the workspace's shared folder). Both sit inside `computerRunDirs`' roots, so no agent path rule had to change; the mount points are made by `prepareHostDirectoryMounts` and docker's `CreateMountpoint: false` (`HostConfig.Mounts`, never `Binds`), so a missing source fails the setup instead of docker making a root-owned folder (the folders belong to the run accounts, so a dev app running as a plain user gets `EACCES` and makes them with a throwaway root container over the computer's folder instead). **Mounts only exist at container creation**, so `reconcileComputerHostDirectories` (after every link change, and from `sync-computers`) reprovisions a computer whose `metadata.host_mounts` (`hostDirectoryMountEntry` entries) differ, skipping a busy one (`isComputerBusy`; the cron retries) and `MAIN_COMPUTER_URL` ones. **A link is all it takes: Cobble gives every bot that sees the folder access to it itself.** `applyHostDirectoryGrant` computes the uids the live crew implies, runs `grantHostDirectory` (a throwaway container of the computer's image as root, `setfacl -R -m u:<uid>:rwX` on the folder and default entries on its folders) and records them in `host_directory_grants` (`uids`, `granted_at`, `error`). It is ACL entries only: ownership, group and mode are never touched, so the folder stays the host owner's exactly as it was. It runs on link and unlink, on a source change, when a bot joins a computer or a workspace, from `sync-computers` (`retry: false`, so a folder the user hasn't fixed doesn't start a container every five minutes), and from Give access (`api/admin/host-directories/grant-host-directory`) when it failed; a check refreshes after it. Unlinking a place takes the entries back from the uids no remaining link needs (removing the last link removes them all, so deleting a directory leaves the folder as it was). Check (`probeHostDirectory`: one throwaway container, each account through `setpriv --reuid/--regid/--groups`, `test -r`/`test -w`; mounted read and write, since a read-only mount answers no to every write test) stores `host_directory_checks` per computer, and the page shows `hostDirectoryPermissionCommand` only when the grant couldn't run (a host without ACLs, a folder the daemon can't reach), for the user to run by hand. **Every bot that sees the folder must be able to read and write it,** so the command names the uid of each of them, from the live crew and not from the stored check: `hostDirectoryLinkUids` over `bots`/`bot_computers`/`workspace_bots` (a computer link: every bot reaching it; a workspace link: its bots plus the coordinator), `hostDirectoryAccount` mapping a bot to its uid (coordinator 1000, a worker `100000 + bot_id`). A check that misses a uid now seeing the folder is flagged `hostDirectoryCheckStale`, so the page says to check again rather than showing an old result. **A delete inside a mounted folder asks the user first:** `gate_deletes` on each link (on by default, toggled per link in the page) holds a `computer_bash` command that would remove something in it (`host-directory-delete-guard.ts`, called before the command runs) until the newest user message approves it. `hostDirectoryDeletePaths` reads the plain spellings (`rm`/`rmdir`/`unlink`/`shred`, `find -delete`, `>`/`tee`/`dd of=`, `mv`, `rsync --delete`, `git clean`/`git rm`), `gatedMountFor` matches them against the read-write, gated mounts the run reaches (`computerWorkspacePath`, so either spelling; a rename inside the folder is not a delete), and `grabDeleteApproval` wants one of the exact paths plus an agreeing word in the newest user message, which is how an `ask_user` answer counts. Not approved, `approvalNote` comes back as the whole result and nothing runs; approved, `keepCopies` keeps a copy of each named path in `<bot folder>/recovered/<stamp>/` (`AppData.HostDirectoryRecoverMaxBytes`; past it no copy is kept and the result says so, and a path already gone is skipped) before the command runs. It is a heuristic at the tool's edge: a script the bot writes and runs still deletes what its account may. The agent's `shareFolder` walk prunes every mount point found in `/proc/self/mountinfo` (`computer/agent/mount-points.ts`) and runs `find -xdev`, so setting up a bot never chowns or chmods through a mount into the host. The app container itself does not mount a source, so Files shows the mount point empty and sizes are not counted.
### Schedules (routines in the UI)
+14
View File
@@ -2919,6 +2919,13 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
options: HostDirectoryAccesses.map((hda) => hda.value),
defaultValue: "read-write",
},
{
fieldName: "gate_deletes",
fieldDescription: `Ask the user before a command deletes or moves out anything in the folder: deleting on a host machine can't be undone`,
dataType: "INTEGER",
options: [0, 1],
defaultValue: 1,
},
],
uniqueConstraints: [
{
@@ -2966,6 +2973,13 @@ const schema: BUN_SQLITE_DatabaseSchemaType = {
options: HostDirectoryAccesses.map((hda) => hda.value),
defaultValue: "read-write",
},
{
fieldName: "gate_deletes",
fieldDescription: `Ask the user before a command deletes or moves out anything in the folder: deleting on a host machine can't be undone`,
dataType: "INTEGER",
options: [0, 1],
defaultValue: 1,
},
],
uniqueConstraints: [
{
+8
View File
@@ -1817,6 +1817,10 @@ export type BUN_SQLITE_COBBLE_HOST_DIRECTORY_COMPUTERS = {
* Read and write, or read only: the same folder is mounted the same way for every bot
*/
access?: "read-write" | "read-only" | "";
/**
* Ask the user before a command deletes or moves out anything in the folder: deleting on a host machine can't be undone
*/
gate_deletes?: 0 | 1 | "";
}
export type BUN_SQLITE_COBBLE_HOST_DIRECTORY_WORKSPACES = {
@@ -1835,6 +1839,10 @@ export type BUN_SQLITE_COBBLE_HOST_DIRECTORY_WORKSPACES = {
host_directory_id?: number | "";
workspace_id?: number | "";
access?: "read-write" | "read-only" | "";
/**
* Ask the user before a command deletes or moves out anything in the folder: deleting on a host machine can't be undone
*/
gate_deletes?: 0 | 1 | "";
}
export type BUN_SQLITE_COBBLE_HOST_DIRECTORY_CHECKS = {
+7 -1
View File
@@ -148,12 +148,19 @@ export default async function runBotTask({
*/
const scopes = await grabRunScopes({ bot, user_id, workspace_id });
/**
* The conversation the run answers in: read before its tools open, so a
* delete inside a host folder can ask its user there.
*/
const session_id = await jobSessionId({ job });
const computer = job.computer_id
? await openComputerTools({
computer_id: job.computer_id,
bot_id: bot.id,
user_id,
workspace_id,
session_id,
dirs,
scopes,
onSecretRef: ({ ref }) => shown.push(ref),
@@ -166,7 +173,6 @@ export default async function runBotTask({
let skills: OpenBotSkills | undefined;
try {
const session_id = await jobSessionId({ job });
const prompt = await grabBotPrompt({ bot_id: bot.id, user_id, workspace_id });
const computers = await grabBotComputers({ bot_id: bot.id, workspace_id });
+15
View File
@@ -250,6 +250,21 @@ export const AppData = {
* folder, so a big one is allowed several minutes.
*/
HostDirectoryGrantTimeoutMs: 10 * 60 * 1000,
/**
* How much of a host folder is copied into the bot's own folder before
* an approved delete: past this, the delete goes ahead without a copy
* and the result says so, since the folder is the user's own data and
* copying a whole disk into the workspace is what the quota guards.
*/
HostDirectoryRecoverMaxBytes: 512 * 1024 * 1024,
/**
* Where the copy of a deleted path is kept, in the run's own folder.
*/
HostDirectoryRecoverFolder: "recovered",
/**
* How long copying the paths an approved delete names may take.
*/
HostDirectoryRecoverTimeoutMs: 5 * 60 * 1000,
/**
* A worker's install request (`request_install`): at most this many
* packages, a reason and notes this long, its answer this long.
@@ -29,6 +29,8 @@ export type ComputerHostDirectoryLink = {
access: HostDirectoryAccess;
scope: "computer" | "workspace";
workspace_id?: number | null;
/** Whether a delete inside the folder waits for the user's approval. */
gate_deletes: boolean;
check: HostDirectoryCheck | null;
};
@@ -115,6 +117,7 @@ export default async function grabComputerHostDirectories({
source,
access: (row.access || "read-write") as HostDirectoryAccess,
scope: "computer" as const,
gate_deletes: Number(row.gate_deletes) != 0,
check: checked_on(Number(row.host_directory_id)),
})),
...(workspace_rows.payload || []).map(({ name, slug, source, ...row }) => ({
@@ -125,6 +128,7 @@ export default async function grabComputerHostDirectories({
access: (row.access || "read-write") as HostDirectoryAccess,
scope: "workspace" as const,
workspace_id: Number(row.workspace_id),
gate_deletes: Number(row.gate_deletes) != 0,
check: checked_on(Number(row.host_directory_id)),
})),
];
@@ -0,0 +1,45 @@
import BunSQLite from "@moduletrace/bun-sqlite";
/**
* Whether the user's latest word in a conversation approves deleting the
* paths a command named.
*
* A delete inside a folder mounted from the host machine waits for the
* user (`host-directory-delete-guard`), and the approval is the user's own
* message: the one an `ask_user` answer sends back (it carries the question
* the bot asked, so the path is in it), or anything they typed that names
* the path and says to go ahead. Only the newest user message counts, so an
* approval from an earlier turn never carries to a later delete.
*/
/** Words that read as the user saying yes. */
const Affirmative = /\b(delete|remove|yes|approve[sd]?|confirm(ed)?|go ahead|do it|ok(ay)?|agreed?)\b/i;
type Params = {
session_id: number | string;
/**
* The spellings of the path the user's message may name: the run's
* own (`/home/cb-4/workspace/...`) and the real one on the computer.
*/
needles: string[];
};
export default async function grabDeleteApproval({ session_id, needles }: Params): Promise<boolean> {
const paths = needles.map((needle) => needle.trim()).filter(Boolean);
if (!paths.length) return false;
const read = await BunSQLite.sql<{ text: string }>({
sql: `SELECT text FROM bot_messages
WHERE session_id = ? AND author = 'user'
ORDER BY id DESC
LIMIT 1`,
values: [Number(session_id)],
});
const text = String(read.payload?.[0]?.text || "");
if (!text) return false;
return Affirmative.test(text) && paths.some((needle) => text.includes(needle));
}
@@ -0,0 +1,58 @@
import BunSQLite from "@moduletrace/bun-sqlite";
import AppError from "@/src/utils/app-error";
import assertHostDirectoryManager from "./assert-host-directory-manager";
type Params = {
user_id: number | string;
host_directory_id: number | string;
computer_id?: number | string;
workspace_id?: number | string;
gate_deletes: boolean;
};
/**
* Whether one link asks the user before a command deletes or moves
* anything out of the folder (`host-directory-delete-guard`). It is read
* on every command, so nothing is set up again.
*/
export default async function setHostDirectoryDeletes({
user_id,
host_directory_id,
computer_id,
workspace_id,
gate_deletes,
}: Params) {
await assertHostDirectoryManager({ user_id });
if (Boolean(computer_id) == Boolean(workspace_id)) {
throw new AppError("Pick the computer or the workspace whose link changes.");
}
const table = computer_id ? "host_directory_computers" : "host_directory_workspaces";
const column = computer_id ? "computer_id" : "workspace_id";
const value = Number(computer_id || workspace_id);
const link = await BunSQLite.sql<{ id: number; gate_deletes: number }>({
sql: `SELECT id, gate_deletes FROM ${table} WHERE host_directory_id = ? AND ${column} = ?`,
values: [host_directory_id, value],
});
const row = link.payload?.[0];
if (!row?.id) {
throw new AppError("That host directory isn't linked there.");
}
const current = Number(row.gate_deletes) != 0;
if (current == gate_deletes) return;
const updated = await BunSQLite.sql({
sql: `UPDATE ${table} SET gate_deletes = ?, updated_at = ? WHERE id = ?`,
values: [gate_deletes ? 1 : 0, Date.now(), row.id],
});
if (!updated.success) {
throw new AppError("Couldn't change how deletes in the folder are handled.");
}
}
@@ -12,6 +12,7 @@ import type { ComputerToolContext } from "./computer-tool-context";
import { computerWorkspaceFullWarning } from "./computer-workspace-room";
import isDestructiveGit from "./destructive-command";
import gitSnapshotNote from "./git-snapshot-note";
import hostDirectoryDeleteGuard from "./host-directory-delete-guard";
import type { GitWorktreeSnapshot } from "./parse-git-snapshot";
import snapshotGitWorktree from "./snapshot-git-worktree";
@@ -31,7 +32,7 @@ type Args = {
* `AppData.ComputerCommandMaxSeconds` when that is set), so a long script
* is never cut short and nothing is left blocking the computer.
*/
export default function computerBashTool({ computer, dirs, shell_path, redact }: ComputerToolContext): HarnessTool<Args> {
export default function computerBashTool({ computer, computer_id, dirs, shell_path, redact, bot_id, workspace_id, session_id }: ComputerToolContext): HarnessTool<Args> {
const max = AppData.ComputerCommandMaxSeconds;
const timeout_note = max > 0
? `Seconds before it is stopped, at most ${max} (${max} when left out).`
@@ -58,6 +59,20 @@ export default function computerBashTool({ computer, dirs, shell_path, redact }:
const cwd = args.cwd ? resolveComputerPath({ path: args.cwd, dirs }) : null;
const seconds = commandTimeoutSeconds({ asked: args.timeout, max });
/**
* A delete inside a folder mounted from the host machine is the
* user's data, and can't be undone there: hold it until they
* approved it, then keep a copy of what it removes.
*/
const gate = await hostDirectoryDeleteGuard({
command: args.command,
cwd,
context: { computer, computer_id, dirs, shell_path, redact, bot_id, workspace_id, session_id },
signal,
});
if (gate?.blocked) return gate.blocked;
/**
* Before anything that would throw uncommitted work away: keep it
* outside the repository, and say where in the result, so a run
@@ -100,6 +115,7 @@ export default function computerBashTool({ computer, dirs, shell_path, redact }:
const full = await computerWorkspaceFullWarning({ computer, dirs }).catch(() => null);
return [
gate?.note || "",
gitSnapshotNote({ snapshots }),
snapshot_failed ? `[The safety snapshot could not be saved before this command; any work it discards may be unrecoverable.]` : "",
`Exit code: ${result.exit_code ?? "unknown"}`,
@@ -4,11 +4,17 @@ import type { ComputerRunDirs } from "@/src/utils/computer-work-dirs";
/**
* What a run's own computer tools share: the computer, the run's folders
* on it (every path is kept inside them), the env file its commands load,
* and the redaction its secret values go through.
* the redaction its secret values go through, and where the run is, so a
* delete inside a folder mounted from the host can wait for its user
* (`host-directory-delete-guard`).
*/
export type ComputerToolContext = {
computer: ComputerApi;
computer_id: number;
dirs: ComputerRunDirs;
shell_path: string;
redact: (text: string) => string;
};
bot_id: number;
workspace_id: number | null;
session_id: number;
};
@@ -43,7 +43,16 @@ const MB = 1024 * 1024;
async function write(content: string) {
const { default: make } = await import("./computer-write-file-tool");
const tool = make({ computer, dirs, shell_path: "/home/cb-9/.cobble/env", redact: (text) => text });
const tool = make({
computer,
computer_id: 1,
dirs,
shell_path: "/home/cb-9/.cobble/env",
redact: (text) => text,
bot_id: 9,
workspace_id: null,
session_id: 1,
});
return tool.run({ args: { path: "report.md", content }, signal: new AbortController().signal });
}
@@ -0,0 +1,231 @@
import path from "node:path";
import { AppData } from "@/src/data/app-data";
import runComputerCommand from "@/src/functions/backend/computers/run-computer-command";
import grabComputerHostDirectories from "@/src/functions/backend/db/host-directories/grab-computer-host-directories";
import grabDeleteApproval from "@/src/functions/backend/db/host-directories/grab-delete-approval";
import { computerRunPath } from "@/src/utils/computer-work-dirs";
import computerWorkspacePath from "@/src/utils/computer-workspace-path";
import gatedMountFor from "@/src/utils/host-directory-gated-target";
import hostDirectoryDeletePaths, { type HostDirectoryDeleteTarget } from "@/src/utils/host-directory-delete-paths";
import shellQuote from "@/src/utils/shell-quote";
import type { ComputerToolContext } from "./computer-tool-context";
/**
* Holds a `computer_bash` command that would delete something inside a
* folder mounted from the host machine until the user approves it, and
* keeps a copy of what it removes.
*
* Deleting on the host can't be undone, and the folder is the user's own
* data, not the bot's: the account may unlink there, so the app is the
* only place a confirmation can sit. It is a heuristic at the tool's edge
* (`hostDirectoryDeletePaths` reads the plain spellings); a script the bot
* writes and runs still removes what its account may, which is why the
* folder is mounted from a copy of it when that matters. The copy is only
* taken once the user approved, in the bot's own folder, so it is theirs
* to clear.
*/
export type HostDirectoryDeleteGuard = {
/** What the bot is told instead of running the command. */
blocked?: string;
/** A line to put in front of the result, when the command ran. */
note?: string;
};
type Gate = {
host_directory_id: number;
name: string;
/** The mount's path on the computer, as the run sees it. */
run_target: string;
/** The same path in the computer's own spelling (what the mount is on). */
real_target: string;
};
type Params = {
command: string;
cwd: string | null;
context: ComputerToolContext;
signal?: AbortSignal;
};
export default async function hostDirectoryDeleteGuard({ command, cwd, context, signal }: Params): Promise<HostDirectoryDeleteGuard | null> {
const { dirs, computer, session_id, computer_id, bot_id, workspace_id } = context;
const start = cwd || dirs.cwd;
const targets = hostDirectoryDeletePaths({ command, cwd: start });
if (!targets.length) return null;
const gates = await grabGates({ computer_id, bot_id, workspace_id, dirs });
const hits = targets
.map((target) => ({ target, gate: gatedMountFor({ target, mounts: gates }) }))
.filter((hit): hit is { target: HostDirectoryDeleteTarget; gate: Gate } => Boolean(hit.gate));
if (!hits.length) return null;
const approved = await grabDeleteApproval({
session_id,
needles: hits.flatMap((hit) => [hit.target.path, computerWorkspacePath({ absolute: hit.target.path }), hit.gate.real_target]),
});
if (!approved) return { blocked: approvalNote({ hits }) };
return keepCopies({ hits, context, signal });
}
/**
* The folder's mounts the run may delete in: its own computer link and the
* links of the workspace it is in (a coordinator reaches every folder on
* the computer, so every mount there), read-write and with the gate on.
*/
async function grabGates({
computer_id,
bot_id,
workspace_id,
dirs,
}: {
computer_id: number;
bot_id: number;
workspace_id: number | null;
dirs: ComputerToolContext["dirs"];
}): Promise<Gate[]> {
const { links, mounts } = await grabComputerHostDirectories({ computer_id });
const linkFor = (mount: (typeof mounts)[number]) =>
links.find(
(link) =>
link.host_directory_id == mount.host_directory_id &&
link.scope == mount.scope &&
(mount.scope == "computer" || Number(link.workspace_id) == Number(mount.workspace_id)),
);
const gates: Gate[] = [];
for (const mount of mounts) {
const link = linkFor(mount);
if (!link || !link.gate_deletes || link.access != "read-write") continue;
/**
* A worker reaches its own computer link and the links of the
* workspace it is in. The coordinator reaches every folder on the
* computer, so every mount counts (a host folder is never the one
* it is working in on its own).
*/
if (dirs.run_as) {
if (mount.scope == "computer" && Number(mount.bot_id) != Number(bot_id)) continue;
if (mount.scope == "workspace" && Number(mount.workspace_id) != Number(workspace_id)) continue;
}
gates.push({
host_directory_id: link.host_directory_id,
name: link.name,
real_target: mount.target,
run_target: computerRunPath({ real: mount.target, dirs }),
});
}
return gates;
}
function approvalNote({ hits }: { hits: { target: HostDirectoryDeleteTarget; gate: Gate }[] }) {
const names = [...new Set(hits.map((hit) => hit.gate.name))];
const paths = [...new Set(hits.map((hit) => hit.target.path))];
return [
`Nothing ran: deleting in ${names.join(", ")}, a folder on the host machine, needs the user's approval first, and what is removed there can't be undone.`,
`Ask them with ask_user: one question that names the exact path (${paths.map((item) => `\`${item}\``).join(", ")}) and what would be removed, with the options "Delete it" and "Keep it".`,
`When they pick "Delete it", their message carries the path back, and you can run the same command again: the app then keeps a copy of what it removes in your own folder.`,
`If this run can't ask (a routine, a hook call or a request from another bot), say so in your report and leave the folder as it is.`,
].join(" ");
}
/**
* Copies the paths an approved delete names into the run's own folder, so
* the user can get them back. Past `HostDirectoryRecoverMaxBytes` a path is
* left out and the result says the delete went ahead without a copy.
*/
async function keepCopies({
hits,
context,
signal,
}: {
hits: { target: HostDirectoryDeleteTarget; gate: Gate }[];
context: ComputerToolContext;
signal?: AbortSignal;
}): Promise<HostDirectoryDeleteGuard> {
const { computer, dirs } = context;
const stamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
const folder = path.posix.join(dirs.bot_dir, AppData.HostDirectoryRecoverFolder, stamp);
const copied: string[] = [];
const too_big: string[] = [];
for (const [index, hit] of hits.entries()) {
if (!(await exists({ context, target: hit.target.path, signal }))) continue;
const bytes = await measure({ context, target: hit.target.path, signal });
if (bytes != null && bytes > AppData.HostDirectoryRecoverMaxBytes) {
too_big.push(hit.target.path);
continue;
}
const name = path.posix.basename(hit.target.path) || "path";
const destination = path.posix.join(folder, `${index + 1}-${name}`);
const result = await runComputerCommand({
computer,
command: `mkdir -p ${shellQuote({ text: folder })} && cp -a -- ${shellQuote({ text: hit.target.path })} ${shellQuote({ text: destination })}`,
timeout_ms: AppData.HostDirectoryRecoverTimeoutMs,
run_as: dirs.run_as,
signal,
});
if (result.exit_code != 0) {
return {
blocked: `Nothing was deleted: the app couldn't keep a copy of ${hit.target.path} first (exit code ${result.exit_code ?? "unknown"}). Check that the path still exists and has room, or ask the user to remove it themselves.`,
};
}
copied.push(hit.target.path);
}
const lines = [
copied.length ? `A copy of ${copied.join(", ")} was kept in ${folder} before this delete.` : "",
too_big.length
? `${too_big.join(", ")} was too large to copy (over ${Math.round(AppData.HostDirectoryRecoverMaxBytes / (1024 * 1024))} MB), so it was deleted with no copy kept.`
: "",
].filter(Boolean);
return lines.length ? { note: `[${lines.join(" ")}]` } : {};
}
/**
* Whether the path is still on the computer: a delete of something already
* gone removes nothing, so it needs no copy and no approval held up by it.
*/
async function exists({ context, target, signal }: { context: ComputerToolContext; target: string; signal?: AbortSignal }) {
const result = await runComputerCommand({
computer: context.computer,
command: `test -e ${shellQuote({ text: target })}`,
timeout_ms: 30_000,
run_as: context.dirs.run_as,
signal,
}).catch(() => null);
return result?.exit_code == 0;
}
/**
* How big a path is on the computer, or null when it can't be read.
*/
async function measure({ context, target, signal }: { context: ComputerToolContext; target: string; signal?: AbortSignal }) {
const result = await runComputerCommand({
computer: context.computer,
command: `du -sb -- ${shellQuote({ text: target })} 2>/dev/null | cut -f1`,
timeout_ms: 30_000,
run_as: context.dirs.run_as,
signal,
}).catch(() => null);
const bytes = Number(String(result?.output || "").trim());
return Number.isFinite(bytes) && bytes >= 0 ? bytes : null;
}
@@ -41,6 +41,11 @@ type Params = {
* screenshots.
*/
workspace_id?: number | string | null;
/**
* The conversation the run answers in: a delete inside a folder
* mounted from the host asks its user there.
*/
session_id: number;
/**
* The run's folders on the computer (`computerRunDirs`): every tool is
* kept inside them.
@@ -105,6 +110,7 @@ export default async function openComputerTools({
bot_id,
user_id,
workspace_id,
session_id,
dirs,
scopes,
onSecretRef,
@@ -148,7 +154,16 @@ export default async function openComputerTools({
const client = browser
? await connectMcpServer({ url: target.url, headers: { authorization: `Bearer ${target.token}` }, signal })
: null;
const context: ComputerToolContext = { computer: target, dirs, shell_path: paths.shell_path, redact };
const context: ComputerToolContext = {
computer: target,
computer_id: Number(computer_id),
dirs,
shell_path: paths.shell_path,
redact,
bot_id: Number(bot_id || 0),
workspace_id: workspace_id ? Number(workspace_id) : null,
session_id: Number(session_id),
};
try {
const browser_tools = client
@@ -11,6 +11,7 @@ function render({
error,
checked_at = 1_700_000_000_000,
onGrant,
gate_deletes = true,
}: {
state: HostDirectoryCheckState;
access?: "read-write" | "read-only";
@@ -19,6 +20,7 @@ function render({
error?: string;
checked_at?: number | null;
onGrant?: () => void;
gate_deletes?: boolean;
}) {
return renderToString(
<HostDirectoryLinkRow
@@ -30,8 +32,10 @@ function render({
command={command}
stale={stale}
error={error}
gate_deletes
onGrant={onGrant}
onAccess={() => {}}
onDeletes={() => {}}
onRemove={() => {}}
/>,
);
@@ -33,6 +33,10 @@ type Props = {
* Why the last check couldn't say anything about it.
*/
error?: string | null;
/**
* Whether a delete inside the folder waits for the user.
*/
gate_deletes: boolean;
busy?: boolean;
checking?: boolean;
granting?: boolean;
@@ -43,6 +47,10 @@ type Props = {
*/
onGrant?: () => void;
onAccess: () => void;
/**
* Turns asking before a delete on or off for this place.
*/
onDeletes: () => void;
onRemove: () => void;
};
@@ -60,12 +68,14 @@ export default function HostDirectoryLinkRow({
command,
stale,
error,
gate_deletes,
busy,
checking,
granting,
onCheck,
onGrant,
onAccess,
onDeletes,
onRemove,
}: Props) {
const access_title =
@@ -117,6 +127,18 @@ export default function HostDirectoryLinkRow({
disabled={busy || checking}
onClick={onAccess}
/>
<SettingsRowAction
title={
gate_deletes
? "Stop asking: the bots can delete in it without your approval"
: "Ask you before a bot deletes anything in it"
}
label={
gate_deletes ? "Ask before deletes" : "Delete freely"
}
disabled={busy || checking}
onClick={onDeletes}
/>
<SettingsRowAction
title={`Unmount it from ${name}`}
label="Remove"
@@ -51,9 +51,14 @@ type LinkView = {
error?: string | null;
checking?: boolean;
granting?: boolean;
/**
* Whether a delete inside the folder waits for the user.
*/
gate_deletes: boolean;
onCheck: () => void;
onGrant: () => void;
onAccess: () => void;
onDeletes: () => void;
onRemove: () => void;
};
@@ -182,6 +187,7 @@ export default function HostDirectoryRow({
command: command({ access, state, uids: link.uids }),
checking: checking == Number(link.computer_id),
granting,
gate_deletes: Number(link.gate_deletes) != 0,
onCheck: () => check({ computer_ids: [Number(link.computer_id)] }),
onGrant: grant,
onAccess: () =>
@@ -194,6 +200,15 @@ export default function HostDirectoryRow({
access == "read-write" ? "read-only" : "read-write",
},
}),
onDeletes: () =>
post({
path: "set-host-directory-deletes",
key: `deletes-${link.id}`,
body: {
computer_id: Number(link.computer_id),
gate_deletes: !(Number(link.gate_deletes) != 0),
},
}),
onRemove: () =>
post({
path: "unlink-host-directory",
@@ -223,6 +238,7 @@ export default function HostDirectoryRow({
command: command({ access, state, uids: link.uids }),
checking: (link.computer_ids || []).includes(checking || -1),
granting,
gate_deletes: Number(link.gate_deletes) != 0,
onCheck: () => check({ computer_ids: link.computer_ids || [] }),
onGrant: grant,
onAccess: () =>
@@ -235,6 +251,15 @@ export default function HostDirectoryRow({
access == "read-write" ? "read-only" : "read-write",
},
}),
onDeletes: () =>
post({
path: "set-host-directory-deletes",
key: `deletes-${link.id}`,
body: {
workspace_id: Number(link.workspace_id),
gate_deletes: !(Number(link.gate_deletes) != 0),
},
}),
onRemove: () =>
post({
path: "unlink-host-directory",
@@ -315,10 +340,13 @@ export default function HostDirectoryRow({
command={link.command}
stale={link.stale}
error={link.error}
gate_deletes={link.gate_deletes}
checking={link.checking}
busy={Boolean(busy)}
onCheck={link.onCheck}
onGrant={link.onGrant}
onAccess={link.onAccess}
onDeletes={link.onDeletes}
onRemove={link.onRemove}
/>
))
@@ -0,0 +1,49 @@
import userAuth from "@/src/functions/backend/auth/user-auth";
import setHostDirectoryDeletes from "@/src/functions/backend/db/host-directories/set-host-directory-deletes";
import { SetHostDirectoryDeletesRequestSchema } from "@/src/schemas/host-directory-schema";
import AppError from "@/src/utils/app-error";
import parseWithSchema from "@/src/utils/parse-with-schema";
import isReadOnlyUser from "@/src/utils/rbac/is-read-only-user";
import safeErrorMessage from "@/src/utils/safe-error-message";
import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bunext/types";
/**
* Whether one link asks the user before a bot deletes anything in its
* folder: deleting on the host machine can't be undone.
*/
export const handler: BunextAPIRouteHandler<APIResponseObject<{ host_directory_id: number }>> = async ({ req, body }) => {
try {
if (req.method != "POST") {
throw new AppError(`Method not allowed`);
}
const { user, user_types } = await userAuth({ req });
if (!user?.logged_in_status || !user.id) {
return { success: false, msg: `Unauthorized`, logoutUser: true };
}
if (isReadOnlyUser({ user_types: user_types || [] })) {
throw new AppError(`This user can only read records.`);
}
const data = parseWithSchema({ schema: SetHostDirectoryDeletesRequestSchema, data: body });
await setHostDirectoryDeletes({
user_id: user.id,
host_directory_id: data.host_directory_id,
computer_id: data.computer_id || undefined,
workspace_id: data.workspace_id || undefined,
gate_deletes: data.gate_deletes,
});
return {
success: true,
msg: data.gate_deletes
? `The bots now ask you before deleting anything there.`
: `The bots can delete there without asking you.`,
};
} catch (error: unknown) {
return { success: false, msg: safeErrorMessage({ error }) };
}
};
+10 -1
View File
@@ -81,4 +81,13 @@ export const CheckHostDirectoryRequestSchema = z.object({
computer_id: z.coerce.number().int().positive("Pick the computer to check it on"),
});
export type CheckHostDirectoryRequest = z.infer<typeof CheckHostDirectoryRequestSchema>;
export type CheckHostDirectoryRequest = z.infer<typeof CheckHostDirectoryRequestSchema>;
export const SetHostDirectoryDeletesRequestSchema = UnlinkHostDirectoryRequestSchema.extend({
/**
* True asks the user before a command deletes or moves anything out of
* the folder, which is what a new link does.
*/
gate_deletes: z.boolean(),
});
export type SetHostDirectoryDeletesRequest = z.infer<typeof SetHostDirectoryDeletesRequestSchema>;
@@ -0,0 +1,101 @@
import { describe, expect, test } from "bun:test";
import hostDirectoryDeletePaths from "./host-directory-delete-paths";
const cwd = "/home/cb-4/workspace/workspaces/5/proj";
function paths(command: string) {
return hostDirectoryDeletePaths({ command, cwd });
}
describe("hostDirectoryDeletePaths", () => {
test("rm takes every path it names, past its flags", () => {
expect(paths("rm -rf build dist")).toEqual([
{ path: `${cwd}/build`, kind: "delete" },
{ path: `${cwd}/dist`, kind: "delete" },
]);
});
test("a quoted path with spaces stays one path", () => {
expect(paths("rm \"my notes/today.txt\"")).toEqual([
{ path: `${cwd}/my notes/today.txt`, kind: "delete" },
]);
});
test("an absolute path is kept as it is", () => {
expect(paths("rm -f /home/gem/workspace/workspaces/5/proj/a.log")).toEqual([
{ path: "/home/gem/workspace/workspaces/5/proj/a.log", kind: "delete" },
]);
});
test("a flag-looking path after -- is a path", () => {
expect(paths("rm -- -old.log")).toEqual([{ path: `${cwd}/-old.log`, kind: "delete" }]);
});
test("prefix words are read past", () => {
expect(paths("sudo rm -rf a && xargs rm b")).toEqual([
{ path: `${cwd}/a`, kind: "delete" },
{ path: `${cwd}/b`, kind: "delete" },
]);
});
test("find -delete takes its starting point, not its tests", () => {
expect(paths("find . -name '*.log' -delete")).toEqual([{ path: cwd, kind: "delete" }]);
expect(paths("find /tmp/x -type f -exec rm {} +")).toEqual([{ path: "/tmp/x", kind: "delete" }]);
});
test("a stdout redirect empties the file; an append does not", () => {
expect(paths("echo done > report.md")).toEqual([{ path: `${cwd}/report.md`, kind: "truncate" }]);
expect(paths("echo done >> report.md")).toEqual([]);
});
test("a stderr redirect is read too", () => {
expect(paths("make 2> build.log")).toEqual([{ path: `${cwd}/build.log`, kind: "truncate" }]);
});
test("dd and tee write over the file they name", () => {
expect(paths("dd if=/dev/zero of=disk.img bs=1M count=1")).toEqual([
{ path: `${cwd}/disk.img`, kind: "truncate" },
]);
expect(paths("cat notes | tee out.txt")).toEqual([{ path: `${cwd}/out.txt`, kind: "truncate" }]);
expect(paths("cat notes | tee -a out.txt")).toEqual([]);
});
test("mv names its source and where it would go", () => {
expect(paths("mv a.txt /tmp/a.txt")).toEqual([
{ path: `${cwd}/a.txt`, kind: "move", destination: "/tmp/a.txt" },
]);
});
test("rsync --delete takes its destination", () => {
expect(paths("rsync -a --delete src/ mirror/")).toEqual([
{ path: `${cwd}/mirror`, kind: "delete" },
]);
expect(paths("rsync -a src/ mirror/")).toEqual([]);
});
test("git clean and git rm take the tree they run in", () => {
expect(paths("git clean -fdx")).toEqual([{ path: cwd, kind: "delete" }]);
expect(paths("git -C other rm a.txt")).toEqual([{ path: `${cwd}/other`, kind: "delete" }]);
expect(paths("git status")).toEqual([]);
});
test("reading commands are left alone", () => {
expect(paths("ls -la && cat report.md && grep -r foo .")).toEqual([]);
expect(paths("find . -name '*.log'")).toEqual([]);
});
test("each command in a chain is read on its own", () => {
expect(paths("cd build && rm -f a.txt; rm b.txt")).toEqual([
{ path: `${cwd}/a.txt`, kind: "delete" },
{ path: `${cwd}/b.txt`, kind: "delete" },
]);
});
test("a repeated path is named once", () => {
expect(paths("rm -f a.txt && rm -f a.txt")).toEqual([{ path: `${cwd}/a.txt`, kind: "delete" }]);
});
test("a path with a glob is kept as written, so the folder is still matched", () => {
expect(paths("rm hosts/proj/*.log")).toEqual([{ path: `${cwd}/hosts/proj/*.log`, kind: "delete" }]);
});
});
+358
View File
@@ -0,0 +1,358 @@
import path from "node:path";
/**
* What a `computer_bash` command would remove, empty or move out of a
* folder, as the run sees the paths.
*
* Deleting inside a folder mounted from the host machine can't be undone
* on the host, so the app refuses such a command until the user approves
* it (`host-directory-delete-guard`). This is the part that reads the
* command: a heuristic, since a script the bot writes and runs can remove
* anything its account may, but it catches the plain spellings a bot
* actually uses (`rm -rf`, `find -delete`, `>`, `mv` out, `git clean`).
*/
export type HostDirectoryDeleteTarget = {
/** The absolute path, as the run sees it (quoted and relative words resolved). */
path: string;
/** What it would do to it. */
kind: "delete" | "truncate" | "move";
/** For a move: where the path would go. */
destination?: string;
};
type Params = {
command: string;
/** The folder a relative word lands in (the run's own, unless the call named another). */
cwd: string;
};
/** Words that say how the next word runs, never what runs. */
const PrefixWords: readonly string[] = ["sudo", "env", "command", "exec", "time", "nohup", "nice", "xargs", "!"];
/** Programs that remove what they name. */
const DeletePrograms: readonly string[] = ["rm", "rmdir", "unlink", "shred", "srm"];
/** The words that end one command and start the next. */
const Separators: readonly string[] = [";", "&&", "||", "|", "&", "\n", "(", ")"];
/** Git's global options that take the next word, so it is not the subcommand. */
const GitValueOptions: readonly string[] = ["-C", "-c", "--git-dir", "--work-tree", "--namespace", "--config-env", "--exec-path"];
export default function hostDirectoryDeletePaths({ command, cwd }: Params): HostDirectoryDeleteTarget[] {
const targets: HostDirectoryDeleteTarget[] = [];
for (const segment of segments({ command })) {
targets.push(...segmentTargets({ words: segment, cwd }));
}
return dedupe({ targets });
}
/**
* The command's words, with quotes read as one word, and separators as
* their own tokens so each command is read on its own.
*/
export function shellWords({ command }: { command: string }): string[] {
const words: string[] = [];
let current = "";
let started = false;
let quote: "'" | '"' | null = null;
const flush = () => {
if (started) words.push(current);
current = "";
started = false;
};
for (let index = 0; index < command.length; index++) {
const char = command[index]!;
if (quote == "'") {
if (char == "'") quote = null;
else current += char;
continue;
}
if (quote == '"') {
if (char == '"') quote = null;
else if (char == "\\" && index + 1 < command.length) {
index++;
current += command[index];
} else current += char;
continue;
}
if (char == "'" || char == '"') {
quote = char;
started = true;
continue;
}
if (char == "\\" && index + 1 < command.length) {
index++;
current += command[index];
started = true;
continue;
}
if (/\s/.test(char) || Separators.includes(char)) {
flush();
if (Separators.includes(char)) words.push(char);
continue;
}
if (char == ">" || char == "<") {
flush();
const operator = `${char}${command[index + 1] == char ? char : ""}${char == ">" && command[index + 1] == "|" ? "|" : ""}`;
words.push(operator);
index += operator.length - 1;
continue;
}
current += char;
started = true;
}
flush();
return words;
}
/**
* The words of each command in the line: a separator starts the next one.
*/
function segments({ command }: { command: string }): string[][] {
const segments: string[][] = [];
let current: string[] = [];
for (const word of shellWords({ command })) {
if (!Separators.includes(word)) {
current.push(word);
continue;
}
if (current.length) segments.push(current);
current = [];
}
if (current.length) segments.push(current);
return segments;
}
function segmentTargets({ words, cwd }: { words: string[]; cwd: string }): HostDirectoryDeleteTarget[] {
const targets: HostDirectoryDeleteTarget[] = [];
const resolve = (word: string) => resolvePath({ word, cwd });
/**
* A redirect that empties the file it names: `>` and `>|` truncate,
* `>>` only adds.
*/
for (let index = 0; index < words.length; index++) {
const word = words[index]!;
if (word != ">" && word != ">|") continue;
const target = words[index + 1];
if (!target || target == "&" || target.startsWith("&")) continue;
targets.push({ path: resolve(target), kind: "truncate" });
}
const lead = leadingProgram({ words });
if (!lead) return targets;
const { program, args } = lead;
if (DeletePrograms.includes(program)) {
for (const word of pathWords({ args })) {
targets.push({ path: resolve(word), kind: "delete" });
}
return targets;
}
if (program == "truncate") {
for (const word of pathWords({ args })) {
targets.push({ path: resolve(word), kind: "truncate" });
}
return targets;
}
if (program == "tee") {
if (args.some((arg) => arg == "-a" || arg == "--append")) return targets;
for (const word of pathWords({ args })) {
targets.push({ path: resolve(word), kind: "truncate" });
}
return targets;
}
if (program == "dd") {
for (const word of args) {
if (!word.startsWith("of=")) continue;
targets.push({ path: resolve(word.slice(3)), kind: "truncate" });
}
return targets;
}
if (program == "find") {
const deletes = args.some(
(arg, index) =>
arg == "-delete" ||
(arg == "-exec" &&
["rm", "rmdir", "unlink", "shred"].includes(String(args[index + 1] || "").split("/").pop() || "")),
);
if (!deletes) return targets;
for (const word of startWords({ args })) {
targets.push({ path: resolve(word), kind: "delete" });
}
return targets;
}
if (program == "rsync") {
const names = pathWords({ args });
const destination = names[names.length - 1];
if (!args.includes("--delete") || !destination || names.length < 2) return targets;
targets.push({ path: resolve(destination), kind: "delete" });
return targets;
}
if (program == "mv") {
const names = pathWords({ args });
const destination = names[names.length - 1];
if (!destination || names.length < 2) return targets;
for (const word of names.slice(0, -1)) {
targets.push({ path: resolve(word), kind: "move", destination: resolve(destination) });
}
return targets;
}
if (program == "git") {
/**
* `git clean` and `git rm` delete what is in the tree they run
* in, which is the cwd unless `-C` names another one.
*/
let dir = cwd;
let subcommand: string | null = null;
for (let index = 0; index < args.length; index++) {
const arg = args[index]!;
if (GitValueOptions.includes(arg)) {
if (arg == "-C" && args[index + 1]) dir = resolve(args[index + 1]!);
index++;
continue;
}
if (arg.startsWith("-")) continue;
subcommand = arg;
break;
}
if (subcommand == "clean" || subcommand == "rm") {
targets.push({ path: dir, kind: "delete" });
}
}
return targets;
}
function leadingProgram({ words }: { words: string[] }) {
let index = 0;
while (
index < words.length &&
(PrefixWords.includes(words[index]!) || /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[index]!))
) {
index++;
}
const word = words[index];
if (!word) return null;
return { program: (word.split("/").pop() || "").toLowerCase(), args: words.slice(index + 1) };
}
/**
* The words a program acts on: flags are skipped, and after `--` nothing
* is a flag any more (`rm -- -old.log`).
*/
function pathWords({ args }: { args: string[] }): string[] {
const paths: string[] = [];
let flags_done = false;
for (const word of args) {
if (!flags_done && word == "--") {
flags_done = true;
continue;
}
if (!flags_done && word.startsWith("-") && word != "-") continue;
paths.push(word);
}
return paths;
}
/**
* `find`'s starting points: its words before the first test or action.
*/
function startWords({ args }: { args: string[] }): string[] {
const paths: string[] = [];
for (const word of args) {
if (word.startsWith("-")) break;
paths.push(word);
}
return paths;
}
/**
* The absolute path a word names, as the run's shell would read it: `~`
* and a relative word land in the cwd.
*/
export function resolvePath({ word, cwd }: { word: string; cwd: string }): string {
const raw = word.replace(/\\/g, "/");
const home_relative = raw == "~" ? "" : raw.startsWith("~/") ? raw.slice(2) : null;
const absolute =
home_relative != null
? path.posix.join(cwd, home_relative)
: raw.startsWith("/")
? raw
: path.posix.join(cwd, raw || ".");
return path.posix.normalize(absolute).replace(/(.)\/+$/, "$1");
}
function dedupe({ targets }: { targets: HostDirectoryDeleteTarget[] }): HostDirectoryDeleteTarget[] {
const seen = new Set<string>();
return targets.filter((target) => {
const key = `${target.kind}:${target.path}:${target.destination || ""}`;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}
@@ -0,0 +1,102 @@
import { describe, expect, test } from "bun:test";
import gatedMountFor, { type HostDirectoryGatedMount } from "./host-directory-gated-target";
const workspace_mount: HostDirectoryGatedMount = {
name: "Projects",
real_target: "/home/gem/workspace/workspaces/5/projects",
run_target: "/home/cb-4/workspace/workspaces/5/projects",
};
const computer_mount: HostDirectoryGatedMount = {
name: "Photos",
real_target: "/home/gem/workspace/bots/4/hosts/photos",
run_target: "/home/cb-4/workspace/hosts/photos",
};
const mounts = [workspace_mount, computer_mount];
describe("gatedMountFor", () => {
test("a worker's spelling of a path in a mounted folder is held", () => {
expect(
gatedMountFor({
target: { path: "/home/cb-4/workspace/workspaces/5/projects/a.txt", kind: "delete" },
mounts,
}),
).toBe(workspace_mount);
});
test("the computer's own spelling of the same path is held too", () => {
expect(
gatedMountFor({
target: { path: "/home/gem/workspace/workspaces/5/projects/a.txt", kind: "delete" },
mounts,
}),
).toBe(workspace_mount);
});
test("a computer link inside the bot's own folder is held", () => {
expect(
gatedMountFor({
target: { path: "/home/cb-4/workspace/hosts/photos/2024/a.jpg", kind: "delete" },
mounts,
}),
).toBe(computer_mount);
});
test("the bot's own files are not held", () => {
expect(
gatedMountFor({
target: { path: "/home/cb-4/workspace/users/1/notes.md", kind: "delete" },
mounts,
}),
).toBeNull();
});
test("a path that only shares a prefix with a mount is not inside it", () => {
expect(
gatedMountFor({
target: { path: "/home/cb-4/workspace/workspaces/5/projects-old/a.txt", kind: "delete" },
mounts,
}),
).toBeNull();
});
test("a move inside the same folder is a rename, so nothing leaves the host", () => {
expect(
gatedMountFor({
target: {
path: "/home/cb-4/workspace/workspaces/5/projects/a.txt",
kind: "move",
destination: "/home/cb-4/workspace/workspaces/5/projects/archive/a.txt",
},
mounts,
}),
).toBeNull();
});
test("a move out of the folder is held", () => {
expect(
gatedMountFor({
target: {
path: "/home/cb-4/workspace/workspaces/5/projects/a.txt",
kind: "move",
destination: "/home/cb-4/workspace/users/1/a.txt",
},
mounts,
}),
).toBe(workspace_mount);
});
test("a move from one mounted folder into another is held", () => {
expect(
gatedMountFor({
target: {
path: "/home/cb-4/workspace/hosts/photos/a.jpg",
kind: "move",
destination: "/home/cb-4/workspace/workspaces/5/projects/a.jpg",
},
mounts,
}),
).toBe(computer_mount);
});
});
+44
View File
@@ -0,0 +1,44 @@
import { isInsideDir } from "./computer-work-dirs";
import computerWorkspacePath from "./computer-workspace-path";
import type { HostDirectoryDeleteTarget } from "./host-directory-delete-paths";
/**
* A folder mounted from the host machine that asks before a delete, as the
* run sees it and as the computer spells it.
*/
export type HostDirectoryGatedMount = {
name: string;
/** The mount's path in the computer's own spelling. */
real_target: string;
/** The same folder as the run sees it. */
run_target: string;
};
/**
* Which mounted folder a delete target is in, if any.
*
* A path is checked as the computer spells it, so both a worker's
* `/home/cb-<bot>/workspace/...` and the real `/home/gem/workspace/...`
* match. A move is only held when it would take the path out of the folder:
* a rename inside it leaves the host with the same files.
*/
export default function gatedMountFor({
target,
mounts,
}: {
target: HostDirectoryDeleteTarget;
mounts: HostDirectoryGatedMount[];
}): HostDirectoryGatedMount | null {
const real = computerWorkspacePath({ absolute: target.path });
const mount = mounts.find((item) => isInsideDir({ parent: item.real_target, child: real }));
if (!mount) return null;
if (target.kind == "move" && target.destination) {
const destination = computerWorkspacePath({ absolute: target.destination });
if (isInsideDir({ parent: mount.real_target, child: destination })) return null;
}
return mount;
}