fix(vm): devvm agent save applies all or nothing under the login lock; a lock's wait and a walk end with their context; a link to the home folder counts unless only root can change it

All or nothing:
- devvm agent save goes through devvm agent import's undo journal: each
  plan's files are written into a staging folder of the agent's store
  (saver.stage, newStage, the import's .devvm-import- name, swept by the
  next import or save), then put in place (applyPlan: each file renamed in,
  the one it replaces kept aside as a hard link, folders made, what a folder
  no longer has moved aside, seeds and kept entries left), and the
  .claude.json subset saved last with secrets.SaveLogins, which holds the
  login's lock. A failure after the first change puts every agent's store
  and the login back; an undo that fails too says so
  (agent_save_undo_failed) and keeps the staging folder.
- applyStages (and stageSet) is what both commands apply through;
  importStage is now storeStage, pruneIn takes an fs.FS, and pruneFolder
  moves a folder's leftovers aside. pruneStore and applySettings go.
- A file in the VM where the store has a folder, or the other way round,
  fails the save before anything changes (agent_save_store_folder,
  agent_save_store_file; sameKind), where the stage would have replaced it without the diff
  showing; storeFiles reads such a path as empty.

Contexts:
- platform.LockDir flocks a folder, polling until ctx ends as LockFile
  does (waitLock is their shared loop); agentlogin's lockLogin is it, so
  the lock is the one an older devvm's proxy takes. LockLogin, LockFolder,
  File.CaptureRequest, Capture, SetKey, Remove and
  secrets.Store.CaptureRequest take a ctx. A capture whose reply the
  endpoint has given is saved with agentlogin.AfterReply's context, the
  exchange's without its end and bounded by two minutes of its own, so the
  exchange's deadline never loses a rotated login while a refresh or a save
  holds the lock, and a stalled holder never holds it for ever
  (File.Capture, secrets.Store.Capture, its loginsDir included).
- safefile.Walk takes a ctx and stops before each folder and batch once it
  ends; readSettings, followLinks and follower.copy pass theirs.
- LockFolder's comment said its lock was another than a login file's in
  the same folder; it's the same (.claude.json's), and says so.

Links while a state can't be read:
- homeHops exempted every link on the way to the home folder, on the
  claim that no project folder can hold one, which --unsafe-folder breaks.
  rootOnly exempts a link only when every folder above it, up to /, is
  root's, has no group or other write bit and the system says you can't
  write it (platform.Writable, access(2), which counts ACLs and FUSE), and
  devvm doesn't run as root.

The structure test lets internal/agentlogin import internal/platform and
counts platform.LockDir in its status-lines rule.

Tests that fail without their fix: TestAgentSaveApplyFailsWhole (a rename
and the login failing), TestAgentSaveUndoFails, TestAgentSaveLoginLock
(waits under agent_login_waiting; Ctrl-C leaves the stores as they were),
TestAgentSaveKindChanged, TestAgentImportHomeBelowALink,
TestCaptureOutlivesItsDeadline, TestClaudeCaptureOutlivesItsDeadline,
TestWalkCancelled, TestLockLogin (synctest:
a deadline and a cancel). New: TestLockDir (synctest, and a plain flock's
lock), TestRootOnly, TestWritable, the status-lines rule's LockDir case.
TestStoreOpsRefuseLinks checks openStoreDir in pruneStore's place.

Docs: internals/agents.md (saving, the staging folder, links to the home
folder), using/coding-agents.md, Contributing's CLI and structure pages;
CHANGELOG.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
w3cjandClaude Opus 5.5 committed 2026-11-19 16:49:51 -07:00
1 parent cb7177b32c
commit f80fd2df60
45 files changed
+1183 -388

No files matched your search

+2 -1
View File
@@ -138,7 +138,7 @@ These changes are on `main` and go out in the next release.
- **The proxy's child connects only through `devvm _proxy`:** wherever its sandbox runs, on macOS and on Linux, it refuses the child every connection of its own, so `devvm _proxy` looks up each name for it and opens each connection, once its own read of your rules and this machine's addresses allows the address. So a bug that a VM drove in the child can't reach this machine's services on `localhost`, such as your dev servers, Docker's published ports and other VMs' proxies, nor this machine's own addresses or your LAN's private addresses, unless a rule names the address, just as the VM can't. A rule such as `devvm network allow 127.0.0.1:5432` still applies from the next connection, and a company proxy on `localhost` still works, though the child reaches whatever that company proxy reaches, as the VM does. Because `devvm _proxy` looks up its names, the child reads no file below `/etc` on Linux and doesn't talk to mDNSResponder on macOS ([the child's sandbox](https://next.devvm.dev/docs/internals/network/#the-childs-sandbox)).
- **`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, folders and links, 128 MiB, and 16 MiB in one file, 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. An import that fails, while it reads, such as at a file that changed meanwhile, or while it puts the settings and logins in place, such as at a login it can't save, leaves the store as it was, and in the rare case that putting it back fails too, it names what it kept. 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 of each VM whose state it can't read, as it can't tell where that VM's project folder is. It leaves out an agent's folder that a link in a VM's project folder leads elsewhere, and while a VM's state can't be read, it leaves out every link out of an agent's folder, and an agent's folder or login whose path leads through a link, naming the state, so run `devvm doctor` and import again ([importing from this machine](https://next.devvm.dev/docs/using/coding-agents/#importing-from-this-machine)).
- **`devvm agent import` copies at most 20,000 files, folders and links, 128 MiB, and 16 MiB in one file, 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. An import that fails, while it reads, such as at a file that changed meanwhile, or while it puts the settings and logins in place, such as at a login it can't save, leaves the store as it was, and in the rare case that putting it back fails too, it names what it kept. 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 of each VM whose state it can't read, as it can't tell where that VM's project folder is. It leaves out an agent's folder that a link in a VM's project folder leads elsewhere, and while a VM's state can't be read, it leaves out every link out of an agent's folder, and an agent's folder or login whose path leads through a link, one on the way to your home folder included unless only root can change it, naming the state, so run `devvm doctor` and import again ([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.
@@ -156,6 +156,7 @@ These changes are on `main` and go out in the next release.
- **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)). When devvm can't read the volume at the launch after a renumbering, such as when `diskutil` doesn't answer, the volume stays to check, and each launch looks it up until it can. On Linux, where reading the volume costs nothing, every launch checks it, so a Btrfs snapshot rolled back at the folder's path, or the folder after you give its volume a new UUID, needs `devvm adopt` too.
- **Two devvms no longer write the agent store at once:** `devvm agent import`, `devvm agent save` and a start that cleans Claude Code's plugins out of the store now take turns, so a second one waits, saying so, until the first is done, where before their files could mix or one could fail partway. A save that finds the store changed since it showed what differs saves nothing, rather than write over an import ([importing from this machine](https://next.devvm.dev/docs/using/coding-agents/#importing-from-this-machine)).
- **A failed `devvm agent save` leaves the store as it was:** a save that failed partway, such as at a file it couldn't write in one agent's store or at the Claude Code login it saves last, left the agents it had saved before the failure saved and the rest not. It now saves all or nothing, as an import does, and in the rare case that putting the store back fails too, it names what it kept. A file in the VM where the store has a folder, or the other way round, fails the save before anything changes, naming the store's path. It also saves Claude Code's `~/.claude.json` part holding the lock of Claude Code's logins, which a VM's proxy holds while it saves a Claude Code login made in that VM, so the two take turns, and Ctrl-C while it waits for either lock ends the wait ([saving a VM's settings](https://next.devvm.dev/docs/using/coding-agents/#saving-a-vms-settings)).
- **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)).
- **An export can't put what an import leaves out into a VM:** `devvm history import` left out the agents' logins and the files devvm's setup writes by their names as an export wrote them, so an export that spelled one another way, such as `.claude/./settings.json` or `.claude//plugins`, got it into the VM's home. The import now refuses a name with a `.` or empty part, and deletes what it leaves out by its path once it's unpacked ([importing history](https://next.devvm.dev/docs/internals/agents/#importing-history)).
+1 -1
View File
@@ -34,7 +34,7 @@ func ListAll(ctx context.Context, e *Env) ([]Listed, []Known, error) {
The status line shows only in a terminal, without `-v` and until the run is interrupted, as nothing would clear one started after that. The UI keeps status lines as a stack: a logged command or a `Status` inside another shows its own line until it ends, and then the outer one is drawn again, so a phase can show one line around steps that show their own. A message said under a status line, whether `Info`, `Warn`, `Note` or data on `Stdout()`, clears the line, prints, and draws the line again below it, so a warning never lands on the status line. A question, the picker and `ui.Terminal`, which a command in the VM that draws on the terminal gets, hold the status line until they're done, so its redraw never goes over a prompt or what the user types.
A wait for a lock that another devvm holds shows a status line only while it waits, never when the lock is free: `platform.LockFile` and `platform.LockFileShared` take a `platform.Waiting`, which they call once they find the lock held and whose end they call once the wait ends, and `msg.Waiting(status, label)` makes one from a Reporter's `Status` and a label, such as `vm_state_waiting`. Only `internal/state`, for a VM's lock or the layout's, and `internal/trust`, which take no Reporter, take the run's `Status` from the context (`msg.StatusOf`), which the run's root sets (`msg.WithStatus`), and forbidigo keeps it to them; the layout's migration shows `layout_migrating` while it runs. An agent's login file, whose lock is a folder's that the proxy holds while it refreshes the login, takes its wait as `agentlogin.File`'s `Waiting` (`agent_login_waiting`). Only a lock that never waits, such as one on a file just made, passes `nil`, which the structure test's `status-lines` rule holds to `statusSites`; a `Waiting` that's nil at run time, or a lock taken another way than `internal/platform`'s, is review only.
A wait for a lock that another devvm holds shows a status line only while it waits, never when the lock is free: `platform.LockFile`, `platform.LockFileShared` and `platform.LockDir` take a `platform.Waiting`, which they call once they find the lock held and whose end they call once the wait ends, and `msg.Waiting(status, label)` makes one from a Reporter's `Status` and a label, such as `vm_state_waiting`. Only `internal/state`, for a VM's lock or the layout's, and `internal/trust`, which take no Reporter, take the run's `Status` from the context (`msg.StatusOf`), which the run's root sets (`msg.WithStatus`), and forbidigo keeps it to them; the layout's migration shows `layout_migrating` while it runs. An agent's login file, whose lock is its folder's (`platform.LockDir`), which the proxy holds while it refreshes the login, takes its wait as `agentlogin.File`'s `Waiting` (`agent_login_waiting`), and its wait ends with the caller's context, as every lock's does. Only a lock that never waits, such as one on a file just made, passes `nil`, which the structure test's `status-lines` rule holds to `statusSites`; a `Waiting` that's nil at run time, or a lock taken another way than `internal/platform`'s, is review only.
Work that takes the terminal never runs under a status line, as its redraw would go over what it shows: a VM's shell, `ssh-add` asking for a key's passphrase (`checkAgent`, `Agent.Ensure`) and an agent's login in the VM. A launch shows its status lines around those steps rather than across them. A background process, such as the proxy, a forwarder or a link session, has no terminal and shows none.
+2 -2
View File
@@ -19,7 +19,7 @@ weight: 3
| `dropped-errors` | in non-test files, no function assigns a `Wait`'s error, or a `strconv` parse's, to `_`, such as `_ = cmd.Wait()` or `n, _ := strconv.Atoi(s)`, unless `droppedErrors` lists it with why, because a failed wait would read as a clean exit and text that isn't a number as 0 |
| `read-limits` | in non-test files, every `io.ReadAll` reads through an `io.LimitReader` made in its call, such as `io.ReadAll(io.LimitReader(r, limit+1))`, unless `unboundedReads` lists its function with why, so a peer or a file that never ends can't fill the memory |
| `folder-ids` | in non-test files outside `internal/platform`, no function compares a folder's identity or its volume with `==` or `!=`, but with `""`, switches on one, passes one to `strings.EqualFold`, `strings.Compare`, `slices.Contains` or `slices.Index`, or keys a map by one, indexed or in a map's literal, its type written out or a named map type of the module's: a field named `Folder` or `GitID`, a call of a state's `Folder` or `FolderVolume`, of `FolderID`, `folderID` or `FolderDevice`, or a name in the same function that one of those, or such a name, was assigned to, unless `exactFolderIDs` lists it with why, because a boot can number an unchanged folder's device anew, which only `platform.SameFolder` and `platform.SameOpenFolder` allow for |
| `status-lines` | in non-test files outside the folders `statusFree` lists, a function that does slow work, which makes a host command with `exec.Command` or `exec.CommandContext`, runs host git through `internal/hostgit`, walks a folder with `fs.WalkDir`, `filepath.Walk`, `filepath.WalkDir`, `hostsafety.Walk` or `safefile.Walk`, looks up a volume with `platform.VolumeUUID`, makes a request with `internal/fetch`'s `Open`, `Resolve`, `Get` or `Download`, waits for a lock with `platform.LockFile` or `LockFileShared` whose waiting is `nil`, or runs a backend's command outside a step with its `Runner`'s `Output` or `Attach`, shows a status line itself, with a Reporter's `Status`, a `LoggedCmd` step or its `Runner`'s `Run`, unless `statusSites` lists it with why, so the user sees what devvm waits for ([status lines](cli.md#status-lines)) |
| `status-lines` | in non-test files outside the folders `statusFree` lists, a function that does slow work, which makes a host command with `exec.Command` or `exec.CommandContext`, runs host git through `internal/hostgit`, walks a folder with `fs.WalkDir`, `filepath.Walk`, `filepath.WalkDir`, `hostsafety.Walk` or `safefile.Walk`, looks up a volume with `platform.VolumeUUID`, makes a request with `internal/fetch`'s `Open`, `Resolve`, `Get` or `Download`, waits for a lock with `platform.LockFile`, `LockFileShared` or `LockDir` whose waiting is `nil`, or runs a backend's command outside a step with its `Runner`'s `Output` or `Attach`, shows a status line itself, with a Reporter's `Status`, a `LoggedCmd` step or its `Runner`'s `Run`, unless `statusSites` lists it with why, so the user sees what devvm waits for ([status lines](cli.md#status-lines)) |
The layers:
@@ -27,7 +27,7 @@ The layers:
- `internal/backend/...` imports none of `internal/vm`, `build`, `tools`, `netpolicy`, `secrets`, `project`, `gitprotect`, `sshconfig`, `sshagent`, `trust` or `vmssh`, so the port forwarder and the link sessions stay devvm's on every backend.
- Only `internal/backend/registry` and `internal/cli` import a backend (`lima`); only tests import `backendtest`, `internal/leaktest`, `internal/memnet`, and `internal/stubtest` and the packages below it, which import only `internal/msg` and each other. The stubs' binary, `internal/stubtest/stub`, and its state, `internal/stubtest/stubstate`, import nothing else of devvm's, because the binary stands in for the tools devvm runs and is built apart from it.
- `internal/proxy` imports no other devvm package but `internal/daemon`, `internal/landlock`, `internal/redact`, `internal/safefile` and `internal/vmname`.
- `assets`, `locales`, `internal/platform`, `internal/msg/gen`, `internal/testbuild`, `internal/hostgit`, `internal/shell`, `internal/vmname`, `internal/daemon`, `internal/fetch`, `internal/jsonc`, `internal/redact`, `internal/agents`, `internal/safefile`, `internal/landlock`, `internal/leaktest` and `internal/memnet` import no devvm package; `internal/agentlogin` only `internal/agents`, `internal/fetch`, `internal/jsonc`, `internal/proxy`, `internal/redact`, `internal/safefile` and `internal/state`, because it holds agents' logins; `internal/msg` only `locales` and `internal/vmname`; `internal/paths` only `internal/msg` and `internal/vmname`; `internal/state` only `internal/msg`, `internal/paths`, `internal/platform` and `internal/vmname`; `internal/image` only `assets`, `internal/agents`, `internal/msg`, `internal/paths` and `internal/shell`; `internal/devcontainer` only `internal/image`, `internal/jsonc`, `internal/msg` and `internal/shell`.
- `assets`, `locales`, `internal/platform`, `internal/msg/gen`, `internal/testbuild`, `internal/hostgit`, `internal/shell`, `internal/vmname`, `internal/daemon`, `internal/fetch`, `internal/jsonc`, `internal/redact`, `internal/agents`, `internal/safefile`, `internal/landlock`, `internal/leaktest` and `internal/memnet` import no devvm package; `internal/agentlogin` only `internal/agents`, `internal/fetch`, `internal/jsonc`, `internal/platform`, `internal/proxy`, `internal/redact`, `internal/safefile` and `internal/state`, because it holds agents' logins; `internal/msg` only `locales` and `internal/vmname`; `internal/paths` only `internal/msg` and `internal/vmname`; `internal/state` only `internal/msg`, `internal/paths`, `internal/platform` and `internal/vmname`; `internal/image` only `assets`, `internal/agents`, `internal/msg`, `internal/paths` and `internal/shell`; `internal/devcontainer` only `internal/image`, `internal/jsonc`, `internal/msg` and `internal/shell`.
Everything it holds the code to is in `devvm()` in `internal/structure/structure_test.go`:
+3 -3
View File
@@ -22,9 +22,9 @@ Every VM sets `OPENCODE_DISABLE_AUTOUPDATE=1`, as it sets `DISABLE_AUTOUPDATER=1
The import copies only the paths in [the store's table](../using/coding-agents.md#devvms-agent-store), from `~/.claude`, `~/.claude.json`, `~/.codex`, `~/.config/opencode`, `~/.local/share/opencode` and `~/.pi/agent`, so it never copies your history, such as `~/.claude/projects`, `~/.codex`'s sessions or `~/.pi/agent/sessions`, and never `~/.claude/.credentials.json`. Of `~/.claude/plugins` it copies only what a seed has, `known_marketplaces.json`, `marketplaces` and `cache`, whether the folder is in `~/.claude` or a link you allowed leads to it, so this machine's own entries, such as each plugin's data in `data`, its MCP bundles in `mcpb`, the plugins that claude.ai synced, its trash and its record of the plugins it installed, never reach the store ([Claude Code's plugins](#claude-codes-plugins)). Claude Code's plugin records name the plugins' folders by their paths, so the store's copies of the JSON files in `~/.claude/plugins` name the plugins' folders in the store, where the VMs mount them.
A link inside an agent's folder that leads to a file inside it is copied as that file only when the file, by the name the link resolves to, one link at a time, is one of the settings that the import copies of the folder itself. So a link never copies what the import leaves out, such as `~/.claude/projects`, `~/.claude/.credentials.json` or a plugin's data in `~/.claude/plugins/data`, and a name that differs from a setting's only in case, which a Mac's file system would still find, is left out too. The import reads each file it listed, a link's by the path the link resolved to, through the agent's folder opened one folder at a time, each from its parent, without following a link in any part of the path, and it fails unless the file it opened is the one it listed. A VM whose project folder is inside an agent's folder, such as a skill you work on in `~/.claude/skills`, can change a link or a folder there between the listing and the read, so such a change fails the import rather than copy what the new link leads to, and devvm warns, before it reads anything, of each VM whose project folder is inside an agent's folder or holds it. A VM whose state devvm can't read gets a warning of its own, naming its state file, because devvm can't tell where its project folder is, and while any state can't be read, devvm leaves out, with a warning naming the state, every path it would read through a link: an agent's folder or login whose path passes through one, and every link out of an agent's folder. It doesn't count the links on the way to your home folder itself, which no project folder can hold, as devvm refuses a project folder that holds your home folder. devvm opens an agent's folder twice, as a root to list it and one folder at a time to read it, and fails the import, naming the folder, unless both are the same folder, so a VM can't swap the folder between the two. A project folder that holds an agent's folder, such as `~/.pi` for pi's `~/.pi/agent`, lets its VM put a link in the agent folder's place, so devvm resolves the folder's path one link at a time and leaves the folder out, with a warning, when a link in a VM's project folder leads it out of that folder, which would let the VM choose any folder of this machine's, such as your home folder. A login file in a folder left out so, such as pi's `auth.json`, is left out with it. Otherwise devvm reads the folder where the path led when it resolved it, and an agent's login file, but Claude Code's `~/.claude.json`, where its path led when devvm resolved it, one link at a time, and left out in the same way, through its folder opened one folder at a time without following a link, never resolved again, the file itself opened without following one, a regular file of at most 128 MiB, so a link, a FIFO or an endless file that a VM put in its place fails the import. It copies at most 20,000 files, folders and links, 128 MiB, and 16 MiB in one file, of each agent's folder, the bounds of [saving a VM's settings](#saving-a-vms-settings), so such a VM can't fill the store that every VM with the agent mounts. It reads each folder 256 entries at a time and counts every entry as it reads it, a link, a socket or a FIFO as much as a file, stopping at 20,000, so a folder of millions of entries never costs it more than that and one batch, and a folder that holds more fails the import before anything is written, naming the folder. It goes at most 128 folders deep, in paths of at most 4,096 bytes, as it opens each folder from the agent's folder down, one name at a time, through the folder opened one folder at a time, so a chain of folders nested deeper fails the import in the same way, and a link or a FIFO swapped in for a folder as it walks fails it rather than leading elsewhere or holding it. A file that grows past 16 MiB, or past what's left of the 128 MiB, between the listing and the read fails the import too, naming the file. The copy of a Claude Code plugin record names the store's longer paths, so it can be larger than the file, and what it grows counts against the same bounds, so a copy that would pass them fails the import, naming the folder.
A link inside an agent's folder that leads to a file inside it is copied as that file only when the file, by the name the link resolves to, one link at a time, is one of the settings that the import copies of the folder itself. So a link never copies what the import leaves out, such as `~/.claude/projects`, `~/.claude/.credentials.json` or a plugin's data in `~/.claude/plugins/data`, and a name that differs from a setting's only in case, which a Mac's file system would still find, is left out too. The import reads each file it listed, a link's by the path the link resolved to, through the agent's folder opened one folder at a time, each from its parent, without following a link in any part of the path, and it fails unless the file it opened is the one it listed. A VM whose project folder is inside an agent's folder, such as a skill you work on in `~/.claude/skills`, can change a link or a folder there between the listing and the read, so such a change fails the import rather than copy what the new link leads to, and devvm warns, before it reads anything, of each VM whose project folder is inside an agent's folder or holds it. A VM whose state devvm can't read gets a warning of its own, naming its state file, because devvm can't tell where its project folder is, and while any state can't be read, devvm leaves out, with a warning naming the state, every path it would read through a link: an agent's folder or login whose path passes through one, and every link out of an agent's folder. That counts the links on the way to your home folder too, because a VM made with `--unsafe-folder` on a folder that holds your home folder holds them, but not a link that only root can change, such as macOS's `/var` or the `/home` of Fedora Silverblue, whose folders up to `/` are root's alone, by their modes and by what the system says you may write, an ACL included: a VM changes this machine's files only as you, so no VM can change where such a link leads. devvm opens an agent's folder twice, as a root to list it and one folder at a time to read it, and fails the import, naming the folder, unless both are the same folder, so a VM can't swap the folder between the two. A project folder that holds an agent's folder, such as `~/.pi` for pi's `~/.pi/agent`, lets its VM put a link in the agent folder's place, so devvm resolves the folder's path one link at a time and leaves the folder out, with a warning, when a link in a VM's project folder leads it out of that folder, which would let the VM choose any folder of this machine's, such as your home folder. A login file in a folder left out so, such as pi's `auth.json`, is left out with it. Otherwise devvm reads the folder where the path led when it resolved it, and an agent's login file, but Claude Code's `~/.claude.json`, where its path led when devvm resolved it, one link at a time, and left out in the same way, through its folder opened one folder at a time without following a link, never resolved again, the file itself opened without following one, a regular file of at most 128 MiB, so a link, a FIFO or an endless file that a VM put in its place fails the import. It copies at most 20,000 files, folders and links, 128 MiB, and 16 MiB in one file, of each agent's folder, the bounds of [saving a VM's settings](#saving-a-vms-settings), so such a VM can't fill the store that every VM with the agent mounts. It reads each folder 256 entries at a time and counts every entry as it reads it, a link, a socket or a FIFO as much as a file, stopping at 20,000, so a folder of millions of entries never costs it more than that and one batch, and a folder that holds more fails the import before anything is written, naming the folder. It goes at most 128 folders deep, in paths of at most 4,096 bytes, as it opens each folder from the agent's folder down, one name at a time, through the folder opened one folder at a time, so a chain of folders nested deeper fails the import in the same way, and a link or a FIFO swapped in for a folder as it walks fails it rather than leading elsewhere or holding it. A file that grows past 16 MiB, or past what's left of the 128 MiB, between the listing and the read fails the import too, naming the file. The copy of a Claude Code plugin record names the store's longer paths, so it can be larger than the file, and what it grows counts against the same bounds, so a copy that would pass them fails the import, naming the folder.
The import reads and writes every agent's settings into a staging folder of the agent's store first, `.devvm-import-` and a random name, beside the agent's folder there, so no VM mounts it. A file that fails to read, changed since it was listed or passes the bounds, fails the import with the store as it was, the staging folder taken out, and so does an interrupt before every agent's settings are staged, its staging folders taken out by the run's cleanups. Once every agent's settings are staged, the import moves each file into place and moves what your home folder no longer has aside, into a folder of the staging folder, where a file it replaces is kept too, as a second hard link, so each file is still replaced in one rename. Then it saves the logins, all or none, reading each login file it replaces first. A failure from then on, such as a rename that fails or a login that can't be saved, puts back every agent's store and every login as they were, the last change first, and an interrupt waits for that, or for the import to finish, before the run's cleanups take the staging folder out. It puts back every agent's store that it changed, even after putting one back fails, and only then, when one did fail, says so, naming each store it couldn't put back and its staging folder, which it keeps, as it holds what devvm couldn't put back, until the next import. A run that's killed while it puts the settings in place can leave the store partly replaced, so run the import again. The staging folders go once the import is done. The import holds the store's lock, `agents.lock` in devvm's data folder, from its staging to its logins, as [the save](#saving-a-vms-settings) does while it writes, and a start does while it cleans [Claude Code's plugins](#claude-codes-plugins), once it finds something to take out, so no two of them change the store at once: the second waits, under a status line, until the first is done. A staging folder that a killed import left counts as nothing of the agent's, so the import doesn't ask before it replaces a store that holds only that, and the next import of that agent takes it out first. A replacement keeps the store's folders, so a running VM's mounts still show them. Where the store has a folder and the home folder now has a file, or the other way round, as when a link that led to a folder now leads to a file, the import replaces it. Before they write anything, both the import and [the save](#saving-a-vms-settings) check every folder and file they'll write by its path: each part of the path below devvm's config folder must be a folder, never a link, so a link there, which only a hand-made store has and which could lead to your home folder, fails the command, naming it, before the store changes, for any of the agents the command handles. A link in the store in place of a settings file is replaced, never followed. They then write only through the agent's store, or its folder there, opened from devvm's config folder as a root, every part of its path a folder, so a link put in the store after the check can't lead a write out of it. They also reach a folder of the store that they empty from devvm's config folder in the same way, as the start does for [Claude Code's plugins](#claude-codes-plugins), and devvm's config folder itself may be a link, as a dotfiles repo's is.
The import reads and writes every agent's settings into a staging folder of the agent's store first, `.devvm-import-` and a random name, beside the agent's folder there, so no VM mounts it. A file that fails to read, changed since it was listed or passes the bounds, fails the import with the store as it was, the staging folder taken out, and so does an interrupt before every agent's settings are staged, its staging folders taken out by the run's cleanups. Once every agent's settings are staged, the import moves each file into place and moves what your home folder no longer has aside, into a folder of the staging folder, where a file it replaces is kept too, as a second hard link, so each file is still replaced in one rename. Then it saves the logins, all or none, reading each login file it replaces first. A failure from then on, such as a rename that fails or a login that can't be saved, puts back every agent's store and every login as they were, the last change first, and an interrupt waits for that, or for the import to finish, before the run's cleanups take the staging folder out. It puts back every agent's store that it changed, even after putting one back fails, and only then, when one did fail, says so, naming each store it couldn't put back and its staging folder, which it keeps, as it holds what devvm couldn't put back, until the next import or save. A run that's killed while it puts the settings in place can leave the store partly replaced, so run the import again. The staging folders go once the import is done. The import holds the store's lock, `agents.lock` in devvm's data folder, from its staging to its logins, as [the save](#saving-a-vms-settings) does while it writes, and a start does while it cleans [Claude Code's plugins](#claude-codes-plugins), once it finds something to take out, so no two of them change the store at once: the second waits, under a status line, until the first is done. A staging folder that a killed import or save left counts as nothing of the agent's, so the import doesn't ask before it replaces a store that holds only that, and the next import or save of that agent takes it out first. A replacement keeps the store's folders, so a running VM's mounts still show them. Where the store has a folder and the home folder now has a file, or the other way round, as when a link that led to a folder now leads to a file, the import replaces it. Before they write anything, both the import and [the save](#saving-a-vms-settings) check every folder and file they'll write by its path: each part of the path below devvm's config folder must be a folder, never a link, so a link there, which only a hand-made store has and which could lead to your home folder, fails the command, naming it, before the store changes, for any of the agents the command handles. A link in the store in place of a settings file is replaced, never followed. They then write only through the agent's store, or its folder there, opened from devvm's config folder as a root, every part of its path a folder, so a link put in the store after the check can't lead a write out of it. They also reach a folder of the store that they empty from devvm's config folder in the same way, as the start does for [Claude Code's plugins](#claude-codes-plugins), and devvm's config folder itself may be a link, as a dotfiles repo's is.
opencode 2 keeps its logins in its own database rather than in `~/.local/share/opencode/auth.json`, so when this machine's opencode is version 2 or later, devvm reads its logins with `opencode auth export` and saves them in the store in the format of `auth.json`, the file that devvm copies for opencode 1. When `opencode auth export` fails, the import fails too, and the store keeps the login it had.
@@ -42,7 +42,7 @@ The import reads each agent's folder through that folder as an `os.Root`, so no
The save reads only the settings in [the store's table](../using/coding-agents.md#devvms-agent-store) from the VM's home, and never the logins, so it never reads your history, `~/.claude/.credentials.json`, `~/.codex/auth.json`, opencode's `auth.json` or pi's. From the VM's `~/.claude.json` it keeps only the settings, account state and MCP servers, as the import does, and the VM leaves out its per-project entries before it sends anything. devvm puts that part in the store's logins folder, where the import keeps it too. A folder that the store already has is mounted read-only in the VM, so the agent there can't change it, and the save leaves it as it is, but Claude Code's plugins folder, which is the VM's own, with the store's as its seed ([Claude Code's plugins](#claude-codes-plugins)). A folder that the store doesn't have yet is the VM's own until you save it, and once the VM next starts with the store's new folder mounted, its setup links that folder in place of its own ([mounts](../using/coding-agents.md#mounts)).
devvm treats everything the VM sends as untrusted, because the agent in the VM could have changed any of it. It reads at most 128 MiB from the VM, in at most 20,000 files, folders and links, none of the files larger than 16 MiB, and when the VM sends more, or sends a path outside the agents' settings or a name with a character that a terminal wouldn't show, devvm saves nothing. Each file it saves is yours alone (mode 600), or mode 700 when it was executable in the VM, so it never keeps a set-user-ID or set-group-ID bit. A link in a settings folder that leads to a file in the same folder becomes a copy of that file. devvm leaves out any other link, any other kind of file, such as a socket, and a settings file that it can't parse whole, such as a `settings.json` that isn't JSON, and it warns you about each. When it leaves out a file in a folder, the store keeps its own copy of that file. A settings file that the VM doesn't have stays in the store. A folder that the VM sends, but Claude Code's plugins folder, replaces the store's folder whole, so devvm writes each of its files again and takes out the files that the VM's folder doesn't have, but it keeps the store's folder itself, so a running VM's mounts still show it. The save writes holding the store's lock, as [the import](#importing) does, and once it holds the lock, it plans again from the store as it is then: when that differs from what it showed you, as when an import wrote the store while you read the diff, it saves nothing and says so, rather than write over that change. A save that fails partway, unlike an import, can leave the store partly saved, so run it again.
devvm treats everything the VM sends as untrusted, because the agent in the VM could have changed any of it. It reads at most 128 MiB from the VM, in at most 20,000 files, folders and links, none of the files larger than 16 MiB, and when the VM sends more, or sends a path outside the agents' settings or a name with a character that a terminal wouldn't show, devvm saves nothing. Each file it saves is yours alone (mode 600), or mode 700 when it was executable in the VM, so it never keeps a set-user-ID or set-group-ID bit. A link in a settings folder that leads to a file in the same folder becomes a copy of that file. devvm leaves out any other link, any other kind of file, such as a socket, and a settings file that it can't parse whole, such as a `settings.json` that isn't JSON, and it warns you about each. When it leaves out a file in a folder, the store keeps its own copy of that file. A settings file that the VM doesn't have stays in the store. A folder that the VM sends, but Claude Code's plugins folder, replaces the store's folder whole, so devvm writes each of its files again and takes out the files that the VM's folder doesn't have, but it keeps the store's folder itself, so a running VM's mounts still show it. The save writes holding the store's lock, as [the import](#importing) does, and once it holds the lock, it plans again from the store as it is then: when that differs from what it showed you, as when an import wrote the store while you read the diff, it saves nothing and says so, rather than write over that change. Where the store has a folder and the VM has a file, or the other way round, the save saves nothing and names the store's path, because putting one in the other's place would take out what the store has there, which the diff doesn't show. It then saves all or nothing, as the import does: it writes every agent's files into a staging folder of the agent's store first, with the import's name, `.devvm-import-` and a random name, and takes out any that a killed import or save left there. Then it moves each file into place and moves aside what a folder the VM sent no longer has, and it saves the part of `~/.claude.json` last, holding the lock of the folder of Claude Code's logins, which a VM's proxy holds while it saves a Claude Code login made in that VM, so the two take turns. A failure from then on, such as a rename that fails or the login that can't be saved, puts back every agent's store and the login as they were, the last change first, and when putting a store back fails too, devvm says so, naming each store it couldn't put back and its staging folder, which it keeps until the next import or save. A run that's killed while it puts the settings in place can leave the store partly saved, so run the save again. A Ctrl-C while the save waits for the store's lock or the login's ends the wait, and the save leaves the store as it was.
The VM's [copies](../using/coding-agents.md#copies) of the settings files and of `~/.claude.json` hold placeholders, such as `devvm-redacted`, where the store has your secrets. devvm puts the store's secret back in place of each placeholder, as long as the VM's copy had that placeholder in that place and nothing around it changed, such as the URL of the MCP server that a header is for. When something around a placeholder changed, devvm leaves the whole file out and warns you, so a VM can't send a secret it never saw to another host, and you can make that change in the store's file yourself. devvm also leaves out any other file that holds a placeholder, such as a skill. No VM gets opencode's files in `~/.config/opencode` that are neither settings nor Markdown, such as a `.env`, so devvm leaves out the VM's own file of that name and keeps the store's.
+1 -1
View File
@@ -153,7 +153,7 @@ Without either, two layouts keep your settings in a dotfiles repo and import the
### Saving a VM's settings
When you change an agent's settings in a VM, for example by installing a Claude Code plugin there with `claude plugin install` or `/plugin`, or by changing `~/.claude/settings.json`, `devvm agent save` copies them into the store, so every VM with that agent gets them. With no argument it saves every agent that the folder's VM has, and `devvm agent save claude` saves only the agents you name. devvm starts a stopped VM for it. It reads only the settings, never the logins or your history, treats everything the VM sends as untrusted, and puts your secrets back where the VM's copies hold placeholders ([how](../internals/agents.md#saving-a-vms-settings)). It reads at most 128 MiB from the VM, in at most 20,000 files, folders and links, none of the files larger than 16 MiB, and when the VM sends more, or sends a path outside the agents' settings, devvm saves nothing.
When you change an agent's settings in a VM, for example by installing a Claude Code plugin there with `claude plugin install` or `/plugin`, or by changing `~/.claude/settings.json`, `devvm agent save` copies them into the store, so every VM with that agent gets them. With no argument it saves every agent that the folder's VM has, and `devvm agent save claude` saves only the agents you name. devvm starts a stopped VM for it. It reads only the settings, never the logins or your history, treats everything the VM sends as untrusted, and puts your secrets back where the VM's copies hold placeholders ([how](../internals/agents.md#saving-a-vms-settings)). It reads at most 128 MiB from the VM, in at most 20,000 files, folders and links, none of the files larger than 16 MiB, and when the VM sends more, or sends a path outside the agents' settings, devvm saves nothing. A save that fails partway leaves the store as it was.
```sh
devvm agent save # show what changed in the VM's agents' settings, then save them
+3 -2
View File
@@ -3,6 +3,7 @@ package agentlogin
import (
"bytes"
"cmp"
"context"
"encoding/json"
"errors"
"maps"
@@ -83,7 +84,7 @@ func OpencodeImport(vmCopy []byte) ([]byte, error) {
// ChatGPT login gone; for one with a key for each provider
// (agents.ProviderKeys) as provider's entry, of KeyProviders, the other
// providers kept (a pi entry's env too).
func (f File) SetKey(provider string, key redact.Secret) error {
func (f File) SetKey(ctx context.Context, provider string, key redact.Secret) error {
if key.TrimSpace().Empty() || strings.ContainsAny(key.Reveal(), "\r\n") { //nolint:forbidigo // the key's check before it's saved
return errors.New("the API key is empty or more than one line")
}
@@ -97,7 +98,7 @@ func (f File) SetKey(provider string, key redact.Secret) error {
default:
return errKeyProvider
}
unlock, err := f.lockStore()
unlock, err := f.lockStore(ctx)
if err != nil {
return err
}
+16 -15
View File
@@ -1,6 +1,7 @@
package agentlogin
import (
"context"
"encoding/json"
"slices"
"strings"
@@ -24,8 +25,8 @@ func TestSetKey(t *testing.T) {
}
c := storeFile(t, Codex, ".codex/auth.json")
must(t, c.lockStoreWrite(map[string]any{"tokens": map[string]any{"access_token": "at"}}))
must(t, c.SetKey("", redact.NewSecret("sk-test")))
must(t, c.lockStoreWrite(t.Context(), map[string]any{"tokens": map[string]any{"access_token": "at"}}))
must(t, c.SetKey(t.Context(), "", redact.NewSecret("sk-test")))
m := readStore(t, c)
if str(m, "OPENAI_API_KEY") != "sk-test" || str(m, "auth_mode") != "apikey" || m["tokens"] != nil {
t.Errorf("Codex's login: %v", m)
@@ -35,8 +36,8 @@ func TestSetKey(t *testing.T) {
}
o := storeFile(t, Opencode, "auth.json")
must(t, o.lockStoreWrite(map[string]any{"openai": map[string]any{"type": "oauth", "access": "a", "refresh": "r", "expires": 1}}))
must(t, o.SetKey("anthropic", redact.NewSecret("sk-ant")))
must(t, o.lockStoreWrite(t.Context(), map[string]any{"openai": map[string]any{"type": "oauth", "access": "a", "refresh": "r", "expires": 1}}))
must(t, o.SetKey(t.Context(), "anthropic", redact.NewSecret("sk-ant")))
m = readStore(t, o)
if e := obj(m, "anthropic"); str(e, "type") != "api" || str(e, "key") != "sk-ant" || str(obj(m, "openai"), "refresh") != "r" {
t.Errorf("opencode's login: %v", m)
@@ -48,7 +49,7 @@ func TestSetKey(t *testing.T) {
}{
{c, "anthropic", "k"}, {o, "", "k"}, {o, "lmstudio", "k"}, {c, "", " "}, {c, "", "a\nb"},
} {
if err := bad.f.SetKey(bad.provider, redact.NewSecret(bad.key)); err == nil {
if err := bad.f.SetKey(t.Context(), bad.provider, redact.NewSecret(bad.key)); err == nil {
t.Errorf("SetKey(%s, %q, %q) took it", bad.f.Kind, bad.provider, bad.key)
}
}
@@ -65,11 +66,11 @@ func TestSetKey(t *testing.T) {
func TestOpencodeImport(t *testing.T) {
o := storeFile(t, Opencode, "auth.json")
access := jwtWith(time.Now().Add(time.Hour), map[string]any{"email": "[email protected]"})
must(t, o.lockStoreWrite(map[string]any{
must(t, o.lockStoreWrite(t.Context(), map[string]any{
"lmstudio": map[string]any{"type": "api", "key": "lms-kept"},
"openai": map[string]any{"type": "oauth", "access": access, "refresh": "rt-secret", "expires": 1, "accountId": "acct-1"},
}))
must(t, o.SetKey("anthropic", redact.NewSecret("sk-ant-secret")))
must(t, o.SetKey(t.Context(), "anthropic", redact.NewSecret("sk-ant-secret")))
o.Salt = "s4lt"
c, err := o.VMCopy()
must(t, err)
@@ -146,9 +147,9 @@ func TestProviderKeys(t *testing.T) {
}
for _, id := range KeyProviders(kind) {
f := storeFile(t, kind, "auth.json")
must(t, f.lockStoreWrite(map[string]any{}))
must(t, f.lockStoreWrite(t.Context(), map[string]any{}))
key := id + "-e2efake-key"
must(t, f.SetKey(id, redact.NewSecret(key)))
must(t, f.SetKey(t.Context(), id, redact.NewSecret(key)))
f.Salt = "s1"
ph := prefix[id] + "devvm-proxy-managed-" + kind + "-" + id + "-s1"
bs := bindings(t, f)
@@ -177,8 +178,8 @@ func TestProviderKeys(t *testing.T) {
}
// lockStoreWrite writes m as f's login, its folder made.
func (f File) lockStoreWrite(m map[string]any) error {
unlock, err := f.lockStore()
func (f File) lockStoreWrite(ctx context.Context, m map[string]any) error {
unlock, err := f.lockStore(ctx)
if err != nil {
return err
}
@@ -195,26 +196,26 @@ func TestChatGPT(t *testing.T) {
if _, ok, err := c.ChatGPT(); ok || err != nil {
t.Errorf("no file: %v, %v", ok, err)
}
must(t, c.lockStoreWrite(map[string]any{"tokens": map[string]any{
must(t, c.lockStoreWrite(t.Context(), map[string]any{"tokens": map[string]any{
"id_token": jwtWith(exp, map[string]any{"email": "[email protected]"}), "access_token": jwtWith(exp, nil),
}}))
if e, ok, err := c.ChatGPT(); e != "[email protected]" || !ok || err != nil {
t.Errorf("Codex: %q, %v, %v", e, ok, err)
}
must(t, c.SetKey("", redact.NewSecret("sk-test")))
must(t, c.SetKey(t.Context(), "", redact.NewSecret("sk-test")))
if _, ok, _ := c.ChatGPT(); ok {
t.Error("an API key read as a ChatGPT login")
}
o := storeFile(t, Opencode, "auth.json")
must(t, o.lockStoreWrite(map[string]any{"openai": map[string]any{
must(t, o.lockStoreWrite(t.Context(), map[string]any{"openai": map[string]any{
"type": "oauth",
"access": jwtWith(exp, map[string]any{"https://api.openai.com/profile": map[string]any{"email": "[email protected]"}}),
}}))
if e, ok, err := o.ChatGPT(); e != "[email protected]" || !ok || err != nil {
t.Errorf("opencode: %q, %v, %v", e, ok, err)
}
must(t, o.lockStoreWrite(map[string]any{"openai": map[string]any{"type": "oauth", "access": "opaque"}}))
must(t, o.lockStoreWrite(t.Context(), map[string]any{"openai": map[string]any{"type": "oauth", "access": "opaque"}}))
if e, ok, _ := o.ChatGPT(); e != "" || !ok {
t.Errorf("opencode without claims: %q, %v", e, ok)
}
+26 -8
View File
@@ -25,6 +25,7 @@ package agentlogin
import (
"bytes"
"cmp"
"context"
"encoding/json"
"errors"
"fmt"
@@ -110,6 +111,19 @@ func captureOf(agent string) (captureFormat, string, bool) {
return nil, "", false
}
// replySave is how long saving a login whose reply the endpoint has given may take
// (AfterReply).
const replySave = 2 * time.Minute
// AfterReply is the context that saving a login takes once the endpoint has given its reply,
// which may have rotated the refresh token: ctx's values without its end, so the exchange's
// deadline never loses the login while the save waits for a lock that a refresh holds, bounded
// by replySave of its own, so a holder that stalls, such as a Keychain that asks, never holds
// the save for ever.
func AfterReply(ctx context.Context) (context.Context, context.CancelFunc) {
return context.WithTimeout(context.WithoutCancel(ctx), replySave)
}
// CaptureKind is the kind of the agent's login file that a login the proxy captures goes in: its
// first whose format captures logins (Claude Code's OAuth login, beside its .claude.json), else
// its own name's.
@@ -291,12 +305,13 @@ func readLogin(path string) (map[string]any, error) {
return m, err
}
// lockStore readies f's folder in the store and holds its lock (lockLogin).
func (f File) lockStore() (func(), error) {
// lockStore readies f's folder in the store and holds its lock (lockLogin), waiting until ctx
// ends.
func (f File) lockStore(ctx context.Context) (func(), error) {
if err := state.PrivateDir(filepath.Dir(f.Path)); err != nil {
return nil, err
}
return lockLogin(f.Path, f.Waiting)
return lockLogin(ctx, f.Path, f.Waiting)
}
// CaptureRequest returns a token request's body as it goes on to the agent's endpoint, f the
@@ -305,7 +320,7 @@ func (f File) lockStore() (func(), error) {
// login, whose refresh token is managed, goes nowhere: answer is the reply the VM gets, the
// store's login as placeholders, since the host refreshes it. A request whose reply can't be
// captured is refused, and so is an exchange for another id_token.
func (f File) CaptureRequest(ctype string, body []byte) (out, answer []byte, err error) {
func (f File) CaptureRequest(ctx context.Context, ctype string, body []byte) (out, answer []byte, err error) {
t, err := parseTokenRequest(ctype, body)
if err != nil {
return nil, nil, err
@@ -317,7 +332,7 @@ func (f File) CaptureRequest(ctype string, body []byte) (out, answer []byte, err
if t.grant() != grantExchange && !refresh {
return body, nil, nil
}
unlock, err := f.lockStore()
unlock, err := f.lockStore(ctx)
if err != nil {
return nil, nil, err
}
@@ -367,12 +382,13 @@ func openaiManagedReply(at, id redact.Secret, salt string) ([]byte, error) {
}
// Capture saves the login in reply, the agent's endpoint's success for the token request req (of
// Content-Type ctype), in f, the store's login file, in the agent's own format, under its lock: a
// Content-Type ctype), in f, the store's login file, in the agent's own format, under its lock,
// waited for with AfterReply's context: a
// code's replaces the login there, a refresh's or an exchange's adds to it, and the store keeps
// only the newest refresh token. It returns the reply the VM gets: placeholders ending in f.Salt in
// place of the tokens, no refresh token, and an expiry at farFuture. A reply without the tokens a
// login needs is refused, and nothing is saved.
func (f File) Capture(ctype string, req, reply []byte) ([]byte, error) {
func (f File) Capture(ctx context.Context, ctype string, req, reply []byte) ([]byte, error) {
t, err := parseTokenRequest(ctype, req)
if err != nil {
return nil, err
@@ -388,7 +404,9 @@ func (f File) Capture(ctype string, req, reply []byte) ([]byte, error) {
if !ok {
return nil, f.errKind()
}
unlock, err := f.lockStore()
ctx, cancel := AfterReply(ctx)
defer cancel()
unlock, err := f.lockStore(ctx)
if err != nil {
return nil, err
}
+43 -10
View File
@@ -1,6 +1,7 @@
package agentlogin
import (
"context"
"encoding/json"
"errors"
"net/url"
@@ -10,6 +11,7 @@ import (
"slices"
"strings"
"testing"
"testing/synctest"
"time"
"github.com/devvmhq/devvm/internal/agents"
@@ -52,7 +54,7 @@ func readStore(t *testing.T, f File) map[string]any {
// capture is f.Capture, its reply to the VM decoded, checked to hold none of secrets.
func capture(t *testing.T, f File, ctype string, req, rep []byte, secrets ...string) map[string]any {
t.Helper()
out, err := f.Capture(ctype, req, rep)
out, err := f.Capture(t.Context(), ctype, req, rep)
must(t, err)
for _, s := range secrets {
if strings.Contains(string(out), s) {
@@ -73,6 +75,37 @@ func openaiTokens() (string, string) {
jwtWith(time.Now().Add(time.Hour), map[string]any{"https://api.openai.com/auth": openaiAuth, "scp": "x"})
}
// A reply the endpoint has given is saved even when the login's lock is held past the exchange's
// deadline, as by a refresh in another VM's proxy: the reply may have rotated the refresh token,
// so giving up at the deadline would lose the login. The capture waits for the lock, and saves.
func TestCaptureOutlivesItsDeadline(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
idToken, accessToken := openaiTokens()
f := storeFile(t, Codex, "auth.json")
must(t, os.MkdirAll(filepath.Dir(f.Path), 0o700))
unlock, err := LockLogin(t.Context(), f.Path, nil)
must(t, err)
ctx, cancel := context.WithTimeout(t.Context(), time.Second)
defer cancel()
code := form("grant_type", grantCode, "code", "c", "client_id", openaiClientID, "code_verifier", "v")
rep := reply(map[string]any{"id_token": idToken, "access_token": accessToken, "refresh_token": "rt-real", "expires_in": 3600})
got := make(chan error, 1)
go func() {
_, err := f.Capture(ctx, formType, code, rep)
got <- err
}()
time.Sleep(time.Minute) // past the exchange's deadline, the lock still held
synctest.Wait()
unlock()
if err := <-got; err != nil {
t.Fatalf("held past the deadline: %v", err)
}
if rt := str(obj(readStore(t, f), "tokens"), "refresh_token"); rt != "rt-real" {
t.Errorf("the store's refresh token %q", rt)
}
})
}
// Codex's ChatGPT login, as codex login makes it: the code's reply saved in the store as Codex
// keeps it, the VM given the placeholders its bindings name; then the API-key exchange, whose
// id_token placeholder becomes the real one on its way out, and whose key is saved and replaced.
@@ -80,7 +113,7 @@ func TestCodexCapture(t *testing.T) {
idToken, accessToken := openaiTokens()
f := storeFile(t, Codex, "auth.json")
code := form("grant_type", grantCode, "code", "c", "client_id", openaiClientID, "code_verifier", "v")
if b, answer, err := f.CaptureRequest(formType, code); err != nil || string(b) != string(code) || answer != nil {
if b, answer, err := f.CaptureRequest(t.Context(), formType, code); err != nil || string(b) != string(code) || answer != nil {
t.Fatalf("the code's request = %q, %v; want it as it is", b, err)
}
vm := capture(t, f, formType, code, reply(map[string]any{
@@ -111,12 +144,12 @@ func TestCodexCapture(t *testing.T) {
return form("grant_type", grantExchange, "client_id", openaiClientID, "requested_token", apiKeyToken,
"subject_token", subject, "subject_token_type", idTokenType)
}
out, _, err := f.CaptureRequest(formType, exchange(vm["id_token"].(string)))
out, _, err := f.CaptureRequest(t.Context(), formType, exchange(vm["id_token"].(string)))
if q, _ := url.ParseQuery(string(out)); err != nil || q.Get("subject_token") != idToken || q.Get("requested_token") != apiKeyToken {
t.Fatalf("the exchange goes out as %q, %v", out, err)
}
for _, other := range []string{"", "x", openaiPlaceholder(redact.NewSecret(idToken), "another-vm")} {
if _, _, err := f.CaptureRequest(formType, exchange(other)); err == nil {
if _, _, err := f.CaptureRequest(t.Context(), formType, exchange(other)); err == nil {
t.Errorf("an exchange for %q went out", other)
}
}
@@ -133,7 +166,7 @@ func TestCodexCapture(t *testing.T) {
// The VM's own refresh (Codex's is JSON) carries managed: it goes nowhere, and the VM gets the
// store's login as placeholders again.
refresh, _ := json.Marshal(map[string]string{"grant_type": grantRefresh, "client_id": openaiClientID, "refresh_token": managed})
out, answer, err := f.CaptureRequest(jsonType, refresh)
out, answer, err := f.CaptureRequest(t.Context(), jsonType, refresh)
var again map[string]any
if err != nil || out != nil || json.Unmarshal(answer, &again) != nil || again["access_token"] != bs[1].Placeholder ||
again["refresh_token"] != managed || again["id_token"] != vm0["id_token"] || strings.Contains(string(answer), "rt-real") {
@@ -142,7 +175,7 @@ func TestCodexCapture(t *testing.T) {
// A refresh of another refresh token goes out, and its reply is captured: the store keeps only
// the newest refresh token, and the rest.
refresh, _ = json.Marshal(map[string]string{"grant_type": grantRefresh, "client_id": openaiClientID, "refresh_token": "rt-elsewhere"})
if b, answer, err := f.CaptureRequest(jsonType, refresh); err != nil || string(b) != string(refresh) || answer != nil {
if b, answer, err := f.CaptureRequest(t.Context(), jsonType, refresh); err != nil || string(b) != string(refresh) || answer != nil {
t.Errorf("another refresh: %q, %q, %v", b, answer, err)
}
capture(t, f, jsonType, refresh, reply(map[string]any{"access_token": "at-2", "refresh_token": "rt-2"}), "at-2", "rt-2")
@@ -194,14 +227,14 @@ func TestCaptureRefuses(t *testing.T) {
{"tokens that aren't strings", ClaudeOAuth, jsonType, []byte(`{"grant_type":"authorization_code"}`), reply(map[string]any{"access_token": 1, "refresh_token": 2})},
} {
f := storeFile(t, tc.kind, "auth.json")
if out, err := f.Capture(tc.ctype, tc.req, tc.reply); err == nil {
if out, err := f.Capture(t.Context(), tc.ctype, tc.req, tc.reply); err == nil {
t.Errorf("%s: captured, the VM given %s", tc.name, out)
}
if _, err := os.Stat(f.Path); !errors.Is(err, os.ErrNotExist) {
t.Errorf("%s: the store's file is there: %v", tc.name, err)
}
}
if _, err := (File{Kind: "other", Path: filepath.Join(t.TempDir(), "x")}).Capture(formType, code, reply(map[string]any{"access_token": "a"})); err == nil {
if _, err := (File{Kind: "other", Path: filepath.Join(t.TempDir(), "x")}).Capture(t.Context(), formType, code, reply(map[string]any{"access_token": "a"})); err == nil {
t.Error("a login of no agent's captured")
}
}
@@ -239,7 +272,7 @@ func TestOpencodeCapture(t *testing.T) {
// The VM's own refresh, with managed or with its copy's refresh token, the access token's
// placeholder, is answered with the placeholders.
for _, rt := range []string{managed, ph} {
if out, answer, err := f.CaptureRequest(formType, form("grant_type", grantRefresh, "refresh_token", rt)); err != nil || out != nil ||
if out, answer, err := f.CaptureRequest(t.Context(), formType, form("grant_type", grantRefresh, "refresh_token", rt)); err != nil || out != nil ||
!strings.Contains(string(answer), ph) || strings.Contains(string(answer), "rt-real") {
t.Errorf("the VM's refresh with %.20s: %q, %s, %v", rt, out, answer, err)
}
@@ -462,7 +495,7 @@ func FuzzCapture(f *testing.F) {
}
}
fl := File{Kind: kinds[int(kind)%len(kinds)], Path: filepath.Join(t.TempDir(), "logins", "auth.json"), Salt: salt}
out, err := fl.Capture(ctype, req, rep)
out, err := fl.Capture(t.Context(), ctype, req, rep)
if err != nil {
if _, serr := os.Stat(fl.Path); !errors.Is(serr, os.ErrNotExist) {
t.Fatalf("refused (%v), and the store was written", err)
+13 -11
View File
@@ -123,7 +123,7 @@ func (f File) claudeOAuthGet(ctx context.Context, name string) (redact.Secret, e
if name != ClaudeOAuthName && name != ClaudeConnectorsName {
return redact.Secret{}, fmt.Errorf("no Claude Code login %q", name)
}
unlock, err := lockLogin(f.Path, f.Waiting)
unlock, err := lockLogin(ctx, f.Path, f.Waiting)
if errors.Is(err, os.ErrNotExist) {
return redact.Secret{}, ErrClaudeNoLogin
} else if err != nil {
@@ -271,24 +271,26 @@ func ClaudeToken(ctype string, req, reply []byte, placeholder string) (redact.Se
}
// LockFolder holds an exclusive lock on dir, a folder of logins, while one login replaces another
// across files, and returns the unlock. It's another lock than a login file's own (lockLogin's,
// on its folder), so its holder can take that one too. It shows waiting while it waits (lockLogin).
func LockFolder(dir string, waiting func() (end func())) (func(), error) {
return lockLogin(filepath.Join(dir, "lock"), waiting)
// across files, and returns the unlock. It's the lock of the folder itself, which a login file
// directly in dir, such as Claude Code's .claude.json, shares (lockLogin), so its holder may take
// only the locks of login files in the folders below dir, such as .claude/.credentials.json's.
// It shows waiting while it waits, until ctx ends (lockLogin).
func LockFolder(ctx context.Context, dir string, waiting func() (end func())) (func(), error) {
return lockLogin(ctx, filepath.Join(dir, "lock"), waiting)
}
// LockLogin holds the lock of the login file at path, on its folder, which
// the proxy holds while it refreshes and writes the login back, so a
// caller that reads the file and writes it again, or puts it back, never
// loses a refresh made meanwhile. It shows waiting while it waits
// (lockLogin), and returns the unlock.
func LockLogin(path string, waiting func() (end func())) (func(), error) {
return lockLogin(path, waiting)
// loses a refresh made meanwhile. It shows waiting while it waits, until
// ctx ends (lockLogin), and returns the unlock.
func LockLogin(ctx context.Context, path string, waiting func() (end func())) (func(), error) {
return lockLogin(ctx, path, waiting)
}
// Remove deletes f, the store's login file, under its lock: none there is no error.
func (f File) Remove() error {
unlock, err := lockLogin(f.Path, f.Waiting)
func (f File) Remove(ctx context.Context) error {
unlock, err := lockLogin(ctx, f.Path, f.Waiting)
if errors.Is(err, os.ErrNotExist) {
return nil
} else if err != nil {
+5 -5
View File
@@ -86,28 +86,28 @@ func TestClaudeCapture(t *testing.T) {
}
// The VM's own refresh, with its managed refresh token, is answered with the placeholder.
refresh := []byte(`{"grant_type":"refresh_token","refresh_token":"devvm-proxy-managed","client_id":"x","scope":"user:inference"}`)
if out, answer, err := f.CaptureRequest(jsonType, refresh); err != nil || out != nil || !strings.Contains(string(answer), ph) ||
if out, answer, err := f.CaptureRequest(t.Context(), jsonType, refresh); err != nil || out != nil || !strings.Contains(string(answer), ph) ||
strings.Contains(string(answer), "real") || !strings.Contains(string(answer), "user:profile") {
t.Errorf("the VM's refresh: %q, %s, %v", out, answer, err)
}
// A refresh with another token goes on, and its reply adds to the login.
other := []byte(`{"grant_type":"refresh_token","refresh_token":"sk-ant-ort01-other","client_id":"x"}`)
if out, answer, err := f.CaptureRequest(jsonType, other); err != nil || string(out) != string(other) || answer != nil {
if out, answer, err := f.CaptureRequest(t.Context(), jsonType, other); err != nil || string(out) != string(other) || answer != nil {
t.Errorf("another refresh: %q, %s, %v", out, answer, err)
}
capture(t, f, jsonType, other, reply(map[string]any{"access_token": "sk-ant-oat01-new", "expires_in": 3600}), "sk-ant-oat01-new") //nolint:gosec // a test's fake token
if o := obj(readStore(t, f), "claudeAiOauth"); str(o, "accessToken") != "sk-ant-oat01-new" || str(o, "refreshToken") != "sk-ant-ort01-real" {
t.Errorf("after the refresh: %v", o)
}
must(t, f.Remove())
must(t, f.Remove(t.Context()))
if _, err := os.Stat(f.Path); !errors.Is(err, os.ErrNotExist) {
t.Errorf("after Remove: %v", err)
}
must(t, f.Remove())
must(t, f.Remove(t.Context()))
if ok, err := f.ClaudeLogin(); ok || err != nil {
t.Errorf("ClaudeLogin with none = %v, %v", ok, err)
}
if out, _, err := f.CaptureRequest(jsonType, refresh); err == nil {
if out, _, err := f.CaptureRequest(t.Context(), jsonType, refresh); err == nil {
t.Errorf("the VM's refresh with no login answered: %s", out)
}
if bs := bindings(t, File{Kind: ClaudeOAuth, Path: writeFile(t, map[string]any{})}); len(bs) != 0 {
+5 -5
View File
@@ -24,26 +24,26 @@ import (
func TestCursorCapture(t *testing.T) {
f := File{Kind: agents.Cursor, Path: filepath.Join(t.TempDir(), "auth.json"), Salt: salt}
poll := "uuid=u-1&verifier=v-1"
out, answer, err := f.CaptureRequest(formType, []byte(poll))
out, answer, err := f.CaptureRequest(t.Context(), formType, []byte(poll))
if err != nil || string(out) != poll || answer != nil {
t.Fatalf("CaptureRequest(poll) = %q, %q, %v", out, answer, err)
}
for _, req := range []string{"uuid=u-1", "verifier=v-1", "grant_type=authorization_code&code=c", "grant_type=refresh_token&refresh_token=" + managed} {
if _, _, err := f.CaptureRequest(formType, []byte(req)); !errors.Is(err, errGrant) {
if _, _, err := f.CaptureRequest(t.Context(), formType, []byte(req)); !errors.Is(err, errGrant) {
t.Errorf("CaptureRequest(%s) = %v", req, err)
}
}
if _, err := f.Capture(formType, []byte(poll), []byte(`{"accessToken":"at-only"}`)); err == nil {
if _, err := f.Capture(t.Context(), formType, []byte(poll), []byte(`{"accessToken":"at-only"}`)); err == nil {
t.Error("a reply without a refresh token was saved")
}
if _, err := f.Capture(formType, []byte(poll), []byte(`{"xaiAccessToken":"x","xaiRefreshToken":"y"}`)); err == nil {
if _, err := f.Capture(t.Context(), formType, []byte(poll), []byte(`{"xaiAccessToken":"x","xaiRefreshToken":"y"}`)); err == nil {
t.Error("an xAI sign-in's reply was saved")
}
if _, err := os.Stat(f.Path); !errors.Is(err, os.ErrNotExist) {
t.Errorf("a refused reply wrote the store's login: %v", err)
}
at := jwtWith(time.Now().Add(time.Hour), map[string]any{"sub": "auth0|1"})
vm, err := f.Capture(formType, []byte(poll), []byte(`{"accessToken":"`+at+`","refreshToken":"rt-real","selectedTeamId":7}`))
vm, err := f.Capture(t.Context(), formType, []byte(poll), []byte(`{"accessToken":"`+at+`","refreshToken":"rt-real","selectedTeamId":7}`))
must(t, err)
var got map[string]any
must(t, json.Unmarshal(vm, &got))
+1 -1
View File
@@ -126,7 +126,7 @@ func TestLoginsGolden(t *testing.T) {
for _, provider := range append([]string{""}, KeyProviders(kind)...) {
k := File{Kind: kind, Path: filepath.Join(t.TempDir(), "auth.json")}
must(t, os.WriteFile(k.Path, []byte(data), 0o600))
if err := k.SetKey(provider, redact.NewSecret("sk-e2efake-saved")); err != nil {
if err := k.SetKey(t.Context(), provider, redact.NewSecret("sk-e2efake-saved")); err != nil {
out.WriteString("set key " + provider + ": " + err.Error() + "\n")
continue
}
+8 -22
View File
@@ -36,17 +36,16 @@ import (
"maps"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"slices"
"sort"
"strings"
"syscall"
"time"
"github.com/devvmhq/devvm/internal/agents"
"github.com/devvmhq/devvm/internal/fetch"
"github.com/devvmhq/devvm/internal/platform"
"github.com/devvmhq/devvm/internal/proxy"
"github.com/devvmhq/devvm/internal/redact"
"github.com/devvmhq/devvm/internal/safefile"
@@ -234,24 +233,11 @@ func readJSON(path string) (map[string]any, error) {
// would lose one result or get the login revoked. It returns the unlock. When another holds the
// lock, it calls waiting, if any, before it waits, and what that returned once it has the lock,
// so a run with a terminal shows a status line while it waits, and none when the lock is free.
func lockLogin(path string, waiting func() (end func())) (func(), error) {
d, err := os.Open(filepath.Dir(path)) //nolint:forbidigo // a folder, locked, never read
if err != nil {
return nil, err
}
fd := int(d.Fd())
err = syscall.Flock(fd, syscall.LOCK_EX|syscall.LOCK_NB)
if errors.Is(err, syscall.EWOULDBLOCK) {
if waiting != nil {
defer waiting()()
}
err = syscall.Flock(fd, syscall.LOCK_EX) // held only while a login is read, refreshed and written
}
if err != nil {
_ = d.Close()
return nil, err
}
return func() { _ = syscall.Flock(fd, syscall.LOCK_UN); _ = d.Close() }, nil
// The wait ends with ctx, as at Ctrl-C or a deadline, with ctx's error. It's the folder's own
// lock (platform.LockDir), a flock of the folder as an older devvm took it, so a VM's proxy that
// an older devvm started takes turns with this one.
func lockLogin(ctx context.Context, path string, waiting func() (end func())) (func(), error) {
return platform.LockDir(ctx, filepath.Dir(path), waiting)
}
// writeJSON replaces path atomically, keeping it mode 600.
@@ -412,7 +398,7 @@ func codexVM(m map[string]any, salt string) (map[string]any, []string) {
}
func (f File) codexGet(ctx context.Context, name string) (redact.Secret, error) {
unlock, err := lockLogin(f.Path, f.Waiting)
unlock, err := lockLogin(ctx, f.Path, f.Waiting)
if err != nil {
return redact.Secret{}, err
}
@@ -540,7 +526,7 @@ func opencodeSplit(m map[string]any, pass []string) VMFile {
}
func (f File) opencodeGet(ctx context.Context, name string) (redact.Secret, error) {
unlock, err := lockLogin(f.Path, f.Waiting)
unlock, err := lockLogin(ctx, f.Path, f.Waiting)
if err != nil {
return redact.Secret{}, err
}
+51 -28
View File
@@ -15,6 +15,7 @@ import (
"strings"
"syscall"
"testing"
"testing/synctest"
"time"
"github.com/devvmhq/devvm/internal/fetch"
@@ -525,36 +526,58 @@ func TestClaudeCopy(t *testing.T) {
// One lookup at a time per login folder: a second waits until the first has written back,
// showing its waiting once it finds the lock held, which ends once it has it; a free lock shows
// none.
// none. A wait ends with its context too, a deadline's or a cancel's, as at Ctrl-C.
func TestLockLogin(t *testing.T) {
p := filepath.Join(t.TempDir(), "auth.json")
waits, ends := 0, 0
waiting := func() func() {
waits++
return func() { ends++ }
}
unlock, err := lockLogin(p, waiting)
if err != nil || waits != 0 {
t.Fatalf("a free lock: %v, waits %d", err, waits)
}
got := make(chan bool)
go func() {
u, err := lockLogin(p, waiting)
if err == nil {
u()
synctest.Test(t, func(t *testing.T) {
p := filepath.Join(t.TempDir(), "auth.json")
waits, ends := 0, 0
waiting := func() func() {
waits++
return func() { ends++ }
}
got <- true
}()
select {
case <-got:
t.Fatal("a second lock didn't wait")
case <-time.After(200 * time.Millisecond):
}
unlock()
<-got
if waits != 1 || ends != 1 {
t.Errorf("held: waits %d, ends %d", waits, ends)
}
unlock, err := lockLogin(t.Context(), p, waiting)
if err != nil || waits != 0 {
t.Fatalf("a free lock: %v, waits %d", err, waits)
}
got := make(chan error, 1)
go func() {
u, err := lockLogin(t.Context(), p, waiting)
if err == nil {
u()
}
got <- err
}()
synctest.Wait()
select {
case err := <-got:
t.Fatalf("a second lock didn't wait: %v", err)
default:
}
unlock()
if err := <-got; err != nil || waits != 1 || ends != 1 {
t.Errorf("held: %v, waits %d, ends %d", err, waits, ends)
}
unlock, err = LockLogin(t.Context(), p, nil)
if err != nil {
t.Fatal(err)
}
defer unlock()
ctx, cancel := context.WithTimeout(t.Context(), time.Hour)
defer cancel()
if _, err := LockLogin(ctx, p, nil); !errors.Is(err, context.DeadlineExceeded) {
t.Errorf("held past a deadline: %v", err)
}
ctx, cancel = context.WithCancel(t.Context())
go func() {
_, err := LockFolder(ctx, filepath.Dir(p), nil) // the same folder's lock
got <- err
}()
synctest.Wait()
cancel()
if err := <-got; !errors.Is(err, context.Canceled) {
t.Errorf("held, cancelled: %v", err)
}
})
}
// An MCP server's host goes into the allowlist: only a DNS name, on 443.
+4 -4
View File
@@ -132,12 +132,12 @@ func TestPiSetKey(t *testing.T) {
t.Errorf("KeyProviders(pi) = %v", got)
}
p := storeFile(t, Pi, ".pi/agent/auth.json")
must(t, p.lockStoreWrite(map[string]any{
must(t, p.lockStoreWrite(t.Context(), map[string]any{
"openai": map[string]any{"type": "api_key", "key": "old", "env": map[string]any{"OPENAI_ORG": "org-1"}},
"lmstudio": map[string]any{"type": "api_key", "key": "lms"},
}))
must(t, p.SetKey("openai", redact.NewSecret("sk-new")))
must(t, p.SetKey("anthropic", redact.NewSecret("sk-ant")))
must(t, p.SetKey(t.Context(), "openai", redact.NewSecret("sk-new")))
must(t, p.SetKey(t.Context(), "anthropic", redact.NewSecret("sk-ant")))
m := readStore(t, p)
switch e := obj(m, "openai"); {
case str(e, "type") != "api_key" || str(e, "key") != "sk-new" || str(obj(e, "env"), "OPENAI_ORG") != "org-1":
@@ -145,7 +145,7 @@ func TestPiSetKey(t *testing.T) {
case str(obj(m, "anthropic"), "key") != "sk-ant" || str(obj(m, "lmstudio"), "key") != "lms":
t.Errorf("pi's login: %v", m)
}
if err := p.SetKey("lmstudio", redact.NewSecret("k")); err == nil {
if err := p.SetKey(t.Context(), "lmstudio", redact.NewSecret("k")); err == nil {
t.Error("SetKey(pi, lmstudio) took it")
}
if bs, _ := p.Bindings(); len(bs) != 2 {
+3
View File
@@ -514,6 +514,9 @@ var docs = map[string]string{ //nolint:gosec // message IDs and pages, not crede
"agent_save_none": "using/coding-agents#saving-a-vms-settings",
"agent_save_refused": "using/coding-agents#saving-a-vms-settings",
"agent_save_store_changed": "using/coding-agents#saving-a-vms-settings",
"agent_save_undo_failed": "using/coding-agents#saving-a-vms-settings",
"agent_save_store_folder": "using/coding-agents#saving-a-vms-settings",
"agent_save_store_file": "using/coding-agents#saving-a-vms-settings",
"agent_save_unsafe": "using/coding-agents#saving-a-vms-settings",
"agent_save_too_much": "using/coding-agents#saving-a-vms-settings",
"agent_save_link_left_out": "using/coding-agents#saving-a-vms-settings",
+19 -1
View File
@@ -198,7 +198,7 @@ func AgentImportTooMuch(agent string, folder string) M {
return M{id: "agent_import_too_much", vals: []val{{"agent", agent}, {"folder", folder}}}
}
// AgentImportUndoFailed is [agent_import_undo_failed]: "Putting {{.stores}} back as they were failed ({{.undo}}) after the import failed ({{.why}}), so they may hold some of the new settings. Copy what you need from {{.dirs}}, which the next import deletes, then run devvm agent import again."
// AgentImportUndoFailed is [agent_import_undo_failed]: "Putting {{.stores}} back as they were failed ({{.undo}}) after the import failed ({{.why}}), so they may hold some of the new settings. Copy what you need from {{.dirs}}, which the next import or save deletes, then run devvm agent import again."
func AgentImportUndoFailed(dirs string, stores string, undo string, why string) M {
return M{id: "agent_import_undo_failed", vals: []val{{"dirs", dirs}, {"stores", stores}, {"undo", undo}, {"why", why}}}
}
@@ -463,11 +463,26 @@ func AgentSaveStoreChanged(vm vmname.VM) M {
return M{id: "agent_save_store_changed", vals: []val{{"vm", string(vm)}}}
}
// AgentSaveStoreFile is [agent_save_store_file]: "devvm's agent store has a file at {{.path}}, where {{.vm}} has a folder, so devvm saved nothing. Move the store's file aside, then run devvm agent save again."
func AgentSaveStoreFile(path string, vm vmname.VM) M {
return M{id: "agent_save_store_file", vals: []val{{"path", path}, {"vm", string(vm)}}}
}
// AgentSaveStoreFolder is [agent_save_store_folder]: "devvm's agent store has a folder at {{.path}}, where {{.vm}} has a file, so devvm saved nothing. Move the store's folder aside, then run devvm agent save again."
func AgentSaveStoreFolder(path string, vm vmname.VM) M {
return M{id: "agent_save_store_folder", vals: []val{{"path", path}, {"vm", string(vm)}}}
}
// AgentSaveTooMuch is [agent_save_too_much]: "{{.vm}} sent more than devvm saves at once, so devvm saved nothing. Take out what the agents' settings folders don't need, such as a plugin's build files."
func AgentSaveTooMuch(vm vmname.VM) M {
return M{id: "agent_save_too_much", vals: []val{{"vm", string(vm)}}}
}
// AgentSaveUndoFailed is [agent_save_undo_failed]: "Putting {{.stores}} back as they were failed ({{.undo}}) after saving {{.vm}}'s settings failed ({{.why}}), so they may hold some of them. Copy what you need from {{.dirs}}, which the next import or save deletes, then run devvm agent save again."
func AgentSaveUndoFailed(dirs string, stores string, undo string, vm vmname.VM, why string) M {
return M{id: "agent_save_undo_failed", vals: []val{{"dirs", dirs}, {"stores", stores}, {"undo", undo}, {"vm", string(vm)}, {"why", why}}}
}
// AgentSaveUnparsed is [agent_save_unparsed]: "devvm left out {{.path}} in {{.vm}}, because it isn't a settings file devvm can read."
func AgentSaveUnparsed(path string, vm vmname.VM) M {
return M{id: "agent_save_unparsed", vals: []val{{"path", path}, {"vm", string(vm)}}}
@@ -5771,7 +5786,10 @@ var specs = map[string]spec{
"agent_save_refused": {},
"agent_save_runs": {},
"agent_save_store_changed": {fields: []string{"vm"}},
"agent_save_store_file": {fields: []string{"path", "vm"}},
"agent_save_store_folder": {fields: []string{"path", "vm"}},
"agent_save_too_much": {fields: []string{"vm"}},
"agent_save_undo_failed": {fields: []string{"dirs", "stores", "undo", "vm", "why"}},
"agent_save_unparsed": {fields: []string{"path", "vm"}},
"agent_save_unsafe": {fields: []string{"path", "vm"}},
"agent_save_withheld": {fields: []string{"path", "vm"}},
+2 -2
View File
@@ -62,13 +62,13 @@ func tokenRequest(x proxy.Exchange) (ctype string, body []byte) {
// Request is the token request's body as it goes on, or the reply the VM
// gets instead. A GET's query goes on as the proxy read it, with no body.
func (c Capturer) Request(_ context.Context, x proxy.Exchange) (out, answer []byte, err error) {
func (c Capturer) Request(ctx context.Context, x proxy.Exchange) (out, answer []byte, err error) {
_, salt, agent, err := c.vm(x)
if err != nil {
return nil, nil, err
}
ctype, body := tokenRequest(x)
out, answer, err = c.Secrets.CaptureRequest(agent, salt, ctype, body)
out, answer, err = c.Secrets.CaptureRequest(ctx, agent, salt, ctype, body)
if x.Method == http.MethodGet {
out = nil
}
+4
View File
@@ -8,6 +8,10 @@ import "io/fs"
// this system, always yes.
func SameDevice(fs.FileInfo, fs.FileInfo) bool { return true }
// Writable reports whether this process may write the folder: yes, as
// this system can't tell.
func Writable(string) bool { return true }
// Links is how many names a file has: 1, as this system can't tell.
func Links(fs.FileInfo) uint64 { return 1 }
+31
View File
@@ -0,0 +1,31 @@
//go:build unix
package platform
import (
"os"
"testing"
)
// Writable is the system's answer: a folder of your own is, / isn't
// (unless you're root), and neither is a folder of your own that you took
// your write away from.
func TestWritable(t *testing.T) {
if os.Geteuid() == 0 {
t.Skip("root writes every folder")
}
dir := t.TempDir()
if !Writable(dir) {
t.Errorf("your own folder: not writable")
}
if Writable("/") {
t.Errorf("/: writable")
}
if err := os.Chmod(dir, 0o500); err != nil { //nolint:gosec // G302: a folder, read-only to its owner
t.Fatal(err)
}
t.Cleanup(func() { _ = os.Chmod(dir, 0o700) }) //nolint:gosec // G302: a folder, writable again for its cleanup
if Writable(dir) {
t.Errorf("a read-only folder of your own: writable")
}
}
+10
View File
@@ -3,11 +3,21 @@
package platform
import (
"errors"
"io/fs"
"strconv"
"syscall"
)
// Writable reports whether this process may write the folder dir, as the
// system judges it (access(2)), its ACLs and a network or FUSE file
// system's own answer included, which a folder's mode bits alone don't
// show; true when the system can't tell.
func Writable(dir string) bool {
err := syscall.Access(dir, 0x2) // W_OK
return err == nil || !errors.Is(err, syscall.EACCES) && !errors.Is(err, syscall.EPERM) && !errors.Is(err, syscall.EROFS)
}
// Links is how many names the file fi describes has (its link count): 1
// when the system can't tell.
func Links(fi fs.FileInfo) uint64 {
+3
View File
@@ -15,6 +15,9 @@ func LockFile(context.Context, string, Waiting) (func(), error) { return nil, no
// LockFileShared is unsupported here.
func LockFileShared(context.Context, string, Waiting) (func(), error) { return nil, noLock() }
// LockDir is unsupported here.
func LockDir(context.Context, string, Waiting) (func(), error) { return nil, noLock() }
// LockHeld is unsupported here.
func LockHeld(string) (bool, error) { return false, noLock() }
+70
View File
@@ -9,7 +9,9 @@ import (
"os"
"os/exec"
"path/filepath"
"syscall"
"testing"
"testing/synctest"
"time"
)
@@ -99,6 +101,74 @@ func TestLockFileWaiting(t *testing.T) {
}
}
// A folder's lock is held by one at a time, as a file's is: another waits
// for it, showing its wait once, until its context ends, a deadline or a
// cancel, and gets it once it's let go. It's the lock a plain flock of the
// folder takes, as an older devvm's proxy takes it. A folder that isn't
// there isn't made.
func TestLockDir(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
dir := t.TempDir()
unlock, err := LockDir(t.Context(), dir, nil)
if err != nil {
t.Fatal(err)
}
waits, ends := 0, 0
waiting := func() func() {
waits++
return func() { ends++ }
}
ctx, cancel := context.WithTimeout(t.Context(), time.Minute)
if _, err := LockDir(ctx, dir, waiting); !errors.Is(err, context.DeadlineExceeded) || waits != 1 || ends != 1 {
t.Errorf("held, to a deadline: %v, waits %d, ends %d", err, waits, ends)
}
cancel()
ctx, cancel = context.WithCancel(t.Context())
got := make(chan error, 1)
go func() {
_, err := LockDir(ctx, dir, nil)
got <- err
}()
synctest.Wait()
cancel()
if err := <-got; !errors.Is(err, context.Canceled) {
t.Errorf("held, cancelled: %v", err)
}
go func() {
u, err := LockDir(t.Context(), dir, nil)
if err == nil {
u()
}
got <- err
}()
synctest.Wait()
unlock()
if err := <-got; err != nil {
t.Errorf("once let go: %v", err)
}
d, err := os.Open(dir) //nolint:gosec // G304: the test's own temp folder
if err != nil {
t.Fatal(err)
}
defer func() { _ = d.Close() }()
if err := syscall.Flock(int(d.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
t.Fatal(err)
}
ctx, cancel = context.WithTimeout(t.Context(), time.Minute)
defer cancel()
if _, err := LockDir(ctx, dir, nil); !errors.Is(err, context.DeadlineExceeded) {
t.Errorf("held by a plain flock: %v", err)
}
missing := filepath.Join(dir, "no")
if _, err := LockDir(t.Context(), missing, nil); !errors.Is(err, os.ErrNotExist) {
t.Errorf("a missing folder: %v", err)
}
if _, err := os.Stat(missing); err == nil {
t.Error("LockDir made the folder")
}
})
}
// A holder may remove the lock file before it lets go: one waiting for
// the removed file takes the lock on the new one, so two never hold it.
func TestLockFileRemoved(t *testing.T) {
+48 -19
View File
@@ -84,25 +84,9 @@ func lockFile(ctx context.Context, path string, how int, waiting Waiting) (unloc
if err != nil {
return nil, err
}
for {
got, err := flock(f, how)
if err != nil {
_ = f.Close()
return nil, err
}
if got {
break
}
if waiting != nil {
end = waiting()
waiting = nil
}
select {
case <-ctx.Done():
_ = f.Close()
return nil, ctx.Err()
case <-time.After(lockTick):
}
if err := waitLock(ctx, f, how, &waiting, &end); err != nil {
_ = f.Close()
return nil, err
}
if current(f, path) {
return func() { _ = f.Close() }, nil
@@ -111,6 +95,51 @@ func lockFile(ctx context.Context, path string, how int, waiting Waiting) (unloc
}
}
// LockDir holds an exclusive lock on the folder dir itself, as LockFile
// holds one on a file, until unlock is called or the process ends,
// waiting for another process that holds it until ctx ends, while waiting
// (Waiting) says so. It never makes the folder: one that isn't there is
// os.ErrNotExist. Its descriptor isn't inherited (close on exec).
func LockDir(ctx context.Context, dir string, waiting Waiting) (unlock func(), err error) {
var end func()
defer func() {
if end != nil {
end()
}
}()
f, err := os.Open(dir) //nolint:gosec // a folder, locked, never read
if err != nil {
return nil, err
}
if err := waitLock(ctx, f, syscall.LOCK_EX, &waiting, &end); err != nil {
_ = f.Close()
return nil, err
}
return func() { _ = f.Close() }, nil
}
// waitLock takes the lock how says on f, trying again lockTick apart
// until ctx ends. The first time it finds the lock held, it calls
// *waiting, if any, sets it nil and keeps what it returned in *end, for
// its caller to call once its wait is over.
func waitLock(ctx context.Context, f *os.File, how int, waiting *Waiting, end *func()) error {
for {
got, err := flock(f, how)
if err != nil || got {
return err
}
if *waiting != nil {
*end = (*waiting)()
*waiting = nil
}
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(lockTick):
}
}
}
// flock tries the lock how says on f once, without waiting: got is false
// while another holds it.
func flock(f *os.File, how int) (got bool, err error) {
+2 -1
View File
@@ -1,6 +1,7 @@
package platform
// Waiting is what a wait for a lock shows (LockFile, LockFileShared): it's
// Waiting is what a wait for a lock shows (LockFile, LockFileShared,
// LockDir): it's
// called once, when another process holds the lock, never when it's free,
// and the func it returns once the wait ends, with the lock got or not.
// Each caller with a terminal passes a status line of its own, a label
+23 -8
View File
@@ -1,6 +1,7 @@
package safefile
import (
"context"
"errors"
"io"
"io/fs"
@@ -36,15 +37,20 @@ const (
// a VM filled with millions of entries costs a walk no more than b.Max entries and a batch,
// where fs.WalkDir reads a folder whole before it looks at any bound. It stops with ErrTooMany
// too at a folder more than walkMaxDepth below root, or a path longer than walkMaxPath. fsys
// opens a folder as an fs.ReadDirFile, as os.DirFS, an os.Root's FS and a Root's FS do.
func Walk(fsys fs.FS, root string, b *Bound, fn fs.WalkDirFunc) error {
// opens a folder as an fs.ReadDirFile, as os.DirFS, an os.Root's FS and a Root's FS do. It
// stops with ctx's error once ctx ends, as at Ctrl-C or a deadline, before it reads a folder or
// its next batch.
func Walk(ctx context.Context, fsys fs.FS, root string, b *Bound, fn fs.WalkDirFunc) error {
if err := ctx.Err(); err != nil {
return err
}
info, err := fs.Stat(fsys, root)
if err != nil {
err = fn(root, nil, err)
} else if b.Seen++; b.Seen > b.Max {
return ErrTooMany
} else {
err = walk(fsys, root, fs.FileInfoToDirEntry(info), 0, b, fn)
err = walk(ctx, fsys, root, fs.FileInfoToDirEntry(info), 0, b, fn)
}
if errors.Is(err, fs.SkipDir) || errors.Is(err, fs.SkipAll) {
return nil
@@ -54,7 +60,7 @@ func Walk(fsys fs.FS, root string, b *Bound, fn fs.WalkDirFunc) error {
// walk is Walk below its root: fn on the entry d at name, depth below the root, then on what's
// in it when it's a folder.
func walk(fsys fs.FS, name string, d fs.DirEntry, depth int, b *Bound, fn fs.WalkDirFunc) error {
func walk(ctx context.Context, fsys fs.FS, name string, d fs.DirEntry, depth int, b *Bound, fn fs.WalkDirFunc) error {
if depth > walkMaxDepth || len(name) > walkMaxPath {
return ErrTooMany
}
@@ -64,9 +70,11 @@ func walk(fsys fs.FS, name string, d fs.DirEntry, depth int, b *Bound, fn fs.Wal
}
return err
}
es, err := readDir(fsys, name, b)
es, err := readDir(ctx, fsys, name, b)
if errors.Is(err, ErrTooMany) {
return err
} else if done := ctx.Err(); done != nil {
return done
} else if err != nil {
// As fs.WalkDir does: fn on the folder again, with the error.
if err = fn(name, d, err); err != nil {
@@ -77,7 +85,7 @@ func walk(fsys fs.FS, name string, d fs.DirEntry, depth int, b *Bound, fn fs.Wal
}
}
for _, e := range es {
if err := walk(fsys, path.Join(name, e.Name()), e, depth+1, b, fn); err != nil {
if err := walk(ctx, fsys, path.Join(name, e.Name()), e, depth+1, b, fn); err != nil {
if errors.Is(err, fs.SkipDir) {
break // the rest of this folder skipped
}
@@ -88,8 +96,12 @@ func walk(fsys fs.FS, name string, d fs.DirEntry, depth int, b *Bound, fn fs.Wal
}
// readDir reads the folder name in fsys a batch at a time, counting each entry in b, and returns
// its entries sorted by name, or ErrTooMany once b.Seen passes b.Max.
func readDir(fsys fs.FS, name string, b *Bound) ([]fs.DirEntry, error) {
// its entries sorted by name, or ErrTooMany once b.Seen passes b.Max, or ctx's error once ctx
// ends.
func readDir(ctx context.Context, fsys fs.FS, name string, b *Bound) ([]fs.DirEntry, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
f, err := fsys.Open(name)
if err != nil {
return nil, err
@@ -101,6 +113,9 @@ func readDir(fsys fs.FS, name string, b *Bound) ([]fs.DirEntry, error) {
}
var es []fs.DirEntry
for {
if err := ctx.Err(); err != nil {
return nil, err
}
batch, err := d.ReadDir(walkBatch)
if b.Seen += len(batch); b.Seen > b.Max {
return nil, ErrTooMany
+76 -11
View File
@@ -3,6 +3,7 @@
package safefile
import (
"context"
"errors"
"io/fs"
"os"
@@ -91,7 +92,7 @@ func TestWalkAsWalkDir(t *testing.T) {
return tc.stop(p, d)
})
b := &Bound{Max: 100}
gotErr := Walk(fsys, tc.root, b, func(p string, d fs.DirEntry, _ error) error {
gotErr := Walk(t.Context(), fsys, tc.root, b, func(p string, d fs.DirEntry, _ error) error {
got = append(got, p)
return tc.stop(p, d)
})
@@ -100,12 +101,12 @@ func TestWalkAsWalkDir(t *testing.T) {
}
}
b := &Bound{Max: 100}
if err := Walk(fsys, ".", b, func(string, fs.DirEntry, error) error { return nil }); err != nil || b.Seen != 11 {
if err := Walk(t.Context(), fsys, ".", b, func(string, fs.DirEntry, error) error { return nil }); err != nil || b.Seen != 11 {
t.Errorf("counted %d entries (%v), want the root and 10", b.Seen, err)
}
// A root that isn't there is fn's to judge, as fs.WalkDir's is.
var gotErr error
err := Walk(fsys, "nowhere", &Bound{Max: 1}, func(_ string, _ fs.DirEntry, err error) error { gotErr = err; return err })
err := Walk(t.Context(), fsys, "nowhere", &Bound{Max: 1}, func(_ string, _ fs.DirEntry, err error) error { gotErr = err; return err })
if !errors.Is(err, fs.ErrNotExist) || !errors.Is(gotErr, fs.ErrNotExist) {
t.Errorf("no root: %v, fn got %v", err, gotErr)
}
@@ -135,7 +136,7 @@ func TestWalkBound(t *testing.T) {
}
read = 0
b := &Bound{Max: 100}
err := Walk(countFS{fsys, &read}, "many", b, func(p string, _ fs.DirEntry, _ error) error {
err := Walk(t.Context(), countFS{fsys, &read}, "many", b, func(p string, _ fs.DirEntry, _ error) error {
if p != "many" {
met++
}
@@ -145,16 +146,80 @@ func TestWalkBound(t *testing.T) {
t.Errorf("past the bound: %v, read %d entries, fn met %d", err, read, met)
}
b = &Bound{Max: n + 1}
if err := Walk(fsys, "many", b, func(string, fs.DirEntry, error) error { return nil }); err != nil || b.Seen != n+1 {
if err := Walk(t.Context(), fsys, "many", b, func(string, fs.DirEntry, error) error { return nil }); err != nil || b.Seen != n+1 {
t.Errorf("at the bound: %v, seen %d", err, b.Seen)
}
b = &Bound{Max: n + 1}
_ = Walk(fsys, "many", b, func(string, fs.DirEntry, error) error { return nil })
if err := Walk(fsys, "many", b, func(string, fs.DirEntry, error) error { return nil }); !errors.Is(err, ErrTooMany) {
_ = Walk(t.Context(), fsys, "many", b, func(string, fs.DirEntry, error) error { return nil })
if err := Walk(t.Context(), fsys, "many", b, func(string, fs.DirEntry, error) error { return nil }); !errors.Is(err, ErrTooMany) {
t.Errorf("a second walk on a spent bound: %v", err)
}
}
// A walk ends with its context, as at Ctrl-C or a deadline: one whose
// context has ended reads nothing, and one cancelled as it goes reads no
// folder, or batch of one, after that, and meets nothing more.
func TestWalkCancelled(t *testing.T) {
const n = 4 * walkBatch
fsys := fstest.MapFS{"a/x": {}, "b/x": {}}
for i := range n {
fsys["many/"+strconv.Itoa(i)] = &fstest.MapFile{}
}
ctx, cancel := context.WithCancel(t.Context())
cancel()
read, met := 0, 0
err := Walk(ctx, countFS{fsys, &read}, ".", &Bound{Max: 10 * n}, func(string, fs.DirEntry, error) error { met++; return nil })
if !errors.Is(err, context.Canceled) || read != 0 || met != 0 {
t.Errorf("an ended context: %v, read %d entries, met %d", err, read, met)
}
ctx, cancel = context.WithCancel(t.Context())
defer cancel()
read = 0
var got []string
err = Walk(ctx, countFS{fsys, &read}, ".", &Bound{Max: 10 * n}, func(p string, _ fs.DirEntry, _ error) error {
got = append(got, p)
if p == "a" {
cancel()
}
return nil
})
if !errors.Is(err, context.Canceled) || !slices.Equal(got, []string{".", "a"}) || read != 3 {
t.Errorf("cancelled at a: %v, met %q, read %d entries, want the root's 3", err, got, read)
}
ctx, cancel = context.WithCancel(t.Context())
defer cancel()
read = 0
err = Walk(ctx, countFS{batchFS{fsys, cancel}, &read}, "many", &Bound{Max: 10 * n}, func(string, fs.DirEntry, error) error { return nil })
if !errors.Is(err, context.Canceled) || read != walkBatch {
t.Errorf("cancelled after a batch: %v, read %d entries, want one batch's %d", err, read, walkBatch)
}
}
// batchFS is fsys whose folders call cancel once they've handed out a
// batch.
type batchFS struct {
fsys fs.FS
cancel func()
}
func (c batchFS) Open(name string) (fs.File, error) {
f, err := c.fsys.Open(name)
if d, ok := f.(fs.ReadDirFile); ok && err == nil {
return batchDir{d, c.cancel}, nil
}
return f, err
}
type batchDir struct {
fs.ReadDirFile
cancel func()
}
func (d batchDir) ReadDir(n int) ([]fs.DirEntry, error) {
defer d.cancel()
return d.ReadDirFile.ReadDir(n)
}
// A chain of folders deeper than walkMaxDepth, or a path longer than
// walkMaxPath, stops the walk with ErrTooMany, though it holds few
// entries; a chain at the depth bound walks whole.
@@ -171,7 +236,7 @@ func TestWalkDepth(t *testing.T) {
{"one deeper", chain(walkMaxDepth+1, "a"), false},
{"a long path", chain(walkMaxPath/200+1, strings.Repeat("a", 200)), false},
} {
err := Walk(tc.fsys, ".", &Bound{Max: 1000}, func(_ string, _ fs.DirEntry, err error) error { return err })
err := Walk(t.Context(), tc.fsys, ".", &Bound{Max: 1000}, func(_ string, _ fs.DirEntry, err error) error { return err })
if (err == nil) != tc.ok || !tc.ok && !errors.Is(err, ErrTooMany) {
t.Errorf("%s: %v", tc.name, err)
}
@@ -205,7 +270,7 @@ func TestWalkErrors(t *testing.T) {
t.Cleanup(func() { _ = os.Chmod(shut, 0o700) }) //nolint:gosec // G302: a folder, readable again for its cleanup
for _, skip := range []bool{false, true} {
var met []string
err := Walk(os.DirFS(dir), ".", &Bound{Max: 10}, func(p string, _ fs.DirEntry, err error) error {
err := Walk(t.Context(), os.DirFS(dir), ".", &Bound{Max: 10}, func(p string, _ fs.DirEntry, err error) error {
if err != nil {
met = append(met, p+" failed")
if skip {
@@ -224,7 +289,7 @@ func TestWalkErrors(t *testing.T) {
t.Errorf("skip %v: met %q (%v), want %q", skip, met, err, want)
}
}
err := Walk(noDirFS{tree()}, ".", &Bound{Max: 10}, func(_ string, _ fs.DirEntry, err error) error { return err })
err := Walk(t.Context(), noDirFS{tree()}, ".", &Bound{Max: 10}, func(_ string, _ fs.DirEntry, err error) error { return err })
if err == nil {
t.Error("a folder opened as a file: listed")
}
@@ -275,7 +340,7 @@ func TestWalkRoot(t *testing.T) {
must(t, err)
defer func() { _ = r.Close() }()
var got []string
err = Walk(r.FS(), ".", &Bound{Max: 10}, func(p string, d fs.DirEntry, err error) error {
err = Walk(t.Context(), r.FS(), ".", &Bound{Max: 10}, func(p string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
+5 -5
View File
@@ -55,13 +55,13 @@ func (c Claude) Login(ctx context.Context) (string, error) {
// lock holds the lock of the Claude Code logins folder in devvm's store
// while one Claude Code login replaces the other, and returns the unlock.
func (c Claude) lock() (func(), error) {
func (c Claude) lock(ctx context.Context) (func(), error) {
// The folder of its .claude.json: devvm's store of Claude Code's logins.
dir := filepath.Dir(LoginFile(c.s.Dirs, agents.Claude))
if err := state.PrivateDir(dir); err != nil {
return nil, err
}
return agentlogin.LockFolder(dir, loginWaiting(c.s, agents.Claude))
return agentlogin.LockFolder(ctx, dir, loginWaiting(c.s, agents.Claude))
}
// saveToken saves a Claude Code token and takes the OAuth login away,
@@ -70,7 +70,7 @@ func (c Claude) saveToken(ctx context.Context, value redact.Secret) error {
if err := c.s.save(ctx, ClaudeToken, value); err != nil {
return err
}
return c.s.login(agents.ClaudeOAuth, "").Remove()
return c.s.login(agents.ClaudeOAuth, "").Remove(ctx)
}
// capture is Store.Capture for Claude Code, ok false for another agent.
@@ -84,7 +84,7 @@ func (c Claude) capture(ctx context.Context, agent, salt, ctype string, req, rep
if agent != agents.Claude {
return nil, false, nil
}
unlock, err := c.lock()
unlock, err := c.lock(ctx) // AfterReply's, from Store.Capture
if err != nil {
return nil, true, err
}
@@ -101,7 +101,7 @@ func (c Claude) capture(ctx context.Context, agent, salt, ctype string, req, rep
}
return vm, true, c.saveToken(ctx, tok)
}
vm, err = c.s.captureFile(agent, salt).Capture(ctype, req, reply)
vm, err = c.s.captureFile(agent, salt).Capture(ctx, ctype, req, reply)
if err != nil {
return nil, true, err
}
+34
View File
@@ -4,10 +4,12 @@ import (
"context"
"errors"
"os"
"path/filepath"
"slices"
"strconv"
"strings"
"testing"
"testing/synctest"
"time"
"github.com/devvmhq/devvm/internal/agentlogin"
@@ -38,6 +40,38 @@ func bindingNames(t *testing.T, s *Store, st *state.VM) []string {
return names
}
// A Claude Code login whose reply the endpoint has given is saved even when the lock of Claude
// Code's logins is held past the exchange's deadline, as by a devvm agent save: the reply may
// have rotated the refresh token, so giving up at the deadline would lose the login.
func TestClaudeCaptureOutlivesItsDeadline(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
s, _ := testStore(t, true, nil)
dir := filepath.Dir(LoginFile(s.Dirs, agents.Claude))
if err := state.PrivateDir(dir); err != nil {
t.Fatal(err)
}
unlock, err := agentlogin.LockFolder(t.Context(), dir, nil)
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(t.Context(), time.Second)
defer cancel()
login := []byte(`{"grant_type":"authorization_code","code":"c","client_id":"x"}`)
got := make(chan error, 1)
go func() {
_, err := s.Capture(ctx, "claude", "salt", "application/json", login,
[]byte(`{"access_token":"sk-ant-oat01-oauth","refresh_token":"sk-ant-ort01-r","scope":"user:inference"}`))
got <- err
}()
time.Sleep(time.Minute) // past the exchange's deadline, the lock still held
synctest.Wait()
unlock()
if err := <-got; err != nil || !s.HasLogin(agents.ClaudeOAuth) {
t.Errorf("held past the deadline: %v, saved %v", err, s.HasLogin(agents.ClaudeOAuth))
}
})
}
// devvm keeps one Claude Code login, the newest: setup-token's token, captured, is the claude
// secret, and takes the OAuth login away; an OAuth login, captured, takes the saved token away;
// devvm secret set claude takes the OAuth login away too. A token in devvm's environment wins.
+9 -6
View File
@@ -192,7 +192,7 @@ func SaveLogins(ctx context.Context, s *Store, logins []Login) error {
if err := state.PrivateDir(dir); err != nil {
return err
}
unlock, err := agentlogin.LockLogin(file, loginWaiting(s, l.Kind))
unlock, err := agentlogin.LockLogin(ctx, file, loginWaiting(s, l.Kind))
if err != nil {
return err
}
@@ -258,11 +258,11 @@ func (s *Store) captureFile(agent, salt string) agentlogin.File {
// CaptureRequest returns a token request a VM's proxy captures the reply
// to, for the agent's login (proxy.Capturer's Request): its body as it
// goes on, or the reply the VM gets instead (agentlogin.File.CaptureRequest).
func (s *Store) CaptureRequest(agent, salt, ctype string, body []byte) (out, answer []byte, err error) {
func (s *Store) CaptureRequest(ctx context.Context, agent, salt, ctype string, body []byte) (out, answer []byte, err error) {
if !isLogin(agent) {
return nil, nil, msg.NoSecret(agent)
}
return s.captureFile(agent, salt).CaptureRequest(ctype, body)
return s.captureFile(agent, salt).CaptureRequest(ctx, ctype, body)
}
// Capture saves the agent's login in reply, its token endpoint's answer to
@@ -271,13 +271,16 @@ func (s *Store) CaptureRequest(agent, salt, ctype string, body []byte) (out, ans
// placeholders ending in salt. Claude Code's login is captured its own way
// (Claude.capture).
func (s *Store) Capture(ctx context.Context, agent, salt, ctype string, req, reply []byte) ([]byte, error) {
// The endpoint has given its reply, so the exchange's deadline doesn't end the save.
ctx, cancel := agentlogin.AfterReply(ctx)
defer cancel()
if err := s.loginsDir(ctx, agent); err != nil {
return nil, err
}
if vm, ok, err := ClaudeOf(s).capture(ctx, agent, salt, ctype, req, reply); ok {
return vm, err
}
return s.captureFile(agent, salt).Capture(ctype, req, reply)
return s.captureFile(agent, salt).Capture(ctx, ctype, req, reply)
}
// loginsDir readies the agent's logins folder in devvm's store: the
@@ -300,7 +303,7 @@ func (s *Store) SaveKey(ctx context.Context, kind, provider string, key redact.S
if err := s.loginsDir(ctx, kind); err != nil {
return err
}
return s.login(kind, "").SetKey(provider, key)
return s.login(kind, "").SetKey(ctx, provider, key)
}
// LoginSum is a hash of the agent's login file in devvm's store, "" when
@@ -551,7 +554,7 @@ func (s *Store) Save(ctx context.Context, name string, value redact.Secret) erro
return s.save(ctx, name, value)
}
c := ClaudeOf(s)
unlock, err := c.lock()
unlock, err := c.lock(ctx)
if err != nil {
return err
}
+2 -2
View File
@@ -481,7 +481,7 @@ func TestCapture(t *testing.T) {
var excluded []string
s.ExcludeFromBackup = func(_ context.Context, dir string) error { excluded = append(excluded, dir); return nil }
code := []byte("grant_type=authorization_code&code=c")
if b, answer, err := s.CaptureRequest("codex", "salt", "", code); err != nil || string(b) != string(code) || answer != nil {
if b, answer, err := s.CaptureRequest(t.Context(), "codex", "salt", "", code); err != nil || string(b) != string(code) || answer != nil {
t.Errorf("CaptureRequest = %q, %q, %v", b, answer, err)
}
tok := "eyJhbGciOiJub25lIn0.eyJleHAiOjF9.sig"
@@ -504,7 +504,7 @@ func TestCapture(t *testing.T) {
t.Errorf("kept out of backups: %q", excluded)
}
for _, f := range []func() error{
func() error { _, _, err := s.CaptureRequest("aider", "salt", "", code); return err },
func() error { _, _, err := s.CaptureRequest(t.Context(), "aider", "salt", "", code); return err },
func() error { _, err := s.Capture(t.Context(), "aider", "salt", "", code, reply); return err },
} {
if err := f(); msg.NamesOf(err) != "no_secret secret=aider" {
+8 -1
View File
@@ -57,7 +57,7 @@ func slowCall(f srcFile, n ast.Node) string {
return c.what
}
}
if pkg := importName(f, "github.com/devvmhq/devvm/internal/platform"); pkg != "" && (name == pkg+".LockFile" || name == pkg+".LockFileShared") {
if pkg := importName(f, "github.com/devvmhq/devvm/internal/platform"); pkg != "" && (name == pkg+".LockFile" || name == pkg+".LockFileShared" || name == pkg+".LockDir") {
if len(call.Args) == 3 {
if id, ok := call.Args[2].(*ast.Ident); ok && id.Name == "nil" {
return "waits for a lock showing nothing"
@@ -164,6 +164,13 @@ func statusCases() []ruleCase {
r: on,
want: &want{ruleStatus, "list a/a.go: lock in statusSites"},
},
{
name: "a folder's lock's wait that shows nothing",
files: map[string]string{"a/a.go": "package a\n\nimport (\n\t\"context\"\n\n\t\"github.com/devvmhq/devvm/internal/platform\"\n)\n\n" +
"func lock(ctx context.Context) (func(), error) { return platform.LockDir(ctx, \"x\", nil) }\n"},
r: on,
want: &want{ruleStatus, "list a/a.go: lock in statusSites"},
},
{
name: "a lock's wait with a status line",
files: map[string]string{"a/a.go": "package a\n\nimport (\n\t\"context\"\n\n\t\"github.com/devvmhq/devvm/internal/platform\"\n)\n\n" +
+2 -2
View File
@@ -156,8 +156,8 @@ func devvm() rules {
{
// Agents' logins hold their tokens: the package that reads,
// refreshes and writes them knows nothing of VMs or the UI.
name: "internal/agentlogin imports only internal/agents, internal/fetch, internal/jsonc, internal/proxy, internal/redact, internal/safefile and internal/state",
from: []string{"internal/agentlogin"}, exceptTo: []string{"internal/agents", "internal/fetch", "internal/jsonc", "internal/proxy", "internal/redact", "internal/safefile", "internal/state"},
name: "internal/agentlogin imports only internal/agents, internal/fetch, internal/jsonc, internal/platform, internal/proxy, internal/redact, internal/safefile and internal/state",
from: []string{"internal/agentlogin"}, exceptTo: []string{"internal/agents", "internal/fetch", "internal/jsonc", "internal/platform", "internal/proxy", "internal/redact", "internal/safefile", "internal/state"},
to: []string{"..."},
},
{
+140 -102
View File
@@ -252,7 +252,7 @@ func (im AgentImport) readAll(ctx context.Context, names []string, all *[]*hostA
}
*all = append(*all, h)
}
return im.followLinks(*all, folders)
return im.followLinks(ctx, *all, folders)
}
// confirm asks before an import replaces what the store has of the
@@ -320,7 +320,7 @@ func (im AgentImport) read(ctx context.Context, agent string, folders *projectFo
h.close()
return nil, msg.AgentImportReadFailed(path, err.Error()).Because(err)
}
if err := im.readSettings(h, folder); err != nil {
if err := im.readSettings(ctx, h, folder); err != nil {
h.close()
if errors.Is(err, errFolderTooMany) {
return nil, msg.AgentImportTooMuch(agent, path)
@@ -428,8 +428,8 @@ func (im AgentImport) readOpencode2(ctx context.Context, h *hostAgent) error {
// readSettings lists the agent's settings files and folders in h.root,
// the home folder's folder, relative to it, but what of a seed's folder
// is this machine's own (agents.MachineOwn), such as Claude Code's
// plugins' data.
func (im AgentImport) readSettings(h *hostAgent, folder string) error {
// plugins' data. Its walk ends with ctx (safefile.Walk).
func (im AgentImport) readSettings(ctx context.Context, h *hostAgent, folder string) error {
home := filepath.Join(im.Dirs.Home, folder)
var inner []string
for _, rel := range slices.Concat(agentDirs(im.Dirs.Home, h.agent), agentFiles(im.Dirs.Home, h.agent), agentLinks(im.Dirs.Home, h.agent)) {
@@ -456,7 +456,7 @@ func (im AgentImport) readSettings(h *hostAgent, folder string) error {
}
// Through the folder opened one folder at a time, whose FS opens a folder only as what
// it listed, never a link or a FIFO a VM swapped in for it (safefile.ErrSwapped).
err = safefile.Walk(h.safe.FS(), in, &h.entries, func(p string, d fs.DirEntry, err error) error {
err = safefile.Walk(ctx, h.safe.FS(), in, &h.entries, func(p string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
@@ -590,7 +590,7 @@ func (im AgentImport) save(ctx context.Context, found []*hostAgent) error {
return err
}
defer unlock()
var all []*importStage
var all []*storeStage
defer func() {
for _, s := range all {
s.discard()
@@ -622,41 +622,64 @@ func (im AgentImport) save(ctx context.Context, found []*hostAgent) error {
}
// applyAll puts every stage in place (apply), then saves the logins
// found, all or none, and on a failure undoes every stage's changes,
// failing with agent_import_undo_failed, which keeps the staging folder
// of what it couldn't put back, when that fails too. It holds every
// stage's lock throughout, so an interrupted run's cleanup, which may
// run meanwhile, waits until the store is whole again; interrupted
// before it starts, it puts nothing in place.
func (im AgentImport) applyAll(ctx context.Context, all []*importStage, found []*hostAgent) error {
for _, s := range all {
s.mu.Lock()
defer s.mu.Unlock()
}
if err := ctx.Err(); err != nil {
return err
}
for _, s := range all {
if s.gone {
return context.Canceled // its cleanup took the staging folder out
}
}
// found, all or none (applyStages), failing with agent_import_undo_failed
// when putting the store back fails too.
func (im AgentImport) applyAll(ctx context.Context, all []*storeStage, found []*hostAgent) error {
var logins []secrets.Login
for _, h := range found {
if h.hasLog {
logins = append(logins, secrets.Login{Kind: h.agent, Data: h.login})
}
}
return applyStages(ctx, stageSet{dirs: im.Dirs, secrets: im.Secrets, all: all, logins: logins, apply: im.apply, undoFailed: msg.AgentImportUndoFailed})
}
// stageSet is what applyStages puts in place: the stages (all), each put
// in place with apply, then the logins, saved in devvm's store of logins
// (secrets), and the message for an undo that fails, given the staging
// folders kept, the stores not put back, what failed putting them back
// and what failed first.
type stageSet struct {
dirs paths.Dirs
secrets *secrets.Store
all []*storeStage
logins []secrets.Login
apply func(*storeStage) error
undoFailed func(dirs, stores, undo, why string) msg.M
}
// applyStages puts every stage of set in place, then saves its logins,
// all or none (secrets.SaveLogins, under each login's lock), and on a
// failure undoes every stage's changes, the last stage first, failing
// with set's undoFailed, which keeps the staging folder of what it
// couldn't put back, when that fails too. It holds every stage's lock
// throughout, so an interrupted run's cleanup, which may run meanwhile,
// waits until the store is whole again; interrupted before it starts, it
// puts nothing in place. devvm agent import and devvm agent save both
// apply through it.
func applyStages(ctx context.Context, set stageSet) error {
for _, s := range set.all {
s.mu.Lock()
defer s.mu.Unlock()
}
if err := ctx.Err(); err != nil {
return err
}
for _, s := range set.all {
if s.gone {
return context.Canceled // its cleanup took the staging folder out
}
}
var err error
done := 0
for _, s := range all {
if err = im.apply(s); err != nil {
for _, s := range set.all {
if err = set.apply(s); err != nil {
break
}
done++
}
if err == nil {
if err = secrets.SaveLogins(ctx, im.Secrets, logins); err == nil {
if err = secrets.SaveLogins(ctx, set.secrets, set.logins); err == nil {
return nil
}
}
@@ -666,34 +689,36 @@ func (im AgentImport) applyAll(ctx context.Context, all []*importStage, found []
// staging folder, which holds what wasn't put back.
var undos []error
var stores, kept []string
for i := min(done, len(all)-1); i >= 0; i-- {
s := all[i]
for i := min(done, len(set.all)-1); i >= 0; i-- {
s := set.all[i]
if undo := s.undo(); undo != nil {
s.keep = true
undos = append(undos, undo)
stores = append(stores, agentStore(im.Dirs, s.h.agent))
kept = append(kept, s.tmpPath(im.Dirs))
stores = append(stores, agentStore(set.dirs, s.agent))
kept = append(kept, s.tmpPath(set.dirs))
}
}
if len(undos) > 0 {
undo := errors.Join(undos...)
return msg.AgentImportUndoFailed(strings.Join(kept, ", "), strings.Join(stores, ", "), undo.Error(), err.Error()).Because(errors.Join(err, undo))
return set.undoFailed(strings.Join(kept, ", "), strings.Join(stores, ", "), undo.Error(), err.Error()).Because(errors.Join(err, undo))
}
return err
}
// importStage is an agent's settings written into a staging folder of
// its store (AgentImport.stage), not yet in place: root is the agent's
// store, and tmp the staging folder in it, a name no setting has
// (stagePrefix).
type importStage struct {
h *hostAgent
root *os.Root
tmp string
// storeStage is an agent's settings written into a staging folder of
// its store (newStage), not yet in place: root is the agent's store, and
// tmp the staging folder in it, a name no setting has (stagePrefix). h
// is what an import read of the agent (AgentImport.stage); a save's
// stage has none.
type storeStage struct {
agent string
h *hostAgent
root *os.Root
tmp string
// remove takes out the cleanup that takes the staging folder out of
// an interrupted run (stage).
// an interrupted run (newStage).
remove func()
// mu is held by the apply (applyAll) and by that cleanup, which sets
// mu is held by the apply (applyStages) and by that cleanup, which sets
// gone once it took the staging folder out, so neither runs while the
// other does.
mu *sync.Mutex
@@ -707,23 +732,24 @@ type importStage struct {
keep bool
}
// asideDir is the folder of an import's staging folder that apply moves
// what it replaces or takes out of the store into, until the import is
// done: no setting's folder has its name.
// asideDir is the folder of an import's or a save's staging folder that
// its apply moves what it replaces or takes out of the store into, until
// the command is done: no setting's folder has its name.
const asideDir = "replaced"
// tmpPath is the staging folder's path.
func (s *importStage) tmpPath(d paths.Dirs) string {
return filepath.Join(agentStore(d, s.h.agent), s.tmp)
func (s *storeStage) tmpPath(d paths.Dirs) string {
return filepath.Join(agentStore(d, s.agent), s.tmp)
}
// stagePrefix starts the name of an import's staging folder in an agent's
// store, beside the agent's folder there, so no VM mounts it. One that a
// killed import left is taken out by the next import of that agent
// (sweepStages), and counts as nothing of the agent's (inStore).
// stagePrefix starts the name of an import's or a save's staging folder in
// an agent's store, beside the agent's folder there, so no VM mounts it.
// One that a killed import or save left is taken out by the next import
// or save of that agent (sweepStages), and counts as nothing of the
// agent's (inStore).
const stagePrefix = ".devvm-import-"
// sweepStages takes out the staging folders that killed imports left in
// sweepStages takes out the staging folders that killed imports and saves left in
// store, the agent's store, reached from devvm's config folder config as
// openStoreDir reaches it.
func sweepStages(config, store string) error {
@@ -748,7 +774,7 @@ func sweepStages(config, store string) error {
// discard takes the staging folder out, with what's left in it, unless
// keep, and closes the store; a second call does nothing.
func (s *importStage) discard() {
func (s *storeStage) discard() {
if s.root == nil {
return
}
@@ -768,7 +794,7 @@ func (s *importStage) discard() {
// so does an interrupt, through a cleanup that stays until discard. First
// it takes out what killed imports left (sweepStages), even for an agent
// with no settings, for which it returns nil.
func (im AgentImport) stage(h *hostAgent) (_ *importStage, err error) {
func (im AgentImport) stage(h *hostAgent) (_ *storeStage, err error) {
config, store := im.Dirs.Config, agentStore(im.Dirs, h.agent)
if err := sweepStages(config, store); err != nil {
return nil, err
@@ -780,31 +806,12 @@ func (im AgentImport) stage(h *hostAgent) (_ *importStage, err error) {
if err := im.checkStore(newStoreGuard(config), h); err != nil {
return nil, err
}
root, err := makeStoreDir(config, store)
s, err := newStage(im.Reporter, config, store, h.agent)
if err != nil {
return nil, err
}
s := &importStage{h: h, root: root, tmp: stagePrefix + rand.Text(), mu: &sync.Mutex{}}
// An interrupted run's cleanups may run while stage or apply still does,
// so this one reaches the staging folder through a root of its own, and
// waits for an apply that started (applyAll), which leaves the store
// whole, to end.
tmp, mu := s.tmp, s.mu
s.remove = im.AddCleanup(func(context.Context) {
if !im.Interrupted() {
return
}
mu.Lock()
defer mu.Unlock()
if s.keep {
return // it holds what an undo couldn't put back
}
s.gone = true
if r, err := openStoreDir(config, store); err == nil && r != nil {
_ = r.RemoveAll(tmp) // best effort, as discard's
_ = r.Close()
}
})
s.h = h
root := s.root
defer func() {
if err != nil {
s.discard()
@@ -823,13 +830,45 @@ func (im AgentImport) stage(h *hostAgent) (_ *importStage, err error) {
return s, nil
}
// newStage opens the agent's store, store, from devvm's config folder
// config as a root (makeStoreDir), and names a new staging folder in it,
// with the cleanup that takes the staging folder out of an interrupted
// run, until discard takes the cleanup out. An interrupted run's cleanups
// may run while a stage is written or applied, so this one reaches the
// staging folder through a root of its own, and waits for an apply that
// started (applyStages), which leaves the store whole, to end.
func newStage(r msg.Reporter, config, store, agent string) (*storeStage, error) {
root, err := makeStoreDir(config, store)
if err != nil {
return nil, err
}
s := &storeStage{agent: agent, root: root, tmp: stagePrefix + rand.Text(), mu: &sync.Mutex{}}
tmp, mu := s.tmp, s.mu
s.remove = r.AddCleanup(func(context.Context) {
if !r.Interrupted() {
return
}
mu.Lock()
defer mu.Unlock()
if s.keep {
return // it holds what an undo couldn't put back
}
s.gone = true
if r, err := openStoreDir(config, store); err == nil && r != nil {
_ = r.RemoveAll(tmp) // best effort, as discard's
_ = r.Close()
}
})
return s, nil
}
// apply puts what s staged in place in the agent's store, as save says,
// through the one root that stage opened, keeping each change's undo
// (s.done): what it replaces or takes out is moved aside into the
// staging folder (asideDir), a file it replaces kept there as a hard link,
// so the file is replaced in one rename, and the folders it makes are
// noted. Nothing it replaces goes until the import is done (discard).
func (im AgentImport) apply(s *importStage) error {
func (im AgentImport) apply(s *storeStage) error {
folder := agents.Of(s.h.agent).Folder
keep := map[string]bool{}
if err := s.root.Mkdir(filepath.Join(s.tmp, asideDir), 0o700); err != nil {
@@ -859,13 +898,13 @@ func (im AgentImport) apply(s *importStage) error {
markKept(keep, rel)
}
keep[s.tmp] = true
return pruneIn(s.root, keep, s.tmp, s.moveAside)
return pruneIn(s.root.FS(), keep, s.tmp, s.moveAside)
}
// undo puts back what apply changed, the last change first, going on
// past a change it can't undo, and returns what failed; none when apply
// changed nothing.
func (s *importStage) undo() error {
func (s *storeStage) undo() error {
var errs []error
for i := len(s.done) - 1; i >= 0; i-- {
errs = append(errs, s.done[i]())
@@ -876,7 +915,7 @@ func (s *importStage) undo() error {
// moveAside moves what's at rel in the store, relative to it, into the
// staging folder's asideDir, for undo to move back.
func (s *importStage) moveAside(rel string) error {
func (s *storeStage) moveAside(rel string) error {
s.aside++
to := path.Join(s.tmp, asideDir, strconv.Itoa(s.aside))
if err := s.root.Rename(filepath.FromSlash(rel), filepath.FromSlash(to)); err != nil {
@@ -886,11 +925,22 @@ func (s *importStage) moveAside(rel string) error {
return nil
}
// pruneFolder moves aside what the store's folder rel, relative to the
// store, has that isn't kept, by its path relative to rel (pruneIn), for
// undo to move back.
func (s *storeStage) pruneFolder(rel string, keep map[string]bool) error {
folder, err := fs.Sub(s.root.FS(), rel)
if err != nil {
return err
}
return pruneIn(folder, keep, "", func(p string) error { return s.moveAside(path.Join(rel, p)) })
}
// clearKind moves aside what's at rel in the store, relative to it, when
// it isn't a folder (dir) or a regular file (!dir), so a folder can be
// made or a file put there. A link, which only a hand-made store could
// have, goes too, never followed.
func (s *importStage) clearKind(rel string, dir bool) error {
func (s *storeStage) clearKind(rel string, dir bool) error {
fi, err := s.root.Lstat(filepath.FromSlash(rel))
switch {
case errors.Is(err, fs.ErrNotExist):
@@ -906,7 +956,7 @@ func (s *importStage) clearKind(rel string, dir bool) error {
// mkdirAll makes the folder rel in the store, relative to it, with the
// folders above it that aren't there (0700), each one's undo taking it
// out again.
func (s *importStage) mkdirAll(rel string) error {
func (s *storeStage) mkdirAll(rel string) error {
var missing []string
for p := rel; p != "." && p != "/"; p = path.Dir(p) {
_, err := s.root.Lstat(filepath.FromSlash(p))
@@ -930,7 +980,7 @@ func (s *importStage) mkdirAll(rel string) error {
// to it, where clearKind left nothing or a regular file: that file is
// kept as a hard link in the staging folder's asideDir first, so the
// rename replaces it at once and undo can put it back.
func (s *importStage) replace(from, rel string) error {
func (s *storeStage) replace(from, rel string) error {
src, dst := filepath.FromSlash(from), filepath.FromSlash(rel)
_, err := s.root.Lstat(dst)
if errors.Is(err, fs.ErrNotExist) {
@@ -1005,7 +1055,7 @@ func (im AgentImport) readFile(h *hostAgent, folder, p string) ([]byte, fs.FileI
// a copy that grows past the bounds the file was read within fails the
// import (hostAgent.grew). A file read through a link out of the folder
// (h.from) is read through its root, as linkSource.read says.
func (im AgentImport) stageFile(s *importStage, folder, p string) error {
func (im AgentImport) stageFile(s *storeStage, folder, p string) error {
h := s.h
data, fi, err := im.readFile(h, folder, p)
if err != nil {
@@ -1046,23 +1096,11 @@ func markKept(keep map[string]bool, p string) {
}
}
// pruneStore takes out what's in store, a folder of the store, that
// isn't kept, through it as a root reached from devvm's config folder
// (openStoreDir), so it never follows a link to the folder or out of it.
func pruneStore(config, store string, keep map[string]bool) error {
root, err := openStoreDir(config, store)
if err != nil || root == nil {
return err
}
defer func() { _ = root.Close() }()
return pruneIn(root, keep, "", func(p string) error { return root.RemoveAll(filepath.FromSlash(p)) })
}
// pruneIn takes what's in root, a folder of the store opened as
// pruneStore opens one, that isn't kept, out with take, each by its path
// relative to root, but nothing of the folder skip.
func pruneIn(root *os.Root, keep map[string]bool, skip string, take func(string) error) error {
return fs.WalkDir(root.FS(), ".", func(p string, d fs.DirEntry, err error) error {
// pruneIn takes what's in folder, a folder of the store opened through
// the root that newStage opened, that isn't kept, out with take, each by
// its path relative to folder, but nothing of the folder skip.
func pruneIn(folder fs.FS, keep map[string]bool, skip string, take func(string) error) error {
return fs.WalkDir(folder, ".", func(p string, d fs.DirEntry, err error) error {
switch {
case err != nil:
return err
+9 -5
View File
@@ -572,9 +572,10 @@ func TestAgentImportLinkedStoreOfAnother(t *testing.T) {
}
}
// pruneStore and makeStoreDir, which an import's every write goes through
// (clearKind's included), reach the store from devvm's config folder,
// never through a link, so what a link leads to keeps everything.
// openStoreDir and makeStoreDir, which an import's and a save's every
// write goes through (clearKind's and pruneIn's included), reach the store
// from devvm's config folder, never through a link, so what a link leads
// to keeps everything.
func TestStoreOpsRefuseLinks(t *testing.T) {
config := t.TempDir()
victim := t.TempDir()
@@ -586,8 +587,11 @@ func TestStoreOpsRefuseLinks(t *testing.T) {
if err := os.Symlink(victim, store); err != nil {
t.Fatal(err)
}
if _, ok := errors.AsType[storeLink](pruneStore(config, store, map[string]bool{})); !ok {
t.Error("pruneStore: no storeLink")
if r, err := openStoreDir(config, store); err == nil {
_ = r.Close()
t.Error("openStoreDir: opened through a link")
} else if _, ok := errors.AsType[storeLink](err); !ok {
t.Errorf("openStoreDir: %v, not a storeLink", err)
}
for _, dir := range []string{store, filepath.Join(store, ".claude")} {
if r, err := makeStoreDir(config, dir); err == nil {
+45 -19
View File
@@ -1,6 +1,7 @@
package vm
import (
"context"
"errors"
"io/fs"
"os"
@@ -12,6 +13,7 @@ import (
"github.com/devvmhq/devvm/internal/agents"
"github.com/devvmhq/devvm/internal/msg"
"github.com/devvmhq/devvm/internal/paths"
"github.com/devvmhq/devvm/internal/platform"
"github.com/devvmhq/devvm/internal/safefile"
"github.com/devvmhq/devvm/internal/settings"
"github.com/devvmhq/devvm/internal/vmname"
@@ -224,7 +226,7 @@ func (im AgentImport) linkRoots() ([]string, error) {
// (follower.copy). One a VM could have chosen (projectFolders.chosen) is left
// out with a warning, whatever allows it. folders are the VMs' folders
// the import read at its start.
func (im AgentImport) followLinks(all []*hostAgent, folders *projectFolders) error {
func (im AgentImport) followLinks(ctx context.Context, all []*hostAgent, folders *projectFolders) error {
var out []*linkOut
owner := map[*linkOut]*hostAgent{}
for _, h := range all {
@@ -274,7 +276,7 @@ func (im AgentImport) followLinks(all []*hostAgent, folders *projectFolders) err
follow = append(follow, l)
}
for _, l := range follow {
if err := f.copy(owner[l], l); err != nil {
if err := f.copy(ctx, owner[l], l); err != nil {
return err
}
}
@@ -320,13 +322,10 @@ type projectVM struct {
// projectFolders is what devvm agent import knows of the VMs' project folders,
// as it read them at its start: each VM's (vms), and the states it
// couldn't read (unread), each by its path, whose VMs' folders it can't
// check, and the links on the way to the home folder itself (homeHops),
// which no project folder can hold, as devvm refuses one that holds the
// home folder.
// check.
type projectFolders struct {
vms []projectVM
unread []string
homeHops []string
vms []projectVM
unread []string
}
// readProjectFolders reads the VMs devvm has, each with its project folder,
@@ -335,9 +334,6 @@ type projectFolders struct {
// or a VM's vm.json.
func readProjectFolders(d paths.Dirs) (*projectFolders, []msg.M) {
f := &projectFolders{}
if _, hops, err := linkHops(d.Home); err == nil {
f.homeHops = hops // else every link counts
}
inv, err := ReadStates(d)
if err != nil {
f.unread = []string{d.VMs()}
@@ -362,10 +358,13 @@ func readProjectFolders(d paths.Dirs) (*projectFolders, []msg.M) {
// through the links hops (linkHops'), when a VM could have chosen where it
// leads, and whether there is one: when it leads through a link in a VM's
// project folder to a place outside it (throughVM,
// agent_import_link_via_vm), or through any link but those on the way to
// the home folder while a VM's state can't be read, as devvm can't tell
// whether that VM's project folder holds it
// (agent_import_link_unread_state). A nil f knows of no VM.
// agent_import_link_via_vm), or through any link you could change while a
// VM's state can't be read, as devvm can't tell whether that VM's project
// folder holds it (agent_import_link_unread_state): the links on the way
// to the home folder count too, as a project folder may hold one, such as
// a VM made with --unsafe-folder on a folder that holds the home folder. A link
// that only root can change (rootOnly), such as macOS's /var or Fedora
// Silverblue's /home, doesn't count. A nil f knows of no VM.
func (f *projectFolders) chosen(path, target string, hops []string) (msg.M, bool) {
if f == nil {
return msg.M{}, false
@@ -373,12 +372,39 @@ func (f *projectFolders) chosen(path, target string, hops []string) (msg.M, bool
if vm := throughVM(f.vms, target, hops); vm != "" {
return msg.AgentImportLinkViaVM(path, vm), true
}
if len(f.unread) > 0 && slices.ContainsFunc(hops, func(h string) bool { return !slices.Contains(f.homeHops, h) }) {
if len(f.unread) > 0 && slices.ContainsFunc(hops, func(h string) bool { return !rootOnly(h) }) {
return msg.AgentImportLinkUnreadState(path, strings.Join(f.unread, ", ")), true
}
return msg.M{}, false
}
// rootOnly reports whether only root can change where the link at hop,
// a physical path (linkHops'), leads: every folder above it, up to /, is
// root's, no one else may write it by its mode bits, and the system says
// you may not write it either (platform.Writable, which an ACL counts in),
// and devvm doesn't run as root. A
// VM changes this machine's files only as you, through its mounts, so no
// VM can change such a link, whatever its project folder holds. Changing
// a link takes writing the folder it's in, or one above, to move that
// folder away.
func rootOnly(hop string) bool {
if os.Getuid() == 0 {
return false
}
for dir := filepath.Dir(hop); ; dir = filepath.Dir(dir) {
fi, err := os.Lstat(dir)
if err != nil || !fi.IsDir() || fi.Mode().Perm()&0o022 != 0 {
return false
}
if uid, _, ok := platform.Owner(fi); !ok || uid != 0 || platform.Writable(dir) {
return false // the mode bits aside, an ACL or a FUSE file system may let you write it
}
if dir == filepath.Dir(dir) {
return true
}
}
}
// warnProjectsInside warns of each VM whose project folder is inside the
// folder of one of the agents named, or holds it (agent_import_project_inside),
// before the import reads anything: code in that VM can change what the
@@ -474,8 +500,8 @@ func (f *follower) projects(path, target string, dir bool) []msg.M {
// folder's folders and files, a link in it read as the file it leads to
// in l.root, and any other link in it left out with a warning. A link
// whose files would pass the import's bounds is left out whole, with a
// warning.
func (f *follower) copy(h *hostAgent, l *linkOut) error {
// warning. Its walk ends with ctx (safefile.Walk).
func (f *follower) copy(ctx context.Context, h *hostAgent, l *linkOut) error {
root, err := openPhysical(l.root)
if err != nil {
return err
@@ -492,7 +518,7 @@ func (f *follower) copy(h *hostAgent, l *linkOut) error {
}
// The entries of every link followed count together, as the walk reads each.
entries := safefile.Bound{Max: linkMaxEntries, Seen: f.budget.entries}
if err := safefile.Walk(root.FS(), ls.base, &entries, ls.visit); err != nil {
if err := safefile.Walk(ctx, root.FS(), ls.base, &entries, ls.visit); err != nil {
if errors.Is(err, errTooMany) || errors.Is(err, safefile.ErrTooMany) {
// What it read counts against the walks' own bound (linkMaxWalked).
f.budget.walked += entries.Seen - f.budget.entries
+54 -5
View File
@@ -393,7 +393,7 @@ func TestAgentImportLinkWalked(t *testing.T) {
f := &follower{im: im.AgentImport, budget: &linkBudget{walked: walked}, warned: map[string]bool{}}
h := &hostAgent{agent: "claude"}
l := &linkOut{p: "skills/x", path: filepath.Join(im.Dirs.Home, ".claude/skills/x"), target: dir, dir: true, root: dir}
if err := f.copy(h, l); err != nil {
if err := f.copy(t.Context(), h, l); err != nil {
t.Fatal(err)
}
h.close()
@@ -413,7 +413,7 @@ func TestAgentImportLinkWalked(t *testing.T) {
}
f := &follower{im: im.AgentImport, budget: &linkBudget{}, warned: map[string]bool{}}
h := &hostAgent{agent: "claude"}
if err := f.copy(h, &linkOut{p: "skills/big", path: filepath.Join(im.Dirs.Home, ".claude/skills/big"), target: big, dir: true, root: big}); err != nil {
if err := f.copy(t.Context(), h, &linkOut{p: "skills/big", path: filepath.Join(im.Dirs.Home, ".claude/skills/big"), target: big, dir: true, root: big}); err != nil {
t.Fatal(err)
}
h.close()
@@ -675,13 +675,62 @@ func TestOpenPhysical(t *testing.T) {
}
}
// A home folder below a link you can change, which a VM made with
// --unsafe-folder on a folder that holds it could change: while a VM's
// state can't be read, the import leaves out every agent folder below it,
// naming the state; with every state readable, it copies them.
func TestAgentImportHomeBelowALink(t *testing.T) {
for _, broken := range []bool{false, true} {
im := newImporter(t)
root := filepath.Dir(im.Dirs.Home)
write(t, root, map[string]string{"real/home/.claude/settings.json": "{}"})
link(t, root, "via", filepath.Join(root, "real"))
home := filepath.Join(root, "via", "home")
im.Dirs.Home = home
state := im.Dirs.VM("devvm-gone-0123456789abc5").State()
if broken {
write(t, filepath.Dir(state), map[string]string{filepath.Base(state): "not json"})
}
if err := im.Run(t.Context(), []string{"claude"}, true); err != nil {
t.Fatalf("broken %v: %v", broken, msg.NamesOf(err))
}
if copied := isFile(filepath.Join(agentStore(im.Dirs, "claude"), ".claude/settings.json")); copied == broken {
t.Errorf("broken %v: copied %v: %q", broken, copied, im.got)
}
warned := slices.Contains(im.got, "agent_import_link_unread_state path="+filepath.Join(home, ".claude")+" state="+state)
if warned != broken {
t.Errorf("broken %v: warned %v: %q", broken, warned, im.got)
}
}
}
// Only a link whose folders, up to /, are root's alone is one only root
// can change: / is, on every host; the test's own folders, and a folder
// root has that others may write, such as /tmp, aren't.
func TestRootOnly(t *testing.T) {
if os.Getuid() == 0 {
t.Skip("as root, no link is root's alone")
}
for hop, want := range map[string]bool{
"/devvm-test-link": true,
filepath.Join(t.TempDir(), "link"): false,
"/tmp/devvm-test-link": false,
filepath.Join(t.TempDir(), "no", "link"): false,
} {
if got := rootOnly(hop); got != want {
t.Errorf("rootOnly(%s) = %v, want %v", hop, got, want)
}
}
}
// While a VM's state can't be read, devvm can't tell whether that VM's
// project folder holds a link, so the import leaves out whatever it
// would read through a link, naming the state, even with --follow-links:
// a link out of an agent's folder, and an agent's folder that is a link,
// its login with it. A link on the way to the home folder itself doesn't
// count, as the test's home may be below one (macOS's /var). The control:
// with every state readable, the same links are followed.
// its login with it. A link on the way to the home folder that only root
// can change doesn't count, as the test's home may be below one (macOS's
// /var). The control: with every state readable, the same links are
// followed.
func TestAgentImportLinksUnreadState(t *testing.T) {
for _, broken := range []bool{false, true} {
im := newImporter(t)
+170 -69
View File
@@ -7,6 +7,7 @@ import (
"io"
"io/fs"
"os"
"path"
"path/filepath"
"reflect"
"slices"
@@ -98,9 +99,14 @@ func (sv saver) plans(agents []string) ([]agentPlan, error) {
return plans, nil
}
// applyAll puts every plan into the store, holding the store's lock
// (lockStore), once every plan's paths are checked (checkPlan), so a link
// on the way to any agent's fails the save before it changes any. It runs
// applyAll puts every plan into the store, all or nothing, holding the
// store's lock (lockStore), once every plan's paths are checked
// (checkPlan), so a link on the way to any agent's fails the save before
// it changes any. Each plan's files are written whole into a staging
// folder of its agent's store first (stage), then put in place (apply),
// and the .claude.json subset saved last, under its login's lock, as an
// import's logins are (applyStages): a failure after the first change
// puts back every agent's store, and the logins, as they were. It runs
// under a status line, as it copies and runs git on each marketplace's
// config.
func (sv saver) applyAll(ctx context.Context, plans []agentPlan) error {
@@ -115,14 +121,42 @@ func (sv saver) applyAll(ctx context.Context, plans []agentPlan) error {
}
g := newStoreGuard(sv.Dirs.Config)
for _, p := range plans {
if err := checkPlan(g, p); err != nil {
if err := checkPlan(g, p, sv.s.vm); err != nil {
return storeErr(err)
}
}
for _, p := range plans {
if err := sv.apply(ctx, p); err != nil {
return err
var all []*storeStage
defer func() {
for _, s := range all {
s.discard()
}
}()
planOf := map[*storeStage]agentPlan{}
var logins []secrets.Login
for _, p := range plans {
s, err := sv.stage(p)
if err != nil {
return storeErr(err)
}
if s != nil {
all = append(all, s)
planOf[s] = p
}
if p.claude != nil {
logins = append(logins, secrets.Login{Kind: agents.Claude, Data: p.claude})
}
}
err = applyStages(ctx, stageSet{
dirs: sv.Dirs, secrets: sv.Proxy.Secrets, all: all, logins: logins,
apply: func(s *storeStage) error { return applyPlan(s, planOf[s]) },
undoFailed: func(dirs, stores, undo, why string) msg.M {
return msg.AgentSaveUndoFailed(dirs, stores, undo, sv.s.vm, why)
},
})
if err != nil {
return err
}
for _, p := range plans {
sv.Info(msg.AgentSettingsSaved(p.agent, p.store, sv.s.vm))
var written []string
for _, d := range p.folders {
@@ -461,9 +495,13 @@ type storeFile struct {
}
// storeFiles returns what's in a folder of the store but folders, by its
// path relative to it; none when it isn't there.
// path relative to it; none when it isn't there, or isn't a folder, which
// the save then refuses (sameKind).
func storeFiles(dir string) (map[string]storeFile, error) {
have := map[string]storeFile{}
if fi, err := os.Lstat(dir); err == nil && !fi.IsDir() {
return have, nil
}
root, err := safefile.OpenRoot(dir)
if errors.Is(err, fs.ErrNotExist) {
return have, nil
@@ -525,30 +563,122 @@ func fileMode(exec bool) os.FileMode {
return 0o600
}
// apply puts p into the store: each settings file written whole, each
// folder's files written whole and what the folder in the store has that
// the VM's doesn't taken out, but what was left out and anything of a
// seed's folder, so the folders VMs mount stay the same folders; the
// .claude.json subset as the store's. A link on the way to anything it
// writes fails it, naming the link (storeGuard), and nothing is written
// through one.
func (sv saver) apply(ctx context.Context, p agentPlan) error {
if err := sv.applySettings(p); err != nil {
return storeErr(err)
// stage writes p's settings files, and its folders' files, whole into a
// new staging folder of its agent's store (newStage), not yet in place,
// after taking out what killed imports and saves left there
// (sweepStages); nil for a plan with none, such as one of the .claude.json
// subset alone.
func (sv saver) stage(p agentPlan) (_ *storeStage, err error) {
config := sv.Dirs.Config
if err := sweepStages(config, p.store); err != nil {
return nil, err
}
if p.claude != nil {
return sv.Proxy.Secrets.SaveLogin(ctx, agents.Claude, p.claude)
if len(p.files) == 0 && len(p.folders) == 0 {
return nil, nil
}
s, err := newStage(sv.Reporter, config, p.store, p.agent)
if err != nil {
return nil, err
}
defer func() {
if err != nil {
s.discard()
}
}()
if err := s.root.Mkdir(s.tmp, 0o700); err != nil {
return nil, err
}
files := slices.Clone(p.files)
for _, d := range p.folders {
files = append(files, d.files...)
}
for _, f := range files {
if err := state.WriteFileIn(s.root, filepath.Join(s.tmp, filepath.FromSlash(f.rel)), f.data, fileMode(f.exec)); err != nil {
return nil, err
}
}
return s, nil
}
// applyPlan puts p, which s staged, in place in the store, through the
// one root that newStage opened, keeping each change's undo, as
// AgentImport.apply does: each settings file renamed into place, the one
// it replaces kept aside as a hard link; each folder made where it isn't;
// and what a folder in the store has that the VM's doesn't moved aside,
// but what was left out and anything of a seed's folder, so the folders
// VMs mount stay the same folders. What's aside goes once the save is
// done (discard). A link or another kind of file where a folder or a
// file goes is moved aside too, never followed, though checkPlan fails
// the save first on a link on the way.
func applyPlan(s *storeStage, p agentPlan) error {
if err := s.root.Mkdir(path.Join(s.tmp, asideDir), 0o700); err != nil {
return err
}
put := func(rel string) error {
if err := s.clearKind(rel, false); err != nil {
return err
}
if err := s.mkdirAll(path.Dir(rel)); err != nil {
return err
}
return s.replace(path.Join(s.tmp, rel), rel)
}
dir := func(rel string) error {
if err := s.clearKind(rel, true); err != nil {
return err
}
return s.mkdirAll(rel)
}
for _, f := range p.files {
if err := put(f.rel); err != nil {
return err
}
}
for _, d := range p.folders {
if err := dir(d.rel); err != nil {
return err
}
in := func(rel string) string { return strings.TrimPrefix(rel, d.rel+"/") }
keep := map[string]bool{}
for _, sub := range d.dirs {
if err := dir(sub); err != nil {
return err
}
markKept(keep, in(sub))
}
for _, f := range d.files {
if err := put(f.rel); err != nil {
return err
}
markKept(keep, in(f.rel))
}
for _, k := range d.kept {
markKept(keep, in(k))
}
if d.seed {
continue
}
if err := s.pruneFolder(d.rel, keep); err != nil {
return err
}
}
return nil
}
// checkPlan checks every path in the store that p would write
// (storeGuard), so a link fails the save before it writes p. The save
// checks every plan's first, before it applies any.
func checkPlan(g *storeGuard, p agentPlan) error {
// checks every plan's first, before it applies any. vm is the VM whose
// settings p saves.
func checkPlan(g *storeGuard, p agentPlan, vm vmname.VM) error {
in := func(rel string) string { return filepath.Join(p.store, filepath.FromSlash(rel)) }
file := func(rel string) error {
if err := g.file(in(rel)); err != nil {
return err
}
return sameKind(in(rel), false, vm)
}
for _, f := range p.files {
if err := g.file(in(f.rel)); err != nil {
if err := file(f.rel); err != nil {
return err
}
}
@@ -557,9 +687,12 @@ func checkPlan(g *storeGuard, p agentPlan) error {
if err := g.folder(in(dir)); err != nil {
return err
}
if err := sameKind(in(dir), true, vm); err != nil {
return err
}
}
for _, f := range d.files {
if err := g.file(in(f.rel)); err != nil {
if err := file(f.rel); err != nil {
return err
}
}
@@ -567,52 +700,20 @@ func checkPlan(g *storeGuard, p agentPlan) error {
return nil
}
// applySettings puts p's settings files and folders into the store, as
// apply says.
func (sv saver) applySettings(p agentPlan) error {
if err := checkPlan(newStoreGuard(sv.Dirs.Config), p); err != nil || len(p.files) == 0 && len(p.folders) == 0 {
return err
// sameKind fails the save when the store has a folder at path where the
// save writes a file of vm's (dir false, agent_save_store_folder), or a
// file where it makes a folder (agent_save_store_file): putting one in the
// other's place would take out what the store has there, which the diff
// doesn't show. Nothing there, or a link or another kind of file, which
// the write replaces without following, passes.
func sameKind(path string, dir bool, vm vmname.VM) error {
// An error is nothing there, or a part above that isn't a folder, which the write fails on.
fi, err := os.Lstat(path)
if err == nil && dir && fi.Mode().IsRegular() {
return msg.AgentSaveStoreFile(path, vm)
}
root, err := makeStoreDir(sv.Dirs.Config, p.store)
if err != nil {
return err
}
defer func() { _ = root.Close() }()
write := func(rel string, data []byte, exec bool) error {
return state.WriteFileIn(root, filepath.FromSlash(rel), data, fileMode(exec))
}
mkdir := func(rel string) error { return root.MkdirAll(filepath.FromSlash(rel), 0o700) }
for _, f := range p.files {
if err := write(f.rel, f.data, f.exec); err != nil {
return err
}
}
for _, d := range p.folders {
if err := mkdir(d.rel); err != nil {
return err
}
keep := map[string]bool{}
for _, dir := range d.dirs {
if err := mkdir(dir); err != nil {
return err
}
markKept(keep, strings.TrimPrefix(dir, d.rel+"/"))
}
for _, f := range d.files {
if err := write(f.rel, f.data, f.exec); err != nil {
return err
}
markKept(keep, strings.TrimPrefix(f.rel, d.rel+"/"))
}
for _, k := range d.kept {
markKept(keep, strings.TrimPrefix(k, d.rel+"/"))
}
if d.seed {
continue
}
if err := pruneStore(sv.Dirs.Config, filepath.Join(p.store, filepath.FromSlash(d.rel)), keep); err != nil {
return err
}
if err == nil && !dir && fi.IsDir() {
return msg.AgentSaveStoreFolder(path, vm)
}
return nil
}
+2 -2
View File
@@ -407,7 +407,7 @@ func TestAgentSavePlanAndApply(t *testing.T) {
}
}
if err := st.apply(t.Context(), p); err != nil {
if err := st.applyAll(t.Context(), []agentPlan{p}); err != nil {
t.Fatal(err)
}
for rel, want := range map[string]string{
@@ -477,7 +477,7 @@ func TestAgentSaveLinkedStore(t *testing.T) {
if err != nil {
t.Fatal(err)
}
err = st.apply(t.Context(), p)
err = st.applyAll(t.Context(), []agentPlan{p})
if want := "agent_store_link link=" + link; msg.NamesOf(err) != want {
t.Errorf("a link at %s: %v, want %s", at, msg.NamesOf(err), want)
}
+211 -3
View File
@@ -10,6 +10,7 @@ import (
"strings"
"testing"
"github.com/devvmhq/devvm/internal/agentlogin"
"github.com/devvmhq/devvm/internal/agents"
"github.com/devvmhq/devvm/internal/msg"
"github.com/devvmhq/devvm/internal/paths"
@@ -307,12 +308,219 @@ func TestAgentImportUndoFails(t *testing.T) {
}
}
// newFailingSave is a save of Claude Code's and Codex's settings, in that
// order, into a store that has older ones: Claude Code's a changed file,
// a folder whose old.md the save takes out, and its .claude.json, a login;
// Codex's a changed file.
func newFailingSave(t *testing.T) (st *saveTest, plans []agentPlan) {
t.Helper()
st = newSaveTest(t, saveTar(t, true,
te{name: ".claude/CLAUDE.md", data: "new"},
te{name: ".claude/skills/"},
te{name: ".claude/skills/a.md", data: "a"},
te{name: saveOwn + "/claude.json", data: `{"theme": "light"}`},
te{name: ".codex/AGENTS.md", data: "new"},
), "claude", "codex")
write(t, st.store("claude"), map[string]string{".claude/CLAUDE.md": "old", ".claude/skills/old.md": "old"})
write(t, st.store("codex"), map[string]string{".codex/AGENTS.md": "old"})
if err := st.Proxy.Secrets.SaveLogin(t.Context(), agents.Claude, []byte(`{"theme": "dark"}`)); err != nil {
t.Fatal(err)
}
plans, err := st.plans([]string{"claude", "codex"})
if err != nil || len(plans) != 2 || plans[0].claude == nil {
t.Fatalf("plans: %v, %+v", err, plans)
}
return st, plans
}
// saveOldLogin is the login a failed save leaves (newFailingSave): as it
// was before it.
const saveOldLogin = `{"theme": "dark"}`
// saveOldStores are the stores a failed save leaves (newFailingSave), as
// storeTree lists them: as they were before it.
func saveOldStores() []string {
return []string{"claude/.claude", "claude/.claude/CLAUDE.md=old", "claude/.claude/skills", "claude/.claude/skills/old.md=old", "codex/.codex", "codex/.codex/AGENTS.md=old"}
}
// A save whose store can't take what it staged, at a file's rename (Codex's,
// after Claude Code's settings went in place) or at the .claude.json
// login, saved last, leaves every agent's store and the login as they
// were, and no staging folder. The control: the same save with nothing
// failing puts them all in place.
func TestAgentSaveApplyFailsWhole(t *testing.T) {
for _, fail := range []string{"", "rename", "login"} {
st, plans := newFailingSave(t)
claude, codex := st.store("claude"), st.store("codex")
locked := filepath.Join(codex, ".codex")
switch fail {
case "rename":
if os.Geteuid() == 0 {
continue // root writes what it can't
}
if err := os.Chmod(locked, 0o500); err != nil { //nolint:gosec // G302: a folder, read-only to its owner
t.Fatal(err)
}
t.Cleanup(func() { _ = os.Chmod(locked, 0o700) }) //nolint:gosec // G302: a folder, writable again for its cleanup
case "login":
st.Proxy.Secrets.ExcludeFromBackup = func(context.Context, string) error { return errors.New("no more") }
}
err := st.applyAll(t.Context(), plans)
_ = os.Chmod(locked, 0o700) //nolint:gosec // G302: a folder, writable again
login := readFile(t, secrets.LoginFile(st.Dirs, agents.Claude))
want := []string{"claude/.claude", "claude/.claude/CLAUDE.md=new", "claude/.claude/skills", "claude/.claude/skills/a.md=a", "codex/.codex", "codex/.codex/AGENTS.md=new"}
if fail == "" {
if err != nil || login == saveOldLogin {
t.Errorf("nothing fails: %v, login %s", msg.NamesOf(err), login)
}
} else {
want = saveOldStores()
if err == nil || login != saveOldLogin {
t.Errorf("%s fails: %v, login %s", fail, err, login)
}
}
if got := storeTree(t, claude, codex); !slices.Equal(got, want) {
t.Errorf("%q fails: the store has %q, want %q", fail, got, want)
}
}
}
// A save never puts a file where the store has a folder, or a folder where
// it has a file, which would take out what the store has there without the
// diff showing it: it saves nothing and names the store's path, the
// store as it was. The control: the same save into a store without them.
func TestAgentSaveKindChanged(t *testing.T) {
for _, c := range []struct {
have map[string]string
id, under string // the message, and the store's path it names, relative to the store
}{
{have: nil},
{have: map[string]string{".claude/CLAUDE.md/mine": "store's"}, id: "agent_save_store_folder", under: ".claude/CLAUDE.md"},
{have: map[string]string{".claude/skills": "store's"}, id: "agent_save_store_file", under: ".claude/skills"},
} {
have := c.have
st := newSaveTest(t, saveTar(t, true,
te{name: ".claude/CLAUDE.md", data: "new"},
te{name: ".claude/skills/"},
te{name: ".claude/skills/a.md", data: "a"},
), "claude")
store := st.store("claude")
write(t, store, have)
before := storeTree(t, store)
plans, err := st.plans([]string{"claude"})
if err != nil {
t.Fatal(err)
}
err = st.applyAll(t.Context(), plans)
if have == nil {
if err != nil {
t.Errorf("no swap: %v", msg.NamesOf(err))
}
continue
}
if want := c.id + " path=" + filepath.Join(store, filepath.FromSlash(c.under)) + " vm=vm"; msg.NamesOf(err) != want {
t.Errorf("%v: %v, want %s", have, msg.NamesOf(err), want)
}
if got := storeTree(t, store); !slices.Equal(got, before) {
t.Errorf("%v: the store changed: %q, was %q", have, got, before)
}
}
}
// A save whose undo fails too, as Codex's store can't be written once the
// login fails, still puts back Claude Code's store and says so
// (agent_save_undo_failed), naming the store it couldn't put back and its
// staging folder, which it keeps; the next save takes it out.
func TestAgentSaveUndoFails(t *testing.T) {
if os.Geteuid() == 0 {
t.Skip("root writes what it can't")
}
st, plans := newFailingSave(t)
claude, codex := st.store("claude"), st.store("codex")
locked := filepath.Join(codex, ".codex")
st.Proxy.Secrets.ExcludeFromBackup = func(context.Context, string) error {
if err := os.Chmod(locked, 0o500); err != nil { //nolint:gosec // G302: a folder, read-only to its owner, so the undo can't put config.toml back
t.Fatal(err)
}
return errors.New("no more")
}
t.Cleanup(func() { _ = os.Chmod(locked, 0o700) }) //nolint:gosec // G302: a folder, writable again for its cleanup
err := st.applyAll(t.Context(), plans)
_ = os.Chmod(locked, 0o700) //nolint:gosec // G302: a folder, writable again
if msg.IDOf(err) != "agent_save_undo_failed" || !strings.Contains(msg.NamesOf(err), " stores="+codex+" ") || !strings.Contains(msg.NamesOf(err), " vm=vm ") {
t.Fatalf("undo failed: %v", msg.NamesOf(err))
}
if got, want := storeTree(t, claude), saveOldStores()[:4]; !slices.Equal(got, want) {
t.Errorf("Claude Code's store %q, want it put back, %q", got, want)
}
kept, _ := filepath.Glob(filepath.Join(codex, stagePrefix+"*"))
if len(kept) != 1 || !strings.Contains(msg.NamesOf(err), "dirs="+kept[0]+" ") {
t.Errorf("the staging folder kept: %q, %v", kept, msg.NamesOf(err))
}
st.Proxy.Secrets.ExcludeFromBackup = func(context.Context, string) error { return nil }
s, err := st.stage(plans[1])
if err != nil {
t.Fatal(err)
}
if left, _ := filepath.Glob(filepath.Join(codex, stagePrefix+"*")); len(left) != 1 || left[0] == kept[0] {
t.Errorf("the next save's stage left %q, want only its own", left)
}
s.discard()
}
// A save writes the .claude.json login under its lock, the one a VM's
// proxy holds while it refreshes a login: held, the save waits under a
// status line (agent_login_waiting), the login as it was meanwhile, then
// saves. A Ctrl-C while it waits ends the wait, and the save leaves the
// stores as they were.
func TestAgentSaveLoginLock(t *testing.T) {
for _, cancelled := range []bool{false, true} {
st, plans := newFailingSave(t)
file := secrets.LoginFile(st.Dirs, agents.Claude)
unlock, err := agentlogin.LockLogin(t.Context(), file, nil)
if err != nil {
t.Fatal(err)
}
t.Cleanup(unlock)
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
waits, before := 0, ""
fake, _ := st.Reporter.(*msg.Fake)
fake.OnStatus = func(m msg.M) {
if m.ID() != "agent_login_waiting" {
return
}
if waits++; waits == 1 {
before = readFile(t, file)
if cancelled {
cancel()
} else {
unlock()
}
}
}
err = st.applyAll(ctx, plans)
after := readFile(t, file)
if waits != 1 || before != saveOldLogin {
t.Errorf("cancelled %v: waited %d times, the login then %s", cancelled, waits, before)
}
if cancelled {
got := storeTree(t, st.store("claude"), st.store("codex"))
if !errors.Is(err, context.Canceled) || after != saveOldLogin || !slices.Equal(got, saveOldStores()) {
t.Errorf("cancelled: %v, login %s, stores %q", err, after, got)
}
} else if err != nil || after == saveOldLogin {
t.Errorf("let go: %v, login %s", msg.NamesOf(err), after)
}
}
}
// An interrupted run's cleanup never takes the staging folder out while
// the apply runs: the apply holds the stage's lock throughout, its logins'
// save included. A cleanup that ran first, before the apply, leaves it
// nothing to put in place, and the store as it was.
func TestAgentImportInterruptedApply(t *testing.T) {
setup := func(t *testing.T) (*importer, *importStage, *hostAgent, *[]func(context.Context)) {
setup := func(t *testing.T) (*importer, *storeStage, *hostAgent, *[]func(context.Context)) {
im := newImporter(t)
write(t, agentStore(im.Dirs, "codex"), map[string]string{".codex/config.toml": "old"})
write(t, im.Dirs.Home, map[string]string{".codex/config.toml": "new", ".codex/auth.json": `{"OPENAI_API_KEY": "k"}`})
@@ -345,7 +553,7 @@ func TestAgentImportInterruptedApply(t *testing.T) {
}
return nil
}
if err := im.applyAll(t.Context(), []*importStage{s}, []*hostAgent{h}); err != nil || !held {
if err := im.applyAll(t.Context(), []*storeStage{s}, []*hostAgent{h}); err != nil || !held {
t.Errorf("applied: %v, the stage's lock held through the logins %v", msg.NamesOf(err), held)
}
(*cleanups)[0](t.Context())
@@ -356,7 +564,7 @@ func TestAgentImportInterruptedApply(t *testing.T) {
t.Run("first", func(t *testing.T) {
im, s, h, cleanups := setup(t)
(*cleanups)[0](t.Context())
if err := im.applyAll(t.Context(), []*importStage{s}, []*hostAgent{h}); !errors.Is(err, context.Canceled) {
if err := im.applyAll(t.Context(), []*storeStage{s}, []*hostAgent{h}); !errors.Is(err, context.Canceled) {
t.Errorf("applied after the cleanup: %v", err)
}
if got := readFile(t, filepath.Join(agentStore(im.Dirs, "codex"), ".codex/config.toml")); got != "old" || im.Secrets.HasLogin("codex") {
+1 -1
View File
@@ -363,7 +363,7 @@ func TestAgentSaveClaudePlugins(t *testing.T) {
if !slices.Equal(f.added, []string{"cache/v/SKILL.md"}) || !slices.Equal(f.changed, []string{"known_marketplaces.json"}) || len(f.removed) != 0 {
t.Errorf("plugins = added %q, changed %q, removed %q", f.added, f.changed, f.removed)
}
if err := st.apply(t.Context(), p); err != nil {
if err := st.applyAll(t.Context(), []agentPlan{p}); err != nil {
t.Fatal(err)
}
for _, rel := range []string{"cache/m/SKILL.md", "marketplaces/m/README.md", "cache/v/SKILL.md"} {
+13 -1
View File
@@ -3367,7 +3367,7 @@ other = "devvm left out {{.path}}, because it leads through a link and devvm cou
[agent_import_undo_failed]
description = "stores are the folders of agents' settings in devvm's store that weren't put back, comma-separated; why is what failed the import; undo is what failed putting them back; dirs are the staging folders that hold what wasn't put back"
other = "Putting {{.stores}} back as they were failed ({{.undo}}) after the import failed ({{.why}}), so they may hold some of the new settings. Copy what you need from {{.dirs}}, which the next import deletes, then run devvm agent import again."
other = "Putting {{.stores}} back as they were failed ({{.undo}}) after the import failed ({{.why}}), so they may hold some of the new settings. Copy what you need from {{.dirs}}, which the next import or save deletes, then run devvm agent import again."
[agent_import_too_much]
description = "folder is the agent's folder in the home folder"
@@ -3438,6 +3438,18 @@ other = "reading {{.vm}}'s agent settings"
description = "a status step: devvm agent save compares what the VM sent with devvm's agent store"
other = "comparing {{.vm}}'s agent settings with devvm's agent store"
[agent_save_store_folder]
description = "path is a folder of devvm's agent store where the VM has a file"
other = "devvm's agent store has a folder at {{.path}}, where {{.vm}} has a file, so devvm saved nothing. Move the store's folder aside, then run devvm agent save again."
[agent_save_store_file]
description = "path is a file of devvm's agent store where the VM has a folder"
other = "devvm's agent store has a file at {{.path}}, where {{.vm}} has a folder, so devvm saved nothing. Move the store's file aside, then run devvm agent save again."
[agent_save_undo_failed]
description = "stores are the folders of agents' settings in devvm's store that weren't put back, comma-separated; vm is the VM whose settings were being saved; why is what failed the save; undo is what failed putting them back; dirs are the staging folders that hold what wasn't put back"
other = "Putting {{.stores}} back as they were failed ({{.undo}}) after saving {{.vm}}'s settings failed ({{.why}}), so they may hold some of them. Copy what you need from {{.dirs}}, which the next import or save deletes, then run devvm agent save again."
[agent_settings_saved]
other = "devvm saved {{.agent}}'s settings from {{.vm}} into {{.dir}}."
+3 -3
View File
@@ -1,7 +1,7 @@
# Each package's test coverage, in percent: the unit tests and the CLI tests together.
# mise run test fails when a package drops below its line; mise run coverage raises them.
cmd/devvm 100.0
internal/agentlogin 95.4
internal/agentlogin 95.6
internal/agents 100.0
internal/backend 97.1
internal/backend/backendtest 74.4
@@ -22,11 +22,11 @@ internal/image 99.4
internal/jsonc 97.1
internal/leaktest 87.5
internal/memnet 96.8
internal/msg 72.2
internal/msg 72.5
internal/msg/gen 93.9
internal/netpolicy 91.9
internal/paths 98.1
internal/platform 90.4
internal/platform 90.8
internal/ports 92.6
internal/project 98.6
internal/proxy 93.6
-1
View File
@@ -41,7 +41,6 @@ bounds internal/tools/tools.go: - tools/tools.go: result 1 of `ParseToolFile()`
checked internal/trust/ca.go: - trust/ca.go: result 0 of `GenerateKey()` lacking guarding; accessed field `PublicKey` via the assignment(s): - `ecdsa.GenerateKey(...)` to `key` at trust/ca.go
bounds internal/ui/pick.go: - ui/pick.go: unassigned variable `out` returned from `lines()` in position 0 - ui/pick.go: result 0 of `lines()` sliced into via the assignment(s): - `p.lines()` to `all` at ui/pick.go
bounds internal/ui/table.go: - ui/table.go: unassigned variable `widths` sliced into
bounds internal/vm/agentimport.go: - vm/agentimport.go: unassigned variable `all` passed as arg `all` to `applyAll()` - vm/agentimport.go: function parameter `all` sliced into
mapkey internal/vm/agentlinks.go: - vm/agentlinks.go: deep read from local variable `owner` lacking guarding; passed as arg `h` to `copy()` - vm/agentlinks.go: function parameter `h` accessed field `roots`
bounds internal/vm/agentlinks.go: - vm/agentlinks.go: unassigned variable `roots` returned from `linkRoots()` in position 0 - vm/agentlinks.go: result 0 of `linkRoots()` sliced into via the assignment(s): - `im.linkRoots()` to `roots` at vm/agentlinks.go
mapkey internal/vm/agentsave.go: - vm/agentsave.go: deep read from field `entries` lacking guarding; accessed field `data` via the assignment(s): - `sv.s.entries[n]` to `e` at vm/agentsave.go