diff --git a/docs/content/docs/contributing/_index.md b/docs/content/docs/contributing/_index.md index 9248d6ee..9f582554 100644 --- a/docs/content/docs/contributing/_index.md +++ b/docs/content/docs/contributing/_index.md @@ -396,7 +396,7 @@ The sections so far: - `project`: devvm in a new project folder (under `/tmp/devvm-go-e2e/p`) makes a VM from base and opens a shell there, which reads its commands from devvm's input. The folder and the shared tools are mounted and nothing else is, there's no SSH agent, no Docker (no docker layer) and the hostname is the folder's. The ssh config lists it as `devvm-web` with its host keys pinned; through an `~/.ssh/config` of the run's own that includes it under a `Host *` forwarding the agent, `ssh devvm-web` works, forwards no agent (a throwaway one), and refuses a changed host key. `.git` is locked (macOS) and git in the VM can still commit. `devvm stop` stops it and drops its entry, and on macOS reports and locks a submodule git folder the VM added. `TestE2EExecQuoting` in `internal/backend/registry`, which runs only there (`DEVVM_E2E_VM` names the VM), checks that arguments with spaces, quotes, `$`, newlines and globs, a folder and input reach the guest as given, through the `Exec` of the backend the VM's state records, so one test covers every backend. Then a VM from a `devcontainer.json`, with no ports by default: its `forwardPorts` said and not forwarded, none reaching this machine, its `containerEnv` in the shell and its commands, its `postCreateCommand` run once in the folder, its `postStartCommand` at each start (again after `devvm restart`), nothing written to the folder, and a changed file warned about without changing the VM. Then a claude VM with a fake agent config, history, git identity and token in a home of its own: `devvm agent import` copies the agent's settings into the sandbox's agent store without the history or the links out of its folder, the store's folder is mounted read-only and linked into the VM's home, and the home folder's isn't mounted, its settings are copied and its history isn't, the VM gets the git identity, the timezone and its hostname, and, open as it is, the token's placeholder and never the token. `devvm agent save` without a terminal shows the VM's changed `settings.json` as a diff and its new `commands` folder's file, then refuses and saves nothing, and after a yes it saves both into the store, but neither the VM's fake login beside them nor the folder's link out of it. Then SSH agents, with a home of their own and throwaway keys: a `--ssh-agent` VM uses a throwaway agent standing for yours; after `devvm ssh-agent add` and `devvm ssh-agent devvm` it keeps yours, in its shell and by name, until a restart, then uses only devvm's own agent's key, in its shells and by name; after `devvm ssh-agent off`, none. - `gc`: a VM from a folder named `img-keep`, which is named like an image, and a fixture layer edited after its build: `devvm gc` deletes the stale image and its record and an old tool image no VM lists (once there's a tools lock), and keeps base and the VM. - `tools`: first, the shared tools resolve to upstream's newest versions, with devvm's pinned mise (downloaded once), each download with its checksum. This section is the only one that uses the newest versions, and no other step checks for them (`DEVVM_NO_TOOL_CHECK`). At the section's end, e2e puts the pinned lock back. Then a node project's VM: node, npm, pnpm, bun and yarn at the locked versions, each a read-only EROFS image, the share read-only even for root, `npm i -g` into the VM's home, a non-login shell over SSH, an `.nvmrc`'s own version, the tools mounted at boot without devvm, and a second node VM that builds nothing. Last, a .NET project's VM on the allowlist tier, chosen by its solution file: the shared SDK at the locked version from the share, a console project that restores a package from NuGet, builds and runs, `dotnet tool install -g` into `~/.dotnet/tools` with the tool run from a non-login shell, a workload installed into `~/.dotnet`, nothing of it blocked, and a `global.json`'s own SDK installed into the VM. -- `network`: a VM with Claude Code, Codex, opencode and pi and `--network allowlist`, a fake token in devvm's environment and a fake `~/.claude.json` and Codex login in a home of its own, which `devvm agent import` copies into the sandbox's agent store, only yours to read. Its proxy runs and the self-check passed; its password was in no host process's arguments while devvm launched it (`ps`, sampled), and the guest has it; `ssh devvm-net` reaches it; direct connections fail, even as root, to an address and to other ports; an allowed host works and others, or other ports, are blocked; a line in the VM's policy file that reads as a deny but isn't a rule makes the running proxy refuse an allowed host, with no allow command in `devvm network log --blocked`, `devvm network rm` warns of it, and the host works again once it's gone; DNS fails at once; the host's loopback services are out of reach, directly or through the proxy; the proxy refuses requests without the VM's password; the token is nowhere in the VM, which has its own CA and the next one, its own placeholder and logins' copies with placeholders only; the proxy puts the token in for its host (for the VM's own placeholder only), an MCP server's header and Codex's key for theirs, over TLS the VM verifies; a second allowlist VM has CAs of its own, each VM trusts only its own and has no key, each proxy serves and presents only its own VM's CAs, and `devvm rm` deletes one VM's CAs and leaves the other's; the home folder's and the store's login files are unchanged. `devvm agent save` saves the VM's changed `~/.claude.json` with the store's MCP header in place of its placeholder, and once the VM changes that server's URL it leaves the file out, so the store keeps the server as it was. `devvm secret set github --stdin` saves a fake token (in the Keychain on macOS, under the run's service, found through a link to `~/Library/Keychains` in the VM's home), read from a file so it's in no process's arguments, and `devvm secret` lists it saved, while asking `devvm secret` for a `get` subcommand is refused without printing it; `secret use github` binds it to the running proxy at once, and on the next launch the VM has its own placeholder in `GH_TOKEN`, never the token, which the proxy puts in for `api.github.com`; `secret unuse` and `rm` take the binding and the token away. `TestE2ESelfCheck` in `internal/netpolicy` runs the self-check on the VM: it passes, then, once the VM is started outside devvm, it fails and stops the VM. `devvm stop` stops the VM and its proxy at once. `devvm network open` makes its next start direct, its proxy set in the guest and answering, and the open VM holds no real secret either: the token is nowhere in it, its environment and Codex's login hold only its placeholders, its proxy puts the token in over TLS the VM verifies with its own CA, and a request that goes around the proxy carries only the placeholder and gets a 401 from the token's host. Then `devvm network internet` and `devvm network none` change its tier at once, the VM running on. Restarted behind the run's company proxy on this machine's loopback, named in the shell's `HTTPS_PROXY` with a fake password that the check reads from a file, the guest has the proxy and reaches GitHub through it, while devvm's run logs hold the password only as `` and Lima's `ha.stderr.log` only as stars. `devvm network allowlist` while it runs open shows it `unenforced` until `devvm restart` starts it confined; `devvm network open` while it runs confined keeps it on its proxy until it next starts. Behind a company proxy of the run's own that fakes OpenAI's token endpoint with a certificate from the run's CA, a login made in the VM is captured: the store gets the fake tokens and API key, and the VM gets placeholders. Then `devvm agent login codex` runs the real Codex's login in the VM, curl on this machine opens its callback with the state Codex's address names, through the forward of `localhost:1455`, devvm names the account the store saved, the VM's Codex holds only placeholders, and the forward is gone once the login ends, and gone too after an interrupted login. `devvm agent login opencode --device-code` runs the real opencode 2's Codex device code login in the VM, which the fake endpoint answers too, devvm says the store saved the login, and `opencode auth export` in the VM shows only placeholders. A second VM with opencode has `OPENCODE_DISABLE_AUTOUPDATE=1` in its login shell, makes its database and imports a credential of its own, then `devvm agent login opencode --api-key --provider openrouter --stdin` saves a fake key from the first VM, and at the second VM's next launch its opencode has devvm's entry with the key's placeholder, never the key, beside its own credential, and once its database is deleted and made again, the next launch gives it the key's placeholder again. pi runs in the network VM with `PI_SKIP_VERSION_CHECK=1` and `PI_TELEMETRY=0`, in a login shell and in a non-login `bash -c` alike, and an install it can't write to, and its policy reaches its catalog at `pi.dev`. Its terminal UI, started in a terminal of `script`'s, finds base's `fdfind` and `rg` and downloads nothing into `~/.pi/agent/bin`, while with a `PATH` that has no `fdfind` the same start downloads `fd`, which shows the start reached that check. The same company proxy fakes Claude's token endpoint and Anthropic's API, which logs the token each request brings, or the `x-api-key`: `devvm agent login pi --api-key --provider anthropic --stdin` saves a fake key, the VM's pi holds only its placeholder, and pi's own request reaches the API with the key the proxy put in, which no log holds. Then `claude setup-token`'s request, as curl, makes the fake token the `claude` secret and gives the VM its placeholder, and the API gets the token for it. Then `devvm agent login claude` runs the real Claude Code's `claude auth login` in the VM, its code pasted on devvm's input with the state its address names, the store keeps the fake login and the `claude` secret is gone, the VM's `~/.claude/.credentials.json` holds only placeholders and its environment no token, and once the store's access token is due, the VM's next request makes the host refresh it at Claude's endpoint through the company proxy. This machine's TLS doesn't trust the run's CA, so that refresh fails, the store keeps its login and the proxy's log says so, and `TestClaudeOAuthGet` checks a refresh that succeeds. +- `network`: a VM with Claude Code, Codex, opencode and pi and `--network allowlist`, a fake token in devvm's environment and a fake `~/.claude.json` and Codex login in a home of its own, which `devvm agent import` copies into the sandbox's agent store, only yours to read. Its proxy runs and the self-check passed; its password was in no host process's arguments while devvm launched it (`ps`, sampled), and the guest has it; `ssh devvm-net` reaches it; direct connections fail, even as root, to an address and to other ports; an allowed host works and others, or other ports, are blocked; a line in the VM's policy file that reads as a deny but isn't a rule makes the running proxy refuse an allowed host, with no allow command in `devvm network log --blocked`, `devvm network rm` warns of it, and the host works again once it's gone; DNS fails at once; the host's loopback services are out of reach, directly or through the proxy; the proxy refuses requests without the VM's password; the token is nowhere in the VM, which has its own CA and the next one, its own placeholder and logins' copies with placeholders only; the proxy puts the token in for its host (for the VM's own placeholder only), an MCP server's header and Codex's key for theirs, over TLS the VM verifies; a second allowlist VM has CAs of its own, each VM trusts only its own and has no key, each proxy serves and presents only its own VM's CAs, and `devvm rm` deletes one VM's CAs and leaves the other's; the home folder's and the store's login files are unchanged. `devvm agent save` saves the VM's changed `~/.claude.json` with the store's MCP header in place of its placeholder, and once the VM changes that server's URL it leaves the file out, so the store keeps the server as it was. `devvm secret set github --stdin` saves a fake token (in the Keychain on macOS, under the run's service, found through a link to `~/Library/Keychains` in the VM's home), read from a file so it's in no process's arguments, and `devvm secret` lists it saved, while asking `devvm secret` for a `get` subcommand is refused without printing it; `secret use github` binds it to the running proxy at once, and on the next launch the VM has its own placeholder in `GH_TOKEN`, never the token, which the proxy puts in for `api.github.com`; `secret unuse` and `rm` take the binding and the token away. `TestE2ESelfCheck` in `internal/netpolicy` runs the self-check on the VM: it passes, then, once the VM is started outside devvm, it fails and stops the VM. `devvm stop` stops the VM and its proxy at once. `devvm network open` makes its next start direct, its proxy set in the guest and answering, and the open VM holds no real secret either: the token is nowhere in it, its environment and Codex's login hold only its placeholders, its proxy puts the token in over TLS the VM verifies with its own CA, and a request that goes around the proxy carries only the placeholder and gets a 401 from the token's host. Then `devvm network internet` and `devvm network none` change its tier at once, the VM running on. Restarted behind the run's company proxy on this machine's loopback, named in the shell's `HTTPS_PROXY` with a fake password that the check reads from a file, the guest has the proxy and reaches GitHub through it, while devvm's run logs hold the password only as `` and Lima's `ha.stderr.log` only as stars. `devvm network allowlist` while it runs open shows it `unenforced` until `devvm restart` starts it confined; `devvm network open` while it runs confined keeps it on its proxy until it next starts. Behind a company proxy of the run's own that fakes OpenAI's token endpoint with a certificate from the run's CA, a login made in the VM is captured: the store gets the fake tokens and API key, and the VM gets placeholders. Then `devvm agent login codex` runs the real Codex's login in the VM, curl on this machine opens its callback with the state Codex's address names, through the forward of `localhost:1455`, devvm names the account the store saved, the VM's Codex holds only placeholders, and the forward is gone once the login ends, and gone too after an interrupted login. `devvm agent login opencode --device-code` runs the real opencode 2's Codex device code login in the VM, which the fake endpoint answers too, devvm says the store saved the login, and `opencode auth export` in the VM shows only placeholders. A second VM with opencode has `OPENCODE_DISABLE_AUTOUPDATE=1` in its login shell, makes its database and imports a credential of its own, then `devvm agent login opencode --api-key --provider openrouter --stdin` saves a fake key from the first VM, and at the second VM's next launch its opencode has devvm's entry with the key's placeholder, never the key, beside its own credential, and once its database is deleted and made again, the next launch gives it the key's placeholder again. With a local server's fake key and a Copilot Enterprise login added to the store's opencode login, its next launch warns that both are withheld, and neither the VM's `auth.json` nor its opencode holds the key or the tokens. Once `config.toml`'s `[pass-keys]` lists both providers under `opencode`, the launch notes the key as passed, the VM's `auth.json` and its opencode's database have it, and the login's tokens still stay out. pi runs in the network VM with `PI_SKIP_VERSION_CHECK=1` and `PI_TELEMETRY=0`, in a login shell and in a non-login `bash -c` alike, and an install it can't write to, and its policy reaches its catalog at `pi.dev`. Its terminal UI, started in a terminal of `script`'s, finds base's `fdfind` and `rg` and downloads nothing into `~/.pi/agent/bin`, while with a `PATH` that has no `fdfind` the same start downloads `fd`, which shows the start reached that check. The same company proxy fakes Claude's token endpoint and Anthropic's API, which logs the token each request brings, or the `x-api-key`: `devvm agent login pi --api-key --provider anthropic --stdin` saves a fake key, the VM's pi holds only its placeholder, and pi's own request reaches the API with the key the proxy put in, which no log holds. Then `claude setup-token`'s request, as curl, makes the fake token the `claude` secret and gives the VM its placeholder, and the API gets the token for it. Then `devvm agent login claude` runs the real Claude Code's `claude auth login` in the VM, its code pasted on devvm's input with the state its address names, the store keeps the fake login and the `claude` secret is gone, the VM's `~/.claude/.credentials.json` holds only placeholders and its environment no token, and once the store's access token is due, the VM's next request makes the host refresh it at Claude's endpoint through the company proxy. This machine's TLS doesn't trust the run's CA, so that refresh fails, the store keeps its login and the proxy's log says so, and `TestClaudeOAuthGet` checks a refresh that succeeds. - `nix`: the nix layer. A copy of `assets/layers/nix.sh` as a layer of the run's own, built behind a company proxy of the run's own, reaches Nix's releases through it and leaves no proxy settings for `nix-daemon` (and not the company proxy's password) anywhere on its image's disk. Then a folder with `package.json`, `flake.nix` and `.envrc` gets a VM with node on the nix layer (`--layers nix`) on the allowlist tier: Nix and direnv at their pins, a store that's root's, `sandbox` on with no fallback, `trusted-users` root alone and an untrusted user's `--option substituters` ignored, `nix-daemon` with the VM's own proxy in devvm's drop-in alone, `nix run nixpkgs#hello` from Nix's cache, a build in Nix's sandbox, `sudo nix` and `nix` over ssh, the flake's dev shell (nixpkgs at a pinned revision) loaded by direnv in an interactive shell, its `node` ahead of the shared node prompt after prompt and gone outside the folder, nix-direnv's cache in the VM's home with no `.direnv` in the folder, a fixed-output download from a host that isn't allowed refused with `403` and named by `devvm-why`, and after `devvm network open` and `devvm restart`, no drop-in and no proxy for the daemon. - `from`: run with a `docker` that isn't running, so nothing comes from Docker. Its container images go by their pinned digests, as `node:24@sha256:…`, so devvm looks them up nowhere, except the company proxy's `alpine:3.21`, which keeps its tag so that devvm's registry lookup is checked too. A VM from `node:24` with node, python and Claude Code on the docker and nix layers (Debian 12, in a home of its own) boots, with its base keyed by the pinned digest, its node, python and claude at the locked versions, GNU `tar` as its commands find it, its tool images built in a clone of devvm's own Ubuntu base when the run builds them, the docker layer's Docker from Docker's Debian repository, and the nix layer's Nix under systemd running `nix run nixpkgs#hello` and a build in Nix's sandbox; a VM from `alpine:3` with node and dotnet, which its `package.json` and `global.json` call for, on the docker, nix and desktop layers runs node and pnpm from musl tool images, and dotnet's musl SDK with ICU, which makes and runs a console project, built in its own base and keyed and recorded by its digest, the docker layer's Docker on OpenRC, the desktop layer's programs from Alpine's packages, with no crashed services, and the nix layer's Nix as an OpenRC service, with `nix run nixpkgs#hello` and a sandboxed build, then after `devvm network allowlist` and `devvm restart` a download only its daemon makes from a host that isn't allowed refused with the proxy's `403`, and with GNU `tar` as its commands find it, `devvm history import` puts an export into it, while an export with a path outside the agents' history imports nothing there; base builds from `ubuntu:26.04`; and the build VM and its temporary folders are gone. diff --git a/docs/content/docs/internals/network.md b/docs/content/docs/internals/network.md index f158caf5..b78fb3aa 100644 --- a/docs/content/docs/internals/network.md +++ b/docs/content/docs/internals/network.md @@ -221,12 +221,12 @@ Agents' login files also stay on the host, in devvm's agent store, which `devvm Codex's login is `~/.local/share/devvm/logins/codex/.codex/auth.json`, opencode's is `~/.local/share/devvm/logins/opencode/.local/share/opencode/auth.json` and pi's is `~/.local/share/devvm/logins/pi/.pi/agent/auth.json`, the store's copies of `~/.codex/auth.json`, `~/.local/share/opencode/auth.json` and `~/.pi/agent/auth.json`. The VM's copy holds placeholders, shaped like a JWT where the tools read claims, and the bindings put the store's API key or access token into requests for the provider's hosts: - For Codex, those are OpenAI's hosts, `api.openai.com`, and `chatgpt.com` for a ChatGPT login. -- For opencode, they're the hosts of Anthropic, OpenAI and OpenRouter keys, and of OpenAI and GitHub Copilot logins, but not Copilot Enterprise. +- For opencode, they're the hosts of Anthropic, OpenAI and OpenRouter keys, and of OpenAI and GitHub Copilot logins, but not Copilot Enterprise. opencode keeps one entry per provider, `{"type":"api","key","metadata"}`, `{"type":"oauth","refresh","access","expires","accountId","enterpriseUrl"}` or `{"type":"wellknown","key","token"}`. A bound key's entry reaches the VM as `{"type","key"}` alone, its key the placeholder, so its `metadata` stays on this machine, and a bound OAuth login's keeps only the fields that name its account beside the placeholders (`internal/agentlogin/logins.go`'s `opencodeVM`). - For pi, they're the hosts of Anthropic, OpenAI and OpenRouter keys, `api.anthropic.com` with the `x-api-key` header, and `api.openai.com` and `openrouter.ai` with `Authorization`. pi keeps one entry per provider, `{"type":"api_key","key","env"}` or `{"type":"oauth","access","refresh","expires"}`, and devvm binds only the first kind, with a key that's a value rather than a `!command` or a `$NAME` or `${NAME}` template, which pi fills in from the entry's `env` or the environment (`$$` is a literal `$`). A bound entry reaches the VM as `{"type","key"}` alone, its key the placeholder, so nothing else of it, its `env` included, leaves this machine (`internal/agentlogin/pi.go`). -The store keeps opencode's login in the `auth.json` format of opencode 1: one entry per provider, `{"type":"api","key"}` or `{"type":"oauth","access","refresh","expires"}` with its expiry in milliseconds. opencode 2 keeps its logins in the `credential` table of its SQLite database, `~/.local/share/opencode/opencode.db`, and imports `auth.json` into it once, in the migration that makes the table, so a VM's opencode gets the VM's copy when it first runs there. A VM's placeholders don't change when the host refreshes a login, so the database's copies keep working. After that, the store's opencode logins reach the database through `opencode auth import`, as `auth export` entries with the IDs `cred_devvm_` and the logins' placeholders (`agentlogin.OpencodeImport`): each API key that the proxy puts in, and the OpenAI login from one of opencode's Codex logins. The VM's setup sends these entries on every launch, and `devvm agent login opencode --api-key --provider PROVIDER` sends them at once, both on the input of devvm's guest script `opencode.sh`, never in a command's arguments. The script keeps the last entries it got in `~/.local/state/devvm/opencode-import.json` in the VM. When opencode has made its database and the new entries differ from the record, or the database no longer holds one of their IDs because it was made again, such as after you delete it or a history import replaces it, it logs out of devvm's entries from the last ones with `opencode auth logout`, because `opencode auth import` skips an ID it already has, and then imports the new ones and makes each of them its provider's active credential with `opencode auth switch`, so a ChatGPT login for another account or a key saved from another VM reaches every VM at its next launch. Credentials that you added in the VM yourself have other IDs, so they stay in the database, and `opencode auth switch` makes one of them active again. Before opencode has made its database, the script does nothing and records nothing, because opencode 2.2.5 doesn't always import `auth.json` as it makes the database, so the first launch after opencode has run imports every entry. The script imports each entry on its own, so an entry that opencode refuses doesn't keep the others out, and `devvm agent login` names the providers that opencode refused. A failed import leaves the record as it was, so the next launch tries again. The script and its record live in the VM rather than in the VM's state on the host, because only the VM knows whether its database exists and what it last imported, and a VM that is set up again or has its home copied keeps both together. +The store keeps opencode's login in the `auth.json` format of opencode 1: one entry per provider, `{"type":"api","key"}` or `{"type":"oauth","access","refresh","expires"}` with its expiry in milliseconds. opencode 2 keeps its logins in the `credential` table of its SQLite database, `~/.local/share/opencode/opencode.db`, and imports `auth.json` into it once, in the migration that makes the table, so a VM's opencode gets the VM's copy when it first runs there. A VM's placeholders don't change when the host refreshes a login, so the database's copies keep working. After that, the store's opencode logins reach the database through `opencode auth import`, as `auth export` entries with the IDs `cred_devvm_` (`agentlogin.OpencodeImport`): the placeholder of each API key that the proxy puts in, each key that `[pass-keys]` passes, with its `metadata`, and the OpenAI login's placeholders from one of opencode's Codex logins. The VM's setup sends these entries on every launch, and `devvm agent login opencode --api-key --provider PROVIDER` sends them at once, both on the input of devvm's guest script `opencode.sh`, never in a command's arguments. The script keeps the last entries it got in `~/.local/state/devvm/opencode-import.json` in the VM. When opencode has made its database and the new entries differ from the record, or the database no longer holds one of their IDs because it was made again, such as after you delete it or a history import replaces it, it logs out of devvm's entries from the last ones with `opencode auth logout`, because `opencode auth import` skips an ID it already has, and then imports the new ones and makes each of them its provider's active credential with `opencode auth switch`, so a ChatGPT login for another account or a key saved from another VM reaches every VM at its next launch. Credentials that you added in the VM yourself have other IDs, so they stay in the database, and `opencode auth switch` makes one of them active again. Before opencode has made its database, the script does nothing and records nothing, because opencode 2.2.5 doesn't always import `auth.json` as it makes the database, so the first launch after opencode has run imports every entry. The script imports each entry on its own, so an entry that opencode refuses doesn't keep the others out, and `devvm agent login` names the providers that opencode refused. A failed import leaves the record as it was, so the next launch tries again. The script and its record live in the VM rather than in the VM's state on the host, because only the VM knows whether its database exists and what it last imported, and a VM that is set up again or has its home copied keeps both together. -Each VM's placeholders end in its own random value, so no other VM's placeholder gets its secrets. devvm reads a login file only when it's a regular file, so a FIFO or a device in its place can't hold devvm. devvm refreshes OAuth logins on the host, one lookup at a time, and writes them back to the store's file, so a VM never holds a refresh token. A refresh that has started finishes and is written back even when the request that needed it ends, because OpenAI may already have replaced the refresh token. When a refresh fails, or the store's login no longer has what a binding names, the proxy puts nothing in, and its own log says to log in again with the agent and import the login again (`codex_refresh_failed`, `opencode_refresh_failed`, `codex_no_key`, `codex_no_chatgpt`), or names the login file it couldn't read (`login_read_failed`). devvm copies logins it doesn't know as they are, and warns you (`codex_login_kept`, `opencode_login_kept`, `pi_login_kept`). An opencode OAuth login that devvm doesn't bind, such as Copilot Enterprise's or one for a provider devvm doesn't know, is the exception: its access and refresh tokens become `devvm-redacted` in the VM's copy, so opencode in the VM can't use that login, and devvm warns you (`opencode_login_withheld`). pi's logins are withheld by default: every entry of pi's that devvm doesn't bind, an OAuth login or an API key, reaches the VM with only the fields that name its account or how it logs in, `type`, `expires`, `accountId`, `enterpriseUrl`, `projectId`, `email`, `scope`, `scopes` and `clientId`, each a plain value or a list of strings, and devvm warns you (`pi_login_withheld`). The exception is an API-key entry of a provider that `config.toml`'s `[pass-keys]` lists under `pi` (`settings.PassKeys`), which goes as it is, and devvm notes it (`pi_login_kept`). The table has one key per agent, so another agent's withheld keys can share it. If devvm can't make the VM's copy of a login, it stops the VM's setup (`login_copy_failed`). +Each VM's placeholders end in its own random value, so no other VM's placeholder gets its secrets. devvm reads a login file only when it's a regular file, so a FIFO or a device in its place can't hold devvm. devvm refreshes OAuth logins on the host, one lookup at a time, and writes them back to the store's file, so a VM never holds a refresh token. A refresh that has started finishes and is written back even when the request that needed it ends, because OpenAI may already have replaced the refresh token. When a refresh fails, or the store's login no longer has what a binding names, the proxy puts nothing in, and its own log says to log in again with the agent and import the login again (`codex_refresh_failed`, `opencode_refresh_failed`, `codex_no_key`, `codex_no_chatgpt`), or names the login file it couldn't read (`login_read_failed`). devvm copies the entries of Codex's `auth.json` that it doesn't know as they are, and warns you (`login_kept`). opencode's and pi's logins are withheld by default, by the same rule (`agents.Def`'s `PassKeys`): every entry that devvm doesn't bind, an API key, an OAuth login or opencode's well-known login, reaches the VM with only the fields that name its account or how it logs in, `type`, `expires`, `accountId`, `enterpriseUrl`, `projectId`, `email`, `scope`, `scopes` and `clientId`, each a plain value or a list of strings (`agentlogin`'s `withheldEntry`), and devvm warns you (`login_withheld`). opencode skips an entry that lacks its key or its tokens as it reads `auth.json`, so it doesn't use that provider in the VM. The exception is an API-key entry of a provider that `config.toml`'s `[pass-keys]` lists under the agent's name (`settings.PassKeys`), which goes as it is, and devvm notes it (`login_passed`). It's never an OAuth login, whose tokens a VM never gets, and never a provider that devvm binds, whose key is always its placeholder. The table has one key per agent, so each agent's withheld keys are passed on their own. If devvm can't make the VM's copy of a login, it stops the VM's setup (`login_copy_failed`). [Coding agents](../using/coding-agents.md) lists which files each agent shares. @@ -291,7 +291,7 @@ Taking secrets out of a file works only where devvm can tell a secret from the r - **The agents' mounted folders.** devvm mounts Claude Code's `skills`, `agents`, `commands`, `output-styles` and `plugins`, Codex's `prompts` and `skills`, opencode's subfolders, and pi's `extensions`, `skills`, `prompts` and `themes` whole and read-only, so every file in them reaches the VM, a `.env` in `~/.config/opencode/plugin` included. So does a plugin marketplace's git config in `~/.claude/plugins/marketplaces`, which holds a password or a token when you added a private marketplace with one in its URL. These folders hold code that the agent runs, such as plugins, hooks and the scripts that skills call, so a copy with only settings and Markdown, as opencode's config folder's files get, would break them. A copy without files whose names look secret, such as `.env` or `*.pem`, would miss a key in any other file, and it would need a copy of each folder, which can be large, on every launch, while a mount shows the changes to devvm's agent store at once. So devvm mounts them as they are, and the [coding agents page](../using/coding-agents.md#mounts) says to keep secrets out of them. - **Free text of an unknown shape.** A key in other text, such as a hook's command, stays when it neither starts like a known key nor follows `Bearer` or `Basic`, because devvm can't tell it from a word. -- **Logins devvm can't bind.** The entries of Codex's `auth.json` that devvm doesn't know, opencode's API keys for providers other than Anthropic, OpenAI and OpenRouter, and opencode's well-known logins (`"type": "wellknown"`, which an organization's own config sets up) go into the VM's copy as they are, because devvm doesn't know which hosts they're for, so the proxy couldn't put them in. A local model server's key is one of these. devvm names each (`codex_login_kept`, `opencode_login_kept`). pi's such keys are withheld unless `[pass-keys]` lists their provider, and then they go as they are (`pi_login_kept`). +- **Logins devvm can't bind.** The entries of Codex's `auth.json` that devvm doesn't know go into the VM's copy as they are, because devvm doesn't know which hosts they're for, so the proxy couldn't put them in, and devvm names each (`login_kept`). opencode's and pi's such keys, a local model server's among them, are withheld unless `[pass-keys]` lists their provider, and then they go as they are (`login_passed`). - **pi's settings that undo devvm's.** The VM's copy of pi's `settings.json` leaves out `httpProxy`, `sessionDir` and `selfUpdateCommand` (`agentlogin.PiSettings`, `pi_settings_dropped`), and devvm warns when it sets `defaultProjectTrust` to `always` (`pi_trusts_all`). Its other settings stay, with their keys taken out as above. ## The self-check diff --git a/docs/content/docs/safety/_index.md b/docs/content/docs/safety/_index.md index cbae83da..ee711f09 100644 --- a/docs/content/docs/safety/_index.md +++ b/docs/content/docs/safety/_index.md @@ -62,7 +62,7 @@ flowchart TB | The rest of your home folder, other projects | The VM doesn't mount them. | | Your SSH keys | Only with `devvm ssh-agent on`, and only while you're connected. With `devvm ssh-agent devvm`, the VM can use only the keys you added to devvm's own agent ([details](../using/ssh.md#agent-forwarding)). | | The network | On every tier but open, the VM reaches only its proxy on this machine, which lets it reach what [its tier](network.md#network-tiers) allows. On the open tier it reaches everything this machine reaches, including this machine's own services on `localhost` ([details](network.md#network-tiers)). | -| Your secrets | Your GitHub token, Claude Code's token, the coding agents' logins and API keys and Claude Code's MCP secrets stay on this machine on every network tier, and the proxy puts them into requests ([details](network.md#secrets)). An agent's keys that the proxy can't put in, such as pi's for a local model server, stay on this machine too, unless you pass one to VMs in `config.toml` ([pi logins](../using/coding-agents.md#pi-logins)). | +| Your secrets | Your GitHub token, Claude Code's token, the coding agents' logins and API keys and Claude Code's MCP secrets stay on this machine on every network tier, and the proxy puts them into requests ([details](network.md#secrets)). opencode's and pi's keys that the proxy can't put in, such as a local model server's, stay on this machine too, unless you pass one to VMs in `config.toml` ([opencode logins](../using/coding-agents.md#codex-and-opencode-logins), [pi logins](../using/coding-agents.md#pi-logins)). | > [!NOTE] > Everything here rests on the VM's boundary: the VM runs its own kernel, apart from this machine's. diff --git a/docs/content/docs/safety/attack-vectors.md b/docs/content/docs/safety/attack-vectors.md index 2c05a9bf..13377777 100644 --- a/docs/content/docs/safety/attack-vectors.md +++ b/docs/content/docs/safety/attack-vectors.md @@ -85,7 +85,7 @@ The attacks in this section run the attacker's code, and devvm doesn't stop that - **Worms that use your GitHub token.** Shai-Hulud (2025) spread through npm install scripts. It collected npm, GitHub and cloud credentials, then used them to publish repos and new versions of packages. A VM holds no npm or cloud credentials, and its GitHub token is a placeholder. The proxy still puts the real GitHub token into every request to GitHub's hosts, so a worm in the VM can push, make repos and do whatever else the GitHub token's scope allows. Use a fine-grained GitHub token scoped to the repos the VM needs, or bind none ([saving and binding secrets](network.md#saving-and-binding-secrets)). - **Minting credentials with a secret.** A VM that can use a secret can use it to make another credential that outlasts it. The proxy refuses GitHub REST calls that add an SSH key, a deploy key, a self-hosted runner or a webhook with `403`, but it can't refuse everything, such as GitHub's GraphQL API, an OAuth app grant or other services. If a VM may have done this, rotate the secret and check the service's keys, access tokens and runners. -- **Keys devvm can't tell apart.** devvm takes the keys out of the VM's copies of your agents' settings and logins only where it can tell a key from the rest. A key in other text, such as a hook's command, stays when it neither starts like a known key nor follows `Bearer` or `Basic`. Logins that devvm can't bind go in as they are, such as the entries of Codex's login that devvm doesn't know, opencode's API keys for providers other than Anthropic, OpenAI and OpenRouter, and opencode's well-known logins, and devvm names each one. The agents' folders that the VM mounts whole, such as `~/.claude/skills` or `~/.config/opencode/plugin`, reach the VM with every file in them, so a `.env` in one is in the VM, and so is a private plugin marketplace's git config with a password or an access token in its URL. Keep secrets out of those folders ([what stays in the VM's copies](../internals/network.md#what-stays-in-the-vms-copies)). +- **Keys devvm can't tell apart.** devvm takes the keys out of the VM's copies of your agents' settings and logins only where it can tell a key from the rest. A key in other text, such as a hook's command, stays when it neither starts like a known key nor follows `Bearer` or `Basic`. The entries of Codex's login that devvm doesn't know go in as they are, and devvm names each one. opencode's and pi's keys that devvm can't bind, such as a local model server's, stay on this machine unless you list their provider in `config.toml`'s `[pass-keys]`, and then they go in as they are. The agents' folders that the VM mounts whole, such as `~/.claude/skills` or `~/.config/opencode/plugin`, reach the VM with every file in them, so a `.env` in one is in the VM, and so is a private plugin marketplace's git config with a password or an access token in its URL. Keep secrets out of those folders ([what stays in the VM's copies](../internals/network.md#what-stays-in-the-vms-copies)). - **Your SSH agent.** While [agent forwarding](../using/ssh.md#agent-forwarding) is on, anything in the VM can use the agent's keys to push or log in to servers, though it can't copy them. The VM has the agent while you're connected. `devvm ssh-agent devvm` limits it to the keys you add to [devvm's own agent](../using/ssh.md#devvms-own-agent), and an agent that asks you to approve each use, such as 1Password's or Secretive, narrows it further. ### Git diff --git a/docs/content/docs/using/coding-agents.md b/docs/content/docs/using/coding-agents.md index 632bf21c..12e7c49f 100644 --- a/docs/content/docs/using/coding-agents.md +++ b/docs/content/docs/using/coding-agents.md @@ -161,7 +161,18 @@ Anthropic doesn't document the requests that Claude Code's login sends, so devvm ### Codex and opencode logins -On every network tier, the VM's `auth.json` holds placeholders, and its proxy holds the real API keys and logins. The proxy reads them from the login files in devvm's store as it needs them and refreshes ChatGPT logins there, so when the agent in the VM stops getting answers, the proxy's own log, `proxy.log` in `~/.local/share/devvm/vms//logs/`, may say that refreshing a login failed or that you're no longer logged in that way. To log in again, run [`devvm agent login codex` or `devvm agent login opencode`](#logging-in-with-devvm-agent-login) in the VM's folder, which also gives that VM the new login's placeholders, and the other VMs get them on their next launch. The proxy puts in opencode's API keys for Anthropic, OpenAI and OpenRouter, and its OpenAI and GitHub Copilot logins. The VM gets opencode's API keys for other providers unchanged, and its well-known logins too, which an organization's own opencode config sets up, because devvm doesn't know which hosts those are for. devvm warns you about each. The VM gets opencode's other OAuth logins, such as Copilot Enterprise's, without their access and refresh tokens, so they don't work in the VM, and devvm warns you about each. To use such a provider in the VM, log in to it with an API key on this machine and import the login again. +On every network tier, the VM's `auth.json` holds placeholders, and its proxy holds the real API keys and logins. The proxy reads them from the login files in devvm's store as it needs them and refreshes ChatGPT logins there, so when the agent in the VM stops getting answers, the proxy's own log, `proxy.log` in `~/.local/share/devvm/vms//logs/`, may say that refreshing a login failed or that you're no longer logged in that way. To log in again, run [`devvm agent login codex` or `devvm agent login opencode`](#logging-in-with-devvm-agent-login) in the VM's folder, which also gives that VM the new login's placeholders, and the other VMs get them on their next launch. The proxy puts in opencode's API keys for Anthropic, OpenAI and OpenRouter, and its OpenAI and GitHub Copilot logins. The VM's entry for such an API key holds only its type and the placeholder, so the entry's other fields, such as its `metadata`, stay on this machine. + +devvm keeps every other entry of opencode's `auth.json` on this machine too, because devvm doesn't know which hosts it's for, so the VM gets that entry without its key or its tokens, and devvm warns you about each at every launch. That's an API key for any other provider, such as Gemini's or a local model server's, a well-known login, which an organization's own opencode config sets up, and any other OAuth login, such as Copilot Enterprise's. The VM keeps only the fields of a withheld entry that name the account or how it logs in, such as its type, its `enterpriseUrl` and its expiry, so opencode in the VM doesn't use that provider. To use an OAuth login's provider in the VM, log in to it with an API key on this machine and import the login again. + +To give the VM one provider's API key as it is, such as a local model server's that the VM's proxy can't put in, list the provider under `opencode` in `config.toml`'s `[pass-keys]` table ([config.toml](settings.md#configtoml)), as you would for [pi](#pi-logins). The provider is its entry's name in opencode's `auth.json`, such as `ollama`. Every VM with opencode then gets that entry whole, its `metadata` included, and opencode 2 in the VM imports it into its database too, and devvm says so at each launch. It applies only to entries with an API key, because a VM never gets a login's tokens, and only to providers whose keys the proxy doesn't put in, because a key the proxy puts in is always its placeholder: + +```toml +[pass-keys] +opencode = ["ollama"] +``` + +So when opencode in a VM can't reach a provider whose key works on this machine, such as a local model server's, and devvm's warning at launch names that provider, add it to `[pass-keys]` and run devvm in the folder again. #### Logging in with devvm agent login diff --git a/docs/content/docs/using/settings.md b/docs/content/docs/using/settings.md index 462ce35e..06b81009 100644 --- a/docs/content/docs/using/settings.md +++ b/docs/content/docs/using/settings.md @@ -72,6 +72,7 @@ no-proxy = "localhost,.example.com" # Providers whose API keys an agent's VMs get as they are. [pass-keys] +opencode = ["ollama"] pi = ["ollama"] ``` @@ -79,7 +80,7 @@ Each key takes what its command takes. `network` is a tier, `open`, `internet`, The `[proxy]` table is the [company proxy](../safety/network.md#behind-a-company-proxy) that every VM's proxy, builds and devvm's own downloads go through when the shell you run devvm in sets neither `HTTPS_PROXY` nor `HTTP_PROXY`, whatever the VM's tier. No VM gets the company proxy's settings itself. That shell's settings win over the whole table. `https` and `http` take what `HTTPS_PROXY` and `HTTP_PROXY` take, an `http://` URL or `host:port`, and `no-proxy` takes what `NO_PROXY` takes. A URL never holds a password, and devvm refuses one that does, so put only the user in it and save the password with `devvm secret set proxy`. No command saves the proxy, so it's only ever in `config.toml`. -The `[pass-keys]` table names, for an agent, the providers whose API keys its VMs get as they are, which devvm otherwise keeps on this machine because the VM's proxy can't put them in, such as a local model server's. `pi` is the one agent it takes so far, with a list of pi's provider IDs as pi's `auth.json` names them, in lower case, such as `["ollama"]` ([pi logins](coding-agents.md#pi-logins)). devvm refuses another agent, a name that isn't a provider's ID and a repeat (`config.toml` names the line). Every VM with the agent gets the change at its next launch. No command saves it, so it's only ever in `config.toml`. +The `[pass-keys]` table names, for an agent, the providers whose API keys its VMs get as they are, which devvm otherwise keeps on this machine because the VM's proxy can't put them in, such as a local model server's. It takes `opencode` and `pi`, each with a list of the agent's provider IDs as its `auth.json` names them, in lower case, such as `["ollama"]` ([opencode logins](coding-agents.md#codex-and-opencode-logins), [pi logins](coding-agents.md#pi-logins)). devvm refuses another agent, a name that isn't a provider's ID and a repeat (`config.toml` names the line). Every VM with the agent gets the change at its next launch. No command saves it, so it's only ever in `config.toml`. ### An Ubuntu mirror diff --git a/internal/agentlogin/apikey.go b/internal/agentlogin/apikey.go index e9b4bc74..fb170782 100644 --- a/internal/agentlogin/apikey.go +++ b/internal/agentlogin/apikey.go @@ -30,10 +30,12 @@ var errKeyProvider = errors.New("no API key devvm puts in for that provider") // OpencodeImport is what opencode's auth import reads to give a VM whose opencode has made its // database the logins of vmCopy, the VM's copy of the store's opencode login (File.VMCopy, which -// holds placeholders alone): opencode 2 keeps its logins there and reads auth.json only as it -// makes it. It's each API key devvm puts in (KeyProviders) and OpenAI's Codex login as opencode's -// auth export prints them, sorted by provider, under IDs of devvm's (cred_devvm_), which -// the VM's setup logs out of before it imports a new set, so the user's own credentials stay. +// holds placeholders and passed keys alone): opencode 2 keeps its logins there and reads auth.json +// only as it makes it. It's each API key the copy holds, the placeholders of KeyProviders' and the +// keys config.toml's [pass-keys] passes with their metadata (a withheld entry holds no key), and +// OpenAI's Codex login, as opencode's auth export prints them, sorted by provider, under IDs of +// devvm's (cred_devvm_), which the VM's setup logs out of before it imports a new set, +// so the user's own credentials stay. func OpencodeImport(vmCopy []byte) ([]byte, error) { d := json.NewDecoder(bytes.NewReader(vmCopy)) d.UseNumber() @@ -46,8 +48,11 @@ func OpencodeImport(vmCopy []byte) ([]byte, error) { e := obj(m, id) var v map[string]any switch { - case str(e, "type") == "api" && slices.Contains(KeyProviders(agents.Opencode), id) && str(e, "key") != "": + case str(e, "type") == "api" && str(e, "key") != "": v = map[string]any{"type": "key", "key": str(e, "key")} + if md := obj(e, "metadata"); len(md) > 0 { + v["metadata"] = md + } case str(e, "type") == "oauth" && id == "openai" && str(e, "access") != "": // opencode 2 (checked at v2.2.5) needs a method, Codex's in a browser, whose tokens // come from the endpoint the store refreshes at, and a whole number for expires. diff --git a/internal/agentlogin/format.go b/internal/agentlogin/format.go index a0d0b973..6240a404 100644 --- a/internal/agentlogin/format.go +++ b/internal/agentlogin/format.go @@ -86,9 +86,10 @@ func (opencodeFormat) bindings(m map[string]any, salt string) []proxy.Binding { return opencodeBindings(m, salt) } +// vmCopy: Kept are the providers File.Pass lists, whose entries go as they are. func (opencodeFormat) vmCopy(m map[string]any, f File) (map[string]any, VMFile) { - c := VMFile{Kept: opencodeUnbound(m, false), Withheld: opencodeUnbound(m, true)} - return opencodeVM(m, f.Salt), c + passed, withheld := opencodeSplit(m, f.Pass) + return opencodeVM(m, f.Salt, f.Pass), VMFile{Kept: passed, Withheld: withheld} } func (opencodeFormat) get(ctx context.Context, f File, name string) (string, error) { @@ -112,8 +113,8 @@ func (piFormat) bindings(m map[string]any, salt string) []proxy.Binding { return // vmCopy: Kept are the providers File.Pass lists, whose entries go as they are. func (piFormat) vmCopy(m map[string]any, f File) (map[string]any, VMFile) { - c := VMFile{Kept: piPasses(m, f.Pass), Withheld: piWithheld(m, f.Pass)} - return piVM(m, f.Salt, f.Pass), c + passed, withheld := piSplit(m, f.Pass) + return piVM(m, f.Salt, f.Pass), VMFile{Kept: passed, Withheld: withheld} } func (piFormat) get(_ context.Context, f File, name string) (string, error) { return f.piGet(name) } diff --git a/internal/agentlogin/golden_test.go b/internal/agentlogin/golden_test.go index 946d0f80..d53d0ba2 100644 --- a/internal/agentlogin/golden_test.go +++ b/internal/agentlogin/golden_test.go @@ -50,7 +50,8 @@ func goldenLogins() map[string]string { "zz_extra": map[string]any{"kept": true}, "aa_other": "kept", }), Opencode: enc(map[string]any{ - "anthropic": map[string]any{"type": "api", "key": "sk-ant-e2efake"}, + "anthropic": map[string]any{"type": "api", "key": "sk-ant-e2efake", "metadata": map[string]any{"m": "md-e2efake"}}, + "ollama": map[string]any{"type": "api", "key": "ollama-local", "metadata": map[string]any{"host": "kept"}}, "openrouter": map[string]any{"type": "api", "key": "sk-or-e2efake"}, "openai": map[string]any{"type": "oauth", "access": access, "refresh": "rt-e2efake", "expires": future.UnixMilli(), "accountId": "acct-1"}, "github-copilot": map[string]any{"type": "oauth", "access": "gho_e2efake", "refresh": "gho_e2efake", "expires": 0}, diff --git a/internal/agentlogin/logins.go b/internal/agentlogin/logins.go index 5ad9336f..b54fa0a7 100644 --- a/internal/agentlogin/logins.go +++ b/internal/agentlogin/logins.go @@ -38,6 +38,7 @@ import ( "os" "path/filepath" "regexp" + "slices" "sort" "strings" "syscall" @@ -92,9 +93,9 @@ type File struct { // TokenURL is where OAuth tokens are refreshed: when empty, ClaudeTokenURL for ClaudeOAuth, // else OpenAITokenURL. TokenURL string - // Pass are the providers whose API-key entries the VM's copy holds as they are (pi's, from - // config.toml's [pass-keys]), unless devvm binds them; any other entry devvm doesn't bind is - // withheld. + // Pass are the providers whose API-key entries the VM's copy holds as they are (opencode's + // or pi's, from config.toml's [pass-keys]), unless devvm binds them; any other entry devvm + // doesn't bind is withheld. Pass []string } @@ -106,9 +107,57 @@ func salted(ph, salt string) string { return ph + "-" + salt } +// withheldKeep are the fields a withheld login entry (opencode's or pi's, neither bound nor +// passed) keeps in the VM's copy: those that name an account or how it logs in, never a key or a +// token. +var withheldKeep = []string{"type", "expires", "accountId", "enterpriseUrl", "projectId", "email", "scope", "scopes", "clientId"} + +// withheldEntry is a login entry e as the VM's copy holds it withheld: withheldKeep's fields +// alone, each a plain value or a list of strings. +func withheldEntry(e map[string]any) map[string]any { + kept := map[string]any{} + for _, k := range withheldKeep { + if v, ok := e[k]; ok && plainField(v) { + kept[k] = v + } + } + return kept +} + +// plainField: a string, number, bool or null, or a list of strings. +func plainField(v any) bool { + switch t := v.(type) { + case map[string]any: + return false + case []any: + for _, x := range t { + if _, ok := x.(string); !ok { + return false + } + } + } + return true +} + +// splitUnbound returns the entries of m, a login file of one entry per provider, that devvm +// doesn't bind: those passed, which the VM's copy holds as they are, and the others, which it +// holds withheld (withheldEntry), each sorted. +func splitUnbound(m map[string]any, bound, passed func(id string) bool) (pass, withheld []string) { + for _, id := range sortedKeys(m) { + switch { + case bound(id): + case passed(id): + pass = append(pass, id) + default: + withheld = append(withheld, id) + } + } + return pass, withheld +} + // opencode providers devvm knows: where an API key or access token goes. Logins for other providers -// stay in the VM's copy as they are (a local model server's key, say). pi's API keys are bound for -// opencodeAPI's providers too (pi.go). +// are withheld from the VM's copy unless config.toml's [pass-keys] passes them (opencodeVM). pi's +// API keys are bound for opencodeAPI's providers too (pi.go). type provider struct { hosts []string header string @@ -378,46 +427,65 @@ func opencodeBindings(m map[string]any, salt string) []proxy.Binding { return bs } -func opencodeVM(m map[string]any, salt string) map[string]any { - // An OAuth login devvm doesn't bind loses its tokens: the VM never holds a refresh token. - for _, id := range opencodeUnbound(m, true) { - e := obj(m, id) - for _, k := range []string{"access", "refresh"} { - if str(e, k) != "" { - e[k] = redactMark - } - } - } +// opencodeVM is the VM's copy of opencode's logins m (checked against opencode's auth.json schema +// at v1.19.5 and its import at v2.2.5: {"type":"api","key","metadata"}, +// {"type":"oauth","refresh","access","expires","accountId","enterpriseUrl"} or +// {"type":"wellknown","key","token"}), each entry held in one of three ways: +// - bound: an API key's entry becomes {type, key} alone, its key the placeholder, so its +// metadata stays on the host; an OAuth login's keeps withheldKeep's fields, its access and +// refresh tokens the placeholder. +// - passed: an api entry of a provider pass lists (File.Pass, config.toml's [pass-keys]) that +// devvm doesn't bind goes as it is. +// - withheld: every other entry, OAuth and well-known logins included, as withheldEntry makes +// it, which opencode skips as it reads the file. +func opencodeVM(m map[string]any, salt string, pass []string) map[string]any { + out := map[string]any{} for _, b := range opencodeBindings(m, salt) { - e := obj(m, strings.TrimPrefix(b.Name, "opencode-")) + id := strings.TrimPrefix(b.Name, "opencode-") + e := obj(m, id) if str(e, "type") == "api" { - e["key"] = b.Placeholder + out[id] = map[string]any{"type": "api", "key": b.Placeholder} continue } - e["access"] = b.Placeholder - e["refresh"] = b.Placeholder // Copilot sends this one; nothing else in the VM refreshes + v := withheldEntry(e) + v["access"] = b.Placeholder + v["refresh"] = b.Placeholder // Copilot sends this one; nothing else in the VM refreshes if n, _ := e["expires"].(json.Number); n.String() != "0" { - e["expires"] = farFuture * 1000 + v["expires"] = farFuture * 1000 } + out[id] = v } - return m + for _, id := range sortedKeys(m) { + if _, done := out[id]; done { + continue + } + if opencodePassed(m, id, out, pass) { + out[id] = m[id] + continue + } + out[id] = withheldEntry(obj(m, id)) + } + return out } -// opencodeUnbound returns the providers whose logins devvm doesn't bind, sorted: the OAuth ones -// (which the VM's copy holds without their tokens), or the others (which it holds as they are). -func opencodeUnbound(m map[string]any, oauth bool) []string { - known := map[string]bool{} +// opencodePassed reports whether opencode's entry for provider id goes into the VM's copy as it +// is: an api entry of a provider in pass that devvm doesn't bind, bound holding the bound ones. +func opencodePassed(m map[string]any, id string, bound map[string]any, pass []string) bool { + _, isBound := bound[id] + return !isBound && str(obj(m, id), "type") == "api" && slices.Contains(pass, id) +} + +// opencodeSplit returns the providers of opencode's whose entries the VM's copy holds as they are +// (passed) and those it holds without their keys and tokens (neither bound nor passed), each +// sorted. +func opencodeSplit(m map[string]any, pass []string) (passed, withheld []string) { + bound := map[string]any{} for _, b := range opencodeBindings(m, "") { - known[strings.TrimPrefix(b.Name, "opencode-")] = true + bound[strings.TrimPrefix(b.Name, "opencode-")] = true } - var out []string - for id := range m { - if !known[id] && (str(obj(m, id), "type") == "oauth") == oauth { - out = append(out, id) - } - } - sort.Strings(out) - return out + return splitUnbound(m, + func(id string) bool { _, ok := bound[id]; return ok }, + func(id string) bool { return opencodePassed(m, id, bound, pass) }) } func (f File) opencodeGet(ctx context.Context, name string) (string, error) { @@ -842,11 +910,11 @@ func (f File) Bindings() ([]proxy.Binding, error) { // VMFile is the VM's copy of an agent's file (File.VMCopy). type VMFile struct { Data []byte - // Kept: what of the file the copy holds as it is, sorted: Codex's auth.json keys, opencode's - // providers devvm doesn't know, or pi's providers that File.Pass lists. + // Kept: what of the file the copy holds as it is, sorted: Codex's auth.json keys, or + // opencode's or pi's providers that File.Pass lists. Kept []string - // Withheld: opencode's OAuth logins devvm doesn't bind, or every pi login devvm neither binds - // nor passes, sorted, which the copy holds without their keys and tokens. + // Withheld: every opencode or pi login devvm neither binds nor passes, sorted, which the + // copy holds without their keys and tokens. Withheld []string } diff --git a/internal/agentlogin/logins_test.go b/internal/agentlogin/logins_test.go index f9421ab2..c0aa19d8 100644 --- a/internal/agentlogin/logins_test.go +++ b/internal/agentlogin/logins_test.go @@ -10,6 +10,7 @@ import ( "net/http/httptest" "os" "path/filepath" + "reflect" "slices" "strings" "syscall" @@ -317,12 +318,9 @@ func TestOpencodeLogins(t *testing.T) { t.Errorf("the VM's copy holds %q", secret) } } - if !strings.Contains(out, `"local"`) { - t.Errorf("an unknown provider's login should stay as it is:\n%s", out) - } - // Logins copied as they are, the note's list: wellknown ones too (they hold a token). - if !slices.Equal(kept, []string{"llama-cpp", "mcp"}) { - t.Errorf("kept = %v", kept) + // Nothing passes without config.toml's [pass-keys]: an unknown provider's key is withheld. + if strings.Contains(out, `"local"`) || kept != nil { + t.Errorf("an unknown provider's key reached the VM (kept %v):\n%s", kept, out) } if v, _ := f.Get(t.Context(), "opencode-anthropic"); v != "sk-ant-real" { t.Errorf("anthropic = %q", v) @@ -343,28 +341,56 @@ func TestOpencodeLogins(t *testing.T) { } } -// An OAuth login devvm doesn't bind (a provider it doesn't know, Copilot Enterprise) loses its -// tokens in the VM's copy: the VM never holds a refresh token. -func TestOpencodeUnboundOAuthWithheld(t *testing.T) { - f := File{Kind: Opencode, Path: writeFile(t, map[string]any{ - "anthropic": map[string]any{"type": "oauth", "access": "fake-access-a", "refresh": "fake-refresh-a", "expires": 1}, - "github-copilot": map[string]any{"type": "oauth", "access": "fake-access-e", "refresh": "fake-refresh-e", "expires": 0, "enterpriseUrl": "ghe.example.com"}, - "llama-cpp": map[string]any{"type": "api", "key": "local"}, +// opencode's auth.json in the VM, whole, as pi's is. A bound key (Anthropic's) becomes {type, key} +// alone, its metadata left on the host, and a bound OAuth login (OpenAI's) keeps only the fields +// that name its account beside its placeholders. Every other entry is withheld, keeping only those +// fields: an unknown provider's key, an OAuth login devvm doesn't bind (a provider it doesn't know, +// Copilot Enterprise) and a well-known login, which holds a token. The api entry of a provider +// File.Pass lists (a local model server) goes as it is, but neither an OAuth login File.Pass names +// nor a bound provider's key File.Pass names. +func TestOpencodeVMCopy(t *testing.T) { + f := File{Kind: Opencode, Salt: "s1", Pass: []string{"ollama", "groq-oauth", "anthropic", "mcp"}, Path: writeFile(t, map[string]any{ + "anthropic": map[string]any{"type": "api", "key": "sk-ant-e2efake", "metadata": map[string]any{"account": "md-e2efake"}, "extra": "x-e2efake"}, + "openai": map[string]any{ + "type": "oauth", "access": jwtWith(time.Now().Add(time.Hour), map[string]any{"https://api.openai.com/auth": openaiAuth}), + "refresh": "rt-e2efake-openai", "expires": 1, "accountId": "acct-1", "other": "o-e2efake", + }, + "ollama": map[string]any{"type": "api", "key": "ollama-local", "metadata": map[string]any{"host": "kept"}}, + "groq": map[string]any{"type": "api", "key": "gsk-e2efake", "metadata": map[string]any{"m": "md-e2efake"}}, + "groq-oauth": map[string]any{"type": "oauth", "access": "at-e2efake-passed", "refresh": "rt-e2efake-passed", "expires": 1}, + "github-copilot": map[string]any{"type": "oauth", "access": "at-e2efake-ghe", "refresh": "rt-e2efake-ghe", "expires": 0, "enterpriseUrl": "ghe.example.com"}, + "mcp": map[string]any{"type": "wellknown", "key": "k-e2efake", "token": "t-e2efake"}, //nolint:gosec // fake values })} - out, kept := vmCopy(t, f) - for _, s := range []string{"fake-access-a", "fake-refresh-a", "fake-access-e", "fake-refresh-e"} { - if strings.Contains(out, s) { - t.Errorf("the VM's copy holds %q:\n%s", s, out) - } + c, err := f.VMCopy() + must(t, err) + var vm map[string]any + must(t, json.Unmarshal(c.Data, &vm)) + ph := openaiPlaceholder(str(obj(vm, "openai"), "access"), "s1") + var wantVM map[string]any + must(t, json.Unmarshal([]byte(`{ + "anthropic": {"type": "api", "key": "devvm-proxy-managed-opencode-anthropic-s1"}, + "openai": {"type": "oauth", "access": "`+ph+`", "refresh": "`+ph+`", "expires": 4070908800000, "accountId": "acct-1"}, + "ollama": {"type": "api", "key": "ollama-local", "metadata": {"host": "kept"}}, + "groq": {"type": "api"}, + "groq-oauth": {"type": "oauth", "expires": 1}, + "github-copilot": {"type": "oauth", "expires": 0, "enterpriseUrl": "ghe.example.com"}, + "mcp": {"type": "wellknown"} + }`), &wantVM)) + if !reflect.DeepEqual(vm, wantVM) { + t.Errorf("the VM's copy:\n%s", c.Data) } - if !strings.Contains(out, `"local"`) || !strings.Contains(out, `"ghe.example.com"`) { - t.Errorf("the VM's copy lost what isn't a token:\n%s", out) + if strings.Contains(string(c.Data), "e2efake") { + t.Errorf("the VM's copy holds a key or token:\n%s", c.Data) } - if !slices.Equal(kept, []string{"llama-cpp"}) { - t.Errorf("kept = %v", kept) + if !slices.Equal(c.Kept, []string{"ollama"}) || !slices.Equal(c.Withheld, []string{"github-copilot", "groq", "groq-oauth", "mcp"}) { + t.Errorf("kept %v, withheld %v", c.Kept, c.Withheld) } - if c, err := f.VMCopy(); err != nil || !slices.Equal(c.Withheld, []string{"anthropic", "github-copilot"}) { - t.Errorf("withheld = %v, %v", c.Withheld, err) + // opencode 2's import gets the passed key, its metadata too, beside the bound ones. + imp, err := OpencodeImport(c.Data) + must(t, err) + if !strings.Contains(string(imp), `"id":"cred_devvm_ollama","integrationID":"ollama","label":"devvm","value":{"key":"ollama-local","metadata":{"host":"kept"},"type":"key"}`) || + strings.Contains(string(imp), "groq") || strings.Contains(string(imp), "mcp") { + t.Errorf("opencode's import: %s", imp) } } diff --git a/internal/agentlogin/pi.go b/internal/agentlogin/pi.go index 2ea1d38c..cf2fedeb 100644 --- a/internal/agentlogin/pi.go +++ b/internal/agentlogin/pi.go @@ -13,7 +13,7 @@ package agentlogin // - passed: an api_key entry of a provider the user listed (File.Pass, config.toml's // [pass-keys]), such as a local model server's, which goes as it is. // - withheld: every other entry, OAuth logins included. The VM gets only the fields in -// piWithheldKeep, so no key, token or env value of it reaches the VM. +// withheldKeep (withheldEntry), so no key, token or env value of it reaches the VM. import ( "errors" @@ -55,10 +55,6 @@ func piBindings(m map[string]any, salt string) []proxy.Binding { return bs } -// piWithheldKeep are the fields a withheld entry keeps in the VM's copy: those that name an -// account or how it logs in, never a key or a token. -var piWithheldKeep = []string{"type", "expires", "accountId", "enterpriseUrl", "projectId", "email", "scope", "scopes", "clientId"} - // piPassed reports whether pi's entry for provider id goes into the VM's copy as it is: an api_key // entry of a provider in pass that devvm doesn't bind. func piPassed(m map[string]any, id string, pass []string) bool { @@ -67,8 +63,7 @@ func piPassed(m map[string]any, id string, pass []string) bool { } // piVM is the VM's copy of pi's logins m: bound entries as {type, key} with their placeholders, -// passed ones as they are, and withheld ones with piWithheldKeep's fields alone, each a plain -// value or a list of strings. +// passed ones as they are, and withheld ones as withheldEntry makes them. func piVM(m map[string]any, salt string, pass []string) map[string]any { out := map[string]any{} for _, b := range piBindings(m, salt) { @@ -82,54 +77,17 @@ func piVM(m map[string]any, salt string, pass []string) map[string]any { out[id] = m[id] continue } - e, kept := obj(m, id), map[string]any{} - for _, k := range piWithheldKeep { - if v, ok := e[k]; ok && piPlain(v) { - kept[k] = v - } - } - out[id] = kept + out[id] = withheldEntry(obj(m, id)) } return out } -// piPlain: a string, number, bool or null, or a list of strings. -func piPlain(v any) bool { - switch t := v.(type) { - case map[string]any: - return false - case []any: - for _, x := range t { - if _, ok := x.(string); !ok { - return false - } - } - } - return true -} - -// piPasses returns the providers of pi's whose entries the VM's copy holds as they are (passed), -// sorted. -func piPasses(m map[string]any, pass []string) []string { - var out []string - for _, id := range sortedKeys(m) { - if piPassed(m, id, pass) { - out = append(out, id) - } - } - return out -} - -// piWithheld returns the providers of pi's whose entries the VM's copy holds without their keys and -// tokens (neither bound nor passed), sorted. -func piWithheld(m map[string]any, pass []string) []string { - var out []string - for _, id := range sortedKeys(m) { - if _, bound := piKey(m, id); !bound && !piPassed(m, id, pass) { - out = append(out, id) - } - } - return out +// piSplit returns the providers of pi's whose entries the VM's copy holds as they are (passed) +// and those it holds without their keys and tokens (neither bound nor passed), each sorted. +func piSplit(m map[string]any, pass []string) (passed, withheld []string) { + return splitUnbound(m, + func(id string) bool { _, bound := piKey(m, id); return bound }, + func(id string) bool { return piPassed(m, id, pass) }) } // piVMDropped are the keys of pi's settings.json that the VM's copy leaves out, as each would undo diff --git a/internal/agentlogin/testdata/golden/opencode.txt b/internal/agentlogin/testdata/golden/opencode.txt index 893c26b2..1ef67e05 100644 --- a/internal/agentlogin/testdata/golden/opencode.txt +++ b/internal/agentlogin/testdata/golden/opencode.txt @@ -2,8 +2,8 @@ binding {"name":"opencode-anthropic","kind":"login","agent":"opencode","hosts":[ binding {"name":"opencode-github-copilot","kind":"login","agent":"opencode","hosts":["api.githubcopilot.com"],"header":"Authorization","placeholder":"devvm-proxy-managed-opencode-github-copilot-s4lt"} binding {"name":"opencode-openai","kind":"login","agent":"opencode","hosts":["chatgpt.com"],"header":"Authorization","placeholder":"eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJkZXZ2bSI6InBsYWNlaG9sZGVyLXM0bHQiLCJlbWFpbCI6ImUyZWZha2VAZXhhbXBsZS5jb20iLCJleHAiOjQwNzA5MDg4MDAsImh0dHBzOi8vYXBpLm9wZW5haS5jb20vYXV0aCI6eyJjaGF0Z3B0X2FjY291bnRfaWQiOiJhY2N0LTEiLCJjaGF0Z3B0X3BsYW5fdHlwZSI6InBybyJ9fQ.devvm-placeholder"} binding {"name":"opencode-openrouter","kind":"login","agent":"opencode","hosts":["openrouter.ai"],"header":"Authorization","placeholder":"devvm-proxy-managed-opencode-openrouter-s4lt"} -kept llama-cpp,mcp -withheld copilot-ghe +kept ollama +withheld copilot-ghe,llama-cpp,mcp providers anthropic,openai,openrouter chatgpt e2efake@example.com yes vm copy @@ -13,10 +13,8 @@ vm copy "type": "api" }, "copilot-ghe": { - "access": "devvm-redacted", "enterpriseUrl": "ghe.example.com", "expires": 1, - "refresh": "devvm-redacted", "type": "oauth" }, "github-copilot": { @@ -26,14 +24,18 @@ vm copy "type": "oauth" }, "llama-cpp": { - "key": "local", "type": "api" }, "mcp": { - "key": "k-e2efake", - "token": "t-e2efake", "type": "wellknown" }, + "ollama": { + "key": "ollama-local", + "metadata": { + "host": "kept" + }, + "type": "api" + }, "openai": { "access": "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJkZXZ2bSI6InBsYWNlaG9sZGVyLXM0bHQiLCJlbWFpbCI6ImUyZWZha2VAZXhhbXBsZS5jb20iLCJleHAiOjQwNzA5MDg4MDAsImh0dHBzOi8vYXBpLm9wZW5haS5jb20vYXV0aCI6eyJjaGF0Z3B0X2FjY291bnRfaWQiOiJhY2N0LTEiLCJjaGF0Z3B0X3BsYW5fdHlwZSI6InBybyJ9fQ.devvm-placeholder", "accountId": "acct-1", @@ -47,7 +49,7 @@ vm copy } } opencode import -[{"active":true,"id":"cred_devvm_anthropic","integrationID":"anthropic","label":"devvm","value":{"key":"devvm-proxy-managed-opencode-anthropic-s4lt","type":"key"}},{"active":true,"id":"cred_devvm_openai","integrationID":"openai","label":"devvm","value":{"access":"eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJkZXZ2bSI6InBsYWNlaG9sZGVyLXM0bHQiLCJlbWFpbCI6ImUyZWZha2VAZXhhbXBsZS5jb20iLCJleHAiOjQwNzA5MDg4MDAsImh0dHBzOi8vYXBpLm9wZW5haS5jb20vYXV0aCI6eyJjaGF0Z3B0X2FjY291bnRfaWQiOiJhY2N0LTEiLCJjaGF0Z3B0X3BsYW5fdHlwZSI6InBybyJ9fQ.devvm-placeholder","expires":4070908800000,"metadata":{"accountID":"acct-1"},"methodID":"chatgpt-browser","refresh":"eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJkZXZ2bSI6InBsYWNlaG9sZGVyLXM0bHQiLCJlbWFpbCI6ImUyZWZha2VAZXhhbXBsZS5jb20iLCJleHAiOjQwNzA5MDg4MDAsImh0dHBzOi8vYXBpLm9wZW5haS5jb20vYXV0aCI6eyJjaGF0Z3B0X2FjY291bnRfaWQiOiJhY2N0LTEiLCJjaGF0Z3B0X3BsYW5fdHlwZSI6InBybyJ9fQ.devvm-placeholder","type":"oauth"}},{"active":true,"id":"cred_devvm_openrouter","integrationID":"openrouter","label":"devvm","value":{"key":"devvm-proxy-managed-opencode-openrouter-s4lt","type":"key"}}] +[{"active":true,"id":"cred_devvm_anthropic","integrationID":"anthropic","label":"devvm","value":{"key":"devvm-proxy-managed-opencode-anthropic-s4lt","type":"key"}},{"active":true,"id":"cred_devvm_ollama","integrationID":"ollama","label":"devvm","value":{"key":"ollama-local","metadata":{"host":"kept"},"type":"key"}},{"active":true,"id":"cred_devvm_openai","integrationID":"openai","label":"devvm","value":{"access":"eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJkZXZ2bSI6InBsYWNlaG9sZGVyLXM0bHQiLCJlbWFpbCI6ImUyZWZha2VAZXhhbXBsZS5jb20iLCJleHAiOjQwNzA5MDg4MDAsImh0dHBzOi8vYXBpLm9wZW5haS5jb20vYXV0aCI6eyJjaGF0Z3B0X2FjY291bnRfaWQiOiJhY2N0LTEiLCJjaGF0Z3B0X3BsYW5fdHlwZSI6InBybyJ9fQ.devvm-placeholder","expires":4070908800000,"metadata":{"accountID":"acct-1"},"methodID":"chatgpt-browser","refresh":"eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJkZXZ2bSI6InBsYWNlaG9sZGVyLXM0bHQiLCJlbWFpbCI6ImUyZWZha2VAZXhhbXBsZS5jb20iLCJleHAiOjQwNzA5MDg4MDAsImh0dHBzOi8vYXBpLm9wZW5haS5jb20vYXV0aCI6eyJjaGF0Z3B0X2FjY291bnRfaWQiOiJhY2N0LTEiLCJjaGF0Z3B0X3BsYW5fdHlwZSI6InBybyJ9fQ.devvm-placeholder","type":"oauth"}},{"active":true,"id":"cred_devvm_openrouter","integrationID":"openrouter","label":"devvm","value":{"key":"devvm-proxy-managed-opencode-openrouter-s4lt","type":"key"}}] set key : no API key devvm puts in for that provider set key anthropic { @@ -77,6 +79,13 @@ set key anthropic "token": "t-e2efake", "type": "wellknown" }, + "ollama": { + "key": "ollama-local", + "metadata": { + "host": "kept" + }, + "type": "api" + }, "openai": { "access": "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6ImUyZWZha2VAZXhhbXBsZS5jb20iLCJleHAiOjQwMzkzNzI4MDAsImh0dHBzOi8vYXBpLm9wZW5haS5jb20vYXV0aCI6eyJjaGF0Z3B0X2FjY291bnRfaWQiOiJhY2N0LTEiLCJjaGF0Z3B0X3BsYW5fdHlwZSI6InBybyJ9LCJvdGhlciI6ImRyb3BwZWQifQ.devvm-placeholderreal-signature", "accountId": "acct-1", @@ -93,6 +102,9 @@ set key openai { "anthropic": { "key": "sk-ant-e2efake", + "metadata": { + "m": "md-e2efake" + }, "type": "api" }, "copilot-ghe": { @@ -117,6 +129,13 @@ set key openai "token": "t-e2efake", "type": "wellknown" }, + "ollama": { + "key": "ollama-local", + "metadata": { + "host": "kept" + }, + "type": "api" + }, "openai": { "key": "sk-e2efake-saved", "type": "api" @@ -130,6 +149,9 @@ set key openrouter { "anthropic": { "key": "sk-ant-e2efake", + "metadata": { + "m": "md-e2efake" + }, "type": "api" }, "copilot-ghe": { @@ -154,6 +176,13 @@ set key openrouter "token": "t-e2efake", "type": "wellknown" }, + "ollama": { + "key": "ollama-local", + "metadata": { + "host": "kept" + }, + "type": "api" + }, "openai": { "access": "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJlbWFpbCI6ImUyZWZha2VAZXhhbXBsZS5jb20iLCJleHAiOjQwMzkzNzI4MDAsImh0dHBzOi8vYXBpLm9wZW5haS5jb20vYXV0aCI6eyJjaGF0Z3B0X2FjY291bnRfaWQiOiJhY2N0LTEiLCJjaGF0Z3B0X3BsYW5fdHlwZSI6InBybyJ9LCJvdGhlciI6ImRyb3BwZWQifQ.devvm-placeholderreal-signature", "accountId": "acct-1", diff --git a/internal/agents/agents.go b/internal/agents/agents.go index 52c28cdc..4e2995c8 100644 --- a/internal/agents/agents.go +++ b/internal/agents/agents.go @@ -165,7 +165,7 @@ var Defs = []Def{ OpencodeData + "/auth.json", OpencodeData + "/account.json", OpencodeData + "/mcp-auth.json", OpencodeData + "/bin", }, Env: []Env{{"OPENCODE_DISABLE_AUTOUPDATE", "1"}}, - ChatGPT: true, Keys: ProviderKeys, + ChatGPT: true, Keys: ProviderKeys, PassKeys: true, }, { Name: Pi, Display: "pi", Folder: PiFolder, diff --git a/internal/msg/docs.go b/internal/msg/docs.go index 5c43c9d0..7edd1637 100644 --- a/internal/msg/docs.go +++ b/internal/msg/docs.go @@ -194,7 +194,6 @@ var docs = map[string]string{ //nolint:gosec // message IDs and pages, not crede "net_proxy_down_stopped": "using/troubleshooting#the-proxy-doesnt-start", "no_secret": "safety/network#saving-and-binding-secrets", "login_kept": "using/coding-agents#codex-and-opencode-logins", - "login_oauth_withheld": "using/coding-agents#codex-and-opencode-logins", "login_passed": "using/settings#configtoml", "login_withheld": "using/settings#configtoml", "pi_settings_dropped": "using/coding-agents#pis-settings", diff --git a/internal/msg/messages_gen.go b/internal/msg/messages_gen.go index 1b5b814b..482be72a 100644 --- a/internal/msg/messages_gen.go +++ b/internal/msg/messages_gen.go @@ -2069,11 +2069,6 @@ func LoginKept(agent string, file string, keys string) M { return M{id: "login_kept", vals: []val{{"agent", agent}, {"file", file}, {"keys", keys}}} } -// LoginOauthWithheld is [login_oauth_withheld]: "The VM gets {{.agent}}'s {{.providers}} login without its OAuth tokens, because devvm keeps them on this machine. To use that provider in the VM, log in to it with an API key on this machine and run devvm agent import --force {{.name}}." -func LoginOauthWithheld(agent string, name string, providers string) M { - return M{id: "login_oauth_withheld", vals: []val{{"agent", agent}, {"name", name}, {"providers", providers}}} -} - // LoginPassed is [login_passed]: "The VM gets {{.agent}}'s {{.providers}} login unchanged, as config.toml's [pass-keys] asks." func LoginPassed(agent string, providers string) M { return M{id: "login_passed", vals: []val{{"agent", agent}, {"providers", providers}}} @@ -4464,7 +4459,6 @@ var specs = map[string]spec{ "login_capture_refused": {fields: []string{"agent", "vm"}}, "login_copy_failed": {fields: []string{"agent", "reason", "vm"}}, "login_kept": {fields: []string{"agent", "file", "keys"}}, - "login_oauth_withheld": {fields: []string{"agent", "name", "providers"}}, "login_passed": {fields: []string{"agent", "providers"}}, "login_read_failed": {fields: []string{"file", "reason"}}, "login_withheld": {fields: []string{"agent", "name", "providers"}}, diff --git a/internal/secrets/secrets.go b/internal/secrets/secrets.go index 5876d042..6b10836a 100644 --- a/internal/secrets/secrets.go +++ b/internal/secrets/secrets.go @@ -303,10 +303,8 @@ func (s *Store) VMLogin(kind, salt string) ([]byte, error) { } else if list != "" { s.Warn(msg.LoginKept(d.Display, path.Base(l.Rel), list)) } - if list := strings.Join(c.Withheld, ", "); list != "" && d.PassKeys { + if list := strings.Join(c.Withheld, ", "); list != "" { s.Warn(msg.LoginWithheld(d.Display, d.Name, list)) - } else if list != "" { - s.Warn(msg.LoginOauthWithheld(d.Display, d.Name, list)) } return c.Data, err } diff --git a/internal/secrets/secrets_test.go b/internal/secrets/secrets_test.go index 9ac84ca1..544629fc 100644 --- a/internal/secrets/secrets_test.go +++ b/internal/secrets/secrets_test.go @@ -562,8 +562,8 @@ func TestVMCopies(t *testing.T) { } } if want := []string{ - "login_kept agent=Codex file=auth.json keys=b, extra", "login_kept agent=opencode file=auth.json keys=llama", - "login_oauth_withheld agent=opencode name=opencode providers=other", "login_withheld agent=pi name=pi providers=groq, openai-codex", + "login_kept agent=Codex file=auth.json keys=b, extra", + "login_withheld agent=opencode name=opencode providers=llama, other", "login_withheld agent=pi name=pi providers=groq, openai-codex", }; !slices.Equal(warned, want) { t.Errorf("warned %q, want %q", warned, want) } @@ -574,7 +574,7 @@ func TestVMCopies(t *testing.T) { if err := os.MkdirAll(s.Dirs.Config, 0o700); err != nil { t.Fatal(err) } - if err := os.WriteFile(s.Dirs.ConfigFile(), []byte("[pass-keys]\npi = [\"groq\"]\n"), 0o600); err != nil { + if err := os.WriteFile(s.Dirs.ConfigFile(), []byte("[pass-keys]\npi = [\"groq\"]\nopencode = [\"llama\", \"other\"]\n"), 0o600); err != nil { t.Fatal(err) } var noted []string @@ -589,6 +589,15 @@ func TestVMCopies(t *testing.T) { case !slices.Equal(noted, []string{"login_passed agent=pi providers=groq"}) || !slices.Equal(warned, []string{"login_withheld agent=pi name=pi providers=openai-codex"}): t.Errorf("noted %q, warned %q", noted, warned) } + // opencode's list passes its llama key, but never its other OAuth login. + noted, warned = nil, nil + data, err = s.VMLogin("opencode", salt) + switch { + case err != nil || !strings.Contains(string(data), `"key": "local"`) || strings.Contains(string(data), `"refresh"`): + t.Errorf("opencode's VM copy: %s, %v", data, err) + case !slices.Equal(noted, []string{"login_passed agent=opencode providers=llama"}) || !slices.Equal(warned, []string{"login_withheld agent=opencode name=opencode providers=other"}): + t.Errorf("noted %q, warned %q", noted, warned) + } // A config.toml devvm can't read fails the copy. if err := os.WriteFile(s.Dirs.ConfigFile(), []byte("[pass-keys]\npi = [\"Not A Provider\"]\n"), 0o600); err != nil { t.Fatal(err) diff --git a/internal/settings/passkeys_test.go b/internal/settings/passkeys_test.go index 529fc20d..3966eeec 100644 --- a/internal/settings/passkeys_test.go +++ b/internal/settings/passkeys_test.go @@ -8,34 +8,41 @@ import ( "github.com/devvmhq/devvm/internal/state" ) -// config.toml's [pass-keys]: pi's list of providers, none without it, and -// none for an agent it has no key for; a name that isn't a provider's ID, -// a repeat or an agent devvm has no key for is refused, naming its line. +// config.toml's [pass-keys]: opencode's and pi's lists of providers, each +// agent's own, none without it, and none for an agent it has no key for; a +// name that isn't a provider's ID, a repeat or an agent devvm has no key +// for (Codex) is refused, naming its line. func TestPassKeys(t *testing.T) { d := testDirs(t) for _, c := range []struct { - config string - want []string + config string + pi, opencode []string }{ - {"", nil}, - {"[pass-keys]\n", nil}, - {"[pass-keys]\npi = []\n", []string{}}, - {"[pass-keys]\npi = [\"ollama\", \"lm-studio\"]\n", []string{"ollama", "lm-studio"}}, + {"", nil, nil}, + {"[pass-keys]\n", nil, nil}, + {"[pass-keys]\npi = []\n", []string{}, nil}, + {"[pass-keys]\npi = [\"ollama\", \"lm-studio\"]\n", []string{"ollama", "lm-studio"}, nil}, + {"[pass-keys]\nopencode = [\"ollama\"]\n", nil, []string{"ollama"}}, + {"[pass-keys]\nopencode = [\"llama.cpp\"]\npi = [\"ollama\"]\n", []string{"ollama"}, []string{"llama.cpp"}}, } { write(t, d.ConfigFile(), c.config) - if got, err := PassKeys(d, "pi"); err != nil || !slices.Equal(got, c.want) || (got == nil) != (c.want == nil) { - t.Errorf("%q: %q, %v; want %q", c.config, got, err, c.want) + for agent, want := range map[string][]string{"pi": c.pi, "opencode": c.opencode} { + if got, err := PassKeys(d, agent); err != nil || !slices.Equal(got, want) || (got == nil) != (want == nil) { + t.Errorf("%q for %s: %q, %v; want %q", c.config, agent, got, err, want) + } } - if got, err := PassKeys(d, "opencode"); err != nil || got != nil { - t.Errorf("%q for opencode: %q, %v", c.config, got, err) + if got, err := PassKeys(d, "codex"); err != nil || got != nil { + t.Errorf("%q for codex: %q, %v", c.config, got, err) } } for config, line := range map[string]int{ - "[pass-keys]\npi = [\"Ollama\"]\n": 2, - "[pass-keys]\npi = [\"a\", \"a\"]\n": 2, - "[pass-keys]\npi = \"ollama\"\n": 2, - "# x\n[pass-keys]\nopencode = [\"ollama\"]\n": 3, - "[pass-keys]\npi = []\nnone = [\"ollama\"]\n": 3, + "[pass-keys]\npi = [\"Ollama\"]\n": 2, + "[pass-keys]\npi = [\"a\", \"a\"]\n": 2, + "[pass-keys]\npi = \"ollama\"\n": 2, + "[pass-keys]\nopencode = [\"Not One\"]\n": 2, + "# x\n[pass-keys]\ncodex = [\"ollama\"]\n": 3, + "[pass-keys]\npi = []\nnone = [\"ollama\"]\n": 3, + "[pass-keys]\nopencode = []\nclaude = [\"x\"]\n": 3, } { write(t, d.ConfigFile(), config) _, err := PassKeys(d, "pi") diff --git a/internal/structure/structure_test.go b/internal/structure/structure_test.go index c514898e..412d4adc 100644 --- a/internal/structure/structure_test.go +++ b/internal/structure/structure_test.go @@ -195,7 +195,7 @@ func devvmVars() map[string]string { "internal/agentlogin.claudeServerKeys": table, "internal/agentlogin.openaiAuth": fixture, "internal/agentlogin.endpoints": table, - "internal/agentlogin.piWithheldKeep": table, + "internal/agentlogin.withheldKeep": table, "internal/agentlogin.piVMDropped": table, "internal/cli.version": ldflags, "internal/testbuild.testBuild": ldflags + ", by test builds only", diff --git a/locales/en.toml b/locales/en.toml index 9fa826fb..b4fb4d36 100644 --- a/locales/en.toml +++ b/locales/en.toml @@ -2595,10 +2595,6 @@ other = "{{.vm}} has Claude Code, so the VM always uses the Claude Code token. T description = "agent is the agent as people know it, such as Codex; file is its login file's name, such as auth.json; keys lists what of it devvm doesn't know, its top-level keys or its providers, comma-separated" other = "The VM gets {{.keys}} from {{.agent}}'s {{.file}} unchanged." -[login_oauth_withheld] -description = "agent is the agent as people know it, such as opencode, and name its name in devvm's commands; providers lists its OAuth login providers, comma-separated" -other = "The VM gets {{.agent}}'s {{.providers}} login without its OAuth tokens, because devvm keeps them on this machine. To use that provider in the VM, log in to it with an API key on this machine and run devvm agent import --force {{.name}}." - [login_passed] description = "agent is the agent as people know it, such as pi; providers lists its providers that config.toml's [pass-keys] lists, comma-separated" other = "The VM gets {{.agent}}'s {{.providers}} login unchanged, as config.toml's [pass-keys] asks." diff --git a/testdata/script/agent_import_opencode.txtar b/testdata/script/agent_import_opencode.txtar index d0761dde..07ba9aec 100644 --- a/testdata/script/agent_import_opencode.txtar +++ b/testdata/script/agent_import_opencode.txtar @@ -41,6 +41,59 @@ exec devvm agent import opencode stderr '^devvm: agent_import_opencode_skipped label=ChatGPT provider=openai$' stderr '^devvm: agent_import_none agent=opencode$' +# A VM with opencode: the login's copy holds a placeholder for the +# Anthropic key, without its metadata, and the VM gets the local +# server's key, the well-known login and the Copilot Enterprise login +# without their keys or tokens, warned. +cp $WORK/launch.json $HOME/.local/share/opencode/auth.json +cp $WORK/v1 $STUB_DIR/opencode-version +exec devvm agent import --force opencode +project p +stub_reset +exec devvm --network open --no-git-protect --agents opencode +vm_name P p +stderr '^devvm: login_withheld agent=opencode name=opencode providers=copilot-ghe, mcp, ollama$' +! stderr 'login_passed|login_kept' +exec tar -xOf $STUB_DIR/sync.tar home/.local/share/opencode/auth.json +stdout '"key": "devvm-proxy-managed-opencode-anthropic-[0-9a-f]{32}"' +! stdout 'testfake|"metadata"|"access"|"refresh"|"token"' +exec tar -xOf $STUB_DIR/sync.tar opencode-import.json +stdout 'cred_devvm_anthropic' +! stdout 'ollama|testfake' +grep '"name":"opencode-anthropic"' $P_dir/run/secrets.json + +# config.toml's [pass-keys] gives the VM ollama's key as it is, noted, +# and opencode 2's import gets it too; the OAuth login it names, and the +# Anthropic key, which devvm binds, still don't pass. +cp $WORK/pass.toml $CFG/config.toml +exec devvm host +stderr '^login_passed agent=opencode providers=ollama$' +stderr '^devvm: login_withheld agent=opencode name=opencode providers=copilot-ghe, mcp$' +exec tar -xOf $STUB_DIR/sync.tar home/.local/share/opencode/auth.json +stdout '"key": "ollama-local"' +stdout '"key": "devvm-proxy-managed-opencode-anthropic-[0-9a-f]{32}"' +! stdout 'testfake' +exec tar -xOf $STUB_DIR/sync.tar opencode-import.json +stdout '"id":"cred_devvm_ollama","integrationID":"ollama","label":"devvm","value":\{"key":"ollama-local","type":"key"\}' +# One devvm can't read fails the launch, naming its line. +cp $WORK/badpass.toml $CFG/config.toml +! exec devvm host +stderr 'config\.toml' +rm $CFG/config.toml + +-- launch.json -- +{"anthropic":{"type":"api","key":"sk-ant-testfake","metadata":{"m":"testfake-md"}}, + "ollama":{"type":"api","key":"ollama-local"}, + "mcp":{"type":"wellknown","key":"testfake-wk","token":"testfake-wt"}, + "copilot-ghe":{"type":"oauth","access":"testfake-at","refresh":"testfake-rt","expires":1,"enterpriseUrl":"ghe.example.com"}} +-- pass.toml -- +features = [] +[pass-keys] +opencode = ["ollama", "copilot-ghe", "anthropic"] +-- badpass.toml -- +features = [] +[pass-keys] +opencode = ["Ollama"] -- v1 -- 1.19.5 -- v2 -- diff --git a/tests/e2e/network_test.go b/tests/e2e/network_test.go index 2ef717fc..0dc3bf69 100644 --- a/tests/e2e/network_test.go +++ b/tests/e2e/network_test.go @@ -1002,11 +1002,90 @@ func netOpencodeKeys(n *netRun) { } return nil }, Tail(40)) + netOpencodePassKeys(n, oc, vm) if vm != "" { _, _ = s.Run(devvmCmd(s, oc, "", n.home(), "rm", "--force", "--no-export")) } } +// opencodeLocalKey is the fake key of a local model server's in the +// store's opencode login, which devvm withholds unless config.toml's +// [pass-keys] passes it. +const opencodeLocalKey = "sk-local-e2efake-ollama" + +// netOpencodePassKeys: a key of opencode's that the proxy can't put in, a +// local model server's, reaches the VM, vm in the folder oc, only once +// config.toml's [pass-keys] lists its provider, and then opencode 2's +// database gets it too; an OAuth login it doesn't bind never does, listed +// or not. The store's login and config.toml are put back after. +func netOpencodePassKeys(n *netRun, oc, vm string) { + s := n.s + store := filepath.Join(n.logins, "opencode", ".local", "share", "opencode", "auth.json") + cfg := filepath.Join(s.sb.config(), "devvm", "config.toml") + savedLogin, _ := os.ReadFile(store) + savedCfg, _ := os.ReadFile(cfg) + defer func() { + _ = os.WriteFile(store, savedLogin, 0o600) + _ = os.WriteFile(cfg, savedCfg, 0o600) + }() + launch := func() (Res, error) { + _, r, err := launchWith(s, oc, n.home("DEVVM_MESSAGES=names")) + return r, err + } + s.Check("opencode's key for a provider devvm doesn't bind is withheld from the VM, warned, and the OAuth login it doesn't bind holds no token", func() error { + var m map[string]any + if vm == "" || json.Unmarshal(savedLogin, &m) != nil { + return errors.New("no second VM, or no store login to add to") + } + m["ollama"] = map[string]any{"type": "api", "key": opencodeLocalKey} + m["copilot-ghe"] = map[string]any{"type": "oauth", "access": "at-e2efake-ghe", "refresh": "rt-e2efake-ghe", "expires": 1, "enterpriseUrl": "ghe.example.com"} + b, _ := json.Marshal(m) + if err := os.WriteFile(store, b, 0o600); err != nil { + return err + } + r, err := launch() + switch { + case err != nil: + return failed("the launch failed:\n"+r.Out, err) + case !Matches(r.Out, `^devvm: login_withheld agent=opencode name=opencode providers=(.*, )?copilot-ghe, (.*, )?ollama(, .*)?$`): + return errors.New("no warning names the withheld logins:\n" + r.Out) + } + if has, err := vmHas(s, vm, false, "cat ~/.local/share/opencode/auth.json", "e2efake-ghe", opencodeLocalKey); err != nil || has { + return failed("the VM's auth.json holds a withheld key or token", err) + } + if has, err := vmHas(s, vm, true, "opencode auth export", opencodeLocalKey); err != nil || has { + return failed("the VM's opencode holds the withheld key", err) + } + return nil + }, Tail(40)) + s.Check("... and once config.toml's [pass-keys] lists ollama, the VM and its opencode 2 get that key, noted, but never the OAuth login", func() error { + if vm == "" { + return errNo + } + if err := os.WriteFile(cfg, append(bytes.Clone(savedCfg), []byte("\n[pass-keys]\nopencode = [\"ollama\", \"copilot-ghe\"]\n")...), 0o600); err != nil { + return err + } + r, err := launch() + switch { + case err != nil: + return failed("the launch failed:\n"+r.Out, err) + case !Matches(r.Out, `^login_passed agent=opencode providers=ollama$`): + return errors.New("no note names the passed key:\n" + r.Out) + case vmOut(s, vm, "jq -r .ollama.key ~/.local/share/opencode/auth.json") != opencodeLocalKey: + return errors.New("the VM's auth.json lacks the passed key") + } + if has, err := vmHas(s, vm, false, "cat ~/.local/share/opencode/auth.json", "e2efake-ghe"); err != nil || has { + return failed("the VM's auth.json holds the OAuth login's tokens", err) + } + // Every credential: auth export TARGET resolves the target among opencode's own + // integrations, which a local server's isn't. + if has, err := vmHas(s, vm, true, "opencode auth export", opencodeLocalKey); err != nil || !has { + return errors.New("the VM's opencode didn't import the passed key\n" + n.opencodeWhy(vm)) + } + return nil + }, Tail(40)) +} + // piKey is the fake Anthropic API key devvm agent login pi saves. const piKey = "sk-ant-e2efake-pi"