diff --git a/docs/content/docs/contributing/_index.md b/docs/content/docs/contributing/_index.md index e9ee2433..205a05eb 100644 --- a/docs/content/docs/contributing/_index.md +++ b/docs/content/docs/contributing/_index.md @@ -220,7 +220,7 @@ Then `mise run cli-docs` writes the CLI pages whose help lists the agents, and t ### Adding a provider -The model providers whose API keys the VM's proxy puts in for the agents with a key for each provider, opencode and pi, are one table, `agents.Providers` in `internal/agents/agents.go`. Each `agents.Provider` holds the provider's ID, which is its entry's name in both agents' `auth.json`, its name as people know it, the hosts the agents send its key to and the header they send it in. The opencode and pi formats' bindings, `agentlogin.KeyProviders`, which `devvm agent login --provider` takes and its help lists, and the allowlist lines of each binding's hosts all come from it. A new provider is its entry there, in the order of its ID, and its row in the table in `using/coding-agents.md`'s API keys the proxy puts in, which `TestProvidersComplete` checks against the registry. Read the hosts and the header in both agents' own source first, and in the SDK that each one sends its requests with, because a header that differs from the agents' leaves the key's placeholder in the request, and a host that the agents never send the key to would get the key anyway. Then `mise run cli-docs` writes the CLI page whose help lists the providers, and `UPDATE_GOLDEN=1 go test ./internal/agentlogin -run Golden` writes the golden files that list them. +The model providers whose API keys the VM's proxy puts in for the agents with a key for each provider, opencode and pi, are one table, `agents.Providers` in `internal/agents/agents.go`. Each `agents.Provider` holds the provider's ID, which is its entry's name in both agents' `auth.json`, its name as people know it, the hosts the agents send its key to and the header they send it in, and its `Prefix`, which starts the key's placeholder when an agent checks how the provider's keys start: pi takes an OpenAI key that doesn't start with `sk-` for a Sign in with ChatGPT login, so OpenAI's is `sk-`. The opencode and pi formats' bindings, `agentlogin.KeyProviders`, which `devvm agent login --provider` takes and its help lists, and the allowlist lines of each binding's hosts all come from it. A new provider is its entry there, in the order of its ID, and its row in the table in `using/coding-agents.md`'s API keys the proxy puts in, which `TestProvidersComplete` checks against the registry. Read the hosts, the header and any check of how a key starts in both agents' own source first, and in the SDK that each one sends its requests with, because a header that differs from the agents' leaves the key's placeholder in the request, and a host that the agents never send the key to would get the key anyway. Then `mise run cli-docs` writes the CLI page whose help lists the providers, and `UPDATE_GOLDEN=1 go test ./internal/agentlogin -run Golden` writes the golden files that list them. ## CLI conventions @@ -400,7 +400,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. 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. The same company proxy fakes Groq's API too, and `devvm agent login pi --api-key --provider groq --stdin` saves a fake Groq key, the VM's pi holds only its placeholder, and pi's own request reaches Groq's API with the key in its `Authorization`, which no log holds. It fakes Gemini's API as well, and after `devvm agent login pi --api-key --provider google --stdin` saves a fake Gemini key, the VM's pi holds only its placeholder, and pi's own request reaches Gemini's API with the key in its `x-goog-api-key` and no key in its URL, which no log holds. Then `devvm agent login opencode --api-key --provider groq --stdin` saves a fake Groq key for opencode, the VM's opencode holds only its placeholder, and the request that `opencode run` makes reaches Groq's API with the key in its `Authorization`, 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. The same company proxy fakes Groq's API too, and `devvm agent login pi --api-key --provider groq --stdin` saves a fake Groq key, the VM's pi holds only its placeholder, and pi's own request reaches Groq's API with the key in its `Authorization`, which no log holds. It fakes OpenAI's API as well, and after `devvm agent login pi --api-key --provider openai --stdin` saves a fake OpenAI key, the VM's pi holds only its placeholder, which starts with `sk-`, and pi's own request reaches OpenAI's API as an API key's, asking for `max_output_tokens`, with the key in its `Authorization`, which no log holds. The same company proxy fakes Gemini's API, and after `devvm agent login pi --api-key --provider google --stdin` saves a fake Gemini key, the VM's pi holds only its placeholder, and pi's own request reaches Gemini's API with the key in its `x-goog-api-key` and no key in its URL, which no log holds. Then `devvm agent login opencode --api-key --provider groq --stdin` saves a fake Groq key for opencode, the VM's opencode holds only its placeholder, and the request that `opencode run` makes reaches Groq's API with the key in its `Authorization`, 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/using/coding-agents.md b/docs/content/docs/using/coding-agents.md index 3c3029fb..68c5166e 100644 --- a/docs/content/docs/using/coding-agents.md +++ b/docs/content/docs/using/coding-agents.md @@ -242,7 +242,7 @@ The VM's proxy puts in opencode's and pi's API keys for the providers in this ta | `openrouter` | OpenRouter | `openrouter.ai` | `Authorization` | | `xai` | xAI | `api.x.ai` | `Authorization` | -The Google Gemini key is the Gemini API's, for Google AI Studio. Vertex AI logs in with a Google Cloud account or a service account instead, so devvm withholds its logins, as it does any other provider's. These providers' keys never need `[pass-keys]`, and when it lists one of them all the same, the VM still gets the key's placeholder, not the key, and devvm notes at each launch that you can take the provider out. +The placeholder for an OpenAI key starts with `sk-`, as an OpenAI API key does, because pi takes an OpenAI key that starts any other way for a Sign in with ChatGPT login and then leaves settings such as the longest reply it wants out of its requests. The Google Gemini key is the Gemini API's, for Google AI Studio. Vertex AI logs in with a Google Cloud account or a service account instead, so devvm withholds its logins, as it does any other provider's. These providers' keys never need `[pass-keys]`, and when it lists one of them all the same, the VM still gets the key's placeholder, not the key, and devvm notes at each launch that you can take the provider out. The placeholder keeps a key out of the VM only from the launch that first gives the VM the placeholder. A VM that was given one of these keys as it was before then, such as through `[pass-keys]` when the proxy didn't put that provider's key in, may still hold copies of it. They can be in opencode's database, its write-ahead log and its freed pages, in the disk's free space and anywhere that the VM's own code copied the key. While opencode in the VM fails to import the placeholder, devvm's record of opencode's last import, `~/.local/state/devvm/opencode-import.json`, holds the key too. Those copies still work wherever they are, so when you don't trust that VM, make a new key at the provider, save it with `devvm agent login AGENT --api-key --provider PROVIDER` and revoke the old one. diff --git a/internal/agentlogin/apikey_test.go b/internal/agentlogin/apikey_test.go index 761b3002..e35b327a 100644 --- a/internal/agentlogin/apikey_test.go +++ b/internal/agentlogin/apikey_test.go @@ -121,8 +121,8 @@ func TestOpencodeImport(t *testing.T) { // Each provider's API key, saved as devvm agent login --api-key --provider // saves it for opencode and for pi, is bound for that provider's hosts and // header alone, as checked against both agents' source, under the agent's -// placeholder, which the VM's copy holds in the key's place; Get gives the -// key back. +// placeholder, which starts as the agent checks the provider's keys start +// and which the VM's copy holds in the key's place; Get gives the key back. func TestProviderKeys(t *testing.T) { want := map[string][2]string{ "anthropic": {"api.anthropic.com", "x-api-key"}, "deepseek": {"api.deepseek.com", "Authorization"}, @@ -130,6 +130,8 @@ func TestProviderKeys(t *testing.T) { "mistral": {"api.mistral.ai", "Authorization"}, "openai": {"api.openai.com", "Authorization"}, "openrouter": {"openrouter.ai", "Authorization"}, "xai": {"api.x.ai", "Authorization"}, } + // pi takes an OpenAI key that doesn't start with sk- for a ChatGPT sign-in's token. + prefix := map[string]string{"openai": "sk-"} for _, kind := range []string{Opencode, Pi} { if got := KeyProviders(kind); len(got) != len(want) { t.Errorf("KeyProviders(%s) = %v", kind, got) @@ -140,7 +142,7 @@ func TestProviderKeys(t *testing.T) { key := id + "-e2efake-key" must(t, f.SetKey(id, key)) f.Salt = "s1" - ph := "devvm-proxy-managed-" + kind + "-" + id + "-s1" + ph := prefix[id] + "devvm-proxy-managed-" + kind + "-" + id + "-s1" bs := bindings(t, f) if len(bs) != 1 || bs[0].Name != kind+"-"+id || !slices.Equal(bs[0].Hosts, []string{want[id][0]}) || bs[0].Header != want[id][1] || bs[0].Placeholder != ph { diff --git a/internal/agentlogin/golden_test.go b/internal/agentlogin/golden_test.go index 16a7fca0..3c7c8979 100644 --- a/internal/agentlogin/golden_test.go +++ b/internal/agentlogin/golden_test.go @@ -119,6 +119,14 @@ func TestLoginsGolden(t *testing.T) { saved, err := os.ReadFile(k.Path) must(t, err) out.WriteString("set key " + provider + "\n" + string(saved)) + k.Salt = f.Salt + kb, err := k.Bindings() + must(t, err) + for _, b := range kb { + if b.Name == kind+"-"+provider { + out.WriteString("placeholder " + b.Placeholder + "\n") + } + } } golden(t, kind+".txt", out.Bytes()) }) diff --git a/internal/agentlogin/logins.go b/internal/agentlogin/logins.go index c68d3936..abd9b5a0 100644 --- a/internal/agentlogin/logins.go +++ b/internal/agentlogin/logins.go @@ -168,18 +168,27 @@ func splitUnbound(m map[string]any, pass []string, keyType string, bound, passed type provider struct { hosts []string header string + prefix string // what the VM's placeholder starts with (agents.Provider's Prefix) } // keyProvider is where the API key of the provider whose ID is id goes, false for a provider not // in agents.Providers. func keyProvider(id string) (provider, bool) { p, ok := agents.ProviderOf(id) - return provider{p.Hosts, p.Header}, ok + return provider{p.Hosts, p.Header, p.Prefix}, ok +} + +// keyPlaceholder is the VM's in place of the API key or token of agent's login for the provider +// whose ID is id, in opencode's or pi's file: the provider's prefix, which the agent may check +// the key for, then devvm-proxy-managed, the agent and the provider. +func keyPlaceholder(agent, id, salt string) string { + p, _ := keyProvider(id) + return salted(p.prefix+"devvm-proxy-managed-"+agent+"-"+id, salt) } var opencodeOAuth = map[string]provider{ - "openai": {[]string{"chatgpt.com"}, "Authorization"}, - "github-copilot": {[]string{"api.githubcopilot.com"}, "Authorization"}, + "openai": {hosts: []string{"chatgpt.com"}, header: "Authorization"}, + "github-copilot": {hosts: []string{"api.githubcopilot.com"}, header: "Authorization"}, } // fileMax is the most of an agent's file read: ~/.claude.json keeps every project's history, so it @@ -404,12 +413,6 @@ func (f File) codexGet(ctx context.Context, name string) (string, error) { // --- opencode --- -// opencodePlaceholder is the VM's in place of a provider's API key or token, but OpenAI's OAuth -// login's (openaiPlaceholder). -func opencodePlaceholder(provider, salt string) string { - return salted("devvm-proxy-managed-opencode-"+provider, salt) -} - func opencodeBindings(m map[string]any, salt string) []proxy.Binding { var bs []proxy.Binding for id := range m { @@ -426,7 +429,7 @@ func opencodeBindings(m map[string]any, salt string) []proxy.Binding { if !ok { continue } - ph := opencodePlaceholder(id, salt) + ph := keyPlaceholder(agents.Opencode, id, salt) if id == "openai" && str(e, "type") == "oauth" { ph = openaiPlaceholder(str(e, "access"), salt) // opencode reads the account from it } diff --git a/internal/agentlogin/pi.go b/internal/agentlogin/pi.go index 49c91d19..97309e53 100644 --- a/internal/agentlogin/pi.go +++ b/internal/agentlogin/pi.go @@ -26,11 +26,6 @@ import ( "github.com/devvmhq/devvm/internal/proxy" ) -// piPlaceholder is the VM's in place of a provider's API key in pi's auth.json. -func piPlaceholder(provider, salt string) string { - return salted("devvm-proxy-managed-pi-"+provider, salt) -} - // piTemplate matches a pi key's $NAME or ${NAME}, once its literal $$ are taken out. var piTemplate = regexp.MustCompile(`\$\{?[A-Za-z_]`) @@ -50,7 +45,7 @@ func piBindings(m map[string]any, salt string) []proxy.Binding { for _, id := range sortedKeys(m) { if _, ok := piKey(m, id); ok { p, _ := keyProvider(id) - bs = append(bs, login(agents.Pi, "pi-"+id, p.hosts, p.header, piPlaceholder(id, salt))) + bs = append(bs, login(agents.Pi, "pi-"+id, p.hosts, p.header, keyPlaceholder(agents.Pi, id, salt))) } } return bs diff --git a/internal/agentlogin/testdata/golden/opencode.txt b/internal/agentlogin/testdata/golden/opencode.txt index e55e2bf9..8150e745 100644 --- a/internal/agentlogin/testdata/golden/opencode.txt +++ b/internal/agentlogin/testdata/golden/opencode.txt @@ -99,6 +99,7 @@ set key anthropic "type": "api" } } +placeholder devvm-proxy-managed-opencode-anthropic-s4lt set key deepseek { "anthropic": { @@ -153,6 +154,7 @@ set key deepseek "type": "api" } } +placeholder devvm-proxy-managed-opencode-deepseek-s4lt set key google { "anthropic": { @@ -207,6 +209,7 @@ set key google "type": "api" } } +placeholder devvm-proxy-managed-opencode-google-s4lt set key groq { "anthropic": { @@ -261,6 +264,7 @@ set key groq "type": "api" } } +placeholder devvm-proxy-managed-opencode-groq-s4lt set key mistral { "anthropic": { @@ -315,6 +319,7 @@ set key mistral "type": "api" } } +placeholder devvm-proxy-managed-opencode-mistral-s4lt set key openai { "anthropic": { @@ -362,6 +367,7 @@ set key openai "type": "api" } } +placeholder sk-devvm-proxy-managed-opencode-openai-s4lt set key openrouter { "anthropic": { @@ -412,6 +418,7 @@ set key openrouter "type": "api" } } +placeholder devvm-proxy-managed-opencode-openrouter-s4lt set key xai { "anthropic": { @@ -466,3 +473,4 @@ set key xai "type": "api" } } +placeholder devvm-proxy-managed-opencode-xai-s4lt diff --git a/internal/agentlogin/testdata/golden/pi.txt b/internal/agentlogin/testdata/golden/pi.txt index b87b066a..4d8c39d6 100644 --- a/internal/agentlogin/testdata/golden/pi.txt +++ b/internal/agentlogin/testdata/golden/pi.txt @@ -126,6 +126,7 @@ set key anthropic "type": "api_key" } } +placeholder devvm-proxy-managed-pi-anthropic-s4lt set key deepseek { "amazon-bedrock": { @@ -208,6 +209,7 @@ set key deepseek "type": "api_key" } } +placeholder devvm-proxy-managed-pi-deepseek-s4lt set key google { "amazon-bedrock": { @@ -286,6 +288,7 @@ set key google "type": "api_key" } } +placeholder devvm-proxy-managed-pi-google-s4lt set key groq { "amazon-bedrock": { @@ -364,6 +367,7 @@ set key groq "type": "api_key" } } +placeholder devvm-proxy-managed-pi-groq-s4lt set key mistral { "amazon-bedrock": { @@ -446,6 +450,7 @@ set key mistral "type": "api_key" } } +placeholder devvm-proxy-managed-pi-mistral-s4lt set key openai { "amazon-bedrock": { @@ -524,6 +529,7 @@ set key openai "type": "api_key" } } +placeholder sk-devvm-proxy-managed-pi-openai-s4lt set key openrouter { "amazon-bedrock": { @@ -602,6 +608,7 @@ set key openrouter "type": "api_key" } } +placeholder devvm-proxy-managed-pi-openrouter-s4lt set key xai { "amazon-bedrock": { @@ -684,3 +691,4 @@ set key xai "type": "api_key" } } +placeholder devvm-proxy-managed-pi-xai-s4lt diff --git a/internal/agents/agents.go b/internal/agents/agents.go index 0440dfc2..8b78b8e7 100644 --- a/internal/agents/agents.go +++ b/internal/agents/agents.go @@ -100,13 +100,18 @@ type Provider struct { // Header is the request header the agents send the key in, where the proxy swaps the // placeholder for it. Header string + // Prefix starts the VM's placeholder for its key, as an agent may tell its key from another + // credential by how it starts: pi 1.5.0 takes an OpenAI key that doesn't start with sk- for + // a ChatGPT sign-in's token, and leaves max_output_tokens, temperature and prompt caching's + // settings out of its requests. + Prefix string } // Providers are the providers whose API keys the proxy puts in, sorted by ID: every list of // them comes from here, and the docs' table of them names each (TestProvidersComplete). Each // is checked against opencode 2.2.6's and pi 1.5.0's own source (2026-11): both name it by the // same ID, send its key in that header alone, never in a URL, and to those hosts alone (Gemini's -// API, not Vertex AI's). +// API, not Vertex AI's), and neither checks how a key starts but where Prefix says. // // A bound key still lets the VM mint credentials that work without the proxy, which the proxy // allows because opencode 2.2.6's experimental realtime mode mints them itself @@ -123,7 +128,7 @@ var Providers = []Provider{ {ID: "google", Display: "Google Gemini", Hosts: []string{"generativelanguage.googleapis.com"}, Header: "x-goog-api-key"}, {ID: "groq", Display: "Groq", Hosts: []string{"api.groq.com"}, Header: "Authorization"}, {ID: "mistral", Display: "Mistral", Hosts: []string{"api.mistral.ai"}, Header: "Authorization"}, - {ID: "openai", Display: "OpenAI", Hosts: []string{"api.openai.com"}, Header: "Authorization"}, + {ID: "openai", Display: "OpenAI", Hosts: []string{"api.openai.com"}, Header: "Authorization", Prefix: "sk-"}, {ID: "openrouter", Display: "OpenRouter", Hosts: []string{"openrouter.ai"}, Header: "Authorization"}, {ID: "xai", Display: "xAI", Hosts: []string{"api.x.ai"}, Header: "Authorization"}, } diff --git a/internal/proxy/secrets_test.go b/internal/proxy/secrets_test.go index bbb2d810..c64030a9 100644 --- a/internal/proxy/secrets_test.go +++ b/internal/proxy/secrets_test.go @@ -641,6 +641,53 @@ func TestIntercept(t *testing.T) { } } +// A WebSocket's upgrade in an intercepted tunnel, as opencode opens OpenAI's and xAI's Responses +// API (wss://…/v1/responses), gets the secret put in its header as any request does, and once the +// upstream switches protocols, the proxy carries the connection's bytes both ways. +func TestInterceptWebSocket(t *testing.T) { + t.Parallel() + _, port, _, client := interceptSetup(t, func(w http.ResponseWriter, r *http.Request) { + if !strings.EqualFold(r.Header.Get("Upgrade"), "websocket") { + http.Error(w, "no upgrade", http.StatusBadRequest) + return + } + conn, rw, err := http.NewResponseController(w).Hijack() + if err != nil { + return + } + defer conn.Close() + fmt.Fprintf(rw, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nX-Auth: %s\r\n\r\n", r.Header.Get("Authorization")) + _ = rw.Flush() + b := make([]byte, 4) + if _, err := io.ReadFull(rw, b); err == nil { + _, _ = conn.Write(b) + } + }) + req, _ := http.NewRequestWithContext(t.Context(), http.MethodGet, fmt.Sprintf("https://localhost:%d/v1/responses", port), nil) + req.Header.Set("Authorization", "Bearer PH") + req.Header.Set("Connection", "Upgrade") + req.Header.Set("Upgrade", "websocket") + resp, err := client.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusSwitchingProtocols || resp.Header.Get("X-Auth") != "Bearer real" { + t.Fatalf("the upgrade: %d, the upstream saw %q", resp.StatusCode, resp.Header.Get("X-Auth")) + } + conn, ok := resp.Body.(io.ReadWriteCloser) + if !ok { + t.Fatal("the switched connection can't be written to") + } + if _, err := conn.Write([]byte("ping")); err != nil { + t.Fatal(err) + } + b := make([]byte, 4) + if _, err := io.ReadFull(conn, b); err != nil || string(b) != "ping" { + t.Errorf("the switched connection gave %q, %v", b, err) + } +} + // Every HTTPS request the proxy forwards, in an intercepted tunnel or in absolute form // (handleHTTP), is refused before it goes anywhere when it would make a lasting GitHub // credential, logged as a refused block; plain HTTP carries no secret. diff --git a/tests/e2e/network_test.go b/tests/e2e/network_test.go index 6a56e16e..165e1663 100644 --- a/tests/e2e/network_test.go +++ b/tests/e2e/network_test.go @@ -772,7 +772,7 @@ func netTokenServer(n *netRun) error { if err != nil { return err } - cf, kf, err := ca.Sign("auth", "auth.openai.com", "platform.claude.com", "api.anthropic.com", "api.groq.com", geminiAPIHost) + cf, kf, err := ca.Sign("auth", "auth.openai.com", "platform.claude.com", "api.anthropic.com", "api.groq.com", "api.openai.com", geminiAPIHost) if err != nil { return err } @@ -1096,7 +1096,8 @@ const piKey = "sk-ant-e2efake-pi" // the store; the VM's pi gets only its placeholder, and pi's own request // to Anthropic's API, which the run's fake answers, carries the key the // VM's proxy put in, logged nowhere; a fake Groq key the same, in pi's -// Authorization to Groq's API. +// Authorization to Groq's API; and a fake OpenAI key, whose placeholder +// starts sk- as pi checks, in an API key's request to OpenAI's API. func netPi(n *netRun) { s, vm := n.s, n.vm s.Check("pi runs in the VM from its read-only shared image, its version check and install report off", func() error { @@ -1162,11 +1163,34 @@ func netPi(n *netRun) { } return NoLeak([]string{groqKey}, filepath.Join(n.vmd, "logs"), filepath.Join(s.Paths.Devvm, "logs")) }, Tail(40)) + s.Check("devvm agent login pi --api-key --provider openai: the VM's pi holds a placeholder starting sk-, and sends OpenAI's API an API key's request with the key", func() error { + r, err := n.dv(piOpenAIKey+"\n", n.tokenEnv("DEVVM_MESSAGES=names"), "agent", "login", "pi", "--api-key", "--provider", "openai", "--stdin") + if err != nil || !Matches(r.Out, `^==> agent_key_saved agent=pi provider=openai vm=`) { + return failed("devvm agent login pi --api-key --provider openai didn't save the key:\n"+r.Out, err) + } + ph := "sk-devvm-proxy-managed-pi-openai-" + n.salt + if vmOut(s, vm, "jq -r .openai.key ~/.pi/agent/auth.json") != ph { + return errors.New("the VM's pi login doesn't hold OpenAI's key's placeholder") + } + // The fake answers with a 404, so pi fails, after its request. A key that doesn't start + // with sk- would be a ChatGPT sign-in's token to pi, which leaves max_output_tokens out. + _, _ = s.InVM(vm, `timeout 120 pi --no-session --no-tools -p --provider openai --model gpt-4o "e2e"