diff --git a/CHANGELOG.md b/CHANGELOG.md index e626f91b..261812f1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -139,6 +139,7 @@ These changes are on `main` and go out in the next release. - **`devvm doctor` checks every VM's state:** it reads each VM's `vm.json` and each of its sections as every command on a VM does, and warns of each VM whose state devvm can't read, naming the VM and why, the file included, once, even when it can't read the VM's folder, without changing anything. Such a VM no longer hides doctor's warnings about the other VMs' policy files, nor what `devvm network` warns of every VM ([a file devvm can't read](https://next.devvm.dev/docs/using/troubleshooting/#a-file-devvm-cant-read)). - **A marketplace's credential gets a warning:** when `devvm agent import` or `devvm agent save` copies a Claude Code marketplace that has a password or an access token in its clone's git config or its source in `known_marketplaces.json`, which every VM with Claude Code can read, it warns and names the marketplace, the store's file and the keys, and copies it as before ([mounts](https://next.devvm.dev/docs/using/coding-agents/#mounts)). - **`devvm agent import` copies at most 20,000 files and folders, and 128 MiB, of each agent's folder:** an agent's folder that holds more, such as one a VM's project inside it filled, fails the import before the store changes, naming the folder, so take out what it doesn't need and import again. The import also warns of each VM whose project folder is inside an agent's folder, such as a skill you work on in `~/.claude/skills`, or holds one, such as `~/.pi`, because that VM can change the settings the import copies for every VM, and it leaves out an agent's folder that a link in a VM's project folder leads elsewhere ([importing from this machine](https://next.devvm.dev/docs/using/coding-agents/#importing-from-this-machine)). +- **A launch warns of a project in an agent's folder:** when a VM's project folder is inside a coding agent's folder on this machine, such as `~/.claude/skills/mine`, or holds one, such as `~/.pi`, each launch of the VM warns in one line, because code in the VM can change that agent's settings on this machine ([project folders devvm refuses](https://next.devvm.dev/docs/using/settings/#project-folders-devvm-refuses)). - **Cursor's CLI in a VM can change less of your Cursor account:** its proxy refuses more of the methods that change your account, your team or your cloud agents, such as merging a cloud agent's pull request, forking or pinning a cloud agent, or writing to its machine, while every call the CLI itself makes passes. Do those from Cursor on your machine ([Cursor CLI login](https://next.devvm.dev/docs/using/coding-agents/#cursor-cli-login)). - **Pins:** Cursor's CLI is 2026.11.17-f532c45. @@ -149,6 +150,7 @@ These changes are on `main` and go out in the next release. - **Your claude.ai connectors work in a VM (#61):** with your subscription's login, Claude Code in a VM couldn't use the connectors you added in claude.ai, because the VM's proxy put the login only into requests to `api.anthropic.com`, so those to `mcp-proxy.anthropic.com`, which carries the connectors' traffic, held the login's placeholder and were refused. From each VM's next launch, the proxy puts the login into those too, below `/v1/mcp/`, so a VM with Claude Code can use every connector you added, as Claude Code on this machine can, and code in the VM can read and act through them. Disconnect the ones you don't want VMs to use, or deny `mcp-proxy.anthropic.com` with `devvm network deny` ([your claude.ai connectors](https://next.devvm.dev/docs/safety/attack-vectors/#the-network)). A Claude Code token, from `claude setup-token` or in devvm's environment, still goes only to `api.anthropic.com` ([Claude Code login](https://next.devvm.dev/docs/using/coding-agents/#claude-code-login)). - **A `NO_PROXY` address with a zone no longer goes direct (#59):** an IPv6 address with a zone in your company proxy's `NO_PROXY`, such as `fe80::1%eth0`, sent that address without its zone past the company proxy. Such an entry now matches nothing, as it does in Go's HTTP clients ([behind a company proxy](https://next.devvm.dev/docs/safety/network/#behind-a-company-proxy)). - **Claude Code's plugins work in a VM (#56):** a VM's `~/.claude/plugins` was devvm's agent store's folder, mounted read-only, so everything Claude Code writes there failed, such as a plugin's data in `${CLAUDE_PLUGIN_DATA}`, installing a plugin and updating a marketplace. Each VM's `~/.claude/plugins` is now its own folder, and the store's plugins are Claude Code's read-only seed at `~/.claude/plugins-seed`, so the store's plugins load as before, a plugin keeps its data in the VM, and a plugin you install in a VM stays in that VM until `devvm agent save` copies it into the store. The save adds plugins to the store and never takes one out, and an export of a VM's history leaves its plugins folder out. A store that devvm 0.1.0's import filled keeps only what a seed has, as Breaking above says ([Claude Code's plugins](https://next.devvm.dev/docs/using/coding-agents/#claude-codes-plugins)). +- **devvm's own folders are refused in any case on a Mac:** devvm compared a project folder with your home folder and its own folders by name alone, so on a Mac, where a name's case doesn't count, a project at `~/.Config/devvm/layers` got a VM with read-write access to devvm's settings and layer scripts. devvm now compares the folders themselves too, and refuses such a folder as it refuses `~/.config/devvm/layers`. A VM already made in such a folder still mounts it, so delete it with `devvm rm` there. An SSH key in a folder that a VM mounts by a name in another case is refused in the same way ([project folders devvm refuses](https://next.devvm.dev/docs/using/settings/#project-folders-devvm-refuses)). - **A folder that moved across a restart keeps its VM:** a folder that moved while a restart gave its disk another device number wasn't recognised, so devvm made it a second VM, and the gone folder of a VM whose disk was renumbered was called not connected. Each VM now records its folder's volume, which no renumbering changes: its volume UUID on macOS, and the file system's own ID on Linux's ext4, Btrfs and ZFS. So devvm offers a moved folder its VM by its volume, inode and birth time, and calls a VM's gone folder gone, once the VM has recorded its volume, as After you upgrade says ([a moved or renamed folder](https://next.devvm.dev/docs/using/vms/#a-moved-or-renamed-folder)). A folder at the VM's own path whose disk was renumbered, but on another volume than the one recorded, such as a copy of the disk with a volume ID of its own mounted there, is another folder, so devvm gives it the VM only after `devvm adopt` ([a folder made again](https://next.devvm.dev/docs/using/vms/#a-folder-made-again)). - **A link inside an agent's folder copies only a setting:** `devvm agent import` copied a link inside an agent's folder as the file it led to wherever that file was in the folder, so a link in `~/.claude/skills` or `~/.claude/plugins/cache` could put your history, `~/.claude/.credentials.json` or a plugin's data into the store, where every VM with the agent reads it. Such a link is now copied only when it leads to one of the settings the import copies, and any other is left out with a warning that names where it leads ([importing from this machine](https://next.devvm.dev/docs/using/coding-agents/#importing-from-this-machine)). - **`devvm agent import` no longer copies your plugins' data into every VM:** it copied all of `~/.claude/plugins` into the store, so every VM with Claude Code got the data that your plugins keep on this machine, which can hold their own logins. It now copies only the marketplaces, their records and the plugins' cache, and `devvm agent save` copies only those from a VM ([importing from this machine](https://next.devvm.dev/docs/using/coding-agents/#importing-from-this-machine)). diff --git a/docs/content/docs/contributing/structure.md b/docs/content/docs/contributing/structure.md index 4892f727..eeb388d6 100644 --- a/docs/content/docs/contributing/structure.md +++ b/docs/content/docs/contributing/structure.md @@ -92,7 +92,7 @@ Each package owns these concerns, and a package's `doc.go`, where it has one, ma | `internal/ui` | the only package that prints: `ui.UI`, with messages, prompts, the status line, the run log and the cleanups, and `ui.Main`, which handles signals. It has no package state | | `internal/msg`, `locales` | messages: `en.toml`, the generated functions, the doc links (`docs.go`), the generator (`gen/`), `Reporter` and `Question` ([messages](cli.md#messages)) | | `internal/ports` | a VM's ports section, with the forwards asked for and the host ports chosen, and the one allocator of host ports, under the claims lock, which puts VMs' ssh only on the ports browsers refuse (`SSHPorts`) | -| `internal/paths` | every folder and file devvm uses, a VM's in its folder (`Dirs.VM`, and a project VM's folder, `vms//`, from `Dirs.VMDir`), and host paths resolved and compared (`Physical`, `PhysicalParent`, `Within` and `Below`, where `resolve.go` says which one is for what) | +| `internal/paths` | every folder and file devvm uses, a VM's in its folder (`Dirs.VM`, and a project VM's folder, `vms//`, from `Dirs.VMDir`), and host paths resolved and compared (`Physical`, `PhysicalParent`, `Within`, `Below`, `In` and `Under`, where `resolve.go` says which one is for what) | | `internal/state` | a VM's state, `vm.json`, with its core fields and one section for each package, which changes only in `VM.Update` under the VM's lock. It also owns the layout version (`CheckLayout` and `migrations`, while `testdata/script/layout.txtar` lists every file), every file written whole (`WriteFile`, `WriteFileMode`) and private folders (`PrivateDir`) | | `internal/settings` | the defaults (`Defaults`, `Read`, `Save`), with your `config.toml`, read strictly, over devvm's `settings.json`, and each value's check (`ParsePorts`, `ParseCPUs`, `ParseGiB` and the retention settings) | | `internal/platform` | the code for each system, behind build tags | @@ -153,7 +153,7 @@ The shared tools have one owner too, the table `image.SharedTools` in `internal/ The scripts that devvm's builds run with bash have one owner for the machine they run on, `assets/prelude.sh`, whose `$devvm_arch`, `$devvm_libc` and `devvm_sha` give each script its architecture, its C library and its pinned checksum for each download ([the scripts' prelude](../internals/images.md#the-scripts-prelude)). A script reads them rather than run `uname -m` or look for `apk` itself, and checks that the prelude came first with `: "${devvm_arch:?}"` for each variable it reads, which also tells shellcheck that the variable is set. Go reads each of those scripts through `image.OwnScript`, which puts the prelude before it, so a recipe, a tool image's key and the conversion's copy of `oci/build.sh` all hold the two together. `TestPreludeUsers` in `internal/image` fails when a script that doesn't get the prelude, such as `assets/oci/bootify.sh` or `assets/guest/`'s, uses it, or when a script reads a variable without that check. `testdata/script/prelude.txtar` checks which pin `devvm_sha` picks from each script's pins on arm64 and amd64, with glibc and with musl. A CLI test or a Go test that sources one of these scripts sources `assets/prelude.sh` first. -`internal/paths` also owns how a path on the host is resolved and compared with a folder, in `resolve.go`, whose comment says which resolver each question takes. `paths.Physical` resolves every symlink as far as the path exists, for where a folder or file really is, such as a project folder against devvm's own folders or an SSH key against the folders VMs mount. `paths.PhysicalParent` resolves only the folder's symlinks and keeps the last element as named, for a path that may itself be a symlink devvm mustn't follow, such as a key's recorded path or a Seatbelt rule. `filepath.EvalSymlinks` itself, which fails when the path doesn't exist, is for a path that must exist, such as the folder devvm runs in. Then `paths.Within` tells whether a path is a folder or inside it, and `paths.Below` whether it's inside it only. Both compare names, so both paths are resolved the same way first. +`internal/paths` also owns how a path on the host is resolved and compared with a folder, in `resolve.go`, whose comment says which resolver each question takes. `paths.Physical` resolves every symlink as far as the path exists, for where a folder or file really is, such as a project folder against devvm's own folders or an SSH key against the folders VMs mount. `paths.PhysicalParent` resolves only the folder's symlinks and keeps the last element as named, for a path that may itself be a symlink devvm mustn't follow, such as a key's recorded path or a Seatbelt rule. `filepath.EvalSymlinks` itself, which fails when the path doesn't exist, is for a path that must exist, such as the folder devvm runs in. Then `paths.Within` tells whether a path is a folder or inside it, and `paths.Below` whether it's inside it only. Both compare names, so both paths are resolved the same way first. A check that keeps a VM away from a folder, such as `project.Unsafe`'s, an SSH key against the folders VMs mount, or a project folder against an agent's folder, uses `paths.In` or `paths.Under` instead, which also compare the folder itself: the path, or a folder above it, is the same folder as the other, by device and inode. On a volume that ignores case, as macOS's do by default, `~/.Config/devvm` is `~/.config/devvm`, which a comparison of names alone misses. A VM's state, `vm.json`, has one owner too, `internal/state`, which reads and writes the whole file and knows only its core fields. Every other package that keeps something of a VM's owns one section of it, with its own type, its name (`Section`), and an `Of` that reads it through `state.Section`: `internal/netpolicy` owns `net`, `internal/gitprotect` `git`, `internal/ports` `ports`, `internal/sshagent` `agent`, `internal/tools` `tools`, `internal/secrets` `secrets`, and `internal/vm` `size`, `clone`, `devcontainer`, `desktop` and `links` (`internal/vm/state.go`). A section's type keeps what the user asked for at its top level and what devvm made under `made`. A change goes through `state.VM.Update`, which takes the VM's lock, reads the file again, runs the change and writes the file once: the change sets its section with `state.SetSection` and works out a list's new value from the file as it is then, never from what the command read earlier, so a change another devvm made meanwhile is kept. A change that fails writes nothing. `Update` holds one VM's lock, so a change takes no other lock inside it, and a change to several VMs updates each in turn. Test builds and the tests panic on a lock taken out of that order ([the lock rule](../internals/design.md#the-state-layout)). `state.VM.Claim` is `Update` that also holds the claims lock, for what no two VMs may have (`ports.Allocator` chooses every VM's host port through it), and `state.VM.Create` writes a new VM's whole state once, its ssh alias chosen under the claims lock. A build VM has no state, so `ports.Allocator.Build` chooses its ssh port through `state.Claims`, which holds the claims lock alone. A VM's alias is one `vmname.IsAlias` accepts, or devvm doesn't use it. `internal/vm`'s `checkState` reads every section of the folder's VM's state as the VM is found, so a section that can't be read stops the command instead of reading as empty. A new section adds its check there. diff --git a/docs/content/docs/internals/security.md b/docs/content/docs/internals/security.md index 806ec9a5..cc54052d 100644 --- a/docs/content/docs/internals/security.md +++ b/docs/content/docs/internals/security.md @@ -19,7 +19,9 @@ devvm refuses a project folder that would hand the VM more than the project: - A folder that is or holds your home folder, devvm's settings (`~/.config/devvm`), its state (`~/.local/share/devvm`, which holds its binaries and other VMs' disks) or its Lima home (`unsafe_folder`). - A folder inside devvm's own folders (`unsafe_folder_inside`). A VM in `~/.config/devvm/layers` could rewrite the scripts that every image build runs, and a VM in devvm's data folder could rewrite the files devvm runs on the host. -`--unsafe-folder` mounts such a folder anyway, and devvm says so. A `--clone` VM mounts nothing, so devvm doesn't refuse its folder. +devvm compares each of these folders with the project folder by path and by the folder itself: the project folder, or a folder above it, is the same folder as one of devvm's, by device and inode, or the other way round. So on a volume that ignores case, as a Mac's does by default, a project at `~/.Config/devvm/layers` is inside `~/.config/devvm`, although the two paths differ. `--unsafe-folder` mounts such a folder anyway, and devvm says so. A `--clone` VM mounts nothing, so devvm doesn't refuse its folder. + +A project folder inside a coding agent's folder in your home folder, such as `~/.claude/skills/mine`, or one that holds an agent's folder, such as `~/.pi` for pi's `~/.pi/agent`, gives its VM read-write access to that agent's settings on this machine, such as Claude Code's hooks, which run on the host. devvm doesn't refuse such a folder, because working on a skill in place is common, but each launch of a VM that mounts it warns once, naming every agent's folder it overlaps (`project_agent_folder`), by the same comparison, and by the agent folder's name too, so a folder the VM could make later counts. A `--clone` VM gets no warning. ### One VM per folder diff --git a/docs/content/docs/using/coding-agents.md b/docs/content/docs/using/coding-agents.md index a6deb4f1..e14292f8 100644 --- a/docs/content/docs/using/coding-agents.md +++ b/docs/content/docs/using/coding-agents.md @@ -118,7 +118,7 @@ devvm says which agents it imported and where, and an agent you named that your - The import copies only the paths in the table above, so it never copies your history or `~/.claude/.credentials.json` ([what it copies](../internals/agents.md#importing)). From `~/.claude.json` it keeps only the settings, account state and MCP servers, so your API key and your per-project entries stay out of the store. From `~/.claude/plugins` it copies only the marketplaces, their records and the plugins' cache, never what is this machine's own, such as each plugin's data. - devvm reads each agent's settings inside the agent's own folder, such as `~/.claude`. A link to a file inside the folder becomes a copy of that file when that file is one of the settings that the import copies, such as `~/.claude/CLAUDE.md`. A link to anything else inside the folder, such as your history, `~/.claude/.credentials.json` or a plugin's data, is left out with a warning that names where it leads, and so is a link to a folder inside it, or one that leads nowhere. A login file that's a link is always left out with a warning too. A link that leads out of the folder, by a relative or an absolute path, is copied only when you allow it ([links out of an agent's folder](#links-out-of-an-agents-folder)). - One import copies at most 20,000 files and folders, and 128 MiB, of each agent's own folder. When the folder holds more, devvm imports nothing and names the folder, so take out what it doesn't need, such as a plugin's build files, and import again. -- When a VM's project folder is inside an agent's folder, such as a skill you work on in `~/.claude/skills`, or holds one, such as `~/.pi`, devvm warns that the VM can change the settings it imports for every VM, so keep such a project somewhere else unless you trust that VM. An agent's folder that a link in a VM's project folder leads elsewhere is left out with a warning. +- When a VM's project folder is inside an agent's folder, such as a skill you work on in `~/.claude/skills`, or holds one, such as `~/.pi`, devvm warns that the VM can change the settings it imports for every VM, so keep such a project somewhere else unless you trust that VM. Each launch of such a VM warns too ([project folders devvm refuses](settings.md#project-folders-devvm-refuses)). An agent's folder that a link in a VM's project folder leads elsewhere is left out with a warning. - When the store already has settings or a login of an agent you import, devvm asks in a terminal whether to replace them, with no as the default. Without a terminal, or with `--no-input`, devvm refuses and names `--force`, which replaces them without asking. An agent whose settings aren't in your home folder keeps the store's settings, and one without a login there keeps the store's login. - On macOS, Claude Code keeps its own login in the Keychain, and devvm neither reads it nor copies it. You log Claude Code in from a VM instead, with `devvm agent login claude`, and every VM with Claude Code gets that login ([Claude Code login](#claude-code-login)). - When this machine's opencode is version 2 or later, devvm saves the API key of each provider, and your OpenAI login when you made it with one of opencode's Codex logins, the browser or the headless one. Any other login is left out with a warning that names it, such as opencode's Sign in with ChatGPT, whose tokens a VM can't use, or another provider's OAuth login, and you log in from a VM instead, with `devvm agent login opencode` ([logging in with devvm agent login](#logging-in-with-devvm-agent-login)). When `opencode auth export` fails, the import fails too, and the store keeps the login it had. diff --git a/docs/content/docs/using/settings.md b/docs/content/docs/using/settings.md index f863c844..c7c85583 100644 --- a/docs/content/docs/using/settings.md +++ b/docs/content/docs/using/settings.md @@ -311,9 +311,9 @@ A CA in the folder can read every TLS connection a VM makes, as it can this mach ## Project folders devvm refuses -A VM mounts its project folder read-write, so devvm refuses to make a VM for a folder that would give the VM more than the project. It refuses a folder that is or holds your home folder, `~/.config/devvm`, `~/.local/share/devvm` or devvm's Lima home. It also refuses a folder inside one of devvm's own folders, because a VM there could rewrite the scripts that every image build runs, or the files that devvm runs on this machine. +A VM mounts its project folder read-write, so devvm refuses to make a VM for a folder that would give the VM more than the project. It refuses a folder that is or holds your home folder, `~/.config/devvm`, `~/.local/share/devvm` or devvm's Lima home. It also refuses a folder inside one of devvm's own folders, because a VM there could rewrite the scripts that every image build runs, or the files that devvm runs on this machine. devvm compares the folders themselves, not only their names, so on a Mac, where a name's case doesn't count, `~/.Config/devvm` is refused as `~/.config/devvm` is. -When devvm refuses a folder, make the VM in a project folder inside it, or keep the project somewhere else. A [`--clone`](clone.md) VM mounts nothing from the folder, so devvm doesn't refuse its folder. +When devvm refuses a folder, make the VM in a project folder inside it, or keep the project somewhere else. A [`--clone`](clone.md) VM mounts nothing from the folder, so devvm doesn't refuse its folder. A folder inside a coding agent's folder on this machine, such as a skill you work on in `~/.claude/skills`, or one that holds an agent's folder, such as `~/.pi`, isn't refused, but devvm warns at each launch, because code in the VM can change that agent's settings on this machine. Keep such a project somewhere else unless you trust what runs in its VM. > [!WARNING] > If you mean to give the VM the whole folder, pass `--unsafe-folder` when you make the VM, and devvm warns you that the VM gets read-write access to it ([only the project folder](../internals/security.md#only-the-project-folder)). diff --git a/internal/msg/docs.go b/internal/msg/docs.go index 30a6869f..f130aeee 100644 --- a/internal/msg/docs.go +++ b/internal/msg/docs.go @@ -134,6 +134,7 @@ var docs = map[string]string{ //nolint:gosec // message IDs and pages, not crede "project_folder_changed": "using/vms#a-nested-project-replaced", "project_folder_changed_stopped": "using/vms#a-nested-project-replaced", "project_in_vm_folder": "using/vms#a-nested-project-replaced", + "project_agent_folder": "using/settings#project-folders-devvm-refuses", "adopt_folder_there": "using/vms#a-moved-or-renamed-folder", "adopt_has_vm": "using/vms#a-moved-or-renamed-folder", "adopt_clone": "using/vms#a-moved-or-renamed-folder", diff --git a/internal/msg/messages_gen.go b/internal/msg/messages_gen.go index 7905782e..acee9c8a 100644 --- a/internal/msg/messages_gen.go +++ b/internal/msg/messages_gen.go @@ -3948,6 +3948,11 @@ func ProgramOldFix(fix string, name string, version string) M { return M{id: "program_old_fix", vals: []val{{"fix", fix}, {"name", name}, {"version", version}}} } +// ProjectAgentFolder is [project_agent_folder]: "{{.dir}} overlaps {{.folders}}, so code in the VM can change your coding agents' settings on this machine. Keep the project somewhere else unless you trust it." +func ProjectAgentFolder(dir string, folders string) M { + return M{id: "project_agent_folder", vals: []val{{"dir", dir}, {"folders", folders}}} +} + // ProjectFolderChanged is [project_folder_changed]: "{{.dir}} became a link or another folder after devvm found {{.vm}}, so devvm didn't start the VM, which would have mounted it. Find what replaced it and put the project folder back, then run the command again." func ProjectFolderChanged(dir string, vm vmname.VM) M { return M{id: "project_folder_changed", vals: []val{{"dir", dir}, {"vm", string(vm)}}} @@ -6248,6 +6253,7 @@ var specs = map[string]spec{ "program_missing_fix": {fields: []string{"fix", "name", "program"}}, "program_old": {fields: []string{"min", "name", "version"}}, "program_old_fix": {fields: []string{"fix", "name", "version"}}, + "project_agent_folder": {fields: []string{"dir", "folders"}}, "project_folder_changed": {fields: []string{"dir", "vm"}}, "project_folder_changed_stopped": {fields: []string{"dir", "vm"}}, "project_in_vm_folder": {fields: []string{"dir", "vm"}}, diff --git a/internal/paths/resolve.go b/internal/paths/resolve.go index d80f5d42..f2f9cfb5 100644 --- a/internal/paths/resolve.go +++ b/internal/paths/resolve.go @@ -1,6 +1,7 @@ package paths import ( + "os" "path/filepath" "strings" ) @@ -20,7 +21,8 @@ import ( // TARGET, mise's folder. // // Then Within and Below compare it with a folder that is resolved the -// same way. +// same way, by name; In and Under by identity too, for a check that keeps +// a VM away from a folder. // Physical returns path with its symlinks resolved, as far as it exists: // the part that doesn't is joined, as named, onto the deepest folder that @@ -59,3 +61,36 @@ func Within(path, dir string) bool { func Below(path, dir string) bool { return path != dir && strings.HasPrefix(path, strings.TrimSuffix(dir, "/")+"/") } + +// In reports whether path is dir or inside it: by name, as Within, or by +// identity, path or a folder above it being the same folder as dir, so a +// name that differs only in case on a volume that ignores it, such as +// ~/.Config on macOS, is still dir. A check that keeps a VM away from a +// folder uses In, never Within alone. An empty dir holds nothing. +func In(path, dir string) bool { + if dir == "" { + return false + } + if Within(path, dir) { + return true + } + d, err := os.Stat(dir) + if err != nil { + return false + } + for p := filepath.Clean(path); ; p = filepath.Dir(p) { + if fi, err := os.Stat(p); err == nil && os.SameFile(fi, d) { + return true + } + if filepath.Dir(p) == p { + return false + } + } +} + +// Under reports whether path is inside dir, and isn't dir itself, as In +// finds it: its folder is In dir. +func Under(path, dir string) bool { + path = filepath.Clean(path) + return filepath.Dir(path) != path && In(filepath.Dir(path), dir) +} diff --git a/internal/paths/resolve_test.go b/internal/paths/resolve_test.go index 36b2634c..29a8d113 100644 --- a/internal/paths/resolve_test.go +++ b/internal/paths/resolve_test.go @@ -40,6 +40,54 @@ func TestPhysical(t *testing.T) { } } +// In and Under find a path in a folder by name, as Within and Below do, +// and by identity too: on a volume that ignores case, such as macOS's, a +// name in another case is the same folder. An empty folder holds nothing. +func TestInAndUnder(t *testing.T) { + root, err := filepath.EvalSymlinks(t.TempDir()) + if err != nil { + t.Fatal(err) + } + dir := filepath.Join(root, "dir") + if err := os.MkdirAll(filepath.Join(dir, "sub"), 0o700); err != nil { + t.Fatal(err) + } + cases := []struct { + path, dir string + in, under bool + }{ + {dir, dir, true, false}, + {filepath.Join(dir, "sub"), dir, true, true}, + {filepath.Join(dir, "none", "deeper"), dir, true, true}, + {dir + "x", dir, false, false}, + {root, dir, false, false}, + {"/", "/", true, false}, + {dir, "", false, false}, + } + if _, err := os.Stat(filepath.Join(root, "DIR")); err == nil { + cases = append(cases, []struct { + path, dir string + in, under bool + }{ + {filepath.Join(root, "DIR"), dir, true, false}, + {filepath.Join(root, "Dir", "sub"), dir, true, true}, + {filepath.Join(root, "Dir", "SUB", "none"), dir, true, true}, + {dir, filepath.Join(root, "DIR"), true, false}, + {filepath.Join(root, "DIRx"), dir, false, false}, + }...) + } else { + t.Log("this volume tells names apart by case: only the cases by name ran") + } + for _, tc := range cases { + if got := In(tc.path, tc.dir); got != tc.in { + t.Errorf("In(%s, %s) = %v", tc.path, tc.dir, got) + } + if got := Under(tc.path, tc.dir); got != tc.under { + t.Errorf("Under(%s, %s) = %v", tc.path, tc.dir, got) + } + } +} + // Within is the folder or inside it; Below only inside it. func TestWithinAndBelow(t *testing.T) { for _, tc := range []struct { diff --git a/internal/project/project.go b/internal/project/project.go index 45bb660f..2d591217 100644 --- a/internal/project/project.go +++ b/internal/project/project.go @@ -188,11 +188,12 @@ type Unsafe struct { // Holds returns the first of these folders that dir, a physical path, is // or holds (any folder holds /), each by its physical path -// (paths.Physical), or "". The VM would get them read-write: tokens, the -// proxy's CA key and binary, other VMs' disks. +// (paths.Physical) and by identity (paths.In), so a name in another case +// on a volume that ignores it holds it too, or "". The VM would get them +// read-write: tokens, the proxy's CA key and binary, other VMs' disks. func (u Unsafe) Holds(dir string) string { for _, p := range []string{u.Home, u.Config, u.Data, u.Lima} { - if paths.Within(paths.Physical(p), dir) { + if p != "" && paths.In(paths.Physical(p), dir) { return p } } @@ -200,12 +201,12 @@ func (u Unsafe) Holds(dir string) string { } // Inside returns the first of devvm's own folders that dir, a physical -// path, is below (paths.Below), or "". A VM in the layers folder could -// rewrite the scripts every image build runs; one in the data folder, the -// binaries that run on the host. +// path, is below, by name or identity (paths.Under), or "". A VM in the +// layers folder could rewrite the scripts every image build runs; one in +// the data folder, the binaries that run on the host. func (u Unsafe) Inside(dir string) string { for _, p := range []string{u.Config, u.Data, u.Lima} { - if paths.Below(dir, paths.Physical(p)) { + if p != "" && paths.Under(dir, paths.Physical(p)) { return p } } diff --git a/internal/project/project_test.go b/internal/project/project_test.go index f1d876ed..788d039f 100644 --- a/internal/project/project_test.go +++ b/internal/project/project_test.go @@ -258,6 +258,45 @@ func TestUnsafe(t *testing.T) { } } +// On a volume that ignores case, such as macOS's, a folder named in +// another case is still devvm's own: a project there is or holds it, or +// is inside it. +func TestUnsafeIgnoresCase(t *testing.T) { + root, err := filepath.EvalSymlinks(t.TempDir()) + if err != nil { + t.Fatal(err) + } + u := Unsafe{ + Home: filepath.Join(root, "home"), + Config: filepath.Join(root, "config", "devvm"), + Data: filepath.Join(root, "data", "devvm"), + Lima: filepath.Join(root, "data", "devvm", "lima"), + } + mkdirs(t, u.Home, u.Config, u.Lima) + if _, err := os.Stat(filepath.Join(root, "HOME")); err != nil { + t.Skip("this volume tells names apart by case") + } + for _, tc := range []struct{ dir, holds, inside string }{ + {filepath.Join(root, "HOME"), u.Home, ""}, + {filepath.Join(root, "Config"), u.Config, ""}, + {filepath.Join(root, "Config", "Devvm"), u.Config, ""}, + {filepath.Join(root, "Config", "devvm", "layers"), "", u.Config}, + {filepath.Join(root, "DATA", "devvm", "mise"), "", u.Data}, + {filepath.Join(root, "data", "devvm", "LIMA", "x"), "", u.Data}, + {filepath.Join(root, "HOME", "proj"), "", ""}, + } { + if err := os.MkdirAll(tc.dir, 0o700); err != nil { + t.Fatal(err) + } + if got := u.Holds(tc.dir); got != tc.holds { + t.Errorf("Holds(%s) = %q, want %q", tc.dir, got, tc.holds) + } + if got := u.Inside(tc.dir); got != tc.inside { + t.Errorf("Inside(%s) = %q, want %q", tc.dir, got, tc.inside) + } + } +} + // Parents lists the folders a folder is inside, nearest first, stopping // before the home folder (given through a symlink too) and the root. func TestParents(t *testing.T) { diff --git a/internal/sshagent/sshagent.go b/internal/sshagent/sshagent.go index aca7521b..06a7c72f 100644 --- a/internal/sshagent/sshagent.go +++ b/internal/sshagent/sshagent.go @@ -391,7 +391,9 @@ func (a *Agent) load(ctx context.Context, k AddedKey) (string, error) { // mountedBy returns a project VM that mounts a folder holding the file key // names in the end (a link to a key in a project folder is as readable -// there), or "": both by their physical paths (paths.Physical). +// there), or "": both by their physical paths (paths.Physical), and by +// identity (paths.In), so a folder named in another case on a volume that +// ignores it still holds the key. func (a *Agent) mountedBy(ctx context.Context, key string) (vmname.VM, error) { file := paths.Physical(key) ms, err := a.Mounts(ctx) @@ -399,7 +401,7 @@ func (a *Agent) mountedBy(ctx context.Context, key string) (vmname.VM, error) { return "", err } for _, m := range ms { - if paths.Within(file, paths.Physical(m.Dir)) { + if paths.In(file, paths.Physical(m.Dir)) { return m.VM, nil } } diff --git a/internal/sshagent/sshagent_test.go b/internal/sshagent/sshagent_test.go index 257c385b..0cdb0004 100644 --- a/internal/sshagent/sshagent_test.go +++ b/internal/sshagent/sshagent_test.go @@ -352,6 +352,29 @@ func TestMountedKey(t *testing.T) { } } +// On a volume that ignores case, such as macOS's, a VM that mounts the +// key's folder by a name in another case still mounts the key. +func TestMountedKeyIgnoresCase(t *testing.T) { + a, f, _, tmp, mounts := testAgent(t) + proj := filepath.Join(tmp, "proj") + if err := os.MkdirAll(proj, 0o700); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(tmp, "PROJ")); err != nil { + t.Skip("this volume tells names apart by case") + } + key := filepath.Join(proj, "deploy_key") + writeKey(t, key, "deploy") + *mounts = []Mount{{VM: "devvm-proj-0123456789abcd", Dir: filepath.Join(tmp, "PROJ")}} + want := "agent_key_mounted key=" + key + " vm=devvm-proj-0123456789abcd" + if err := a.Add(t.Context(), key, AddOptions{}); msg.NamesOf(err) != want { + t.Errorf("add: %s, want %s", msg.NamesOf(err), want) + } + if len(f.held) != 0 { + t.Error("the key was loaded") + } +} + // keys lists what the agent holds, then each key added: its file, // fingerprint and options, its lifetime shown when it's the default. func TestKeys(t *testing.T) { diff --git a/internal/vm/agentlinks.go b/internal/vm/agentlinks.go index f7f2c7b2..b4cb4693 100644 --- a/internal/vm/agentlinks.go +++ b/internal/vm/agentlinks.go @@ -57,7 +57,7 @@ type linkOut struct { func outLink(home, p string) (linkOut, bool) { l := linkOut{p: p, path: filepath.Join(home, filepath.FromSlash(p))} target, hops, err := linkHops(l.path) - if err != nil || isIn(target, paths.Physical(home)) { + if err != nil || paths.In(target, paths.Physical(home)) { return l, false } fi, err := os.Stat(target) @@ -114,30 +114,6 @@ func linkHops(p string) (target string, hops []string, err error) { // own bound on a path's links. const linkMaxHops = 40 -// isIn reports whether p is dir or inside it: by name, as paths.Within, -// or by identity, p or a folder above it being the same file as dir, so -// a name that differs only in case on a file system that ignores case, -// such as ~/.SSH on macOS, is still dir. -func isIn(p, dir string) bool { - if paths.Within(p, dir) { - return true - } - d, err := os.Stat(dir) - if err != nil { - return false - } - for { - if fi, err := os.Stat(p); err == nil && os.SameFile(fi, d) { - return true - } - parent := filepath.Dir(p) - if parent == p { - return false - } - p = parent - } -} - // linkSource is where a file read through a link comes from: name in // root, read following a link at its end only within root (follow), and // the import's bounds (budget). @@ -197,14 +173,14 @@ func linkPlaces(d paths.Dirs) []string { // refusedPlace returns the place p, a physical path, is, holds or is in // (linkPlaces), or the home folder when p is it or holds it; "" for none. -// Each is compared by identity too (isIn), so another spelling of a +// Each is compared by identity too (paths.In), so another spelling of a // place, such as ~/.SSH where case doesn't count, is still that place. func refusedPlace(d paths.Dirs, p string) string { - if home := paths.Physical(d.Home); isIn(home, p) { + if home := paths.Physical(d.Home); paths.In(home, p) { return home } for _, place := range linkPlaces(d) { - if isIn(p, place) || isIn(place, p) { + if paths.In(p, place) || paths.In(place, p) { return place } } @@ -363,11 +339,9 @@ func projectVMs(d paths.Dirs) []projectVM { func (im AgentImport) warnProjectsInside(names []string) []projectVM { vms := projectVMs(im.Dirs) for _, a := range names { - // By name too, so a folder that a VM could make just before the import is warned of. folder := filepath.Join(im.Dirs.Home, agents.Of(a).Folder) - phys := paths.Physical(folder) for _, v := range vms { - if isIn(v.dir, phys) || isIn(phys, v.dir) || isIn(folder, v.dir) { + if overlapsAgent(v.dir, folder) { im.Warn(msg.AgentImportProjectInside(v.dir, folder, v.name)) } } @@ -375,6 +349,37 @@ func (im AgentImport) warnProjectsInside(names []string) []projectVM { return vms } +// overlapsAgent reports whether dir, a project folder's physical path, is +// inside folder, an agent's folder in the home folder, or holds it, by +// identity too (paths.In): code in dir's VM can change that agent's +// settings on this machine, and what devvm agent import copies from +// there. folder is compared as named too, so one that a VM could make +// later counts. +func overlapsAgent(dir, folder string) bool { + phys := paths.Physical(folder) + return paths.In(dir, phys) || paths.In(phys, dir) || paths.In(folder, dir) +} + +// warnAgentFolders warns once, when a launch has found t, if the folder +// t's VM mounts is inside an agent's folder in the home folder, or holds +// one (project_agent_folder): code in the VM can change that agent's +// settings on this machine. A --clone VM (clone: a new one) mounts +// nothing, so it gets no warning. +func (e Launch) warnAgentFolders(t *target, clone bool) { + if clone || t.st.Exists() && isClone(t.st) { + return + } + var folders []string + for _, a := range agents.Names() { + if folder := filepath.Join(e.Dirs.Home, agents.Of(a).Folder); overlapsAgent(t.f.Dir, folder) { + folders = append(folders, folder) + } + } + if len(folders) > 0 { + e.Warn(msg.ProjectAgentFolder(t.f.Dir, strings.Join(folders, ", "))) + } +} + // through returns the VM, if any, whose project folder a link on l's way // is in (l.hops) while l's target isn't: that VM chose where l leads, so // l could lead to any file of this machine's, and it's left out, whatever @@ -387,10 +392,10 @@ func (f *follower) through(l *linkOut) vmname.VM { return throughVM(f.projectVMs // machine's. func throughVM(vms []projectVM, target string, hops []string) vmname.VM { for _, v := range vms { - if isIn(target, v.dir) { + if paths.In(target, v.dir) { continue } - if slices.ContainsFunc(hops, func(h string) bool { return isIn(h, v.dir) }) { + if slices.ContainsFunc(hops, func(h string) bool { return paths.In(h, v.dir) }) { return v.name } } @@ -405,7 +410,7 @@ func (f *follower) projects(path, target string, dir bool) []msg.M { var ms []msg.M for _, v := range f.projectVMs() { key := path + "\x00" + v.name.String() - in := isIn(target, v.dir) || dir && isIn(v.dir, target) + in := paths.In(target, v.dir) || dir && paths.In(v.dir, target) if f.warned[key] || !in { continue } diff --git a/internal/vm/parent_test.go b/internal/vm/parent_test.go index f9ac8572..b8f23cd6 100644 --- a/internal/vm/parent_test.go +++ b/internal/vm/parent_test.go @@ -9,6 +9,7 @@ import ( "strings" "testing" + "github.com/devvmhq/devvm/internal/agents" "github.com/devvmhq/devvm/internal/backend" "github.com/devvmhq/devvm/internal/gitprotect" "github.com/devvmhq/devvm/internal/msg" @@ -282,6 +283,68 @@ func TestWarnMounted(t *testing.T) { up("below a --clone VM", Options{}, "") } +// A launch warns once when its project folder is inside a coding agent's +// folder in the home folder, or holds one (project_agent_folder), naming +// every such folder, at the VM's creation and at each launch after it; on +// a volume that ignores case, a name in another case too. A folder +// elsewhere and a new --clone VM, which mounts nothing, get no warning. +func TestWarnAgentFolders(t *testing.T) { + e, _, _ := upEnv(t, allNative()) + home := e.Dirs.Home + var warns msg.Recorder + fake(e).OnWarn = warns.Add + up := func(dir string, o Options, want string) { + t.Helper() + if err := os.MkdirAll(dir, 0o700); err != nil { + t.Fatal(err) + } + e.Dir = dir + warns.Reset() + if err := (Launch{e}).Up(t.Context(), o); !o.Clone && err != nil { + t.Fatalf("%s: %v", dir, msg.NamesOf(err)) + } + var got []string + for _, w := range warns.Names() { + if strings.HasPrefix(w, "project_agent_folder ") { + got = append(got, w) + } + } + if want == "" && len(got) != 0 || want != "" && !slices.Equal(got, []string{want}) { + t.Errorf("%s: warned %q, want %q", dir, got, want) + } + } + claude := filepath.Join(home, ".claude") + skill := filepath.Join(claude, "skills", "mine") + inClaude := "project_agent_folder dir=" + skill + " folders=" + claude + up(skill, Options{Network: "open"}, inClaude) + up(skill, Options{}, inClaude) + pi := filepath.Join(home, ".pi") + if err := os.MkdirAll(filepath.Join(pi, "agent"), 0o700); err != nil { + t.Fatal(err) + } + up(pi, Options{Network: "open"}, "project_agent_folder dir="+pi+" folders="+filepath.Join(pi, "agent")) + // An agent's folder that's a link to the project folder, by where it leads. + dot := filepath.Join(home, "dot") + if err := os.Symlink(dot, filepath.Join(home, ".codex")); err != nil { + t.Fatal(err) + } + up(dot, Options{Network: "open"}, "project_agent_folder dir="+dot+" folders="+filepath.Join(home, ".codex")) + // One line for a folder that holds several, made or not. + var all []string + for _, a := range agents.Names() { + all = append(all, filepath.Join(home, agents.Of(a).Folder)) + } + up(home, Options{Network: "open", UnsafeFolder: true}, "project_agent_folder dir="+home+" folders="+strings.Join(all, ", ")) + up(filepath.Join(home, "src", "app"), Options{Network: "open"}, "") + up(filepath.Join(claude, "skills", "cloned"), Options{Network: "open", Clone: true}, "") + if _, err := os.Stat(filepath.Join(home, ".CLAUDE")); err != nil { + t.Log("this volume tells names apart by case: no check of another case") + return + } + other := filepath.Join(home, ".CLAUDE", "skills", "other") + up(other, Options{Network: "open"}, "project_agent_folder dir="+other+" folders="+claude) +} + func vmNames(t *testing.T, e *Env) []vmname.VM { t.Helper() ns, err := state.VMNames(e.Dirs) diff --git a/internal/vm/up.go b/internal/vm/up.go index 15af68e4..d87b0d10 100644 --- a/internal/vm/up.go +++ b/internal/vm/up.go @@ -72,6 +72,7 @@ func (e Launch) Up(ctx context.Context, o Options) error { return err } e.finder.warnMounted(t, o.Clone) + e.warnAgentFolders(t, o.Clone) // A remake that didn't finish, whose machine may be gone: finished, // never made anew. if remakePending(t.st) { diff --git a/locales/en.toml b/locales/en.toml index a73899ae..d9782f05 100644 --- a/locales/en.toml +++ b/locales/en.toml @@ -1107,6 +1107,10 @@ other = "{{.dir}} became a link or another folder after devvm found {{.vm}}, so description = "dir is the project folder of the VM devvm launches, inside the folder another project VM, vm, mounts read-write" other = "{{.dir}} is inside the folder that {{.vm}} mounts, so code in that VM can change this project's files and replace its folder. To keep the two projects apart, move this one out of that folder." +[project_agent_folder] +description = "dir is the project folder of the VM devvm launches; folders are the coding agents' folders in the home folder that it holds or is inside, comma-separated" +other = "{{.dir}} overlaps {{.folders}}, so code in the VM can change your coding agents' settings on this machine. Keep the project somewhere else unless you trust it." + [project_folder_changed_stopped] description = "dir is vm's project folder, which became a link or another folder while vm started" other = "{{.dir}} became a link or another folder while {{.vm}} started, so devvm stopped the VM, which may have mounted it. Find what replaced it and put the project folder back, then run the command again." diff --git a/testdata/coverage/darwin.txt b/testdata/coverage/darwin.txt index ed18ab64..005fd08d 100644 --- a/testdata/coverage/darwin.txt +++ b/testdata/coverage/darwin.txt @@ -24,7 +24,7 @@ internal/leaktest 87.5 internal/memnet 96.8 internal/msg 72.1 internal/msg/gen 93.9 -internal/netpolicy 91.8 +internal/netpolicy 91.9 internal/paths 98.1 internal/platform 90.4 internal/ports 92.6