mirror of
https://github.com/devvmhq/devvm.git
synced 2026-12-01 21:36:40 -10:00
feat(proxy): the network policy proxy as devvm _proxy
The network policy proxy moves into the binary as internal/proxy (standard library only), run by the hidden devvm _proxy with its own flags. Main returns errors instead of exiting, writes only to the streams devvm hands it (the event log and data on stdout, its log lines on stderr), and returns when the VM's hostagent is gone. The connect mode is gone: devvm _qemu connect does that. Logins copied as they are are warned about through ui. Its tests come along, with a short run, fuzz targets for policy rules, request targets and ClientHellos, a testscript, and the network page of the docs for the proxy. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
22 files changed
+4017
-5
No files matched your search
@@ -7,14 +7,15 @@ devvm: one isolated VM per project folder, cloned from a base image, with toolch
|
||||
| Path | What |
|
||||
| --- | --- |
|
||||
| `cmd/devvm/main.go` | the entry point: runs the root command through `ui.Main` and exits with its code. The only place that calls `os.Exit` |
|
||||
| `internal/cli/` | Cobra commands, one file each (the root, which is up, in `up.go` with the global flags; `build` and `rebuild` in `build.go`; the hidden `_msg`, `_qemu` and `_refresh-tools`, the daily tools check `tools.RefreshDaily` starts), and `script_test.go`, the testscript runner: it puts copies of `base.yaml`, `layers/`, `tools/` and `guest/` next to the built binary, one dated Ubuntu release behind `DEVVM_UBUNTU_URL`, the `mise` stub behind `DEVVM_HOST_MISE` with `MISE_STUB_LOCK` the fixture lock, and adds `stub_calls` and `wait_file`. The root is `devvm [IMAGE]` (`vm.Env.Up`). Global (persistent) flags: `--backend` (through `backend.Registry.For`, for build and rebuild too), `--network-policy`/`--no-network-policy` (mutually exclusive), `--cpus`/`--memory`/`--disk`, `--ports`; up's own: `--unsafe-folder`, `--no-git-protect`. `Execute` prints a command's error with `ui.Warn`: a message as it is, Cobra's own in `usage_error`. Commands end with `fail`: `ui.DieLogged` for a `LoggedError`, `ui.Die` otherwise (`build_failed` or `up_failed` for an error that isn't a message). `root_test.go` never runs up (it would run on the real folders): the scripts do, in their sandbox |
|
||||
| `internal/cli/` | Cobra commands, one file each (the root, which is up, in `up.go` with the global flags; `build` and `rebuild` in `build.go`; the hidden `_msg`, `_qemu`, `_proxy` (`proxy.go`: its arguments to `proxy.Main` with devvm's streams, `ui.Stdout` for the event log and data, `ui.Stderr` for its log lines; `codex_login_kept`/`opencode_login_kept` through `IO.Kept`; an error is `proxy_failed`) and `_refresh-tools`, the daily tools check `tools.RefreshDaily` starts), and `script_test.go`, the testscript runner: it puts copies of `base.yaml`, `layers/`, `tools/` and `guest/` next to the built binary, one dated Ubuntu release behind `DEVVM_UBUNTU_URL`, the `mise` stub behind `DEVVM_HOST_MISE` with `MISE_STUB_LOCK` the fixture lock, and adds `stub_calls` and `wait_file`. The root is `devvm [IMAGE]` (`vm.Env.Up`). Global (persistent) flags: `--backend` (through `backend.Registry.For`, for build and rebuild too), `--network-policy`/`--no-network-policy` (mutually exclusive), `--cpus`/`--memory`/`--disk`, `--ports`; up's own: `--unsafe-folder`, `--no-git-protect`. `Execute` prints a command's error with `ui.Warn`: a message as it is, Cobra's own in `usage_error`. Commands end with `fail`: `ui.DieLogged` for a `LoggedError`, `ui.Die` otherwise (`build_failed` or `up_failed` for an error that isn't a message). `root_test.go` never runs up (it would run on the real folders): the scripts do, in their sandbox |
|
||||
| `internal/vm/` | up (`Env.Up`; `NewEnv` reads the working folder, physical, and sets the host's functions; tests swap `Host`, `Protector`, `Exec`): the folder (`project.New` with the new-VM backend's `NameMax`, `bad_path`, `vm_name_no_room`), the VM's state and its backend (`For`), `Check`, an existing VM (`checkFolder`: `vm_other_folder`; then `vm_exists`, until up opens existing VMs), and for a new one, in order: the unsafe-folder checks, size (flags, else the `size` file, parsed again; host CPUs and memory, base.yaml's disk), ports (flags, else the `ports` file), the image (named, else `project.Detect`, and with only agents named, the detected toolchains under them; `no_image_for`; `CheckLayers`), the network policy refusal without `--no-network-policy` (`network_policy_unavailable`), `backend.Require` for the spec (the tools share always) and `NetDirect`, the tools check when it's due and the image names tools (`tools.Check`), the build (image and tools), the tool files for base's libc, then a `ui.AddCleanup` that on an interrupt deletes the VM and its state and unlocks `.git` (`interrupted_vm`), the state (written before the clone, `net=off`, `libc`, `tools`, size), `CreateVM` (from the image without its tools, with the share at `tools.ShareAt`), `ports`/`ports_set`, `gitprotect.NewVM`, `ssh_remote_hint`, Linux's `setid_files`, `Start`, the setup (`sync.go`: a tar stream of `guest/sync.sh`, `guest/tools.sh` and the VM's tool list on `Exec`'s input, its output in the run log, `sync_failed`), `Shell`, and `Exec` (chdir to the command's folder, `platform.Exec`). `size.go`: `ParseCPUs`, `ParseGiB`, `Size.Check`, `BaseDisk`; `ports.go`: `ParsePorts`, `PortsBackend` |
|
||||
| `internal/project/` | a project folder: `New` (the VM's name, `devvm-<slug>-<14 hex of the path's SHA-1>`, the slug cut to the backend's room, at most 20, `ErrNoRoom` under 4; `BadPathError` for commas and control characters), `Slug`, `Unsafe` (`Holds`, `Inside`, compared by physical paths, as far as they exist), `Detect` (marker files, a fixed order), `SetIDFiles` (one file system, five at most), `SSHRemote` (`git config --file`) |
|
||||
| `internal/gitprotect/` | `.git` protection: `Protector` (`OS`, `Chflags` and `Warn` are fields, for tests) with `NewVM` (off with `--no-git-protect` or off darwin, `git_protect_needs_macos_new` when there's a `.git`; else on: `commondir` and stray worktrees reported, `git_embedded` and `git_modules` recorded as JSON lists of relative paths, the locks, `core.hooksPath` inside, the includes, hook links and outside git dirs reported, their hash as `git_delegations`) and `Unlock`. git runs as a command (`ls-files -s -z` with `core.fsmonitor=false`, `config --file`); paths are locked only when `realInDir` (no symlink below the folder), checked again after `chflags` (`git_lock_raced`). Its tests use real git, and real `chflags` on macOS (`TestRealLocks`, unlocking after) |
|
||||
| `internal/cli/docgen/` | the CLI reference generator (`mise run cli-docs`): `cobra/doc`'s Markdown per command users can run (hidden and help commands left out, no dates), tidied for the site (front matter `title` and `weight`, Cobra's title heading dropped, `##` headings, `text` code blocks, `-` lists), written to `docs/content/docs/cli/` with `_index.md`, every old page there replaced. `TestReferenceIsCurrent` fails when the checked-in pages are stale; `TestStaleReferenceIsCaught` edits commands to prove it |
|
||||
| `internal/build/` | building images on a backend: `Builder` (the default backend's, from `backend.Registry.For`, and the shared tools, `Tools`) with `Build` (the name's image without its tools, then its tools' images, `Tools.Build`, for `BaseLibc`; each missing image under it first; `backend.Require` before anything; an instance without a record is a leftover, `image_leftover`, deleted and built again; the record written last: name, chain, base's Ubuntu image as `digest`, libc), `Rebuild` (shared tools refused, `tools_not_images`; `state.BumpRebuild`; the images built on it listed, `rebuild_replaces`, and asked about in a terminal; then every stale image no VM uses deleted, with its record; one the backend refuses with a message is warned about and kept), `List` (current or stale, by recomputing keys), `WarnIfOutdated` (`vm_outdated`; for up on an existing VM, so nothing calls it yet), `Layers`, `Environments` (base, the toolchains, the layers) and `CheckLayers` (shared tools pass; `unknown_layer`). Its inputs: devvm's files, the user's layers and the rebuild counters; no features yet |
|
||||
| `internal/tools/` | the shared tools: `Tools` (`New`; tests swap `Getenv`, `Detach`, `Info`, `Warn`, `ShareWait` and the mise pin) with `Lock` (resolved first when there's none or `tools/mise.toml` changed; `resolving_tools`, `tools_need_resolve`), `Resolve` (`mise lock --platform linux-<arch>,linux-<arch>-musl` in a temporary folder, `miseCmd`'s `MISE_*` state and `MISE_CEILING_PATHS`; every tool or nothing, `tools_resolve_failed`; the step back, `tool_stepped_back`/`tool_no_download`), `HostMise` (`DEVVM_HOST_MISE`, else the pinned mise, downloaded once into `Dirs.Mise()/<version>` and checked against its SHA-256; `mise_download_failed`, `mise_checksum`), `CheckDue` (a day; `DEVVM_NO_TOOL_CHECK`), `RefreshDaily` (`devvm _refresh-tools` through `platform.StartDetached`, output in `logs/tools-check.log`), `Refresh` (into `mise.lock.next`, swapped in under the share lock), `Check` (`checking_tools`, `tools_check_failed`), `File`/`Files` (`image.ToolFile` on the lock entry; `tool_not_locked`), `LockShare` (`tools/.lock`, `share_waiting`, `share_lock_held`), `Built`, `Build` (`tools_changed`, `tool_unbuilt`, go in a batch of its own; each batch through `Backend.BuildTools` into `tools-build.*` in the data folder, then plain files only, `tool_bad_output`, moved into the share with `FILE.sha256` written `O_EXCL`), `Garbage`, `Remove` (`vm_lacks`, `custom_layer_remove`), `Newer`/`WarnNewer` (`newer_tools`), `Update` (`tools_newest`, `tools_switch`) and `Mounts` (a VM's `FILE TOOL VERSION` lines). `Lock` is mise's lock read line by line (`Entry`, `VersionEntry`, `Version`, `HasDownload`). `Remove`, `WarnNewer`, `Update`, `Garbage` and `RefreshDaily` wait for their callers (up for an existing VM, remove, update, gc) |
|
||||
| `internal/ui/` | the only package that prints: `Say`/`Info`/`Note`/`Warn`/`Die`/`DieLogged`, `Ask`/`Confirm`, `Stdout` (data output), tty detection, the status line (`Status`), the run log (`Logged`, `LoggedCmd`, `WithSteps`, `LogNote`, `LogWriter` for output run some other way), and `Main`: the cleanup stack (`AddCleanup`), `Die`'s recovery, and INT/TERM/HUP (`Interrupted`, exit 130) |
|
||||
| `internal/proxy/` | the network policy proxy, stdlib only (depguard), run as `devvm _proxy` (see its `README.md`): `Main(args, IO)` parses the proxy's own flags (Go's `flag`, one dash or two; `-help` to `IO.Stdout`) and returns errors instead of exiting; it prints nothing itself: the event log goes to `IO.Stdout` or `-log`, its log lines (`logf`, prefix `devvm proxy: `) to `IO.Stderr`. The proxy (CONNECT and absolute-form, the address floor, SNI, the `devvm.proxy` endpoints, `-lifeline`, which makes `Main` return), `policy.go` (rules, re-read on change), `sni.go`, `secrets.go` (interception, the CA, `-init-ca`), `logins.go` (`-login`), `redact.go` (`-redact`). Package state is globals, set by `Main`; tests set them directly. Fuzzed: `FuzzParseRule`, `FuzzRequest`, `FuzzClientHello`. `syscall.Kill`/`Flock` keep it to unix for now |
|
||||
| `internal/ui/` | the only package that prints: `Say`/`Info`/`Note`/`Warn`/`Die`/`DieLogged`, `Ask`/`Confirm`, `Stdout` (data output), `Stderr` (log lines that aren't messages: `devvm _proxy`'s), tty detection, the status line (`Status`), the run log (`Logged`, `LoggedCmd`, `WithSteps`, `LogNote`, `LogWriter` for output run some other way), and `Main`: the cleanup stack (`AddCleanup`), `Die`'s recovery, and INT/TERM/HUP (`Interrupted`, exit 130) |
|
||||
| `internal/msg/` | messages: `messages_gen.go` (one function per message, generated), `M` (text in the user's language, names mode, doc links, `FromArgs` for `_msg`), `Shown` (a value as it is, Go-quoted when it has a control character: paths a VM may have made), the go-i18n bundle, `docs.go` (the doc links: message ID → `"page#anchor"`). `gen/` is the generator (`go generate ./internal/msg`); the tests check the generated file is current, every message renders, every one is called and every doc link is a message, page and heading |
|
||||
| `locales/` | `en.toml`, every message in go-i18n's TOML format (other languages join as `<lang>.toml`), embedded by `locales.go` and loaded with go-i18n's `LoadMessageFileFS` |
|
||||
| `internal/paths/` | names every folder and file devvm uses: the folder holding the binary (after following links), and `Dirs` (XDG data and config folders, devvm's Lima home, `DEVVM_LIMA_HOME`) with a method per state folder and config file |
|
||||
@@ -38,7 +39,7 @@ devvm: one isolated VM per project folder, cloned from a base image, with toolch
|
||||
| `.github/workflows/` | `ci.yml` (lint and test on macOS and Linux), `docs.yml` (the site on GitHub Pages) |
|
||||
| `.agents/skills/security-audit/`, `skills-lock.json` | the security-audit skill, used by the backend reviews |
|
||||
|
||||
Not there yet, and where it goes when its task arrives: `internal/{netpolicy,secrets}`, the other backends (`internal/backend/smolvm/`, `docker/`), `internal/proxy` (stdlib only), more of `internal/platform` (the Keychain), up for an existing VM (in `internal/vm`, with `gitprotect`'s per-run checks), the rest of `guest/sync.sh` and its host side. The rest of the in-VM scripts (`features/`, `oci/`) sit next to the binary, with `base.yaml`, `layers/`, `tools/` and `guest/`; `install.sh`, `scripts/` and `packaging/` handle releases.
|
||||
Not there yet, and where it goes when its task arrives: `internal/{netpolicy,secrets}`, the other backends (`internal/backend/smolvm/`, `docker/`), starting the proxy (`devvm _proxy` exists; nothing runs it yet), more of `internal/platform` (the Keychain), up for an existing VM (in `internal/vm`, with `gitprotect`'s per-run checks), the rest of `guest/sync.sh` and its host side. The rest of the in-VM scripts (`features/`, `oci/`) sit next to the binary, with `base.yaml`, `layers/`, `tools/` and `guest/`; `install.sh`, `scripts/` and `packaging/` handle releases.
|
||||
|
||||
## Tasks
|
||||
|
||||
@@ -147,6 +148,8 @@ Copied:
|
||||
- For up: `docs/commands.md` → `docs/content/docs/commands.md`, rewritten for what exists (up and its options for a new VM, with a "Size and ports" section from `docs/images.md`'s ports and the size options, build, rebuild, the environment); `docs/security.md` → `docs/content/docs/security.md`, rewritten for what's isolated so far (the project folder only, the unsafe folders, one VM per folder, confined builds, `.git` protection; not protected: the VM's writes, the network, ports, Linux set-id bits, escapes); `docs/git-protection.md` → `docs/content/docs/git-protection.md`, rewritten for new VMs (locked at creation, what's reported then, unlocking by hand with `chflags` instead of `devvm git-protect`; strict, the per-run reports and `rm`'s unlock come with their tasks); `docs/images.md`'s detection (from "Which image a VM gets") → `images.md`'s "Which image a new VM gets"; the README's usage → its "Quickstart", with devvm's output. `backends.md` gets "VM names". `tests/e2e.sh`'s `project` and `.git protection` sections → its `project` section, adapted: `newproj`, `launch` and `vm_of` rewritten (the VM from its state, the shell fed its commands on devvm's input instead of none), `devvm ls` checks replaced by state and `limactl list`, Exec's quoting checked by `TestE2EExecQuoting`, the project folders unlocked in the cleanup (no `devvm rm` yet). New: the `chflags` stub (the bats tests redefined `chflags` as a function) and the `limactl` stub's `start-hangs`.
|
||||
- `docs/images.md` → `docs/content/docs/images.md`, more: "Caching"'s "Each image is a stopped Lima instance…" (as "Building", and in `lima.md`'s "Clones and overlays"), the layer naming and stacking of "Which image a VM gets" (as "Layers", without detection, agents and tools, which come with up and the shared tools), and "Build logs and interrupts"' unfinished image (and later the failed build's kept VM, with how to look inside); new: "Rebuilding" and "Outdated VMs" under "Caching", base's record in "Ubuntu's cloud image". `contributing.md` gets "End-to-end tests".
|
||||
- For the shared tools: `tools/mise.toml` (its comment's doc link reworded), `tools/build.sh` (its comment names the lock's path instead of `tool_lock`) and the `tools/*.policy` files as they are; `guest/tools.sh` as it is; `guest/sync.sh`, partly: its shared tools part (installing `tools.sh` and the tool list, the mise config, the stale links, rust, go's telemetry, claude's link, `mise reshim`, `~/.bashrc`'s first line), its header cut to `tools.sh` and `tools`; the rest (hostname, timezone, locale, the apt snapshot, the prompt, git, agents, env, the CA) comes with sync. `tests/fixtures/mise.lock` → `testdata/mise.lock`, as it is. `tests/stubs/mise` → `testdata/stubs/mise`, its comment reworded (`DEVVM_HOST_MISE`). The `limactl` stub's tools build parts (its `location` match loosened for Go's JSON), and new: its `sync.tar`. `docs/images.md` → `docs/content/docs/images.md`: the overview's environments and agents and "Shared tools" → "Shared tools" with "Versions" (now with devvm's own pinned mise), "Building tools" (new: the build VM, the checks, the share lock, tool keys moved there from "Outdated VMs", rebuild's refusal) and "Adding and removing tools" (only that it isn't available yet; adding in place, `devvm remove` and `devvm update` come with up for an existing VM); "Which image a VM gets"' stacking, agents and normal order → "Which image a new VM gets". `commands.md` and `contributing.md` updated (`DEVVM_NO_TOOL_CHECK`, `DEVVM_HOST_MISE`, the stubs, the `tools` e2e section). `tests/e2e.sh`'s "shared tool versions" section and the node half of its "shared tools" section → the `tools` section, adapted: one node VM (from a `package.json`) instead of node+python+claude+codex, `launch` with its shell's input, state files instead of `devvm ls`; new: the share's images and hashes, a second node VM that builds nothing, no build VM left. The `project` section's mounts check now expects the share. Left for their tasks: python and uv, claude and codex, the uv project, rust and go, adding a tool in place, `devvm update`, `devvm remove`, gc keeping images VMs use.
|
||||
- The proxy: `devvm-proxy/*.go` and their tests → `internal/proxy/`, package `proxy`: `main.go` → `proxy.go`, `main_test.go` → `proxy_test.go`, `policy.go`, `sni.go`, `secrets.go`, `secrets_test.go`, `logins.go`, `logins_test.go`, `redact.go`, `redact_test.go` (`go.mod` dropped: it's devvm's module now). Changed: `main` became `Main(args, IO)`, behind the hidden `devvm _proxy` (`internal/cli/proxy.go`), with the same flags on a `flag.FlagSet` of its own (writing into package variables, so `vmName` and the rest are values, not pointers), `-help` printed to stdout; `-connect` and `connectStdio` dropped, with `TestConnectStdio` (already `devvm _qemu connect`, `lima.Connect`, `TestConnect`); `log.Fatal` and the lifeline's `os.Exit(0)` became returned errors and a closed server (`watchLifeline` returns; `lifelineTick` for tests); the event log, the log lines (`logger`, prefix `devvm proxy: ` instead of `devvm-proxy: `), `-login`'s and `-redact`'s output go to the streams `IO` gives instead of `os.Stdout`/`os.Stderr` and the `log` package's; `loginCmd`'s two `devvm: … copied into the VM as it is` lines became `IO.Kept`, which the command warns as `codex_login_kept`/`opencode_login_kept` (opencode's providers sorted); the `-login` usage names claude; lint fixes (errors handled or `_ =`, `%w`, contexts, `ReadHeaderTimeout` on the interception server, De Morgan rewrites, `//nolint:gosec` with reasons for devvm-named files, public IDs and test values), and `dial` refuses a port outside 1–65535 instead of letting `uint16` wrap it (the policy never allowed one). Comments reworded: `devvm _proxy` for `devvm-proxy`, "the devvm binary" for the script, the bats-era "Lead N:" prefixes dropped. Tests: `logOut` reset to `io.Discard` (not `os.Stdout`), a `roundTrip` and `must` helper; new `TestMainRefuses`, `TestMainRuns` (a short run: listens, logs, answers, writes the event log, returns when the hostagent, a `sleep`, is gone), `FuzzParseRule`, `FuzzRequest` (the allow rule a block suggests allows exactly that host and port), `FuzzClientHello`, `TestStderrIsForLogLines` in `internal/ui`, and `testdata/script/proxy.txtar` (`--help`, the refusals, `-init-ca`, `-redact`, `-login`). The placeholders keep their `devvm-proxy-managed` text (data the VM's agents send). `devvm-proxy/README.md` → `internal/proxy/README.md`, rewritten: `devvm _proxy` and `Main`, `proxy.go`, no `-connect`, no build in a VM (`build_proxy`, `tool_intact`) and no Go-in-a-VM testing. Messages: `proxy_failed`, `codex_login_kept`, `opencode_login_kept` (the last two linked to `network.md`). `build.bats` "build_proxy: …" (both) are dropped: the proxy is part of the binary. `docs/network.md` → `docs/content/docs/network.md`, partly: "The proxy" bullet of "How it's enforced" and the rule syntax of "Allowlists" as "The proxy" and "Rules", the proxy's side of "In the VM" (its `403`, the `devvm.proxy` endpoints) and of "Tokens" (interception, `421`, the refused GitHub calls, logins, MCP secrets, settings redaction), rewritten for what exists, plus the README's flags and modes as "devvm _proxy", and "Not covered"; the allowlist defaults, `devvm policy`, `devvm log`, `devvm-why`, `devvm secret` and the self-check come with network policy and those commands.
|
||||
|
||||
Ported from `devvm` (rewritten in Go, not copied):
|
||||
- paths and state (`internal/paths`, `internal/state`): the `*_dir`/`*_file` definitions, XDG and `DEVVM_LIMA_HOME`, `vm_get`/`vm_set`/`new_vm_state`, image records, `from-digests`, and reading and writing the `size`, `ports`, `base-features` and `agent-keys` files. Go's own formats; their callers come with their tasks. Bats cases converted to Go table tests: `cli.bats` "vm_set/vm_get: keys replace, values may contain '='" and the Lima home half of "devvm's own Lima home" (the `devvm limactl` half goes with that command); the file side of `from.bats` "refresh_from_digest records the registry's digest per tag" and of `build.bats`'s libc record. `images.bats` "the chosen features move from the old features file" is dropped: no migration from the bash files.
|
||||
- messages (`internal/msg`, `locales/en.toml`, `devvm _msg`): `messages.sh`'s `msg` helper and the unit tests' names-mode `msg` (values now in sorted key order), and `tests/lint-messages.sh`, whose checks are now the compiler, the generator and the msg tests. No bulk conversion of `messages.sh`: each task writes its own messages. Bats cases converted: `messages.bats` "msg passes values by name, as they are" (`TestValuesAsGiven`, `msg.txtar`) and "every message prints with the names devvm passes" (`TestEveryMessageRenders`); `lint.bats` "a missing, extra or repeated name, an argument that isn't name=value" and the unknown half of "unknown and unused messages" (`TestFromArgs`, `msg.txtar`; in Go code the compiler checks calls), its unused half (`TestEveryMessageIsUsed`), "messages use names, not positional arguments" (the generator's snake_case plain-field check, `TestGenerateRefuses`) and "devvm's calls match messages.sh" (`TestGeneratedFileIsCurrent` plus the compiler). The `internal/ui` cases are listed under ui below. Dropped as bash-specific: `lint.bats` "calls that pass exactly what each message uses" and the "helper with no message" case (the compiler), "helper names in strings, comments, heredocs and arguments aren't calls" (no text parsing in Go), "plain text passes until --strict" and "--strict: prose outside messages.sh" (forbidigo bans printing outside `internal/ui`; prose in `fmt` is a review rule).
|
||||
@@ -156,6 +159,6 @@ Ported from `devvm` (rewritten in Go, not copied):
|
||||
- Ubuntu's cloud image (`internal/ubuntu`): `ubuntu_series`/`ubuntu_version`, `ubuntu_url` with `DEVVM_UBUNTU_URL`, `ubuntu_releases`, `ubuntu_image` and `ubuntu_verify`, with `net/http` (a timeout per request, three retries for failures that may pass, `file://` read by Go's file transport instead of the tests' `ubuntu_releases` override, no redirects to another scheme) instead of `curl`. `SHA256SUMS` and its signature are written to a temporary folder only for gpgv, which runs through `ui.LoggedCmd`, and removed. Its messages: `no_ubuntu_image`, `ubuntu_bad_signature`, `ubuntu_unsigned`. `create_ubuntu_vm` came with build. Bats cases converted to Go tests (`httptest` and `file://` folders, a fake gpgv instead of `tests/stubs/gpgv`, which came later for the CLI tests; no `curl` stub): `build.bats` "ubuntu_image: the newest dated release with an image for this host, and its checksum" (`TestImage`), "ubuntu_image: a checksum that isn't 64 hex digits is skipped, never put in Lima's config" (`TestImageSkipsBadChecksums`, `TestChecksum`), "ubuntu_image: the checksums must be signed by Ubuntu's key (with gpgv); without gpgv, a note" (`TestImageSignature`); "build: base uses Ubuntu's image, and its record says which" came with build. New: `TestRealSignature` (the real key and gpgv on a real release's files, and a changed checksum refused), `TestReleases`, `TestRedirects`, `TestRetries`, `TestCanceled`, and `TestKeyOfTheRealFiles` in `internal/image`.
|
||||
- build and rebuild (`internal/build`, `internal/backend/lima/build.go`, `internal/cli/build.go`, `internal/platform`): `build` and the `build` and `rebuild` entries of `main` (no flags apply yet; `--from` and shared tool names are left out, so a tool's name is an `unknown_layer` until the shared tools come), `build_image` (its record and leftover parts in `internal/build`, its VM in Lima's `BuildImage`), `create_ubuntu_vm`, `build_memory` and `host_mem_gib` (`platform.Memory`), `run_script`, `rebuild_image` (`state.BumpRebuild`; an image in use is the backend's `image_in_use`, warned about and kept, instead of `kept_old_image`), `rebuild_file` (already `paths.RebuildFile`), `check_layers`, `custom_layer_names`, `layer_name_ok`/`is_custom_layer` and `layer_script`, `normalize` (base dropped; toolchain and agent order goes with the shared tools), `image_list` (`List`), `image_built`, `delete_image_key`'s record removal, `interrupted`'s unfinished image (a `ui.AddCleanup` in `BuildImage`) and `warn_if_outdated`'s image half (`Inputs.Outdated`, `WarnIfOutdated`; its newer tools half goes with the shared tools). `confine_build` was ported with Start; its `.confined` marker and `build_vm_unconfined` are dropped (only `BuildImage` starts a build VM, always confined), as is `unconfine`. A failed build keeps its stopped VM for inspection, as the bash does (`run_script` stops it, then `script_failed`), except a failed create or clone, which is deleted (the bash kept it too, as a leftover for the next build): there's nothing in it to inspect. `script_failed` suggests `LIMA_HOME=<devvm's Lima home> limactl shell --start <vm>` instead of `devvm limactl shell` (no `devvm limactl` yet) and drops the `devvm gc` part (no gc yet). Changed: the base features aren't run or hashed yet (with features). Messages: `unknown_layer`, `build_failed`, `image_leftover`, `building_image`, `base_build_time`, `image_ready`, `creating_from_ubuntu`, `cloning_image`, `running_script`, `script_failed`, `interrupted_image`, `unfinished_image`, `rebuild_replaces`, `continue`, `nothing_changed`, `deleted_old_image`, `deleted_unfinished_build`, `vm_outdated`. Bats cases converted: `build.bats` "build: a recorded image is reused" (`build.txtar`, `TestBuild`), "build: an instance without a record is a failed build, rebuilt from scratch" (`build.txtar`), "build: base uses Ubuntu's image, and its record says which" (`build.txtar`, `TestBuildImageBase`), "build: images are created without host mounts" (`build.txtar`, `TestBuildImageBase`, `TestBuildImageLayer`), the base and layer half of "build: each phase numbers its steps, and the count matches what it runs" (`build.txtar`; features and tools go with them), "Ctrl+C during a build deletes the unfinished image, never a finished one" (`build.txtar`, and e2e), and the failed build that keeps its stopped VM (`build.txtar`, `TestBuildImageScriptFails`, and e2e); `images.bats` "normalize: base alone, and base dropped from a list" (`TestNormalize`), "parent_of strips the top layer" (`TestParent`), "custom layers: the user's folder, with names image names can hold and devvm doesn't use" (`TestLayersAndCheckLayers`, `build.txtar`; the tool names half goes with the shared tools), "image_list: current, stale after an edit, and stale without a record" (`TestList`); `layers.bats`, all five (`layers.txtar`, which takes each function from the copy of `layers/base.sh` next to the test binary); `cli.bats` "rebuild refuses names that aren't layers" (`build.txtar`) and "build_memory: …" (`TestFitMemory`); `delete.bats` "rebuild deletes the old image and those built on it, nothing else" (`rebuild.txtar`, `TestRebuild`). Left for their tasks: `images.bats` "normalize: toolchains in fixed order …" and `delete.bats` "rebuild refuses shared tools" (shared tools), `project.bats` "warn_if_outdated: newer shared tools …" (shared tools). New: `TestBuildImageScriptFails`, `TestBuildImageRefuses`, `TestBuildRequires`, `TestFailedBuildHasNoRecord`, `TestRebuildKeepsImagesInUse`, `TestBuildKeepsTheLibc`, `TestOutdated`, `TestParseChain`, `TestLayerName`, `TestBumpRebuild`, `TestMemory`, `TestLimaArch`.
|
||||
- up for a new VM (`internal/vm`, `internal/project`, `internal/gitprotect`, `internal/cli/up.go`, `internal/platform`): `main`'s default case and `parse_args`' up options (Cobra flags; `--from`, `--clone` and `--ssh-agent` are left for their tasks), `up`'s new-VM branch and its end (`ensure_running`, the final `exec limactl shell`), `project` (`bad_path`, the slug, now cut per character rather than per byte, and the hash; `vm_slug_max`'s room through the backend's `NameMax`, refused as `vm_name_no_room` before anything instead of `lima_home_too_long`), `folder_id` (`platform.FolderID`, Go's format), `check_vm_folder` (`checkFolder`; the record for VMs from before folder checks is dropped: no migration), `unsafe_folder_holds`/`unsafe_folder_inside` (with paths resolved as far as they exist), `detect`, `resolve_image` (only with no image named: there are no agents yet), `no_image` (merged into `no_image_for`, which lists the layers), `new_vm_state` (written before the clone, so a failed clone leaves nothing that starts), `size_parse`, `host_cpus` (`runtime.NumCPU`), `host_mem_gib` (`platform.Memory`), `size_check`, `size_default`, `size_opt`, `base_disk`, `new_vm_size` (applied by `CreateVM`), `ports_parse`, `new_vm_ports` (`ports` and `ports_set`, applied by the clone), `hint_ssh_remote` (`ssh_remote_hint` doesn't name `devvm ssh-agent` yet), `setid_check` (`SetIDFiles`; now also on new VMs on Linux hosts, for files an earlier VM of the folder made), `interrupted`'s unfinished VM (a `ui.AddCleanup`), and from git protection `git_dirs`, `worktree_config`, `git_embedded`/`git_embedded_in` (`ls-files -s -z`), `git_protect_paths`, `worktree_strays`, `hooks_path_inside`, `git_delegations` and `resolved_path` (physical paths), `real_in_dir`, `git_flag`, `git_lock`, `git_unlock` (`Unlock`, for the interrupted VM) and `git_protect_check`'s `new` path (`NewVM`; `git_embedded` and `git_modules` as JSON lists, `git_delegations` as a SHA-256). Changed: network policy is refused (`network_policy_unavailable`) without `--no-network-policy` (and with `--network-policy`) until it comes; a VM that exists is refused (`vm_exists`) until up opens existing VMs; `warn_if_outdated` and `refresh_tools_daily` go with that (the bash calls them for existing VMs only); values a VM may have made are Go-quoted (`msg.Shown`) instead of stripped of control characters. Left for their tasks: the tools check and `vm_set libc/tools` (shared tools), `net_choice`, `stop_proxy`, `forget_host_keys`, `net_selfcheck`, `sync_vm`, `write_ssh_config` and the agent mounts (network policy, sync, agent mounts, ssh config), `check_ssh_agent`, `agent_mode` and `--ssh-agent` (ssh-agent), `clone_check_repo`, `seed_clone` and `--clone` (`--clone`), `--from` (`--from`), the existing-VM branch (`add_layers`, the flag-ignored warnings, `git_protect_check check` with its per-run reports, `setid_check` on every run, `apply_agent_forwarding`, `apply_size`/`apply_ports` and their restart warnings, `vm_unfinished`). Messages: `up_failed`, `bad_path`, `vm_name_no_room`, `vm_other_folder`, `vm_exists`, `unsafe_folder`, `unsafe_folder_inside`, `unsafe_folder_used`, `cpus_not_number`, `size_not_gib`, `too_many_cpus`, `too_much_memory`, `port_invalid`, `detected`, `no_image_for`, `network_policy_unavailable`, `creating_from`, `interrupted_vm`, `ssh_remote_hint`, `setid_files`, `git_protect_needs_macos_new`, `git_commondir`, `git_worktree_stray`, `git_not_locked`, `git_lock_raced`, `git_hooks_path`, `git_include_inside`, `git_hook_link_inside`, `git_gitdir_outside`. Bats cases converted: `project.bats` "detect: each marker file" and "detect: several toolchains, in fixed order" (`TestDetect`), "resolve_image: an explicit toolchain or base skips detection", its base and layer half (`up_checks.txtar`), "resolve_image: nothing detected and nothing named is an error" (`up_checks.txtar`), "project: slug and hash from the folder" and "project: paths with spaces work; commas are refused" (`TestSlug`, `TestNew`, `up_checks.txtar`), "a folder that is or holds your home or devvm's state is refused, unless --unsafe-folder" and "a folder inside devvm's config, data or Lima home is refused too, unless --unsafe-folder" (`TestUnsafe`, `up_checks.txtar`), the up half of "a folder made again at the same path doesn't get the old folder's VM" (`up.txtar`), "git_protect_paths: a repo under a path with spaces" (`TestPathsUnderSpaces`), "git_protect_paths: config.worktree with extensions.worktreeConfig, and linked worktrees' files" (`TestPathsWorktrees`), "git_lock never creates or locks anything through a symlink the VM planted under .git" (`TestLockNeverThroughSymlinks`), "git_lock creates and locks a missing hooks folder, so the VM can't add hooks there" (`TestLockCreatesMissingHooks`, `TestRealLocks`), "git_lock flags only real paths: a symlinked .git/config is reported, not locked" (`TestLockOnlyRealPaths`), "git protection never locks another repo through a .git symlink, and prints commonLine truncated
|
||||
- the shared tools (`internal/tools`, `internal/image`, `internal/build`, `internal/vm`, `internal/backend/lima/tools.go`, `internal/platform`, `devvm _refresh-tools`): `lang_layers`/`agent_layers`/`tool_groups`/`is_group`, `group_tools`, `tools_of`, `image_of` (`WithoutTools`), `normalize`'s toolchain and agent order (`image.Normalize`, moved from `internal/build`), `layer_name_ok`'s tool names, `environments` (`Environments`; `unknown_layer` and `no_image_for` now take `envs` and `agents`, as the bash's `pick_image` listed them), `needs_project_layers` and `resolve_image`'s agents (`needsDetection`), `all_tools`, `host_mise` and its pins (with `DEVVM_HOST_MISE` for tests in place of the unit tests' `host_mise` override; `net/http` and `crypto/sha256` instead of `curl` and `shasum`; a status line while it downloads, `downloading_mise`), `resolve_tools`, `tmise` (`miseCmd`), `lock_platforms`, `mise_arch` (from `GOARCH`, not `uname`), `has_download`, `step_back`, `version_block`, `lock_block`, `need_tool_lock` (`Lock`; a failed resolve is `tools_need_resolve` with the log's end, mise's output being in the run log, instead of `tools_resolve_failed` plus its last 5 lines), `tools_check_due`, `refresh_tools_daily` (`RefreshDaily`: `platform.StartDetached`, `Setsid`, instead of `nohup … &`), `refresh_tools`, `check_tools` (`Check`: `checking_tools` always, the resolve's step on the status line), `lock_entry`, `no_download`, `locked_version`, `tool_file`/`tool_files` (`File`, `Files`), `image_libc` (`Builder.BaseLibc`), `tool_of_file` (already `ParseToolFile`), `share_lock`/`share_unlock` (`LockShare`, a `ui.AddCleanup` instead of the trap), `tool_built` (`Built`), `build_tools` and `tools_batch` (`Tools.Build`; the VM's part through the new `Backend.BuildTools`), `tool_garbage` (`Garbage`, taking the VMs' tool files from its caller), `remove_tools` (`Remove`, pure: its caller sets the state), `update`'s tools part (`Update`), `warn_if_outdated`'s newer tools half (`WarnNewer`), `build`'s tools half, `rebuild_image`'s refusal, and from `up` the tools check, the share mount, `vm_set libc`/`tools`, and `sync_vm`'s tools part (`vm.sync`: `guest/sync.sh`, `guest/tools.sh` and the `tools` list as a tar stream on `Exec`'s input, `sync_failed`). Not ported: `tool_intact` (with the proxy, which builds with Go's image), `tools_not_images_rm` (with `devvm images rm`), the `images` listing of tools (with `devvm images`). `Remove`, `Update`, `WarnNewer`, `Garbage` and `RefreshDaily` have no callers until up for an existing VM, remove, update and gc. Messages: `tools_not_images`, `downloading_mise`, `mise_download_failed`, `mise_checksum`, `resolving_tools`, `tools_resolve_failed`, `tools_need_resolve`, `tool_not_locked`, `tool_stepped_back`, `tool_no_download`, `checking_tools`, `tools_check_failed`, `share_lock_held`, `share_waiting`, `tools_changed`, `tool_unbuilt`, `building_tools`, `building_tools_in`, `tools_build_failed`, `tool_bad_output`, `newer_tools`, `vm_lacks`, `custom_layer_remove`, `tools_newest`, `tools_switch`, `sync_failed`. Bats cases converted: `tools.bats`, all twelve: "need_tool_lock: the first use resolves the versions, once" (`TestLockResolvesOnce`, `tools.txtar`), "mise_arch: …" (`TestMiseArch`), "need_tool_lock: a changed tools/mise.toml …" (`TestLockResolvesAgainWhenConfigChanges`), "need_tool_lock: offline with no lock yet …" (`TestLockOffline`, `tools.txtar`), "tmise: mise reads no config above its temp folder …" (`TestMiseCmdCeiling`), "refresh_tools_daily: at most once a day, in the background" (`TestRefreshDaily`, `TestStartDetached`), "tools_check_due: …" (`TestCheckDue`), "refresh_tools: a tool the newest has no download of steps back …" (`TestRefreshStepsBack`), "refresh_tools: with no older version …" (`TestRefreshStepsBackToNothing`), "has_download: …" (`TestHasDownload`), "no_download: only the VM's own platform counts" (`TestHasDownload`, `TestBuildRefuses`), "refresh_tools: newer versions replace the lock; a failure leaves it" (`TestRefresh`, `tools.txtar`); `build.bats` "image_of and tools_of: …" (`TestWithoutToolsAndToolsOf`), "tool files: the lock's version, and a key …", its `tool_files` half (`TestFiles`), "build: a name with tools builds base and the missing tool images, in one throwaway VM" (`TestBuild` in `internal/tools`, `TestBuildTools` in `internal/build` and `internal/backend/lima`, `tools.txtar`), "build: go builds in a VM of its own …" (`TestBuildGoAlone`), "build: a tools build that leaves a symlink instead of an image is refused" and "… plants FILE.sha256 as a symlink …" (`TestBuildHostileOutput`, `tools.txtar`), "tool files: a locked version that isn't shaped like one is refused" (`TestFiles`), the libc half of "tool files: Alpine (musl) bases get their own tool images" (`TestFiles`, `TestBuildTools`), "build: a tool the lock would build from source …" (`TestBuildRefuses`), the tools half of "build: each phase numbers its steps …" (`tooLine truncated
|
||||
- the shared tools (`internal/tools`, `internal/image`, `internal/build`, `internal/vm`, `internal/backend/lima/tools.go`, `internal/platform`, `devvm _refresh-tools`): `lang_layers`/`agent_layers`/`tool_groups`/`is_group`, `group_tools`, `tools_of`, `image_of` (`WithoutTools`), `normalize`'s toolchain and agent order (`image.Normalize`, moved from `internal/build`), `layer_name_ok`'s tool names, `environments` (`Environments`; `unknown_layer` and `no_image_for` now take `envs` and `agents`, as the bash's `pick_image` listed them), `needs_project_layers` and `resolve_image`'s agents (`needsDetection`), `all_tools`, `host_mise` and its pins (with `DEVVM_HOST_MISE` for tests in place of the unit tests' `host_mise` override; `net/http` and `crypto/sha256` instead of `curl` and `shasum`; a status line while it downloads, `downloading_mise`), `resolve_tools`, `tmise` (`miseCmd`), `lock_platforms`, `mise_arch` (from `GOARCH`, not `uname`), `has_download`, `step_back`, `version_block`, `lock_block`, `need_tool_lock` (`Lock`; a failed resolve is `tools_need_resolve` with the log's end, mise's output being in the run log, instead of `tools_resolve_failed` plus its last 5 lines), `tools_check_due`, `refresh_tools_daily` (`RefreshDaily`: `platform.StartDetached`, `Setsid`, instead of `nohup … &`), `refresh_tools`, `check_tools` (`Check`: `checking_tools` always, the resolve's step on the status line), `lock_entry`, `no_download`, `locked_version`, `tool_file`/`tool_files` (`File`, `Files`), `image_libc` (`Builder.BaseLibc`), `tool_of_file` (already `ParseToolFile`), `share_lock`/`share_unlock` (`LockShare`, a `ui.AddCleanup` instead of the trap), `tool_built` (`Built`), `build_tools` and `tools_batch` (`Tools.Build`; the VM's part through the new `Backend.BuildTools`), `tool_garbage` (`Garbage`, taking the VMs' tool files from its caller), `remove_tools` (`Remove`, pure: its caller sets the state), `update`'s tools part (`Update`), `warn_if_outdated`'s newer tools half (`WarnNewer`), `build`'s tools half, `rebuild_image`'s refusal, and from `up` the tools check, the share mount, `vm_set libc`/`tools`, and `sync_vm`'s tools part (`vm.sync`: `guest/sync.sh`, `guest/tools.sh` and the `tools` list as a tar stream on `Exec`'s input, `sync_failed`). Not ported: `tool_intact` (dropped with the proxy's build: the proxy is part of the binary), `tools_not_images_rm` (with `devvm images rm`), the `images` listing of tools (with `devvm images`). `Remove`, `Update`, `WarnNewer`, `Garbage` and `RefreshDaily` have no callers until up for an existing VM, remove, update and gc. Messages: `tools_not_images`, `downloading_mise`, `mise_download_failed`, `mise_checksum`, `resolving_tools`, `tools_resolve_failed`, `tools_need_resolve`, `tool_not_locked`, `tool_stepped_back`, `tool_no_download`, `checking_tools`, `tools_check_failed`, `share_lock_held`, `share_waiting`, `tools_changed`, `tool_unbuilt`, `building_tools`, `building_tools_in`, `tools_build_failed`, `tool_bad_output`, `newer_tools`, `vm_lacks`, `custom_layer_remove`, `tools_newest`, `tools_switch`, `sync_failed`. Bats cases converted: `tools.bats`, all twelve: "need_tool_lock: the first use resolves the versions, once" (`TestLockResolvesOnce`, `tools.txtar`), "mise_arch: …" (`TestMiseArch`), "need_tool_lock: a changed tools/mise.toml …" (`TestLockResolvesAgainWhenConfigChanges`), "need_tool_lock: offline with no lock yet …" (`TestLockOffline`, `tools.txtar`), "tmise: mise reads no config above its temp folder …" (`TestMiseCmdCeiling`), "refresh_tools_daily: at most once a day, in the background" (`TestRefreshDaily`, `TestStartDetached`), "tools_check_due: …" (`TestCheckDue`), "refresh_tools: a tool the newest has no download of steps back …" (`TestRefreshStepsBack`), "refresh_tools: with no older version …" (`TestRefreshStepsBackToNothing`), "has_download: …" (`TestHasDownload`), "no_download: only the VM's own platform counts" (`TestHasDownload`, `TestBuildRefuses`), "refresh_tools: newer versions replace the lock; a failure leaves it" (`TestRefresh`, `tools.txtar`); `build.bats` "image_of and tools_of: …" (`TestWithoutToolsAndToolsOf`), "tool files: the lock's version, and a key …", its `tool_files` half (`TestFiles`), "build: a name with tools builds base and the missing tool images, in one throwaway VM" (`TestBuild` in `internal/tools`, `TestBuildTools` in `internal/build` and `internal/backend/lima`, `tools.txtar`), "build: go builds in a VM of its own …" (`TestBuildGoAlone`), "build: a tools build that leaves a symlink instead of an image is refused" and "… plants FILE.sha256 as a symlink …" (`TestBuildHostileOutput`, `tools.txtar`), "tool files: a locked version that isn't shaped like one is refused" (`TestFiles`), the libc half of "tool files: Alpine (musl) bases get their own tool images" (`TestFiles`, `TestBuildTools`), "build: a tool the lock would build from source …" (`TestBuildRefuses`), the tools half of "build: each phase numbers iLine truncated
|
||||
|
||||
Bash fixes copied: none yet.
|
||||
@@ -5,6 +5,7 @@ title: Docs
|
||||
- [Commands](commands.md): devvm in a project folder, its options, and the image commands.
|
||||
- [Images and VMs](images.md): base and your layers, which image a VM gets, how images are built and cached, and where devvm keeps its state.
|
||||
- [Security model](security.md): what a VM can and can't reach on your machine.
|
||||
- [Network policy](network.md): the proxy that limits a VM to an allowlist and keeps tokens on the host.
|
||||
- [.git protection](git-protection.md): how a VM is kept from changing what git runs on the host.
|
||||
- [Backends](backends.md): what runs the VMs, what each one can do, and choosing one.
|
||||
- [Lima](lima.md): what devvm sets up in Lima, how it confines VMs, and its limits.
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
---
|
||||
title: Network policy
|
||||
weight: 24
|
||||
---
|
||||
|
||||
A VM with network policy reaches only an allowlist of hosts, through a proxy devvm runs on the host, and never holds your tokens. Network policy isn't available for VMs yet: devvm creates them only with `--no-network-policy` ([commands](commands.md)). The proxy itself is in place, and [Lima's confinement](lima.md#confinement) is what makes it a VM's only way out. This page describes the proxy.
|
||||
|
||||
## The proxy
|
||||
|
||||
One proxy runs per VM, on the host, listening on a loopback port: `devvm _proxy`, a hidden command. The VM reaches nothing else, so every connection it makes goes through the proxy. Other programs on the host can reach the port too, so the port alone doesn't identify the VM: every request must carry the VM's password (`Proxy-Authorization`, user `devvm`), or gets `407`. The proxy refuses to start without one. For each connection it:
|
||||
|
||||
- checks `CONNECT host:port` and absolute-form requests (`GET http://host/…`) against the VM's policy files, then tunnels or forwards allowed ones untouched;
|
||||
- takes only host names (letters, digits, `-`, `_`, `.`) and addresses: anything else gets `400` before the policy or the log sees it;
|
||||
- resolves names itself and dials the addresses it checked, refusing the host's own addresses and internal ones (loopback, private, link-local, multicast, unspecified, CGNAT `100.64.0.0/10` and other ranges that aren't the public internet; a NAT64 address `64:ff9b::a.b.c.d` counts as its IPv4 address) unless a rule names the address;
|
||||
- requires a TLS ClientHello in a tunnel to name the `CONNECT` host (SNI). The `Host` inside isn't seen, so a CDN that routes by it can reach other sites it serves;
|
||||
- for hosts with a bound secret, swaps the placeholder in one header for the real value ([Secrets](#secrets)); everything else passes unread;
|
||||
- logs every decision.
|
||||
|
||||
It exits when the VM's Lima hostagent does (`-lifeline`, the hostagent's pid file), or 15 minutes after starting if the hostagent never appears.
|
||||
|
||||
## Rules
|
||||
|
||||
Policy files hold one rule per line; `#` starts a comment, and matching ignores case.
|
||||
|
||||
| Rule | Matches |
|
||||
| --- | --- |
|
||||
| `example.com` | that host only |
|
||||
| `*.example.com` | any subdomain, at any depth, not `example.com` itself |
|
||||
| `**` | any host |
|
||||
| `10.0.0.5`, `10.0.0.0/8`, `fd00::/8` | addresses, IPv4 or IPv6 (also what lets a connection past the internal-address refusal) |
|
||||
| `RULE:22`, `[fd00::1]:22`, `10.0.0.0/8:8080` | only that port; without a port, 443 and 80 |
|
||||
| `!RULE` | deny: a deny beats any allow |
|
||||
|
||||
A denied address is never dialed, even for an allowed name that resolves to it, or to its NAT64 form. The proxy reads several policy files (`-policy`, comma-separated) as one list, and reads each again when it changes. A missing file has no rules; one that changed but can't be read keeps its last rules, so a deny never lapses.
|
||||
|
||||
## Inside the VM
|
||||
|
||||
A blocked request gets `403`, naming the host, the reason and the rule that would allow it. The proxy also answers at `http://devvm.proxy/`:
|
||||
|
||||
- `/blocked`: the last 50 blocks;
|
||||
- `/blocked/new?after=N`: the number of blocks so far, then those after the Nth, each rule once (for a shell prompt to show what a command hit);
|
||||
- `/ca.pem`: devvm's CA certificate, never its key.
|
||||
|
||||
## Secrets
|
||||
|
||||
For hosts with a bound secret (`-secrets`, a JSON list of bindings: a name, host patterns, a header and the placeholder the VM sends; no values), the proxy intercepts `:443` tunnels instead of passing them through. It terminates TLS with a certificate from devvm's own CA (`-ca`, `-cakey`; ECDSA P-256, valid 30 days, no host name in it), replaces the placeholder in the binding's header (inside `Basic` credentials too) with the real value, and forwards the request over a new TLS connection. Absolute-form `https://` requests get the same. Each request must name the bound host: one that names another gets `421`. The bindings are read again for every request, so removing one applies to tunnels already open.
|
||||
|
||||
Values come from `PROGRAM secret get NAME` (`-secret-cmd`), are cached for 5 minutes (30 seconds for agents' logins) and are never logged. GitHub API calls that would make a credential of their own with the token (an account or deploy key, a runner registration, a webhook) are refused with `403`.
|
||||
|
||||
## Agents' logins and settings
|
||||
|
||||
The proxy also prepares the VM's copies of agents' files on the host, so the VM holds placeholders instead of keys:
|
||||
|
||||
- **Codex** (`~/.codex/auth.json`) **and opencode** (its `auth.json`): the VM's copy holds placeholders (shaped like a JWT where the tools read claims), and the bindings put the host's API key or access token into requests for the provider's hosts: OpenAI (`api.openai.com`, `chatgpt.com` for a ChatGPT login), and for opencode Anthropic, OpenAI and OpenRouter keys and OpenAI and GitHub Copilot logins (not Copilot Enterprise). OAuth tokens are refreshed on the host, one lookup at a time, and written back to the host's file, so a VM never holds a refresh token. Logins devvm doesn't know are copied as they are, with a warning.
|
||||
- **Claude Code's MCP servers** (`~/.claude.json`): an HTTPS server's headers become bindings for its host (a DNS name on port 443 only); env values, plain-HTTP servers' headers, user info and secret-looking values in URLs, and secret-named or key-shaped arguments become `devvm-redacted`. The copy keeps only settings, onboarding and account state, and MCP servers; per-project entries never go.
|
||||
- **Settings files** (JSON, JSONC or Codex's TOML): values under secret-looking keys become `devvm-redacted`, except values that name where a secret is (an environment variable's name, `{env:X}`, `${X}`, a path). TOML multi-line strings are refused rather than copied unread.
|
||||
|
||||
## Logs
|
||||
|
||||
Every decision (`tunnel`, `intercept`, `forward`, `blocked`) is a JSON line with the time, the VM, the host and port, the method and path when seen, the rule or reason, and the names of secrets put in, never their values (`-log`, or standard output). The proxy's own lines (what it loaded, what failed upstream) go to standard error: an upstream error stays there, since it can name addresses the VM shouldn't learn.
|
||||
|
||||
## devvm _proxy
|
||||
|
||||
devvm runs the proxy as itself. Flags take one dash or two; errors end in one line, `network policy proxy: …`.
|
||||
|
||||
| Flag | What |
|
||||
| --- | --- |
|
||||
| `-listen` | the address to listen on (default `127.0.0.1:0`) |
|
||||
| `-vm` | the VM's name, for the log |
|
||||
| `-policy` | the policy files, comma-separated |
|
||||
| `-log` | the JSON-lines event log (default: standard output) |
|
||||
| `-lifeline` | the hostagent's pid file: exit when that process is gone |
|
||||
| `-auth-file` | a file holding the VM's password (in a file because a process's arguments are visible to other users); required |
|
||||
| `-ca`, `-cakey` | devvm's CA, for interception |
|
||||
| `-secrets` | the VM's secret bindings, read again when they change |
|
||||
| `-secret-cmd` | the program run as `PROGRAM secret get NAME` for a value |
|
||||
|
||||
Modes that do one thing and exit:
|
||||
|
||||
| Mode | What |
|
||||
| --- | --- |
|
||||
| `-init-ca DIR` | write a new CA (`ca.pem`, and `ca.key` readable only by you, each written whole) into DIR, unless one with over a week left is there |
|
||||
| `-login codex\|opencode\|claude -login-file F -login-vm` | print the VM's copy of the login file; placeholders end in `-login-salt KEY` (or `$DEVVM_LOGIN_SALT`, which keeps it out of the arguments), so each VM's are its own |
|
||||
| `-login … -login-bindings` | print the login's bindings (JSON, no values); with `-login-hosts`, their hosts as rules (`host:443`) |
|
||||
| `-login claude -login-file F -login-secrets` | print the MCP servers whose settings hold secrets |
|
||||
| `-login … -login-get NAME` | print one value, refreshing an OAuth token when it's due |
|
||||
| `-redact json\|toml` | copy standard input to standard output with secret-looking values replaced, their paths on standard error |
|
||||
|
||||
## Not covered
|
||||
|
||||
Anything an allowed host accepts can carry data out, including what the tokens allow (pushes, API calls).
|
||||
@@ -0,0 +1,48 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/w3cj/devvm/internal/msg"
|
||||
"github.com/w3cj/devvm/internal/proxy"
|
||||
"github.com/w3cj/devvm/internal/ui"
|
||||
)
|
||||
|
||||
// newProxyCmd is devvm _proxy: one VM's network policy proxy, and the
|
||||
// one-shot modes devvm runs it in (-init-ca, -login, -redact). Hidden: it's
|
||||
// not for users. Its flags are the proxy's own (one dash or two), parsed by
|
||||
// proxy.Main; its event log and log lines are data, written to devvm's
|
||||
// stdout and stderr.
|
||||
func newProxyCmd() *cobra.Command {
|
||||
return &cobra.Command{
|
||||
Use: "_proxy [flags]",
|
||||
Short: "Run a VM's network policy proxy",
|
||||
Hidden: true,
|
||||
DisableFlagParsing: true,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
err := proxy.Main(args, proxy.IO{
|
||||
Stdin: cmd.InOrStdin(),
|
||||
Stdout: ui.Stdout(),
|
||||
Stderr: ui.Stderr(),
|
||||
Kept: loginKept,
|
||||
})
|
||||
if err != nil {
|
||||
ui.Die(msg.ProxyFailed(err.Error()))
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// loginKept warns about what of an agent's login file goes into the VM's
|
||||
// copy as it is.
|
||||
func loginKept(agent string, names []string) {
|
||||
list := strings.Join(names, ", ")
|
||||
if agent == "codex" {
|
||||
ui.Warn(msg.CodexLoginKept(list))
|
||||
return
|
||||
}
|
||||
ui.Warn(msg.OpencodeLoginKept(list))
|
||||
}
|
||||
@@ -35,7 +35,7 @@ func NewRoot() *cobra.Command {
|
||||
root.SetOut(ui.Stdout())
|
||||
addGlobals(root, g)
|
||||
addUpFlags(root, u)
|
||||
root.AddCommand(newBuildCmd(g), newRebuildCmd(g), newMsgCmd(), newQEMUCmd(), newRefreshToolsCmd())
|
||||
root.AddCommand(newBuildCmd(g), newRebuildCmd(g), newMsgCmd(), newQEMUCmd(), newProxyCmd(), newRefreshToolsCmd())
|
||||
return root
|
||||
}
|
||||
|
||||
|
||||
@@ -42,6 +42,8 @@ var docs = map[string]string{
|
||||
"port_invalid": "commands#size-and-ports",
|
||||
"no_image_for": "images#which-image-a-new-vm-gets",
|
||||
"network_policy_unavailable": "security#what-it-doesnt-protect",
|
||||
"codex_login_kept": "network#agents-logins-and-settings",
|
||||
"opencode_login_kept": "network#agents-logins-and-settings",
|
||||
"setid_files": "security#what-it-doesnt-protect",
|
||||
"git_protect_needs_macos_new": "git-protection#linux-hosts",
|
||||
"git_commondir": "git-protection#what-a-lock-cant-stop",
|
||||
|
||||
@@ -67,6 +67,11 @@ func CloningImage(parent string) M {
|
||||
return M{id: "cloning_image", vals: []val{{"parent", parent}}}
|
||||
}
|
||||
|
||||
// CodexLoginKept is [codex_login_kept]: "Codex's auth.json {{.keys}} is copied into the VM as it is"
|
||||
func CodexLoginKept(keys string) M {
|
||||
return M{id: "codex_login_kept", vals: []val{{"keys", keys}}}
|
||||
}
|
||||
|
||||
// Configuring is [configuring]: "configuring {{.vm}}"
|
||||
func Configuring(vm string) M {
|
||||
return M{id: "configuring", vals: []val{{"vm", vm}}}
|
||||
@@ -337,11 +342,21 @@ func NothingChanged() M {
|
||||
return M{id: "nothing_changed"}
|
||||
}
|
||||
|
||||
// OpencodeLoginKept is [opencode_login_kept]: "opencode's {{.providers}} login is copied into the VM as it is"
|
||||
func OpencodeLoginKept(providers string) M {
|
||||
return M{id: "opencode_login_kept", vals: []val{{"providers", providers}}}
|
||||
}
|
||||
|
||||
// PortInvalid is [port_invalid]: "{{.value}} isn't a port list: use all, none, or ports and ranges like 5173,8000-8010"
|
||||
func PortInvalid(value string) M {
|
||||
return M{id: "port_invalid", vals: []val{{"value", value}}}
|
||||
}
|
||||
|
||||
// ProxyFailed is [proxy_failed]: "network policy proxy: {{.reason}}"
|
||||
func ProxyFailed(reason string) M {
|
||||
return M{id: "proxy_failed", vals: []val{{"reason", reason}}}
|
||||
}
|
||||
|
||||
// QEMUMissing is [qemu_missing]: "{{.program}} isn't installed: install QEMU"
|
||||
func QEMUMissing(program string) M {
|
||||
return M{id: "qemu_missing", vals: []val{{"program", program}}}
|
||||
@@ -622,6 +637,7 @@ var specs = map[string]spec{
|
||||
"building_tools_in": {fields: []string{"vm"}},
|
||||
"checking_tools": {},
|
||||
"cloning_image": {fields: []string{"parent"}},
|
||||
"codex_login_kept": {fields: []string{"keys"}},
|
||||
"configuring": {fields: []string{"vm"}},
|
||||
"continue": {},
|
||||
"cpus_not_number": {fields: []string{"value"}},
|
||||
@@ -676,7 +692,9 @@ var specs = map[string]spec{
|
||||
"no_ubuntu_image": {fields: []string{"url", "version"}},
|
||||
"not_an_image": {fields: []string{"name"}},
|
||||
"nothing_changed": {},
|
||||
"opencode_login_kept": {fields: []string{"providers"}},
|
||||
"port_invalid": {fields: []string{"value"}},
|
||||
"proxy_failed": {fields: []string{"reason"}},
|
||||
"qemu_missing": {fields: []string{"program"}},
|
||||
"qemu_refused": {},
|
||||
"rebuild_replaces": {fields: []string{"above", "image"}},
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
# internal/proxy
|
||||
|
||||
The network policy proxy: one process per VM with [network policy](../../docs/content/docs/network.md), on the host, run as `devvm _proxy`. Go, standard library only (depguard enforces it).
|
||||
|
||||
The VM can reach nothing but this proxy (on macOS its Lima hostagent runs under a Seatbelt profile, on Linux QEMU's network is restricted). Other programs on the host can reach the port too, so the port alone doesn't identify the VM: every request must carry the VM's password (`Proxy-Authorization`, user `devvm`; the VM's proxy URL has it), and the VM's placeholders end in a random value of its own (not the password), so no other VM's or program's placeholder gets a token. It refuses to start without `-auth-file`. For each connection it:
|
||||
|
||||
- answers `407` without the VM's password;
|
||||
- checks `CONNECT host:port` and absolute-form requests (`GET http://host/…`) against the VM's policy files, then tunnels or forwards allowed ones untouched;
|
||||
- resolves names itself, and refuses the host's own addresses and internal ones (loopback, private, link-local, multicast, unspecified, CGNAT `100.64.0.0/10`) unless a rule names the address;
|
||||
- requires a TLS ClientHello in a tunnel to name the CONNECT host (SNI);
|
||||
- for hosts with a bound secret, swaps the placeholder in one header for the real value: it intercepts their `:443` tunnels, and does the same for absolute-form `https://` requests (everything else passes unread);
|
||||
- logs every decision as JSON lines.
|
||||
|
||||
It returns when the VM's hostagent is gone.
|
||||
|
||||
## Files
|
||||
|
||||
| File | What |
|
||||
|---|---|
|
||||
| `proxy.go` | `Main` and the flags, the listener, CONNECT and absolute-form handling, the address floor, the log, the `devvm.proxy` endpoints, `-init-ca` |
|
||||
| `policy.go` | the rule syntax and matching; policy files are re-read when they change |
|
||||
| `sni.go` | reads a tunnel's ClientHello to check its server name |
|
||||
| `secrets.go` | interception for hosts with a bound secret: certificates from devvm's CA, header substitution, values from `-secret-cmd` (cached briefly, never logged) |
|
||||
| `logins.go` | Codex and opencode logins, and Claude Code's MCP secrets (`~/.claude.json`): the VM's copy with placeholders, bindings, and OAuth refresh on the host |
|
||||
| `redact.go` | agents' settings files (`settings.json`, `config.toml`, opencode's config) for VMs with network policy: values under secret-looking keys replaced |
|
||||
| `*_test.go` | unit tests, and fuzz targets for policy rules (`FuzzParseRule`), request targets (`FuzzRequest`) and ClientHellos (`FuzzClientHello`) |
|
||||
|
||||
## How devvm runs it
|
||||
|
||||
`internal/cli/proxy.go` is the hidden `devvm _proxy` command: it hands its arguments to `Main` with devvm's streams (`IO`: the event log and data on `ui.Stdout`, the proxy's own log lines on `ui.Stderr`), warns through `ui` about logins copied as they are (`IO.Kept`), and ends an error with `ui.Die`. The package itself prints nothing.
|
||||
|
||||
```text
|
||||
devvm _proxy -listen 127.0.0.1:PORT -vm NAME -policy FILE,FILE,… -log LOG.jsonl -lifeline HA.pid \
|
||||
-ca ca.pem -cakey ca.key -secrets BINDINGS.json -secret-cmd PATH/TO/devvm -auth-file KEY
|
||||
```
|
||||
|
||||
Flags take one dash or two.
|
||||
|
||||
| Flag | What |
|
||||
|---|---|
|
||||
| `-listen` | the VM's proxy port, on loopback |
|
||||
| `-vm` | the VM's name, for the log |
|
||||
| `-policy` | the policy files, comma-separated, in order; a missing file has no rules |
|
||||
| `-log` | the JSON-lines event log; default stdout |
|
||||
| `-lifeline` | the hostagent's pid file: return when that process is gone |
|
||||
| `-ca`, `-cakey` | devvm's CA, for interception |
|
||||
| `-secrets` | the VM's secret bindings (JSON, no values), re-read when they change |
|
||||
| `-secret-cmd` | the `devvm` binary, run as `devvm secret get NAME` for a value |
|
||||
| `-auth-file` | a file (mode 600) with the VM's key: requests need it as the proxy password, user `devvm` (in a file because a process's arguments are visible to other users) |
|
||||
|
||||
Other modes, each doing one thing and returning:
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| `-init-ca DIR` | write a new CA (`ca.pem`, `ca.key`, each written whole; valid 30 days; no host name in it) into DIR unless one with over a week left is there |
|
||||
| `-login claude -login-file F -login-secrets` | print the MCP servers in `~/.claude.json` whose settings hold env values or headers |
|
||||
| `-login codex\|opencode\|claude -login-file F -login-vm` | print the VM's copy of the login file, with placeholders (`-login-salt KEY`, or `$DEVVM_LOGIN_SALT`, which keeps it out of the arguments: the VM's random salt, which ends them) |
|
||||
| `-login … -login-bindings` | print the login's secret bindings (JSON, no values; `-login-salt` as above); with `-login-hosts`, their hosts as allowlist lines (`host:443`) |
|
||||
| `-login … -login-get NAME` | print one value, refreshing an OAuth token when it's due |
|
||||
| `-redact json\|toml` | copy stdin to stdout with values under secret-looking keys replaced by `devvm-redacted`, their paths on stderr |
|
||||
|
||||
Inside the VM, `http://devvm.proxy/blocked` lists recent blocks, `/blocked/new` those since the last prompt, and `/ca.pem` serves the CA certificate.
|
||||
|
||||
## Testing
|
||||
|
||||
`go test ./internal/proxy` runs the unit tests and the fuzz targets' seeds; `go test -fuzz FuzzRequest ./internal/proxy` fuzzes one. `testdata/script/proxy.txtar` runs `devvm _proxy` itself.
|
||||
@@ -0,0 +1,764 @@
|
||||
package proxy
|
||||
|
||||
// Agent logins kept on the host: Codex (~/.codex/auth.json) and opencode
|
||||
// (~/.local/share/opencode/auth.json). A VM with network policy gets its own copy of the file with
|
||||
// placeholders instead of keys and tokens; the proxy puts the real ones into requests for each
|
||||
// provider's hosts (secrets.go). OAuth access tokens are refreshed here, on the host, and written
|
||||
// back to the host's file, so the host's login keeps working: a VM never holds a refresh token, so
|
||||
// it can't rotate one away.
|
||||
//
|
||||
// devvm _proxy -login codex|opencode -login-file F -login-vm the VM's copy, with placeholders
|
||||
// devvm _proxy -login codex|opencode -login-file F -login-bindings its bindings (JSON, no values)
|
||||
// ... -login-bindings -login-hosts their hosts, as allowlist lines
|
||||
// devvm _proxy -login codex|opencode -login-file F -login-get NAME one value, refreshed when due
|
||||
//
|
||||
// Formats (checked against upstream, 2026-10): Codex keeps OPENAI_API_KEY or tokens{id_token,
|
||||
// access_token, refresh_token, account_id} plus last_refresh; it decodes id_token's claims and
|
||||
// access_token's exp (never the signatures) and refreshes 5 minutes before exp. opencode keeps one
|
||||
// entry per provider: {"type":"api","key"} or {"type":"oauth","access","refresh","expires" (ms)}.
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
// OpenAI's OAuth token endpoint and Codex's public client ID (opencode uses the same one).
|
||||
openaiTokenURL = "https://auth.openai.com/oauth/token" //nolint:gosec // a URL, not a secret
|
||||
openaiClientID = "app_EMoamEEZ73f0CkXaXp7hrann" //nolint:gosec // a public client ID, not a secret
|
||||
// Refresh this long before an access token expires: the proxy caches values for valueTTL.
|
||||
refreshMargin = 10 * time.Minute
|
||||
farFuture = time.Date(2099, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||
httpClient = &http.Client{Timeout: 30 * time.Second}
|
||||
// -login-salt: the VM's key, which ends every placeholder, so each VM's are its own (a proxy
|
||||
// only puts a value in for the placeholders bound for its VM).
|
||||
loginSalt = ""
|
||||
// -login-secrets (claude): print the MCP servers whose settings hold secrets, one per line.
|
||||
loginSecrets = false
|
||||
// -login-hosts: print the bindings' hosts as policy lines (host:443), one per line.
|
||||
loginHosts = false
|
||||
// warnKept is IO.Kept: told what the VM's copy holds as it is.
|
||||
warnKept func(agent string, names []string)
|
||||
)
|
||||
|
||||
// salted: a placeholder made the VM's own.
|
||||
func salted(ph string) string {
|
||||
if loginSalt == "" {
|
||||
return ph
|
||||
}
|
||||
return ph + "-" + loginSalt
|
||||
}
|
||||
|
||||
// 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).
|
||||
type provider struct {
|
||||
hosts []string
|
||||
header string
|
||||
}
|
||||
|
||||
var opencodeAPI = map[string]provider{
|
||||
"anthropic": {[]string{"api.anthropic.com"}, "x-api-key"},
|
||||
"openai": {[]string{"api.openai.com"}, "Authorization"},
|
||||
"openrouter": {[]string{"openrouter.ai"}, "Authorization"},
|
||||
}
|
||||
|
||||
var opencodeOAuth = map[string]provider{
|
||||
"openai": {[]string{"chatgpt.com"}, "Authorization"},
|
||||
"github-copilot": {[]string{"api.githubcopilot.com"}, "Authorization"},
|
||||
}
|
||||
|
||||
func readJSON(path string) (map[string]any, error) {
|
||||
data, err := os.ReadFile(path) //nolint:gosec // devvm names the login file
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
d := json.NewDecoder(bytes.NewReader(data))
|
||||
d.UseNumber()
|
||||
var m map[string]any
|
||||
if err := d.Decode(&m); err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", path, err)
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// lockLogin holds an exclusive lock on the login file's folder while a lookup reads, refreshes and
|
||||
// writes it back: VMs each have a proxy, and two refreshing with the same (rotating) refresh token
|
||||
// would lose one result or get the login revoked. It returns the unlock.
|
||||
func lockLogin(path string) (func(), error) {
|
||||
d, err := os.Open(filepath.Dir(path))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := syscall.Flock(int(d.Fd()), syscall.LOCK_EX); err != nil { //nolint:gosec // file descriptors fit in an int
|
||||
_ = d.Close()
|
||||
return nil, err
|
||||
}
|
||||
return func() { _ = syscall.Flock(int(d.Fd()), syscall.LOCK_UN); _ = d.Close() }, nil //nolint:gosec // as above
|
||||
}
|
||||
|
||||
// writeJSON replaces path atomically, keeping it mode 600.
|
||||
func writeJSON(path string, m map[string]any) error {
|
||||
data, err := json.MarshalIndent(m, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmp, err := os.CreateTemp(filepath.Dir(path), ".devvm-login-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.Remove(tmp.Name())
|
||||
if _, err := tmp.Write(append(data, '\n')); err != nil {
|
||||
_ = tmp.Close()
|
||||
return err
|
||||
}
|
||||
if err := tmp.Chmod(0o600); err != nil {
|
||||
_ = tmp.Close()
|
||||
return err
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmp.Name(), path)
|
||||
}
|
||||
|
||||
// writeRefreshed writes a login just refreshed: the old refresh token may no longer work, so a
|
||||
// failed write (a full disk for a moment, say) is tried again before giving up.
|
||||
func writeRefreshed(path string, m map[string]any) error {
|
||||
var err error
|
||||
for i := 0; i < 3; i++ {
|
||||
if err = writeJSON(path, m); err == nil {
|
||||
return nil
|
||||
}
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func str(m map[string]any, k string) string { s, _ := m[k].(string); return s }
|
||||
func obj(m map[string]any, k string) map[string]any {
|
||||
o, _ := m[k].(map[string]any)
|
||||
return o
|
||||
}
|
||||
|
||||
// --- JWTs (never verified: only read for claims, or made up as placeholders) ---
|
||||
|
||||
func jwtClaims(tok string) map[string]any {
|
||||
parts := strings.Split(tok, ".")
|
||||
if len(parts) != 3 {
|
||||
return nil
|
||||
}
|
||||
raw, err := base64.RawURLEncoding.DecodeString(parts[1])
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var c map[string]any
|
||||
if json.Unmarshal(raw, &c) != nil {
|
||||
return nil
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func jwtExp(tok string) (time.Time, bool) {
|
||||
exp, ok := jwtClaims(tok)["exp"].(float64)
|
||||
return time.Unix(int64(exp), 0), ok
|
||||
}
|
||||
|
||||
// fakeJWT: a JWT-shaped placeholder with these claims and no real signature. Deterministic, so the
|
||||
// same claims give the same placeholder (bindings name it).
|
||||
func fakeJWT(claims map[string]any) string {
|
||||
enc := func(v any) string { b, _ := json.Marshal(v); return base64.RawURLEncoding.EncodeToString(b) }
|
||||
return enc(map[string]string{"alg": "none", "typ": "JWT"}) + "." + enc(claims) + ".devvm-placeholder"
|
||||
}
|
||||
|
||||
// The account claims Codex and opencode read from tokens, without anything that grants access.
|
||||
func accountClaims(tok string) map[string]any {
|
||||
c := jwtClaims(tok)
|
||||
out := map[string]any{"exp": farFuture.Unix(), "devvm": salted("placeholder")}
|
||||
if a, ok := c["https://api.openai.com/auth"]; ok {
|
||||
out["https://api.openai.com/auth"] = a
|
||||
}
|
||||
for _, k := range []string{"email", "https://api.openai.com/profile", "chatgpt_account_id"} {
|
||||
if v, ok := c[k]; ok {
|
||||
out[k] = v
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// --- Codex ---
|
||||
|
||||
func codexBindings(m map[string]any) []binding {
|
||||
var bs []binding
|
||||
if str(m, "OPENAI_API_KEY") != "" {
|
||||
bs = append(bs, binding{Name: "codex-key", Hosts: []string{"api.openai.com"}, Header: "Authorization", Placeholder: salted("sk-devvm-proxy-managed-codex")})
|
||||
}
|
||||
if t := obj(m, "tokens"); str(t, "access_token") != "" {
|
||||
bs = append(bs, binding{
|
||||
Name: "codex", Hosts: []string{"chatgpt.com", "api.openai.com"}, Header: "Authorization",
|
||||
Placeholder: fakeJWT(accountClaims(str(t, "access_token"))),
|
||||
})
|
||||
}
|
||||
return bs
|
||||
}
|
||||
|
||||
// codexKnown: auth.json's keys codexVM knows. Others are copied as they are, and named.
|
||||
var codexKnown = map[string]bool{"OPENAI_API_KEY": true, "tokens": true, "last_refresh": true, "auth_mode": true}
|
||||
|
||||
func codexOthers(m map[string]any) []string {
|
||||
var others []string
|
||||
for k := range m {
|
||||
if !codexKnown[k] {
|
||||
others = append(others, k)
|
||||
}
|
||||
}
|
||||
sort.Strings(others)
|
||||
return others
|
||||
}
|
||||
|
||||
func codexVM(m map[string]any) map[string]any {
|
||||
bs := codexBindings(m)
|
||||
t := obj(m, "tokens")
|
||||
idClaims := accountClaims(str(t, "id_token"))
|
||||
// Every token goes, bound or not (a login without an access token still has the others).
|
||||
for _, k := range []string{"id_token", "refresh_token", "access_token"} {
|
||||
if str(t, k) != "" {
|
||||
t[k] = "devvm-proxy-managed"
|
||||
}
|
||||
}
|
||||
for _, b := range bs {
|
||||
switch b.Name {
|
||||
case "codex-key":
|
||||
m["OPENAI_API_KEY"] = b.Placeholder
|
||||
case "codex":
|
||||
t["id_token"] = fakeJWT(idClaims)
|
||||
t["access_token"] = b.Placeholder
|
||||
// Just refreshed, as far as the VM's Codex can tell: it never tries.
|
||||
m["last_refresh"] = time.Now().UTC().Format(time.RFC3339)
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func codexGet(path, name string) (string, error) {
|
||||
unlock, err := lockLogin(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer unlock()
|
||||
m, err := readJSON(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
switch name {
|
||||
case "codex-key":
|
||||
if k := str(m, "OPENAI_API_KEY"); k != "" {
|
||||
return k, nil
|
||||
}
|
||||
return "", errors.New("Codex isn't logged in with an API key on this machine") //nolint:staticcheck // Codex is a name
|
||||
case "codex":
|
||||
t := obj(m, "tokens")
|
||||
if str(t, "access_token") == "" {
|
||||
return "", errors.New("Codex isn't logged in with ChatGPT on this machine") //nolint:staticcheck // Codex is a name
|
||||
}
|
||||
if exp, ok := jwtExp(str(t, "access_token")); ok && time.Until(exp) > refreshMargin {
|
||||
return str(t, "access_token"), nil
|
||||
}
|
||||
nt, err := refresh(openaiTokenURL, false, map[string]string{
|
||||
"grant_type": "refresh_token", "client_id": openaiClientID, "refresh_token": str(t, "refresh_token"),
|
||||
})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("refreshing Codex's login: %w (run codex on this machine to log in again)", err)
|
||||
}
|
||||
for _, k := range []string{"id_token", "access_token", "refresh_token"} {
|
||||
if v := str(nt, k); v != "" {
|
||||
t[k] = v
|
||||
}
|
||||
}
|
||||
m["last_refresh"] = time.Now().UTC().Format(time.RFC3339)
|
||||
return str(t, "access_token"), writeRefreshed(path, m)
|
||||
}
|
||||
return "", fmt.Errorf("no Codex login %q", name)
|
||||
}
|
||||
|
||||
// --- opencode ---
|
||||
|
||||
func opencodeBindings(m map[string]any) []binding {
|
||||
var bs []binding
|
||||
for id := range m {
|
||||
e := obj(m, id)
|
||||
var p provider
|
||||
var ok bool
|
||||
switch str(e, "type") {
|
||||
case "api":
|
||||
p, ok = opencodeAPI[id]
|
||||
case "oauth":
|
||||
p, ok = opencodeOAuth[id]
|
||||
ok = ok && str(e, "enterpriseUrl") == ""
|
||||
}
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
ph := salted("devvm-proxy-managed-opencode-" + id)
|
||||
if id == "openai" && str(e, "type") == "oauth" {
|
||||
ph = fakeJWT(accountClaims(str(e, "access"))) // opencode reads the account from it
|
||||
}
|
||||
bs = append(bs, binding{Name: "opencode-" + id, Hosts: p.hosts, Header: p.header, Placeholder: ph})
|
||||
}
|
||||
return bs
|
||||
}
|
||||
|
||||
func opencodeVM(m map[string]any) map[string]any {
|
||||
for _, b := range opencodeBindings(m) {
|
||||
e := obj(m, strings.TrimPrefix(b.Name, "opencode-"))
|
||||
if str(e, "type") == "api" {
|
||||
e["key"] = b.Placeholder
|
||||
continue
|
||||
}
|
||||
e["access"] = b.Placeholder
|
||||
e["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.UnixMilli()
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// Providers whose logins the VM's copy still holds as they are.
|
||||
func opencodeOthers(m map[string]any) []string {
|
||||
known := map[string]bool{}
|
||||
for _, b := range opencodeBindings(m) {
|
||||
known[strings.TrimPrefix(b.Name, "opencode-")] = true
|
||||
}
|
||||
var out []string
|
||||
for id := range m {
|
||||
if !known[id] {
|
||||
out = append(out, id)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func opencodeGet(path, name string) (string, error) {
|
||||
unlock, err := lockLogin(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer unlock()
|
||||
m, err := readJSON(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
id := strings.TrimPrefix(name, "opencode-")
|
||||
e := obj(m, id)
|
||||
switch str(e, "type") {
|
||||
case "api":
|
||||
return str(e, "key"), nil
|
||||
case "oauth":
|
||||
if id == "github-copilot" {
|
||||
return str(e, "refresh"), nil // a GitHub token, never refreshed
|
||||
}
|
||||
exp, _ := e["expires"].(json.Number)
|
||||
ms, _ := exp.Int64()
|
||||
if str(e, "access") != "" && time.Until(time.UnixMilli(ms)) > refreshMargin {
|
||||
return str(e, "access"), nil
|
||||
}
|
||||
nt, err := refresh(openaiTokenURL, true, map[string]string{
|
||||
"grant_type": "refresh_token", "client_id": openaiClientID, "refresh_token": str(e, "refresh"),
|
||||
})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("refreshing opencode's %s login: %w (log in again with opencode on this machine)", id, err)
|
||||
}
|
||||
e["access"] = str(nt, "access_token")
|
||||
if v := str(nt, "refresh_token"); v != "" {
|
||||
e["refresh"] = v
|
||||
}
|
||||
secs := 3600.0
|
||||
if v, ok := nt["expires_in"].(float64); ok {
|
||||
secs = v
|
||||
}
|
||||
e["expires"] = time.Now().Add(time.Duration(secs) * time.Second).UnixMilli()
|
||||
return str(e, "access"), writeRefreshed(path, m)
|
||||
}
|
||||
return "", fmt.Errorf("no opencode login %q", id)
|
||||
}
|
||||
|
||||
// refresh posts an OAuth refresh request, as JSON (Codex) or a form (opencode).
|
||||
func refresh(u string, form bool, fields map[string]string) (map[string]any, error) {
|
||||
var body []byte
|
||||
ctype := "application/json"
|
||||
if form {
|
||||
v := url.Values{}
|
||||
for k, f := range fields {
|
||||
v.Set(k, f)
|
||||
}
|
||||
body, ctype = []byte(v.Encode()), "application/x-www-form-urlencoded"
|
||||
} else {
|
||||
body, _ = json.Marshal(fields)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(context.Background(), http.MethodPost, u, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", ctype)
|
||||
resp, err := httpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("%s: %s", u, resp.Status)
|
||||
}
|
||||
var out map[string]any
|
||||
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if str(out, "access_token") == "" {
|
||||
return nil, errors.New("no access_token in the reply")
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// --- Claude Code: MCP servers' secrets in ~/.claude.json ---
|
||||
//
|
||||
// `claude mcp add -s user` keeps a server's env values (stdio servers) and HTTP headers (remote
|
||||
// servers) in ~/.claude.json, in plain text. The VM's copy gets placeholders instead. An HTTPS
|
||||
// server's header becomes a binding for its host, so the proxy puts the real value in (read from
|
||||
// the host's file each time); env values can't be put in by a proxy, so stdio servers that need them
|
||||
// don't get them. Per-project entries (.projects) never go to VMs.
|
||||
|
||||
// The MCP servers, sorted by name, and each one's settings.
|
||||
func claudeServers(m map[string]any) ([]string, map[string]any) {
|
||||
servers := obj(m, "mcpServers")
|
||||
names := make([]string, 0, len(servers))
|
||||
for n := range servers {
|
||||
names = append(names, n)
|
||||
}
|
||||
sort.Strings(names)
|
||||
return names, servers
|
||||
}
|
||||
|
||||
func sortedKeys(m map[string]any) []string {
|
||||
ks := make([]string, 0, len(m))
|
||||
for k := range m {
|
||||
ks = append(ks, k)
|
||||
}
|
||||
sort.Strings(ks)
|
||||
return ks
|
||||
}
|
||||
|
||||
// claudeBindingName: a binding's name from its server and header (names are free text; this is
|
||||
// safe to pass to `devvm secret get`).
|
||||
func claudeBindingName(server, header string) string {
|
||||
h := sha256.Sum256([]byte(server + "\x00" + strings.ToLower(header)))
|
||||
return "claude-mcp-" + hex.EncodeToString(h[:6])
|
||||
}
|
||||
|
||||
// claudeHost: the host of an HTTPS server on the default port (where the proxy intercepts), or "".
|
||||
func claudeHost(s map[string]any) string {
|
||||
u, err := url.Parse(str(s, "url"))
|
||||
if err != nil || u.Scheme != "https" || (u.Port() != "" && u.Port() != "443") {
|
||||
return ""
|
||||
}
|
||||
// A name only: it goes into the VM's allowlist, where an address, a wildcard or a range would
|
||||
// open more than the one server.
|
||||
h := strings.TrimSuffix(strings.ToLower(u.Hostname()), ".")
|
||||
if _, err := netip.ParseAddr(h); err != nil && hostOK(h) && strings.Contains(h, ".") {
|
||||
return h
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func claudeBindings(m map[string]any) []binding {
|
||||
var bs []binding
|
||||
names, servers := claudeServers(m)
|
||||
for _, n := range names {
|
||||
s := obj(servers, n)
|
||||
host := claudeHost(s)
|
||||
if host == "" {
|
||||
continue
|
||||
}
|
||||
for _, h := range sortedKeys(obj(s, "headers")) {
|
||||
name := claudeBindingName(n, h)
|
||||
bs = append(bs, binding{Name: name, Hosts: []string{host}, Header: h, Placeholder: salted("devvm-proxy-managed-" + name)})
|
||||
}
|
||||
}
|
||||
return bs
|
||||
}
|
||||
|
||||
// claudeSecrets: the servers whose settings hold values the VM's copy replaces.
|
||||
func claudeSecrets(m map[string]any) []string {
|
||||
var out []string
|
||||
names, servers := claudeServers(m)
|
||||
for _, n := range names {
|
||||
s := obj(servers, n)
|
||||
if len(obj(s, "env")) > 0 || len(obj(s, "headers")) > 0 || scrubURL(str(s, "url")) != str(s, "url") ||
|
||||
argsHoldSecrets(s["args"]) {
|
||||
out = append(out, n)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// What of ~/.claude.json the VM's copy keeps: settings, onboarding and account state (not
|
||||
// credentials), and MCP servers. Anything else (primaryApiKey, keys a later Claude Code adds) stays
|
||||
// on the host; the VM keeps its own value of it.
|
||||
var claudeTopKeys = map[string]bool{
|
||||
"mcpServers": true, "hasCompletedOnboarding": true, "lastOnboardingVersion": true, "theme": true,
|
||||
"editorMode": true, "verbose": true, "autoCompactEnabled": true, "preferredNotifChannel": true,
|
||||
"messageIdleNotifThresholdMs": true, "shiftEnterKeyBindingInstalled": true, "optionAsMetaKeyInstalled": true,
|
||||
"hasAcknowledgedCostThreshold": true, "bypassPermissionsModeAccepted": true, "hasSeenTasksHint": true,
|
||||
"hasUsedBackslashReturn": true, "oauthAccount": true, "userID": true, "numStartups": true,
|
||||
"firstStartTime": true, "tipsHistory": true, "isQualifiedForDataSharing": true, "hasIdeOnboardingBeenShown": true,
|
||||
"lastReleaseNotesSeen": true, "subscriptionNoticeCount": true, "hasAvailableSubscription": true,
|
||||
"diffTool": true, "todoFeatureEnabled": true, "showExpandedTodos": true, "autoConnectIde": true,
|
||||
"autoInstallIdeExtension": true, "fallbackAvailableWarningThreshold": true,
|
||||
}
|
||||
|
||||
// An MCP server's settings the VM's copy keeps (oauth: only its client ID and callback port).
|
||||
var claudeServerKeys = map[string]bool{
|
||||
"type": true, "url": true, "command": true, "args": true, "env": true,
|
||||
"headers": true, "headersHelper": true, "oauth": true,
|
||||
}
|
||||
|
||||
// Secret-looking names (query parameters, flags) and values (known key shapes, long random strings).
|
||||
var (
|
||||
secretName = regexp.MustCompile(`(?i)(key|token|secret|passw|pwd|auth|bearer|credential|session|sig)`)
|
||||
secretShape = regexp.MustCompile(`^(sk-|sk_|pk_|rk_|ghp_|gho_|ghs_|ghu_|github_pat_|glpat-|xox[abpr]-|AKIA|ASIA|AIza|ya29\.|eyJ)`)
|
||||
uuidShape = regexp.MustCompile(`(?i)^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`)
|
||||
tokenShape = regexp.MustCompile(`^[A-Za-z0-9_\-+=~]{24,}$`)
|
||||
)
|
||||
|
||||
// secretLike: v looks like a key or token: a known prefix, a UUID, or 24+ token characters mixing
|
||||
// letters and digits.
|
||||
func secretLike(v string) bool {
|
||||
if secretShape.MatchString(v) || uuidShape.MatchString(v) {
|
||||
return true
|
||||
}
|
||||
return tokenShape.MatchString(v) && strings.ContainsAny(v, "0123456789") &&
|
||||
strings.ContainsAny(strings.ToLower(v), "abcdefghijklmnopqrstuvwxyz")
|
||||
}
|
||||
|
||||
// scrubURL: the URL without user info, and with secret-looking query values and path segments
|
||||
// replaced (the VM's copy can't have a placeholder there: the proxy only fills in headers).
|
||||
func scrubURL(raw string) string {
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil || raw == "" {
|
||||
return raw
|
||||
}
|
||||
changed := false
|
||||
if u.User != nil {
|
||||
u.User = nil
|
||||
changed = true
|
||||
}
|
||||
if u.RawQuery != "" {
|
||||
q := u.Query()
|
||||
for k, vs := range q {
|
||||
for i, v := range vs {
|
||||
if v != "" && (secretName.MatchString(k) || secretLike(v)) {
|
||||
vs[i] = "devvm-redacted"
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
q[k] = vs
|
||||
}
|
||||
u.RawQuery = q.Encode()
|
||||
}
|
||||
segs := strings.Split(u.Path, "/")
|
||||
for i, s := range segs {
|
||||
if secretLike(s) {
|
||||
segs[i] = "devvm-redacted"
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
return raw
|
||||
}
|
||||
u.Path, u.RawPath = strings.Join(segs, "/"), ""
|
||||
return u.String()
|
||||
}
|
||||
|
||||
// scrubArgs: a server's arguments with secret values replaced: after a secret-named flag
|
||||
// (--api-key X), in --flag=X with one, and any that look like a key.
|
||||
func scrubArgs(v any) (any, bool) {
|
||||
as, ok := v.([]any)
|
||||
if !ok {
|
||||
return v, false
|
||||
}
|
||||
out, changed := make([]any, len(as)), false
|
||||
for i, a := range as {
|
||||
out[i] = a
|
||||
s, ok := a.(string)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
var prev string
|
||||
if i > 0 {
|
||||
prev, _ = as[i-1].(string)
|
||||
}
|
||||
switch {
|
||||
case strings.HasPrefix(prev, "-") && !strings.Contains(prev, "=") && secretName.MatchString(prev) && !strings.HasPrefix(s, "-"):
|
||||
out[i], changed = "devvm-redacted", true
|
||||
case strings.HasPrefix(s, "-") && strings.Contains(s, "="):
|
||||
if k, val, _ := strings.Cut(s, "="); val != "" && (secretName.MatchString(k) || secretLike(val)) {
|
||||
out[i], changed = k+"=devvm-redacted", true
|
||||
}
|
||||
case secretLike(s):
|
||||
out[i], changed = "devvm-redacted", true
|
||||
}
|
||||
}
|
||||
return out, changed
|
||||
}
|
||||
|
||||
func argsHoldSecrets(v any) bool { _, changed := scrubArgs(v); return changed }
|
||||
|
||||
func claudeVM(m map[string]any) map[string]any {
|
||||
for k := range m {
|
||||
if !claudeTopKeys[k] {
|
||||
delete(m, k)
|
||||
}
|
||||
}
|
||||
names, servers := claudeServers(m)
|
||||
for _, n := range names {
|
||||
s := obj(servers, n)
|
||||
if s == nil {
|
||||
delete(servers, n)
|
||||
continue
|
||||
}
|
||||
for k := range s {
|
||||
if !claudeServerKeys[k] {
|
||||
delete(s, k)
|
||||
}
|
||||
}
|
||||
if o := obj(s, "oauth"); o != nil {
|
||||
for k := range o {
|
||||
if k != "clientId" && k != "callbackPort" {
|
||||
delete(o, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
if u, ok := s["url"].(string); ok {
|
||||
s["url"] = scrubURL(u)
|
||||
}
|
||||
if a, ok := s["args"]; ok {
|
||||
s["args"], _ = scrubArgs(a)
|
||||
}
|
||||
for k := range obj(s, "env") {
|
||||
obj(s, "env")[k] = "devvm-redacted"
|
||||
}
|
||||
https := claudeHost(s) != ""
|
||||
for _, h := range sortedKeys(obj(s, "headers")) {
|
||||
if https {
|
||||
obj(s, "headers")[h] = salted("devvm-proxy-managed-" + claudeBindingName(n, h))
|
||||
} else {
|
||||
obj(s, "headers")[h] = "devvm-redacted"
|
||||
}
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func claudeGet(path, name string) (string, error) {
|
||||
m, err := readJSON(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
names, servers := claudeServers(m)
|
||||
for _, n := range names {
|
||||
hs := obj(obj(servers, n), "headers")
|
||||
for _, h := range sortedKeys(hs) {
|
||||
if claudeBindingName(n, h) == name {
|
||||
return str(hs, h), nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("no MCP server header %s in %s", name, path)
|
||||
}
|
||||
|
||||
// loginCmd runs the -login subcommands; it returns what to print.
|
||||
func loginCmd(kind, path string, vm, bindingsOnly bool, get string) (string, error) {
|
||||
if get != "" {
|
||||
switch kind {
|
||||
case "codex":
|
||||
return codexGet(path, get)
|
||||
case "claude":
|
||||
return claudeGet(path, get)
|
||||
}
|
||||
return opencodeGet(path, get)
|
||||
}
|
||||
m, err := readJSON(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
var bs []binding
|
||||
switch kind {
|
||||
case "codex":
|
||||
bs = codexBindings(m)
|
||||
case "opencode":
|
||||
bs = opencodeBindings(m)
|
||||
case "claude":
|
||||
bs = claudeBindings(m)
|
||||
if loginSecrets {
|
||||
return strings.Join(claudeSecrets(m), "\n"), nil
|
||||
}
|
||||
default:
|
||||
return "", fmt.Errorf("unknown login kind %q", kind)
|
||||
}
|
||||
if bindingsOnly && loginHosts {
|
||||
// What the allowlist gets for them: each host on 443 only, since a binding is only
|
||||
// intercepted there.
|
||||
var lines []string
|
||||
seen := map[string]bool{}
|
||||
for _, b := range bs {
|
||||
for _, h := range b.Hosts {
|
||||
if l := h + ":443"; !seen[l] {
|
||||
seen[l] = true
|
||||
lines = append(lines, l)
|
||||
}
|
||||
}
|
||||
}
|
||||
return strings.Join(lines, "\n"), nil
|
||||
}
|
||||
if bindingsOnly {
|
||||
b, _ := json.Marshal(bs)
|
||||
if bs == nil {
|
||||
b = []byte("[]")
|
||||
}
|
||||
return string(b), nil
|
||||
}
|
||||
if !vm {
|
||||
return "", errors.New("-login needs -login-vm, -login-bindings or -login-get")
|
||||
}
|
||||
switch kind {
|
||||
case "codex":
|
||||
if others := codexOthers(m); len(others) > 0 && warnKept != nil {
|
||||
warnKept("codex", others)
|
||||
}
|
||||
m = codexVM(m)
|
||||
case "claude":
|
||||
m = claudeVM(m)
|
||||
default:
|
||||
if others := opencodeOthers(m); len(others) > 0 && warnKept != nil {
|
||||
sort.Strings(others)
|
||||
warnKept("opencode", others)
|
||||
}
|
||||
m = opencodeVM(m)
|
||||
}
|
||||
b, err := json.MarshalIndent(m, "", " ")
|
||||
return string(b), err
|
||||
}
|
||||
@@ -0,0 +1,366 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func writeFile(t *testing.T, v any) string {
|
||||
t.Helper()
|
||||
p := filepath.Join(t.TempDir(), "auth.json")
|
||||
b, _ := json.Marshal(v)
|
||||
if err := os.WriteFile(p, b, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// A fake token endpoint: records the request, answers with new tokens.
|
||||
func tokenServer(t *testing.T, reply map[string]any) *string {
|
||||
t.Helper()
|
||||
var got string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
got = r.Header.Get("Content-Type") + " " + string(b)
|
||||
_ = json.NewEncoder(w).Encode(reply)
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
old := openaiTokenURL
|
||||
openaiTokenURL = srv.URL
|
||||
t.Cleanup(func() { openaiTokenURL = old })
|
||||
return &got
|
||||
}
|
||||
|
||||
func jwtWith(exp time.Time, extra map[string]any) string {
|
||||
c := map[string]any{"exp": exp.Unix()}
|
||||
for k, v := range extra {
|
||||
c[k] = v
|
||||
}
|
||||
return fakeJWT(c) + "real-signature"
|
||||
}
|
||||
|
||||
var openaiAuth = map[string]any{"chatgpt_account_id": "acct-1", "chatgpt_plan_type": "pro"}
|
||||
|
||||
func TestCodexVMCopyHoldsOnlyPlaceholders(t *testing.T) {
|
||||
access := jwtWith(time.Now().Add(time.Hour), map[string]any{"https://api.openai.com/auth": openaiAuth})
|
||||
p := writeFile(t, map[string]any{
|
||||
"OPENAI_API_KEY": "sk-real",
|
||||
"tokens": map[string]any{
|
||||
"id_token": jwtWith(time.Now(), map[string]any{"email": "a@b", "https://api.openai.com/auth": openaiAuth}),
|
||||
"access_token": access, "refresh_token": "rt-real", "account_id": "acct-1",
|
||||
},
|
||||
"last_refresh": "2026-01-01T00:00:00Z", "auth_mode": "chatgpt",
|
||||
})
|
||||
out, err := loginCmd("codex", p, true, false, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, secret := range []string{"sk-real", "rt-real", access} {
|
||||
if strings.Contains(out, secret) {
|
||||
t.Errorf("the VM's copy holds %q:\n%s", secret, out)
|
||||
}
|
||||
}
|
||||
var m map[string]any
|
||||
must(t, json.Unmarshal([]byte(out), &m))
|
||||
tk := m["tokens"].(map[string]any)
|
||||
// Codex decodes these: the account claims survive, and the access token doesn't expire.
|
||||
if c := jwtClaims(tk["id_token"].(string)); c["email"] != "a@b" || c["https://api.openai.com/auth"] == nil {
|
||||
t.Errorf("id_token claims = %v", c)
|
||||
}
|
||||
if exp, ok := jwtExp(tk["access_token"].(string)); !ok || exp.Before(time.Now().AddDate(10, 0, 0)) {
|
||||
t.Errorf("access_token exp = %v %v", exp, ok)
|
||||
}
|
||||
if tk["account_id"] != "acct-1" || m["auth_mode"] != "chatgpt" {
|
||||
t.Errorf("other fields changed: %v", m)
|
||||
}
|
||||
// The bindings name exactly the placeholders in the copy.
|
||||
bs, _ := loginCmd("codex", p, false, true, "")
|
||||
if !strings.Contains(bs, `"codex-key"`) || !strings.Contains(bs, tk["access_token"].(string)) {
|
||||
t.Errorf("bindings = %s", bs)
|
||||
}
|
||||
}
|
||||
|
||||
// A tokens object without an access token still has its other tokens scrubbed.
|
||||
func TestCodexVMScrubsTokensWithoutAnAccessToken(t *testing.T) {
|
||||
p := writeFile(t, map[string]any{"tokens": map[string]any{"refresh_token": "rt-real", "id_token": "id-real"}, "extra": "x"})
|
||||
out, err := loginCmd("codex", p, true, false, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(out, "rt-real") || strings.Contains(out, "id-real") {
|
||||
t.Errorf("the VM's copy holds a token:\n%s", out)
|
||||
}
|
||||
if got := codexOthers(map[string]any{"tokens": 1, "extra": "x", "OPENAI_API_KEY": "k"}); !slices.Equal(got, []string{"extra"}) {
|
||||
t.Errorf("codexOthers = %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// Values from agents' login files are cached briefly: a logout on the host stops them soon.
|
||||
func TestLoginValuesCacheBriefly(t *testing.T) {
|
||||
for name, want := range map[string]time.Duration{
|
||||
"claude": valueTTL, "github": valueTTL, "codex": loginTTL,
|
||||
"codex-key": loginTTL, "opencode-anthropic": loginTTL, "claude-mcp-abc": loginTTL,
|
||||
} {
|
||||
if got := ttlOf(name); got != want {
|
||||
t.Errorf("ttlOf(%q) = %v, want %v", name, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCodexGetRefreshesOnTheHostWhenDue(t *testing.T) {
|
||||
got := tokenServer(t, map[string]any{"access_token": "at-new", "refresh_token": "rt-new", "id_token": "id-new"})
|
||||
p := writeFile(t, map[string]any{"tokens": map[string]any{
|
||||
"access_token": jwtWith(time.Now().Add(time.Minute), nil), "refresh_token": "rt-old", "id_token": "x",
|
||||
}})
|
||||
v, err := loginCmd("codex", p, false, false, "codex")
|
||||
if err != nil || v != "at-new" {
|
||||
t.Fatalf("value = %q, %v", v, err)
|
||||
}
|
||||
if !strings.HasPrefix(*got, "application/json ") || !strings.Contains(*got, `"refresh_token":"rt-old"`) ||
|
||||
!strings.Contains(*got, openaiClientID) {
|
||||
t.Errorf("refresh request = %s", *got)
|
||||
}
|
||||
m, _ := readJSON(p)
|
||||
if tk := obj(m, "tokens"); str(tk, "refresh_token") != "rt-new" || str(tk, "access_token") != "at-new" || str(m, "last_refresh") == "" {
|
||||
t.Errorf("host file = %v", m)
|
||||
}
|
||||
if st, _ := os.Stat(p); st.Mode().Perm() != 0o600 {
|
||||
t.Errorf("mode = %v", st.Mode())
|
||||
}
|
||||
}
|
||||
|
||||
func TestCodexGetLeavesAFreshTokenAlone(t *testing.T) {
|
||||
got := tokenServer(t, map[string]any{"access_token": "at-new"})
|
||||
access := jwtWith(time.Now().Add(time.Hour), nil)
|
||||
p := writeFile(t, map[string]any{"tokens": map[string]any{"access_token": access, "refresh_token": "rt"}})
|
||||
before, _ := os.ReadFile(p) //nolint:gosec // the test's own file
|
||||
if v, err := loginCmd("codex", p, false, false, "codex"); err != nil || v != access {
|
||||
t.Fatalf("value = %q, %v", v, err)
|
||||
}
|
||||
after, _ := os.ReadFile(p) //nolint:gosec // the test's own file
|
||||
if *got != "" || string(before) != string(after) {
|
||||
t.Errorf("refreshed or rewrote a fresh login: %s", *got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpencodeLogins(t *testing.T) {
|
||||
got := tokenServer(t, map[string]any{"access_token": "at-new", "refresh_token": "rt-new", "expires_in": 7200})
|
||||
p := writeFile(t, map[string]any{
|
||||
"anthropic": map[string]any{"type": "api", "key": "sk-ant-real"},
|
||||
"openai": map[string]any{"type": "oauth", "access": jwtWith(time.Now(), map[string]any{"https://api.openai.com/auth": openaiAuth}), "refresh": "rt-old", "expires": time.Now().UnixMilli()},
|
||||
"github-copilot": map[string]any{"type": "oauth", "access": "gho_real", "refresh": "gho_real", "expires": 0},
|
||||
"llama-cpp": map[string]any{"type": "api", "key": "local"},
|
||||
})
|
||||
out, err := loginCmd("opencode", p, true, false, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, secret := range []string{"sk-ant-real", "rt-old", "gho_real"} {
|
||||
if strings.Contains(out, secret) {
|
||||
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)
|
||||
}
|
||||
if v, _ := loginCmd("opencode", p, false, false, "opencode-anthropic"); v != "sk-ant-real" {
|
||||
t.Errorf("anthropic = %q", v)
|
||||
}
|
||||
if v, _ := loginCmd("opencode", p, false, false, "opencode-github-copilot"); v != "gho_real" {
|
||||
t.Errorf("copilot = %q", v)
|
||||
}
|
||||
// openai's access token has expired: refreshed here, as a form, and written back.
|
||||
if v, err := loginCmd("opencode", p, false, false, "opencode-openai"); err != nil || v != "at-new" {
|
||||
t.Fatalf("openai = %q, %v", v, err)
|
||||
}
|
||||
if !strings.HasPrefix(*got, "application/x-www-form-urlencoded ") || !strings.Contains(*got, "refresh_token=rt-old") {
|
||||
t.Errorf("refresh request = %s", *got)
|
||||
}
|
||||
m, _ := readJSON(p)
|
||||
if e := obj(m, "openai"); str(e, "refresh") != "rt-new" || str(e, "access") != "at-new" {
|
||||
t.Errorf("host file = %v", e)
|
||||
}
|
||||
// Logins copied as they are, the note's list: wellknown ones too (they hold a token).
|
||||
m["mcp"] = map[string]any{"type": "wellknown", "key": "k", "token": "t"}
|
||||
others := opencodeOthers(m)
|
||||
if !slices.Contains(others, "llama-cpp") || !slices.Contains(others, "mcp") {
|
||||
t.Errorf("others = %v", others)
|
||||
}
|
||||
}
|
||||
|
||||
// With -login-salt, every placeholder ends in the VM's key, so two VMs' differ.
|
||||
func TestLoginSalt(t *testing.T) {
|
||||
p := writeFile(t, map[string]any{
|
||||
"OPENAI_API_KEY": "sk-real",
|
||||
"tokens": map[string]any{"access_token": jwtWith(time.Now().Add(time.Hour), nil), "refresh_token": "rt"},
|
||||
})
|
||||
t.Cleanup(func() { loginSalt = "" })
|
||||
phs := map[string]bool{}
|
||||
for _, salt := range []string{"aaa", "bbb"} {
|
||||
loginSalt = salt
|
||||
out, err := loginCmd("codex", p, false, true, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var bs []binding
|
||||
must(t, json.Unmarshal([]byte(out), &bs))
|
||||
for _, b := range bs {
|
||||
if phs[b.Placeholder] {
|
||||
t.Errorf("%s: two VMs share placeholder %q", b.Name, b.Placeholder)
|
||||
}
|
||||
phs[b.Placeholder] = true
|
||||
}
|
||||
vm, _ := loginCmd("codex", p, true, false, "")
|
||||
for _, b := range bs {
|
||||
if !strings.Contains(vm, b.Placeholder) {
|
||||
t.Errorf("salt %s: the VM's copy lacks %s's placeholder", salt, b.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(phs) != 4 {
|
||||
t.Errorf("placeholders: %v", phs)
|
||||
}
|
||||
}
|
||||
|
||||
// ~/.claude.json: MCP servers' env values and headers never reach the VM; an HTTPS server's headers
|
||||
// become bindings for its host, and -login-get returns the real value.
|
||||
func TestClaudeMCP(t *testing.T) {
|
||||
p := writeFile(t, map[string]any{
|
||||
"oauthAccount": map[string]any{"emailAddress": "a@b"},
|
||||
"projects": map[string]any{"/x": map[string]any{"mcpServers": map[string]any{"p": map[string]any{"env": map[string]any{"K": "proj-secret"}}}}},
|
||||
"mcpServers": map[string]any{
|
||||
"remote": map[string]any{"type": "http", "url": "https://mcp.example.com/mcp", "headers": map[string]any{"Authorization": "Bearer remote-secret"}},
|
||||
"plain": map[string]any{"type": "http", "url": "http://mcp.example.net/", "headers": map[string]any{"X-Key": "plain-secret"}},
|
||||
"local": map[string]any{"command": "npx", "args": []any{"srv"}, "env": map[string]any{"API_KEY": "env-secret"}},
|
||||
"open": map[string]any{"command": "srv"},
|
||||
},
|
||||
})
|
||||
vm, err := loginCmd("claude", p, true, false, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, s := range []string{"remote-secret", "plain-secret", "env-secret", "proj-secret", "projects"} {
|
||||
if strings.Contains(vm, s) {
|
||||
t.Errorf("the VM's copy holds %q:\n%s", s, vm)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(vm, `"a@b"`) || !strings.Contains(vm, `"npx"`) {
|
||||
t.Errorf("the VM's copy lost settings:\n%s", vm)
|
||||
}
|
||||
out, _ := loginCmd("claude", p, false, true, "")
|
||||
var bs []binding
|
||||
must(t, json.Unmarshal([]byte(out), &bs))
|
||||
if len(bs) != 1 || bs[0].Header != "Authorization" || !slices.Equal(bs[0].Hosts, []string{"mcp.example.com"}) || !strings.Contains(vm, bs[0].Placeholder) {
|
||||
t.Fatalf("bindings %+v", bs)
|
||||
}
|
||||
if v, err := loginCmd("claude", p, false, false, bs[0].Name); err != nil || v != "Bearer remote-secret" {
|
||||
t.Errorf("get %s: %q %v", bs[0].Name, v, err)
|
||||
}
|
||||
loginSecrets = true
|
||||
t.Cleanup(func() { loginSecrets = false })
|
||||
if s, _ := loginCmd("claude", p, false, true, ""); s != "local\nplain\nremote" {
|
||||
t.Errorf("servers with secrets: %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
// One lookup at a time per login folder: a second waits until the first has written back.
|
||||
func TestLockLogin(t *testing.T) {
|
||||
p := filepath.Join(t.TempDir(), "auth.json")
|
||||
unlock, err := lockLogin(p)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := make(chan bool)
|
||||
go func() {
|
||||
u, err := lockLogin(p)
|
||||
if err == nil {
|
||||
u()
|
||||
}
|
||||
got <- true
|
||||
}()
|
||||
select {
|
||||
case <-got:
|
||||
t.Fatal("a second lock didn't wait")
|
||||
case <-time.After(200 * time.Millisecond):
|
||||
}
|
||||
unlock()
|
||||
<-got
|
||||
}
|
||||
|
||||
// An MCP server's host goes into the allowlist: only a DNS name, on 443.
|
||||
func TestClaudeHostIsANameOnly(t *testing.T) {
|
||||
for u, want := range map[string]string{
|
||||
"https://mcp.example.com/x": "mcp.example.com", "https://MCP.Example.com.:443/": "mcp.example.com",
|
||||
"https://1.2.3.4/": "", "https://[::1]/": "", "https://*.example.com/": "", "https://localhost/": "",
|
||||
"http://mcp.example.com/": "", "https://mcp.example.com:8443/": "", "https://a;b.com/": "",
|
||||
} {
|
||||
if got := claudeHost(map[string]any{"url": u}); got != want {
|
||||
t.Errorf("claudeHost(%q) = %q, want %q", u, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginHostsAreAllowlistLines(t *testing.T) {
|
||||
p := writeFile(t, map[string]any{
|
||||
"OPENAI_API_KEY": "sk-real",
|
||||
"tokens": map[string]any{"access_token": jwtWith(time.Now().Add(time.Hour), nil)},
|
||||
})
|
||||
loginHosts = true
|
||||
t.Cleanup(func() { loginHosts = false })
|
||||
out, err := loginCmd("codex", p, false, true, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if out != "api.openai.com:443\nchatgpt.com:443" {
|
||||
t.Errorf("-login-hosts = %q", out)
|
||||
}
|
||||
}
|
||||
|
||||
// With network policy, nothing in the VM's ~/.claude.json carries a secret: not URLs, not
|
||||
// args, not top-level keys; settings and harmless values stay.
|
||||
func TestClaudeVMScrubsURLsArgsAndUnknownKeys(t *testing.T) {
|
||||
p := writeFile(t, map[string]any{ //nolint:gosec // fake values
|
||||
"primaryApiKey": "sk-ant-api03-TOPSECRET", "someFutureKey": "x", "theme": "dark",
|
||||
"mcpServers": map[string]any{
|
||||
"u": map[string]any{"type": "http", "url": "https://user:[email protected]/s/Ab3dEf6hIj9kLm2nOp5qRs8tUv/mcp?api_key=Q1®ion=eu&x=zz9Yy8Xx7Ww6Vv5Uu4Tt3Ss2Rr1"}, //nolint:gosec // fake values
|
||||
"z": map[string]any{"type": "http", "url": "https://mcp.zapier.com/api/mcp/s/3f2c1b4a-9e8d-4c7b-a6f5-0e1d2c3b4a59/mcp"},
|
||||
"a": map[string]any{
|
||||
"command": "npx", "args": []any{
|
||||
"-y", "@scope/server-x", "--api-key", "DUMMYARG", "--token=DUMMYEQ",
|
||||
"--port", "8080", "ghp_DUMMYTOKENVALUE123", "/home/me/data",
|
||||
}, "extra": "DUMMYEXTRA",
|
||||
"oauth": map[string]any{"clientId": "cid", "clientSecret": "DUMMYCS"},
|
||||
},
|
||||
},
|
||||
})
|
||||
out, err := loginCmd("claude", p, true, false, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, s := range []string{
|
||||
"TOPSECRET", "someFutureKey", "DUMMYPASS", "Ab3dEf6hIj9kLm2nOp5qRs8tUv", "Q1", "zz9Yy8Xx7Ww6",
|
||||
"3f2c1b4a-9e8d", "DUMMYARG", "DUMMYEQ", "ghp_DUMMY", "DUMMYEXTRA", "DUMMYCS",
|
||||
} {
|
||||
if strings.Contains(out, s) {
|
||||
t.Errorf("the VM's copy holds %q:\n%s", s, out)
|
||||
}
|
||||
}
|
||||
for _, s := range []string{`"theme": "dark"`, "region=eu", "mcp.example.com", "@scope/server-x", `"8080"`, "/home/me/data", `"cid"`, "--token=devvm-redacted"} {
|
||||
if !strings.Contains(out, s) {
|
||||
t.Errorf("the VM's copy lost %q:\n%s", s, out)
|
||||
}
|
||||
}
|
||||
loginSecrets = true
|
||||
t.Cleanup(func() { loginSecrets = false })
|
||||
if s, _ := loginCmd("claude", p, false, true, ""); s != "a\nu\nz" {
|
||||
t.Errorf("servers with secrets: %q", s)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/netip"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A rule from a policy file. One per line, '#' starts a comment:
|
||||
//
|
||||
// example.com exactly that host
|
||||
// *.example.com any subdomain, at any depth (not example.com itself)
|
||||
// ** any host
|
||||
// 10.0.0.5, 10.0.0.0/8, fd00::/8 addresses (also needed to reach private ranges, see floor)
|
||||
// …:22 only that port; without a port, 443 and 80
|
||||
// !rule deny; a deny beats any allow
|
||||
//
|
||||
// Matching is case-insensitive.
|
||||
type rule struct {
|
||||
text string
|
||||
deny bool
|
||||
host string // "", "**", "*.example.com" or "example.com"
|
||||
prefix netip.Prefix // for address rules
|
||||
port int // 0: 443 and 80
|
||||
}
|
||||
|
||||
func parseRule(line string) (rule, bool) {
|
||||
line = strings.ToLower(strings.TrimSpace(strings.SplitN(line, "#", 2)[0]))
|
||||
if line == "" {
|
||||
return rule{}, false
|
||||
}
|
||||
r := rule{text: line}
|
||||
if strings.HasPrefix(line, "!") {
|
||||
r.deny = true
|
||||
line = strings.TrimSpace(line[1:])
|
||||
}
|
||||
// A port suffix: host:port, 1.2.3.4:port, [v6]:port, or cidr:port.
|
||||
if h, p, err := net.SplitHostPort(line); err == nil {
|
||||
if n, err := strconv.Atoi(p); err == nil && n > 0 && n < 65536 {
|
||||
line, r.port = h, n
|
||||
}
|
||||
} else if i := strings.LastIndex(line, ":"); i > 0 && strings.Contains(line, "/") && !strings.Contains(line[:i], ":") {
|
||||
if n, err := strconv.Atoi(line[i+1:]); err == nil && n > 0 && n < 65536 {
|
||||
line, r.port = line[:i], n
|
||||
}
|
||||
}
|
||||
if p, err := netip.ParsePrefix(line); err == nil {
|
||||
r.prefix = p.Masked()
|
||||
return r, true
|
||||
}
|
||||
if a, err := netip.ParseAddr(line); err == nil {
|
||||
r.prefix = netip.PrefixFrom(a.Unmap(), a.Unmap().BitLen())
|
||||
return r, true
|
||||
}
|
||||
if line == "" || strings.ContainsAny(line, " /\\") {
|
||||
return rule{}, false
|
||||
}
|
||||
r.host = line
|
||||
return r, true
|
||||
}
|
||||
|
||||
func (r rule) portOK(port int) bool {
|
||||
if r.port == 0 {
|
||||
return port == 443 || port == 80
|
||||
}
|
||||
return r.port == port
|
||||
}
|
||||
|
||||
// matchHost: does a host-name rule cover host (lower-case, no port)?
|
||||
func (r rule) matchHost(host string) bool {
|
||||
switch {
|
||||
case r.host == "":
|
||||
return false
|
||||
case r.host == "**":
|
||||
return true
|
||||
case strings.HasPrefix(r.host, "*."):
|
||||
return strings.HasSuffix(host, r.host[1:])
|
||||
default:
|
||||
return r.host == host
|
||||
}
|
||||
}
|
||||
|
||||
// matchAddr: does an address rule cover a? A NAT64 address also matches as the IPv4 address in it,
|
||||
// as internal() judges it, so a deny for an IPv4 address holds on IPv6-only networks too.
|
||||
func (r rule) matchAddr(a netip.Addr) bool {
|
||||
if !r.prefix.IsValid() {
|
||||
return false
|
||||
}
|
||||
a = a.Unmap()
|
||||
if r.prefix.Contains(a) {
|
||||
return true
|
||||
}
|
||||
v4, ok := nat64IPv4(a)
|
||||
return ok && r.prefix.Contains(v4)
|
||||
}
|
||||
|
||||
// policy is the union of several files, each re-read when its mtime changes.
|
||||
type policy struct {
|
||||
mu sync.Mutex
|
||||
files []string
|
||||
mtime map[string]time.Time
|
||||
rules map[string][]rule
|
||||
}
|
||||
|
||||
func newPolicy(files []string) *policy {
|
||||
return &policy{files: files, mtime: map[string]time.Time{}, rules: map[string][]rule{}}
|
||||
}
|
||||
|
||||
func (p *policy) all() []rule {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
var out []rule
|
||||
for _, f := range p.files {
|
||||
st, err := os.Stat(f)
|
||||
if err != nil {
|
||||
delete(p.rules, f) // a missing file has no rules
|
||||
continue
|
||||
}
|
||||
if !st.ModTime().Equal(p.mtime[f]) {
|
||||
b, err := os.ReadFile(f) //nolint:gosec // devvm names the policy files
|
||||
if err != nil { // keep its last rules (a deny dropped for a moment would let through)
|
||||
out = append(out, p.rules[f]...)
|
||||
continue
|
||||
}
|
||||
var rs []rule
|
||||
for _, l := range strings.Split(string(b), "\n") {
|
||||
if r, ok := parseRule(l); ok {
|
||||
rs = append(rs, r)
|
||||
}
|
||||
}
|
||||
p.rules[f], p.mtime[f] = rs, st.ModTime()
|
||||
logf("policy %s: %d rules", f, len(rs))
|
||||
}
|
||||
out = append(out, p.rules[f]...)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// decide whether host:port may be reached. host is a name or an address literal. It returns the
|
||||
// matching rule's text, or why not.
|
||||
func (p *policy) decide(host string, port int) (bool, string) {
|
||||
host = strings.ToLower(strings.TrimSuffix(host, "."))
|
||||
rs := p.all()
|
||||
addr, err := netip.ParseAddr(strings.Trim(host, "[]"))
|
||||
isAddr := err == nil
|
||||
match := func(r rule) bool {
|
||||
if !r.portOK(port) {
|
||||
return false
|
||||
}
|
||||
if isAddr {
|
||||
return r.matchAddr(addr)
|
||||
}
|
||||
return r.matchHost(host)
|
||||
}
|
||||
for _, r := range rs {
|
||||
if r.deny && match(r) {
|
||||
return false, "denied by " + r.text
|
||||
}
|
||||
}
|
||||
for _, r := range rs {
|
||||
if !r.deny && match(r) {
|
||||
return true, r.text
|
||||
}
|
||||
}
|
||||
return false, "not on the allowlist"
|
||||
}
|
||||
|
||||
// addrAllowed: an explicit address rule for a (needed to pass the floor), and no deny for it.
|
||||
func (p *policy) addrAllowed(a netip.Addr, port int) bool {
|
||||
if p.addrDenied(a, port) {
|
||||
return false
|
||||
}
|
||||
for _, r := range p.all() {
|
||||
if !r.deny && r.portOK(port) && r.matchAddr(a) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// addrDenied: a deny rule for address a. A deny beats any allow, including a host rule whose name
|
||||
// resolves to a, so every address the proxy dials is checked against it.
|
||||
func (p *policy) addrDenied(a netip.Addr, port int) bool {
|
||||
for _, r := range p.all() {
|
||||
if r.deny && r.portOK(port) && r.matchAddr(a) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,685 @@
|
||||
// Package proxy is the network policy point for one devvm VM, run as devvm _proxy.
|
||||
//
|
||||
// devvm starts one per VM, listening on a loopback port. The VM's Lima hostagent runs under a
|
||||
// Seatbelt profile, or a restricted QEMU network, that lets the VM reach nothing else, so every
|
||||
// connection the VM makes goes through here. Other programs on the host can reach the port too, so
|
||||
// requests must carry the VM's password (-auth-file), and the VM's placeholders end in its own key:
|
||||
//
|
||||
// - CONNECT host:port and absolute-form requests (GET http://host/…) are checked against the
|
||||
// policy files (see policy.go); allowed ones are tunneled or forwarded, untouched.
|
||||
// - Names are resolved here, and connections to loopback, private, link-local and the host's own
|
||||
// addresses are refused unless a rule names the address (the "floor").
|
||||
// - A tunnel that starts with a TLS ClientHello must name the CONNECT host in its SNI.
|
||||
// - Hosts with a bound secret (-secrets) are intercepted on :443 instead, to put the secret in
|
||||
// (see secrets.go). Everything else passes unread.
|
||||
// - Every decision goes to a JSON-lines log, and http://devvm.proxy/blocked lists recent blocks
|
||||
// (/blocked/new: those since the VM's last prompt; /ca.pem serves the CA).
|
||||
//
|
||||
// It exits when the VM's hostagent does (-lifeline). Standard library only: it prints nothing
|
||||
// itself, but writes to the streams devvm hands Main.
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
listen = "127.0.0.1:0"
|
||||
vmName = "vm"
|
||||
policies = ""
|
||||
logPath = ""
|
||||
lifeline = ""
|
||||
caFile = ""
|
||||
caKeyF = ""
|
||||
initCADir = ""
|
||||
loginKind = ""
|
||||
loginFile = ""
|
||||
loginVM = false
|
||||
loginBnd = false
|
||||
loginGet = ""
|
||||
redactFmt = ""
|
||||
)
|
||||
|
||||
// newFlags defines devvm _proxy's flags on a flag set of its own, writing into the variables above.
|
||||
// Each takes one dash or two.
|
||||
func newFlags() *flag.FlagSet {
|
||||
fs := flag.NewFlagSet("devvm _proxy", flag.ContinueOnError)
|
||||
fs.StringVar(&listen, "listen", "127.0.0.1:0", "address to listen on")
|
||||
fs.StringVar(&vmName, "vm", "vm", "VM name, for logs")
|
||||
fs.StringVar(&policies, "policy", "", "policy files, comma-separated (missing files have no rules)")
|
||||
fs.StringVar(&logPath, "log", "", "JSON-lines event log (default: stdout)")
|
||||
fs.StringVar(&lifeline, "lifeline", "", "pid file of the VM's hostagent: exit when that process is gone")
|
||||
fs.StringVar(&caFile, "ca", "", "CA certificate for interception (PEM); with -cakey")
|
||||
fs.StringVar(&caKeyF, "cakey", "", "CA private key (PEM)")
|
||||
fs.StringVar(&initCADir, "init-ca", "", "write a new CA (ca.pem, ca.key) into this directory unless one is there, and exit")
|
||||
fs.StringVar(&loginKind, "login", "", "codex, opencode or claude: work on that agent's login file (logins.go), with -login-file and one of the next three")
|
||||
fs.StringVar(&loginFile, "login-file", "", "the agent's login file on the host")
|
||||
fs.BoolVar(&loginVM, "login-vm", false, "print the VM's copy of the login file, with placeholders")
|
||||
fs.BoolVar(&loginBnd, "login-bindings", false, "print the login's secret bindings (JSON, no values)")
|
||||
fs.StringVar(&loginGet, "login-get", "", "print one value (refreshing an OAuth token when due)")
|
||||
fs.StringVar(&redactFmt, "redact", "", "json or toml: copy stdin to stdout with secret-named values replaced, their paths on stderr (redact.go)")
|
||||
fs.StringVar(&secretsPath, "secrets", "", "secret bindings (JSON, no values), re-read on change")
|
||||
fs.StringVar(&secretCmd, "secret-cmd", "", "the devvm binary, run as `devvm secret get NAME`")
|
||||
fs.StringVar(&loginSalt, "login-salt", "", "with -login-vm or -login-bindings: the VM's key, which ends its placeholders (default $DEVVM_LOGIN_SALT, which keeps it out of the process's arguments)")
|
||||
fs.BoolVar(&loginSecrets, "login-secrets", false, "with -login claude: print the MCP servers whose settings hold secrets")
|
||||
fs.BoolVar(&loginHosts, "login-hosts", false, "with -login-bindings: print the bindings' hosts as allowlist lines (host:443) instead")
|
||||
fs.StringVar(&authFile, "auth-file", "", "file holding the VM's password: requests need Proxy-Authorization for user devvm with it")
|
||||
return fs
|
||||
}
|
||||
|
||||
// --- who may use the proxy ---
|
||||
|
||||
var (
|
||||
authFile = ""
|
||||
proxyAuth = "" // the VM's password; empty: no check
|
||||
)
|
||||
|
||||
// authorized: the request carries the VM's password (Basic, user devvm). Lima's hostagent makes the
|
||||
// VM's connections, so the port alone can't tell the VM apart from anything else on the host that
|
||||
// reaches it: other VMs, other users. Inside an intercepted tunnel there's no proxy header: the
|
||||
// CONNECT that opened it was checked.
|
||||
func authorized(r *http.Request) bool {
|
||||
if proxyAuth == "" {
|
||||
return true
|
||||
}
|
||||
v := r.Header.Get("Proxy-Authorization")
|
||||
if len(v) < 6 || !strings.EqualFold(v[:6], "basic ") {
|
||||
return false
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(v[6:]))
|
||||
return err == nil && subtle.ConstantTimeCompare(raw, []byte("devvm:"+proxyAuth)) == 1
|
||||
}
|
||||
|
||||
var pol *policy
|
||||
|
||||
// --- events ---
|
||||
|
||||
type event struct {
|
||||
Time string `json:"time"`
|
||||
VM string `json:"vm"`
|
||||
Event string `json:"event"` // tunnel, intercept, forward, blocked
|
||||
Host string `json:"host"`
|
||||
Port int `json:"port"`
|
||||
Method string `json:"method,omitempty"`
|
||||
Path string `json:"path,omitempty"`
|
||||
Rule string `json:"rule,omitempty"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
Agent string `json:"agent,omitempty"`
|
||||
Secrets []string `json:"secrets,omitempty"` // names of secrets put in, never values
|
||||
Refused bool `json:"refused,omitempty"` // blocked whatever the allowlist says: no rule allows it
|
||||
}
|
||||
|
||||
// A block and its number (the first is 1), for /blocked/new.
|
||||
type numbered struct {
|
||||
n int
|
||||
e event
|
||||
}
|
||||
|
||||
var (
|
||||
logMu sync.Mutex
|
||||
logOut io.Writer = io.Discard // Main sets it: -log, else stdout
|
||||
recent []numbered // the last blocks, for /blocked
|
||||
blocks int // blocks so far
|
||||
)
|
||||
|
||||
func record(e event) {
|
||||
e.Time, e.VM = time.Now().UTC().Format(time.RFC3339), vmName
|
||||
b, _ := json.Marshal(e)
|
||||
logMu.Lock()
|
||||
defer logMu.Unlock()
|
||||
fmt.Fprintln(logOut, string(b))
|
||||
if e.Event == "blocked" {
|
||||
blocks++
|
||||
recent = append(recent, numbered{blocks, e})
|
||||
if len(recent) > 50 {
|
||||
recent = recent[len(recent)-50:]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// newBlocks answers /blocked/new?after=N for the VM's prompt: the number of blocks so far on the first
|
||||
// line, then the blocks after the Nth, each rule once, and the command that allows them. No N (a new
|
||||
// shell) means none; an N past the count means the proxy restarted, so every block since counts.
|
||||
func newBlocks(rs []numbered, count int, after string) string {
|
||||
var b strings.Builder
|
||||
fmt.Fprintln(&b, count)
|
||||
n, err := strconv.Atoi(after)
|
||||
if err != nil {
|
||||
return b.String()
|
||||
}
|
||||
if n > count {
|
||||
n = 0
|
||||
}
|
||||
var rules []string
|
||||
seen := map[string]bool{}
|
||||
for _, r := range rs {
|
||||
if r.n <= n {
|
||||
continue
|
||||
}
|
||||
if r.e.Refused {
|
||||
fmt.Fprintf(&b, "devvm: refused %s %s%s (%s)\n", r.e.Method, r.e.Host, r.e.Path, r.e.Reason)
|
||||
continue
|
||||
}
|
||||
rule := ruleFor(r.e.Host, r.e.Port)
|
||||
if seen[rule] {
|
||||
continue
|
||||
}
|
||||
seen[rule] = true
|
||||
rules = append(rules, rule)
|
||||
fmt.Fprintf(&b, "devvm: blocked %s:%d (%s)\n", r.e.Host, r.e.Port, r.e.Reason)
|
||||
}
|
||||
if len(rules) > 0 {
|
||||
fmt.Fprintf(&b, "To allow, run this on the host:\ndevvm policy allow %s\n", strings.Join(rules, " "))
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// logger: the proxy's own log lines (what it loaded, what failed), not events. Main points it at
|
||||
// the stderr devvm hands it.
|
||||
var logger = log.New(io.Discard, "devvm proxy: ", log.LstdFlags)
|
||||
|
||||
func logf(format string, a ...any) { logger.Printf(format, a...) }
|
||||
|
||||
// --- destinations ---
|
||||
|
||||
// The host's own addresses, re-read every 30 seconds: they change (a new network, IPv6 temporary
|
||||
// addresses).
|
||||
var (
|
||||
ownMu sync.Mutex
|
||||
ownAddrs = map[netip.Addr]bool{}
|
||||
ownAt time.Time
|
||||
)
|
||||
|
||||
func loadOwnAddrs() {
|
||||
addrs, _ := net.InterfaceAddrs()
|
||||
own := map[netip.Addr]bool{}
|
||||
for _, a := range addrs {
|
||||
if p, err := netip.ParsePrefix(a.String()); err == nil {
|
||||
own[p.Addr().Unmap()] = true
|
||||
}
|
||||
}
|
||||
ownMu.Lock()
|
||||
ownAddrs, ownAt = own, time.Now()
|
||||
ownMu.Unlock()
|
||||
}
|
||||
|
||||
func isOwn(a netip.Addr) bool {
|
||||
ownMu.Lock()
|
||||
stale := time.Since(ownAt) > 30*time.Second
|
||||
ownMu.Unlock()
|
||||
if stale {
|
||||
loadOwnAddrs()
|
||||
}
|
||||
ownMu.Lock()
|
||||
defer ownMu.Unlock()
|
||||
return ownAddrs[a]
|
||||
}
|
||||
|
||||
// Ranges that aren't the public internet beyond what netip's predicates cover: CGNAT, "this network",
|
||||
// IETF protocol assignments, benchmarking, reserved, local-use NAT64, IPv4-compatible IPv6 (::a.b.c.d,
|
||||
// deprecated) and site-local IPv6 (deprecated, still routed by some systems).
|
||||
var notPublic = []netip.Prefix{
|
||||
netip.MustParsePrefix("100.64.0.0/10"), netip.MustParsePrefix("0.0.0.0/8"),
|
||||
netip.MustParsePrefix("192.0.0.0/24"), netip.MustParsePrefix("198.18.0.0/15"),
|
||||
netip.MustParsePrefix("240.0.0.0/4"), netip.MustParsePrefix("64:ff9b:1::/48"),
|
||||
netip.MustParsePrefix("::/96"), netip.MustParsePrefix("fec0::/10"),
|
||||
}
|
||||
var nat64 = netip.MustParsePrefix("64:ff9b::/96")
|
||||
|
||||
// nat64IPv4: the IPv4 address in a NAT64 address (64:ff9b::a.b.c.d).
|
||||
func nat64IPv4(a netip.Addr) (netip.Addr, bool) {
|
||||
if !nat64.Contains(a) {
|
||||
return netip.Addr{}, false
|
||||
}
|
||||
b := a.As16()
|
||||
return netip.AddrFrom4([4]byte{b[12], b[13], b[14], b[15]}), true
|
||||
}
|
||||
|
||||
// internal: addresses a VM must not reach without an explicit rule: the host itself and its networks.
|
||||
// A NAT64 address (64:ff9b::a.b.c.d, on IPv6-only networks) is judged by the IPv4 address in it.
|
||||
func internal(a netip.Addr) bool {
|
||||
a = a.Unmap()
|
||||
if v4, ok := nat64IPv4(a); ok {
|
||||
return internal(v4)
|
||||
}
|
||||
for _, p := range notPublic {
|
||||
if p.Contains(a) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return a.IsLoopback() || a.IsPrivate() || a.IsLinkLocalUnicast() || a.IsLinkLocalMulticast() ||
|
||||
a.IsMulticast() || a.IsUnspecified() || a.IsInterfaceLocalMulticast() || isOwn(a)
|
||||
}
|
||||
|
||||
var errFloor = errors.New("resolves to an internal address")
|
||||
|
||||
// resolve host to the addresses that may be dialed for port. Callers dial these, not the name, so
|
||||
// a second DNS answer can't swap in an internal address.
|
||||
func resolve(ctx context.Context, host string, port int) ([]netip.Addr, error) {
|
||||
var addrs []netip.Addr
|
||||
if a, err := netip.ParseAddr(strings.Trim(host, "[]")); err == nil {
|
||||
addrs = []netip.Addr{a.Unmap()}
|
||||
} else {
|
||||
ips, err := net.DefaultResolver.LookupNetIP(ctx, "ip", host)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, a := range ips {
|
||||
addrs = append(addrs, a.Unmap())
|
||||
}
|
||||
}
|
||||
var ok []netip.Addr
|
||||
for _, a := range addrs {
|
||||
if !pol.addrDenied(a, port) && (!internal(a) || pol.addrAllowed(a, port)) {
|
||||
ok = append(ok, a)
|
||||
}
|
||||
}
|
||||
if len(ok) == 0 {
|
||||
return nil, errFloor
|
||||
}
|
||||
return ok, nil
|
||||
}
|
||||
|
||||
func dial(ctx context.Context, host string, port int) (net.Conn, error) {
|
||||
addrs, err := resolve(ctx, host, port)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if port < 1 || port > 65535 { // the policy allows none of these; never dial one wrapped around
|
||||
return nil, fmt.Errorf("port %d", port)
|
||||
}
|
||||
d := net.Dialer{Timeout: 15 * time.Second}
|
||||
for _, a := range addrs {
|
||||
c, e := d.DialContext(ctx, "tcp", netip.AddrPortFrom(a, uint16(port)).String())
|
||||
if e == nil {
|
||||
return c, nil
|
||||
}
|
||||
err = e
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// --- the proxy ---
|
||||
|
||||
// hostOK: a host name (letters, digits, '-', '_', '.') or an address. The VM chooses the host, and it
|
||||
// ends up in the log, in the policy and in the allow command devvm suggests for the host's shell.
|
||||
func hostOK(h string) bool {
|
||||
if a, err := netip.ParseAddr(strings.Trim(h, "[]")); err == nil {
|
||||
return a.Zone() == "" // a zone (fe80::1%eth0) is any text
|
||||
}
|
||||
if h == "" || len(h) > 253 {
|
||||
return false
|
||||
}
|
||||
for _, c := range h {
|
||||
if (c < 'a' || c > 'z') && (c < '0' || c > '9') && c != '-' && c != '_' && c != '.' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// splitHostPort: the host, lowercased and without a trailing dot (so the policy, bindings, SNI check
|
||||
// and log all see one form), and the port (def when there's none).
|
||||
func splitHostPort(hp string, def int) (string, int) {
|
||||
norm := func(h string) string { return strings.TrimSuffix(strings.ToLower(h), ".") }
|
||||
h, p, err := net.SplitHostPort(hp)
|
||||
if err != nil {
|
||||
return norm(strings.Trim(hp, "[]")), def
|
||||
}
|
||||
n, err := strconv.Atoi(p)
|
||||
if err != nil {
|
||||
return norm(h), def
|
||||
}
|
||||
return norm(h), n
|
||||
}
|
||||
|
||||
func block(w http.ResponseWriter, e event) {
|
||||
e.Event = "blocked"
|
||||
record(e)
|
||||
w.Header().Set("X-Devvm-Blocked", e.Host)
|
||||
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
fmt.Fprintf(w, "devvm: %s:%d is blocked (%s). Allow it on the host with: devvm policy allow %s\n",
|
||||
e.Host, e.Port, e.Reason, ruleFor(e.Host, e.Port))
|
||||
}
|
||||
|
||||
func ruleFor(host string, port int) string {
|
||||
if port == 443 || port == 80 {
|
||||
return host
|
||||
}
|
||||
return net.JoinHostPort(host, strconv.Itoa(port))
|
||||
}
|
||||
|
||||
// check runs the policy and the floor; on success it returns the rule that allowed host:port.
|
||||
func check(ctx context.Context, host string, port int) (string, string) {
|
||||
ok, why := pol.decide(host, port)
|
||||
if !ok {
|
||||
return "", why
|
||||
}
|
||||
if _, err := resolve(ctx, host, port); err != nil {
|
||||
if errors.Is(err, errFloor) {
|
||||
return "", "it " + err.Error() + "; allow the address itself to reach it"
|
||||
}
|
||||
return "", "can't resolve it: " + err.Error()
|
||||
}
|
||||
return why, ""
|
||||
}
|
||||
|
||||
func handleConnect(w http.ResponseWriter, r *http.Request) {
|
||||
host, port := splitHostPort(r.Host, 443)
|
||||
if !hostOK(host) {
|
||||
http.Error(w, "devvm proxy: not a host name", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
e := event{Host: host, Port: port, Method: "CONNECT"}
|
||||
rule, why := check(r.Context(), host, port)
|
||||
if why != "" {
|
||||
e.Reason = why
|
||||
block(w, e)
|
||||
return
|
||||
}
|
||||
e.Rule = rule
|
||||
if bs := bindingsFor(host); interceptPorts[port] && len(bs) > 0 && caCert != nil {
|
||||
client, buf, err := http.NewResponseController(w).Hijack()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_, _ = client.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n"))
|
||||
intercept(bufConn{client, buf.Reader}, host, port, e)
|
||||
return
|
||||
}
|
||||
up, err := dial(r.Context(), host, port)
|
||||
if err != nil {
|
||||
e.Reason = "connect failed: " + err.Error()
|
||||
block(w, e)
|
||||
return
|
||||
}
|
||||
defer up.Close()
|
||||
client, buf, err := http.NewResponseController(w).Hijack()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer client.Close()
|
||||
_, _ = client.Write([]byte("HTTP/1.1 200 Connection established\r\n\r\n"))
|
||||
|
||||
// TLS: the SNI must be the host that was checked (blunts domain fronting). Other protocols
|
||||
// (SSH on :22, …) pass as they are.
|
||||
first, sni, isTLS := peekClientHello(buf.Reader)
|
||||
if isTLS && !sniMatches(sni, host) {
|
||||
e.Event, e.Reason = "blocked", fmt.Sprintf("TLS name %q doesn't match %s", sni, host)
|
||||
record(e)
|
||||
return
|
||||
}
|
||||
e.Event = "tunnel"
|
||||
record(e)
|
||||
_, _ = up.Write(first)
|
||||
go func() {
|
||||
_, _ = io.Copy(up, buf.Reader) // also drains anything bufio already read
|
||||
if t, ok := up.(*net.TCPConn); ok {
|
||||
_ = t.CloseWrite()
|
||||
}
|
||||
}()
|
||||
_, _ = io.Copy(client, up)
|
||||
}
|
||||
|
||||
// bufConn: a hijacked connection whose first bytes may already sit in the server's bufio.Reader.
|
||||
type bufConn struct {
|
||||
net.Conn
|
||||
r *bufio.Reader
|
||||
}
|
||||
|
||||
func (c bufConn) Read(b []byte) (int, error) { return c.r.Read(b) }
|
||||
|
||||
func sniMatches(sni, host string) bool {
|
||||
if _, err := netip.ParseAddr(host); err == nil {
|
||||
return sni == "" || strings.EqualFold(sni, host)
|
||||
}
|
||||
return strings.EqualFold(strings.TrimSuffix(sni, "."), host)
|
||||
}
|
||||
|
||||
// peekClientHello reads the first TLS record if the stream starts with one, and returns the bytes
|
||||
// read (to replay upstream), the SNI, and whether it was TLS.
|
||||
func peekClientHello(r *bufio.Reader) ([]byte, string, bool) {
|
||||
hdr, err := r.Peek(5)
|
||||
if err != nil || hdr[0] != 0x16 || hdr[1] != 3 {
|
||||
return nil, "", false
|
||||
}
|
||||
n := int(hdr[3])<<8 | int(hdr[4])
|
||||
rec := make([]byte, 5+n)
|
||||
if _, err := io.ReadFull(r, rec); err != nil {
|
||||
return rec, "", true
|
||||
}
|
||||
return rec, sniOf(rec), true
|
||||
}
|
||||
|
||||
// handleHTTP serves absolute-form requests (plain HTTP, or "GET https://…" from clients like
|
||||
// busybox wget) and the reserved http://devvm.proxy/ endpoints.
|
||||
func handleHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Host == "" {
|
||||
http.Error(w, "devvm proxy: not a proxy request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
scheme := "http"
|
||||
if r.URL.Scheme == "https" {
|
||||
scheme = "https"
|
||||
}
|
||||
def := 80
|
||||
if scheme == "https" {
|
||||
def = 443
|
||||
}
|
||||
host, port := splitHostPort(r.URL.Host, def)
|
||||
if !hostOK(host) {
|
||||
http.Error(w, "devvm proxy: not a host name", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if host == "devvm.proxy" {
|
||||
serveReserved(w, r)
|
||||
return
|
||||
}
|
||||
e := event{Host: host, Port: port, Method: r.Method, Path: r.URL.Path, Agent: r.UserAgent()}
|
||||
if _, why := check(r.Context(), host, port); why != "" {
|
||||
e.Reason = why
|
||||
block(w, e)
|
||||
return
|
||||
}
|
||||
// Some clients half-close after sending; don't treat that as the client going away.
|
||||
forwarder(scheme, r.URL.Host, host, port).ServeHTTP(noCloseNotify{w}, r.WithContext(context.WithoutCancel(r.Context())))
|
||||
}
|
||||
|
||||
type noCloseNotify struct{ http.ResponseWriter }
|
||||
|
||||
func (w noCloseNotify) Flush() { _ = http.NewResponseController(w.ResponseWriter).Flush() }
|
||||
|
||||
func serveReserved(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||
switch r.URL.Path {
|
||||
case "/blocked":
|
||||
logMu.Lock()
|
||||
rs := append([]numbered(nil), recent...)
|
||||
logMu.Unlock()
|
||||
if len(rs) == 0 {
|
||||
fmt.Fprintln(w, "devvm: nothing blocked recently")
|
||||
return
|
||||
}
|
||||
var b bytes.Buffer
|
||||
for _, r := range rs {
|
||||
e := r.e
|
||||
if e.Refused {
|
||||
fmt.Fprintf(&b, "%s %s %s%s refused: %s\n", e.Time, e.Method, e.Host, e.Path, e.Reason)
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(&b, "%s %s:%d %s\n allow on the host: devvm policy allow %s\n", e.Time, e.Host, e.Port, e.Reason, ruleFor(e.Host, e.Port))
|
||||
}
|
||||
_, _ = w.Write(b.Bytes())
|
||||
case "/blocked/new":
|
||||
logMu.Lock()
|
||||
s := newBlocks(recent, blocks, r.URL.Query().Get("after"))
|
||||
logMu.Unlock()
|
||||
fmt.Fprint(w, s)
|
||||
case "/ca.pem":
|
||||
if p := caPEM(); p != nil {
|
||||
_, _ = w.Write(p)
|
||||
return
|
||||
}
|
||||
http.Error(w, "devvm proxy: no CA", http.StatusNotFound)
|
||||
default:
|
||||
http.Error(w, "devvm proxy: unknown endpoint", http.StatusNotFound)
|
||||
}
|
||||
}
|
||||
|
||||
func handler(w http.ResponseWriter, r *http.Request) {
|
||||
if !authorized(r) {
|
||||
w.Header().Set("Proxy-Authenticate", `Basic realm="devvm"`)
|
||||
http.Error(w, "devvm proxy: this proxy belongs to another VM", http.StatusProxyAuthRequired)
|
||||
return
|
||||
}
|
||||
if r.Method == http.MethodConnect {
|
||||
handleConnect(w, r)
|
||||
return
|
||||
}
|
||||
handleHTTP(w, r)
|
||||
}
|
||||
|
||||
// lifelineTick: how often watchLifeline looks (tests shorten it).
|
||||
var lifelineTick = 3 * time.Second
|
||||
|
||||
// watchLifeline returns once the hostagent named by the pid file is gone, or never appears. It
|
||||
// follows the first hostagent it sees, not later ones: a restarted VM gets a new proxy.
|
||||
func watchLifeline(path string) {
|
||||
start, pid := time.Now(), 0
|
||||
for range time.Tick(lifelineTick) {
|
||||
if pid == 0 {
|
||||
if b, err := os.ReadFile(path); err == nil { //nolint:gosec // devvm names the pid file
|
||||
|
||||
if p, err := strconv.Atoi(strings.TrimSpace(string(b))); err == nil && p > 0 && syscall.Kill(p, 0) == nil {
|
||||
pid = p
|
||||
}
|
||||
}
|
||||
}
|
||||
if (pid != 0 && syscall.Kill(pid, 0) != nil) || (pid == 0 && time.Since(start) > 15*time.Minute) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// IO is what devvm _proxy reads and writes: devvm's own streams.
|
||||
type IO struct {
|
||||
Stdin io.Reader
|
||||
// Stdout gets data: the event log without -log, and what -login, -redact and -help print.
|
||||
Stdout io.Writer
|
||||
// Stderr gets the proxy's own log lines, and -redact's paths.
|
||||
Stderr io.Writer
|
||||
// Kept is told, with -login-vm, what of an agent's login file the VM's copy holds as it is:
|
||||
// Codex's auth.json keys or opencode's providers devvm doesn't know. Nil: nothing is told.
|
||||
Kept func(agent string, names []string)
|
||||
}
|
||||
|
||||
// Main runs devvm _proxy with args (its flags): the proxy itself, until the VM's hostagent is
|
||||
// gone, or one of the modes that do one thing and return (-init-ca, -login, -redact). -help prints
|
||||
// the flags to std.Stdout. Errors are returned, not printed.
|
||||
func Main(args []string, std IO) error {
|
||||
fs := newFlags()
|
||||
fs.SetOutput(io.Discard)
|
||||
if err := fs.Parse(args); err != nil {
|
||||
if errors.Is(err, flag.ErrHelp) {
|
||||
fs.SetOutput(std.Stdout)
|
||||
fs.PrintDefaults()
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
if fs.NArg() > 0 {
|
||||
return fmt.Errorf("unexpected argument %q", fs.Arg(0))
|
||||
}
|
||||
if loginSalt == "" {
|
||||
loginSalt = os.Getenv("DEVVM_LOGIN_SALT")
|
||||
}
|
||||
logger.SetOutput(std.Stderr)
|
||||
warnKept = std.Kept
|
||||
if loginKind != "" {
|
||||
out, err := loginCmd(loginKind, loginFile, loginVM, loginBnd, loginGet)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = fmt.Fprintln(std.Stdout, out)
|
||||
return err
|
||||
}
|
||||
if redactFmt != "" {
|
||||
return redactCmd(redactFmt, std.Stdin, std.Stdout, std.Stderr)
|
||||
}
|
||||
if initCADir != "" {
|
||||
return initCA(initCADir)
|
||||
}
|
||||
if caFile != "" {
|
||||
if err := loadCA(caFile, caKeyF); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
// Without a password any program on the host could use the proxy, and the VM's tokens with it.
|
||||
if authFile == "" {
|
||||
return errors.New("-auth-file is required")
|
||||
}
|
||||
{
|
||||
b, err := os.ReadFile(authFile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if proxyAuth = strings.TrimSpace(string(b)); proxyAuth == "" {
|
||||
return fmt.Errorf("%s is empty", authFile)
|
||||
}
|
||||
}
|
||||
logOut = std.Stdout
|
||||
if logPath != "" {
|
||||
f, err := os.OpenFile(logPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = f.Close() }()
|
||||
logOut = f
|
||||
}
|
||||
var files []string
|
||||
for f := range strings.SplitSeq(policies, ",") {
|
||||
if f = strings.TrimSpace(f); f != "" {
|
||||
files = append(files, f)
|
||||
}
|
||||
}
|
||||
pol = newPolicy(files)
|
||||
pol.all()
|
||||
loadOwnAddrs()
|
||||
ln, err := net.Listen("tcp", listen) //nolint:noctx // listens for the proxy's whole life
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
logf("listening on %s for %s", ln.Addr(), vmName)
|
||||
srv := &http.Server{Handler: http.HandlerFunc(handler), ReadHeaderTimeout: 30 * time.Second}
|
||||
if lifeline != "" {
|
||||
go func() {
|
||||
watchLifeline(lifeline)
|
||||
logf("the VM's hostagent is gone; exiting")
|
||||
_ = srv.Close()
|
||||
}()
|
||||
}
|
||||
if err := srv.Serve(ln); !errors.Is(err, http.ErrServerClosed) {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,547 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"crypto/tls"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func writePolicy(t *testing.T, rules string) *policy {
|
||||
t.Helper()
|
||||
f := filepath.Join(t.TempDir(), "policy")
|
||||
if err := os.WriteFile(f, []byte(rules), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return newPolicy([]string{f, filepath.Join(t.TempDir(), "missing")})
|
||||
}
|
||||
|
||||
func TestNewBlocks(t *testing.T) {
|
||||
rs := []numbered{
|
||||
{1, event{Host: "old.test", Port: 443, Reason: "not in the allowlist"}},
|
||||
{2, event{Host: "registry.example.com", Port: 443, Reason: "not in the allowlist"}},
|
||||
{3, event{Host: "registry.example.com", Port: 443, Reason: "not in the allowlist"}},
|
||||
{4, event{Host: "db.test", Port: 5432, Reason: "not in the allowlist"}},
|
||||
}
|
||||
newer := "4\n" +
|
||||
"devvm: blocked registry.example.com:443 (not in the allowlist)\n" +
|
||||
"devvm: blocked db.test:5432 (not in the allowlist)\n" +
|
||||
"To allow, run this on the host:\n" +
|
||||
"devvm policy allow registry.example.com db.test:5432\n"
|
||||
all := "4\n" +
|
||||
"devvm: blocked old.test:443 (not in the allowlist)\n" +
|
||||
"devvm: blocked registry.example.com:443 (not in the allowlist)\n" +
|
||||
"devvm: blocked db.test:5432 (not in the allowlist)\n" +
|
||||
"To allow, run this on the host:\n" +
|
||||
"devvm policy allow old.test registry.example.com db.test:5432\n"
|
||||
for _, c := range []struct{ after, want string }{
|
||||
{"1", newer}, // after the prompt that saw block 1: each new rule once
|
||||
{"4", "4\n"}, // nothing new
|
||||
{"", "4\n"}, // a new shell: only the count
|
||||
{"x", "4\n"}, // not a number: the same
|
||||
{"9", all}, // past the count: the proxy restarted, so everything it has
|
||||
} {
|
||||
got := newBlocks(rs, 4, c.after)
|
||||
if got != c.want {
|
||||
t.Errorf("after=%q:\n%s\nwant:\n%s", c.after, got, c.want)
|
||||
}
|
||||
}
|
||||
// A refused request has no rule to allow it.
|
||||
rs = append(rs, numbered{5, event{Host: "api.github.com", Port: 443, Method: "POST", Path: "/user/keys", Reason: "makes a key", Refused: true}})
|
||||
if got, want := newBlocks(rs, 5, "4"), "5\ndevvm: refused POST api.github.com/user/keys (makes a key)\n"; got != want {
|
||||
t.Errorf("refused:\n%s\nwant:\n%s", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecide(t *testing.T) {
|
||||
p := writePolicy(t, `
|
||||
# comment
|
||||
example.com
|
||||
*.github.com # any depth, not the apex
|
||||
github.com:22
|
||||
!evil.github.com
|
||||
10.1.2.3
|
||||
192.168.0.0/16:8080
|
||||
**:9999
|
||||
`)
|
||||
cases := []struct {
|
||||
host string
|
||||
port int
|
||||
want bool
|
||||
}{
|
||||
{"example.com", 443, true},
|
||||
{"EXAMPLE.com", 80, true},
|
||||
{"example.com.", 443, true},
|
||||
{"example.com", 8443, false}, // no port in the rule: 443 and 80 only
|
||||
{"www.example.com", 443, false}, // exact only
|
||||
{"api.github.com", 443, true}, // *. covers subdomains
|
||||
{"a.b.github.com", 443, true}, // at any depth
|
||||
{"github.com", 443, false}, // but not the apex
|
||||
{"github.com", 22, true}, // port rule
|
||||
{"evil.github.com", 443, false}, // deny wins
|
||||
{"10.1.2.3", 443, true}, // address rule
|
||||
{"10.1.2.4", 443, false},
|
||||
{"192.168.5.5", 8080, true}, // cidr with port
|
||||
{"192.168.5.5", 443, false},
|
||||
{"anything.test", 9999, true}, // ** with a port
|
||||
{"anything.test", 443, false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got, why := p.decide(c.host, c.port); got != c.want {
|
||||
t.Errorf("decide(%s, %d) = %v (%s), want %v", c.host, c.port, got, why, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPolicyReload(t *testing.T) {
|
||||
f := filepath.Join(t.TempDir(), "policy")
|
||||
must(t, os.WriteFile(f, []byte("a.test\n"), 0o600))
|
||||
p := newPolicy([]string{f})
|
||||
if ok, _ := p.decide("b.test", 443); ok {
|
||||
t.Fatal("b.test allowed before it was added")
|
||||
}
|
||||
must(t, os.WriteFile(f, []byte("a.test\nb.test\n"), 0o600))
|
||||
must(t, os.Chtimes(f, time.Now().Add(time.Second), time.Now().Add(time.Second)))
|
||||
if ok, why := p.decide("b.test", 443); !ok {
|
||||
t.Fatalf("b.test still blocked after the file changed: %s", why)
|
||||
}
|
||||
// A file that changed but can't be read (mid-rewrite, say) keeps its last rules: its denies too.
|
||||
must(t, os.WriteFile(f, []byte("**\n!c.test\n"), 0o600))
|
||||
must(t, os.Chtimes(f, time.Now().Add(2*time.Second), time.Now().Add(2*time.Second)))
|
||||
p.decide("x.test", 443)
|
||||
must(t, os.Chmod(f, 0))
|
||||
must(t, os.Chtimes(f, time.Now().Add(3*time.Second), time.Now().Add(3*time.Second)))
|
||||
t.Cleanup(func() { _ = os.Chmod(f, 0o600) })
|
||||
if ok, _ := p.decide("c.test", 443); ok {
|
||||
t.Error("c.test's deny was dropped while its file couldn't be read")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInternal(t *testing.T) {
|
||||
for _, s := range []string{
|
||||
"127.0.0.1", "::1", "10.0.0.1", "172.16.3.4", "192.168.1.1", "169.254.169.254",
|
||||
"100.64.0.1", "fd00::1", "fe80::1", "0.0.0.0", "::ffff:127.0.0.1", "224.0.0.1",
|
||||
"0.1.2.3", "192.0.0.8", "198.18.0.1", "240.0.0.1", "64:ff9b::10.0.0.1", "64:ff9b::127.0.0.1", "64:ff9b:1::1",
|
||||
"::7f00:1", "::a00:1", "fec0::1",
|
||||
} {
|
||||
if !internal(netip.MustParseAddr(s)) {
|
||||
t.Errorf("%s should be internal", s)
|
||||
}
|
||||
}
|
||||
for _, s := range []string{"1.1.1.1", "140.82.112.3", "2606:4700::1111", "64:ff9b::1.1.1.1"} {
|
||||
if internal(netip.MustParseAddr(s)) {
|
||||
t.Errorf("%s shouldn't be internal", s)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFloor(t *testing.T) {
|
||||
pol = writePolicy(t, "**\n10.9.8.7\n")
|
||||
if _, err := resolve(t.Context(), "127.0.0.1", 443); !errors.Is(err, errFloor) {
|
||||
t.Errorf("loopback: got %v, want the floor", err)
|
||||
}
|
||||
if _, err := resolve(t.Context(), "10.9.8.6", 443); !errors.Is(err, errFloor) {
|
||||
t.Errorf("private: got %v, want the floor", err)
|
||||
}
|
||||
if a, err := resolve(t.Context(), "10.9.8.7", 443); err != nil || len(a) != 1 {
|
||||
t.Errorf("an address rule should pass the floor: %v %v", a, err)
|
||||
}
|
||||
if _, why := check(t.Context(), "localhost", 443); why == "" {
|
||||
t.Error("localhost passed the floor through '**'")
|
||||
}
|
||||
}
|
||||
|
||||
// A deny beats any allow, for addresses too: a name that resolves to a denied address isn't dialed,
|
||||
// even when a host rule or a wider address rule allows it.
|
||||
func TestAddressDenyAppliesToNames(t *testing.T) {
|
||||
pol = writePolicy(t, "localhost:8080\n127.0.0.0/8:8080\n::1:8080\n!127.0.0.1:8080\n!::1:8080\n")
|
||||
if ok, _ := pol.decide("127.0.0.1", 8080); ok {
|
||||
t.Fatal("the denied address itself is allowed")
|
||||
}
|
||||
if pol.addrAllowed(netip.MustParseAddr("127.0.0.1"), 8080) {
|
||||
t.Error("addrAllowed ignores the deny")
|
||||
}
|
||||
if _, why := check(t.Context(), "localhost", 8080); why == "" {
|
||||
t.Error("localhost, which resolves to denied addresses, passed")
|
||||
}
|
||||
pol = writePolicy(t, "**\n!1.1.1.1\n")
|
||||
if a, err := resolve(t.Context(), "1.1.1.1", 443); err == nil {
|
||||
t.Errorf("a denied public address resolved: %v", a)
|
||||
}
|
||||
// The NAT64 form of a denied IPv4 address (64:ff9b::a.b.c.d, which DNS64 hands out on IPv6-only
|
||||
// networks) is denied too, as the floor judges it by the IPv4 address in it.
|
||||
pol = writePolicy(t, "**\n!203.0.113.0/24\n")
|
||||
n := netip.MustParseAddr("64:ff9b::cb00:7105")
|
||||
if !pol.addrDenied(n, 443) {
|
||||
t.Error("the NAT64 form of a denied address isn't denied")
|
||||
}
|
||||
if a, err := resolve(t.Context(), n.String(), 443); err == nil {
|
||||
t.Errorf("the NAT64 form of a denied address resolved: %v", a)
|
||||
}
|
||||
}
|
||||
|
||||
// With a password, every request needs it (user devvm): CONNECT, absolute-form and devvm.proxy alike.
|
||||
func TestProxyAuth(t *testing.T) {
|
||||
pol = writePolicy(t, "")
|
||||
proxyAuth = "k3y"
|
||||
t.Cleanup(func() { proxyAuth = "" })
|
||||
proxy := httptest.NewServer(http.HandlerFunc(handler))
|
||||
defer proxy.Close()
|
||||
basic := func(s string) string { return "Basic " + base64.StdEncoding.EncodeToString([]byte(s)) }
|
||||
for _, c := range []struct {
|
||||
auth string
|
||||
want int
|
||||
}{
|
||||
{"", http.StatusProxyAuthRequired},
|
||||
{basic("devvm:wrong"), http.StatusProxyAuthRequired},
|
||||
{basic("other:k3y"), http.StatusProxyAuthRequired},
|
||||
{basic("devvm:k3y"), http.StatusOK},
|
||||
} {
|
||||
for _, req := range []string{"GET http://devvm.proxy/blocked HTTP/1.1\r\nHost: devvm.proxy\r\n", "CONNECT devvm.proxy:443 HTTP/1.1\r\nHost: devvm.proxy:443\r\n"} {
|
||||
h := req
|
||||
if c.auth != "" {
|
||||
h += "Proxy-Authorization: " + c.auth + "\r\n"
|
||||
}
|
||||
got, _ := roundTrip(t, proxy.Listener.Addr().String(), h+"\r\n")
|
||||
if strings.HasPrefix(req, "CONNECT") && c.want == http.StatusOK {
|
||||
// Past the password: refused by the (empty) policy instead.
|
||||
if got == http.StatusProxyAuthRequired {
|
||||
t.Errorf("CONNECT with the password got 407")
|
||||
}
|
||||
continue
|
||||
}
|
||||
if got != c.want {
|
||||
t.Errorf("%s with %q: %d, want %d", strings.Fields(req)[0], c.auth, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Hosts are names or addresses; anything else (shell characters, spaces) is refused before the
|
||||
// policy, the log or the suggested allow command see it.
|
||||
func TestOddHostsRefused(t *testing.T) {
|
||||
pol = writePolicy(t, "")
|
||||
logOut = io.Discard
|
||||
proxy := httptest.NewServer(http.HandlerFunc(handler))
|
||||
defer proxy.Close()
|
||||
for _, req := range []string{
|
||||
"CONNECT x;sh*:443 HTTP/1.1\r\nHost: x\r\n\r\n",
|
||||
"GET http://x;sh*/ HTTP/1.1\r\nHost: x;sh*\r\n\r\n",
|
||||
"CONNECT $(id):443 HTTP/1.1\r\nHost: x\r\n\r\n",
|
||||
"CONNECT [fe80::1%25$(id)]:443 HTTP/1.1\r\nHost: x\r\n\r\n",
|
||||
} {
|
||||
code, body := roundTrip(t, proxy.Listener.Addr().String(), req)
|
||||
if code != http.StatusBadRequest || strings.Contains(body, "policy allow") {
|
||||
t.Errorf("%q: %d %q (want 400, no allow command)", strings.SplitN(req, "\r\n", 2)[0], code, body)
|
||||
}
|
||||
}
|
||||
for _, ok := range []string{"example.com", "a-b.c_d.test", "10.0.0.1", "[fd00::1]", "localhost"} {
|
||||
if !hostOK(ok) {
|
||||
t.Errorf("hostOK(%q) = false", ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// roundTrip sends a raw request to the proxy at addr and returns the response's status and body.
|
||||
func roundTrip(t *testing.T, addr, req string) (int, string) {
|
||||
t.Helper()
|
||||
c, err := new(net.Dialer).DialContext(t.Context(), "tcp", addr)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer c.Close()
|
||||
if _, err := c.Write([]byte(req)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp, err := http.ReadResponse(bufio.NewReader(c), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
return resp.StatusCode, string(body)
|
||||
}
|
||||
|
||||
func must(t *testing.T, err error) {
|
||||
t.Helper()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func clientHello(t *testing.T, name string) []byte {
|
||||
t.Helper()
|
||||
a, b := net.Pipe()
|
||||
//nolint:gosec // a test client; it never gets far enough to verify anything
|
||||
c := tls.Client(a, &tls.Config{ServerName: name, InsecureSkipVerify: name == ""})
|
||||
go func() { _ = c.HandshakeContext(t.Context()) }()
|
||||
r := bufio.NewReader(b)
|
||||
must(t, b.SetReadDeadline(time.Now().Add(5*time.Second)))
|
||||
rec, sni, isTLS := peekClientHello(r)
|
||||
_ = a.Close()
|
||||
if !isTLS {
|
||||
t.Fatal("not recognised as TLS")
|
||||
}
|
||||
if sni != name {
|
||||
t.Errorf("sni = %q, want %q", sni, name)
|
||||
}
|
||||
return rec
|
||||
}
|
||||
|
||||
func TestClientHello(t *testing.T) {
|
||||
if rec := clientHello(t, "api.example.com"); len(rec) < 50 || rec[0] != 0x16 {
|
||||
t.Errorf("record not returned for replay: %d bytes", len(rec))
|
||||
}
|
||||
clientHello(t, "")
|
||||
if _, _, isTLS := peekClientHello(bufio.NewReader(bytes.NewReader([]byte("SSH-2.0-OpenSSH_9.9\r\n")))); isTLS {
|
||||
t.Error("SSH treated as TLS")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSNIMatches(t *testing.T) {
|
||||
if !sniMatches("API.example.com", "api.example.com") || sniMatches("other.com", "api.example.com") {
|
||||
t.Error("name check")
|
||||
}
|
||||
if !sniMatches("", "1.2.3.4") || sniMatches("", "example.com") {
|
||||
t.Error("empty SNI is only fine for address literals")
|
||||
}
|
||||
}
|
||||
|
||||
// Main: -help prints the flags, bad arguments and a missing or empty password are errors, and
|
||||
// nothing is served then.
|
||||
func TestMainRefuses(t *testing.T) {
|
||||
var out, errs bytes.Buffer
|
||||
std := IO{Stdin: strings.NewReader(""), Stdout: &out, Stderr: &errs}
|
||||
if err := Main([]string{"--help"}, std); err != nil || !strings.Contains(out.String(), "-auth-file") {
|
||||
t.Errorf("--help: %v, %q", err, out.String())
|
||||
}
|
||||
empty := filepath.Join(t.TempDir(), "key")
|
||||
if err := os.WriteFile(empty, []byte("\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, args := range [][]string{
|
||||
{"-nope"},
|
||||
{"extra"},
|
||||
{},
|
||||
{"-auth-file", filepath.Join(t.TempDir(), "missing")},
|
||||
{"-auth-file", empty},
|
||||
} {
|
||||
if err := Main(args, std); err == nil {
|
||||
t.Errorf("%q: no error", args)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A short run: the proxy listens, logs that it does to stderr, answers with the VM's password, and
|
||||
// returns once the VM's hostagent (here a sleep) is gone.
|
||||
func TestMainRuns(t *testing.T) {
|
||||
lifelineTick = 50 * time.Millisecond
|
||||
t.Cleanup(func() { lifelineTick = 3 * time.Second; proxyAuth = "" })
|
||||
dir := t.TempDir()
|
||||
key, pidFile, logFile := filepath.Join(dir, "key"), filepath.Join(dir, "ha.pid"), filepath.Join(dir, "log.jsonl")
|
||||
if err := os.WriteFile(key, []byte("k3y\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sleep := exec.CommandContext(t.Context(), "sleep", "60")
|
||||
if err := sleep.Start(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = sleep.Process.Kill() })
|
||||
if err := os.WriteFile(pidFile, []byte(strconv.Itoa(sleep.Process.Pid)), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A free port, given back for the proxy to take.
|
||||
ln, err := new(net.ListenConfig).Listen(t.Context(), "tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
addr := ln.Addr().String()
|
||||
_ = ln.Close()
|
||||
|
||||
errs := &syncBuffer{}
|
||||
done := make(chan error)
|
||||
go func() {
|
||||
done <- Main([]string{
|
||||
"--listen", addr, "-vm", "devvm-x", "-auth-file", key, "-lifeline", pidFile, "-log", logFile,
|
||||
"-policy", filepath.Join(dir, "missing"),
|
||||
}, IO{Stdin: strings.NewReader(""), Stdout: io.Discard, Stderr: errs})
|
||||
}()
|
||||
pu, _ := url.Parse("http://devvm:k3y@" + addr)
|
||||
client := &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(pu)}}
|
||||
fetch := func(u string) (int, string, error) {
|
||||
req, _ := http.NewRequestWithContext(t.Context(), http.MethodGet, u, nil)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return 0, "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
return resp.StatusCode, string(b), nil
|
||||
}
|
||||
var code int
|
||||
var body string
|
||||
for range 100 {
|
||||
if code, body, err = fetch("http://devvm.proxy/blocked"); err == nil {
|
||||
break
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if code != http.StatusOK || body == "" {
|
||||
t.Errorf("/blocked: %d %q", code, body)
|
||||
}
|
||||
if code, _, err := fetch("http://blocked.test/"); err != nil || code != http.StatusForbidden {
|
||||
t.Errorf("blocked.test: %d %v", code, err)
|
||||
}
|
||||
b, _ := os.ReadFile(logFile) //nolint:gosec // the test's own file
|
||||
if !strings.Contains(string(b), `"vm":"devvm-x","event":"blocked","host":"blocked.test"`) {
|
||||
t.Errorf("event log = %q", b)
|
||||
}
|
||||
time.Sleep(5 * lifelineTick) // the proxy has seen the hostagent
|
||||
_ = sleep.Process.Kill()
|
||||
_ = sleep.Wait()
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
t.Errorf("Main: %v", err)
|
||||
}
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatalf("still running after the hostagent was gone: %s", errs.String())
|
||||
}
|
||||
if s := errs.String(); !strings.Contains(s, "devvm proxy: ") || !strings.Contains(s, "listening on "+addr+" for devvm-x") ||
|
||||
!strings.Contains(s, "hostagent is gone") {
|
||||
t.Errorf("stderr = %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
type syncBuffer struct {
|
||||
mu sync.Mutex
|
||||
b bytes.Buffer
|
||||
}
|
||||
|
||||
func (s *syncBuffer) Write(p []byte) (int, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.b.Write(p)
|
||||
}
|
||||
|
||||
func (s *syncBuffer) String() string {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.b.String()
|
||||
}
|
||||
|
||||
// The rule syntax: whatever a policy file holds, parsing doesn't panic, a rule's text parses
|
||||
// back to the same rule, and a host rule never holds a space or a slash.
|
||||
func FuzzParseRule(f *testing.F) {
|
||||
for _, s := range []string{
|
||||
"example.com", "*.github.com # c", "github.com:22", "!evil.github.com", "10.1.2.3",
|
||||
"192.168.0.0/16:8080", "**:9999", "[::1]:8080", "::1:8080", "!127.0.0.1:8080", "fd00::/8", "a b", "x/y", "#", ":", "!",
|
||||
} {
|
||||
f.Add(s)
|
||||
}
|
||||
f.Fuzz(func(t *testing.T, line string) {
|
||||
r, ok := parseRule(line)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
again, ok := parseRule(r.text)
|
||||
if !ok || again != r {
|
||||
t.Fatalf("%q: %+v, parsed again %+v (%v)", line, r, again, ok)
|
||||
}
|
||||
if strings.ContainsAny(r.host, " /\\#") {
|
||||
t.Fatalf("%q: host %q", line, r.host)
|
||||
}
|
||||
_ = r.matchHost("example.com")
|
||||
_ = r.matchAddr(netip.MustParseAddr("64:ff9b::a00:1"))
|
||||
})
|
||||
}
|
||||
|
||||
// A request's target, as the handler reads it: one the proxy accepts is a plain host (no shell
|
||||
// characters, for the log and the allow command it suggests), and that allow command's rule
|
||||
// allows exactly that host and port.
|
||||
func FuzzRequest(f *testing.F) {
|
||||
for _, s := range []string{
|
||||
"CONNECT example.com:443 HTTP/1.1\r\nHost: example.com:443\r\n\r\n",
|
||||
"CONNECT [fd00::1]:22 HTTP/1.1\r\nHost: x\r\n\r\n",
|
||||
"CONNECT x;sh*:443 HTTP/1.1\r\nHost: x\r\n\r\n",
|
||||
"CONNECT [fe80::1%25$(id)]:443 HTTP/1.1\r\nHost: x\r\n\r\n",
|
||||
"GET http://Example.COM.:8080/x HTTP/1.1\r\nHost: example.com\r\n\r\n",
|
||||
"GET https://10.0.0.1/ HTTP/1.1\r\nHost: 10.0.0.1\r\n\r\n",
|
||||
"GET / HTTP/1.1\r\nHost: devvm.proxy\r\n\r\n",
|
||||
} {
|
||||
f.Add(s)
|
||||
}
|
||||
dir := f.TempDir()
|
||||
n := 0
|
||||
f.Fuzz(func(t *testing.T, raw string) {
|
||||
r, err := http.ReadRequest(bufio.NewReader(strings.NewReader(raw)))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var host string
|
||||
var port int
|
||||
if r.Method == http.MethodConnect {
|
||||
host, port = splitHostPort(r.Host, 443)
|
||||
} else {
|
||||
def := 80
|
||||
if r.URL.Scheme == "https" {
|
||||
def = 443
|
||||
}
|
||||
host, port = splitHostPort(r.URL.Host, def)
|
||||
}
|
||||
if !hostOK(host) {
|
||||
return
|
||||
}
|
||||
for _, c := range host {
|
||||
if (c < 'a' || c > 'z') && (c < '0' || c > '9') && !strings.ContainsRune("-_.:[]", c) {
|
||||
t.Fatalf("%q: host %q holds %q", raw, host, c)
|
||||
}
|
||||
}
|
||||
if port < 1 || port > 65535 {
|
||||
return // never allowed: no rule names such a port
|
||||
}
|
||||
n++
|
||||
file := filepath.Join(dir, strconv.Itoa(n))
|
||||
if err := os.WriteFile(file, []byte(ruleFor(host, port)+"\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ok, why := newPolicy([]string{file}).decide(host, port); !ok {
|
||||
t.Fatalf("%q: the rule %q doesn't allow %s port %d: %s", raw, ruleFor(host, port), host, port, why)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// A tunnel's first bytes: whatever they are, reading a ClientHello doesn't panic or hang, and
|
||||
// only a TLS handshake record counts as TLS.
|
||||
func FuzzClientHello(f *testing.F) {
|
||||
f.Add([]byte("SSH-2.0-OpenSSH_9.9\r\n"))
|
||||
f.Add([]byte{0x16, 3, 1, 0, 4, 1, 0, 0, 0})
|
||||
f.Add([]byte{0x16, 3, 1, 0xff, 0xff})
|
||||
f.Fuzz(func(t *testing.T, b []byte) {
|
||||
rec, _, isTLS := peekClientHello(bufio.NewReader(bytes.NewReader(b)))
|
||||
if isTLS != (len(b) >= 5 && b[0] == 0x16 && b[1] == 3) {
|
||||
t.Fatalf("% x: TLS = %v", b, isTLS)
|
||||
}
|
||||
if !isTLS && rec != nil {
|
||||
t.Fatalf("% x: a record from a stream that isn't TLS", b)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
package proxy
|
||||
|
||||
// Agents' settings files copied into VMs with network policy (Codex's config.toml, opencode's
|
||||
// opencode.json, Claude Code's settings.json) can hold keys: an MCP server's headers or env, a
|
||||
// provider's apiKey. The proxy can't put those in (it only knows the logins), so the VM's copy gets
|
||||
// "devvm-redacted" for every value whose key looks like a secret's.
|
||||
//
|
||||
// devvm _proxy -redact json|toml < FILE > COPY (the redacted keys' paths on stderr, one per line)
|
||||
//
|
||||
// What's kept although its key matches: values that point elsewhere rather than hold a secret (an
|
||||
// env var's name, {env:X} or ${X}, a path), and non-strings.
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
// The key names: *key*, *token*, *secret*, *password*, Authorization (any case).
|
||||
redactName = regexp.MustCompile(`(?i)(key|token|secret|passw|^authorization$|^proxy-authorization$|^cookie$)`)
|
||||
envName = regexp.MustCompile(`^[A-Z][A-Z0-9_]*$`)
|
||||
envRef = regexp.MustCompile(`^(\{(env|file):[^}]*\}|\$\{?[A-Za-z_][A-Za-z0-9_]*\}?)$`)
|
||||
)
|
||||
|
||||
// redactKeep: a value that names where a secret is rather than holding it.
|
||||
func redactKeep(v string) bool {
|
||||
switch {
|
||||
case v == "" || v == "devvm-redacted":
|
||||
return true
|
||||
case envName.MatchString(v): // an env var's name (Codex's env_key)
|
||||
return true
|
||||
case envRef.MatchString(v):
|
||||
return true
|
||||
case strings.HasPrefix(v, "/") || strings.HasPrefix(v, "~/") || strings.HasPrefix(v, "./"):
|
||||
return true // a path: a helper command or a key file the VM doesn't have
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func redactCmd(format string, in io.Reader, out, names io.Writer) error {
|
||||
data, err := io.ReadAll(in)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var paths []string
|
||||
switch format {
|
||||
case "json":
|
||||
var v any
|
||||
if err := json.Unmarshal(stripJSONC(data), &v); err != nil {
|
||||
return fmt.Errorf("not JSON: %w", err)
|
||||
}
|
||||
v = redactJSON(v, "", &paths)
|
||||
b, err := json.MarshalIndent(v, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := out.Write(append(b, '\n')); err != nil {
|
||||
return err
|
||||
}
|
||||
case "toml":
|
||||
s, err := redactTOML(string(data), &paths)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := io.WriteString(out, s); err != nil {
|
||||
return err
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("unknown format %q", format)
|
||||
}
|
||||
sort.Strings(paths)
|
||||
for _, p := range paths {
|
||||
fmt.Fprintln(names, p)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func redactJSON(v any, path string, paths *[]string) any {
|
||||
switch t := v.(type) {
|
||||
case map[string]any:
|
||||
for k, x := range t {
|
||||
p := k
|
||||
if path != "" {
|
||||
p = path + "." + k
|
||||
}
|
||||
if s, ok := x.(string); ok && redactName.MatchString(k) && !redactKeep(s) {
|
||||
t[k] = "devvm-redacted"
|
||||
*paths = append(*paths, p)
|
||||
continue
|
||||
}
|
||||
t[k] = redactJSON(x, p, paths)
|
||||
}
|
||||
case []any:
|
||||
for i, x := range t {
|
||||
t[i] = redactJSON(x, fmt.Sprintf("%s[%d]", path, i), paths)
|
||||
}
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// stripJSONC: opencode's files may be JSONC: // and /* */ comments, and trailing commas.
|
||||
func stripJSONC(b []byte) []byte {
|
||||
var out []byte
|
||||
inStr, esc := false, false
|
||||
for i := 0; i < len(b); i++ {
|
||||
c := b[i]
|
||||
if inStr {
|
||||
out = append(out, c)
|
||||
switch {
|
||||
case esc:
|
||||
esc = false
|
||||
case c == '\\':
|
||||
esc = true
|
||||
case c == '"':
|
||||
inStr = false
|
||||
}
|
||||
continue
|
||||
}
|
||||
switch {
|
||||
case c == '"':
|
||||
inStr = true
|
||||
out = append(out, c)
|
||||
case c == '/' && i+1 < len(b) && b[i+1] == '/':
|
||||
for i < len(b) && b[i] != '\n' {
|
||||
i++
|
||||
}
|
||||
out = append(out, '\n')
|
||||
case c == '/' && i+1 < len(b) && b[i+1] == '*':
|
||||
i += 2
|
||||
for i+1 < len(b) && (b[i] != '*' || b[i+1] != '/') {
|
||||
i++
|
||||
}
|
||||
i++
|
||||
default:
|
||||
out = append(out, c)
|
||||
}
|
||||
}
|
||||
// Trailing commas: a comma followed (after whitespace) by } or ].
|
||||
return regexp.MustCompile(`,(\s*[}\]])`).ReplaceAll(out, []byte("$1"))
|
||||
}
|
||||
|
||||
// TOML, line by line (Codex's config.toml): `key = "value"` lines, and `{ key = "value", ... }` inline
|
||||
// tables, under [table] headers. Multi-line strings are refused rather than copied unread.
|
||||
var (
|
||||
tomlTable = regexp.MustCompile(`^\s*\[\[?\s*([^\]]+?)\s*\]\]?\s*(#.*)?$`)
|
||||
tomlKV = regexp.MustCompile(`^(\s*)((?:"[^"]*"|'[^']*'|[A-Za-z0-9_.\-]+))(\s*=\s*)(.*)$`)
|
||||
tomlString = regexp.MustCompile(`^("(?:[^"\\]|\\.)*"|'[^']*')(.*)$`)
|
||||
tomlStrings = regexp.MustCompile(`"(?:[^"\\]|\\.)*"|'[^']*'`)
|
||||
tomlInline = regexp.MustCompile(`((?:"[^"]*"|'[^']*'|[A-Za-z0-9_\-]+))(\s*=\s*)("(?:[^"\\]|\\.)*"|'[^']*')`)
|
||||
)
|
||||
|
||||
func tomlUnquote(s string) string {
|
||||
if len(s) >= 2 && (s[0] == '"' || s[0] == '\'') {
|
||||
return s[1 : len(s)-1]
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func redactTOML(s string, paths *[]string) (string, error) {
|
||||
var b strings.Builder
|
||||
table := ""
|
||||
sc := bufio.NewScanner(strings.NewReader(s))
|
||||
sc.Buffer(make([]byte, 1<<20), 1<<20)
|
||||
for sc.Scan() {
|
||||
line := sc.Text()
|
||||
if strings.Contains(line, `"""`) || strings.Contains(line, `'''`) {
|
||||
return "", fmt.Errorf("multi-line strings aren't supported (line %q)", line)
|
||||
}
|
||||
if m := tomlTable.FindStringSubmatch(line); m != nil && !strings.Contains(line, "=") {
|
||||
table = m[1]
|
||||
b.WriteString(line + "\n")
|
||||
continue
|
||||
}
|
||||
m := tomlKV.FindStringSubmatch(line)
|
||||
if m == nil {
|
||||
b.WriteString(line + "\n")
|
||||
continue
|
||||
}
|
||||
key, path := tomlUnquote(m[2]), tomlUnquote(m[2])
|
||||
if table != "" {
|
||||
path = table + "." + key
|
||||
}
|
||||
val := m[4]
|
||||
if sm := tomlString.FindStringSubmatch(val); sm != nil {
|
||||
if last := key[strings.LastIndex(key, ".")+1:]; redactName.MatchString(last) && !redactKeep(tomlUnquote(sm[1])) {
|
||||
val = `"devvm-redacted"` + sm[2]
|
||||
*paths = append(*paths, path)
|
||||
}
|
||||
} else if last := key[strings.LastIndex(key, ".")+1:]; last == "args" && strings.HasPrefix(strings.TrimSpace(val), "[") {
|
||||
// An MCP server's arguments: as in ~/.claude.json (scrubArgs).
|
||||
var as []any
|
||||
for _, q := range tomlStrings.FindAllString(val, -1) {
|
||||
as = append(as, tomlUnquote(q))
|
||||
}
|
||||
if s, changed := scrubArgs(as); changed {
|
||||
b, _ := json.Marshal(s)
|
||||
val = string(b)
|
||||
*paths = append(*paths, path)
|
||||
}
|
||||
} else if strings.HasPrefix(strings.TrimSpace(val), "{") {
|
||||
val = tomlInline.ReplaceAllStringFunc(val, func(kv string) string {
|
||||
p := tomlInline.FindStringSubmatch(kv)
|
||||
if k := tomlUnquote(p[1]); redactName.MatchString(k) && !redactKeep(tomlUnquote(p[3])) {
|
||||
*paths = append(*paths, path+"."+k)
|
||||
return p[1] + p[2] + `"devvm-redacted"`
|
||||
}
|
||||
return kv
|
||||
})
|
||||
}
|
||||
b.WriteString(m[1] + m[2] + m[3] + val + "\n")
|
||||
}
|
||||
return b.String(), sc.Err()
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func redacted(t *testing.T, format, in string) (string, string) {
|
||||
t.Helper()
|
||||
var out, names bytes.Buffer
|
||||
if err := redactCmd(format, strings.NewReader(in), &out, &names); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return out.String(), names.String()
|
||||
}
|
||||
|
||||
// Codex's config.toml with secrets in headers and env, and settings that only name them.
|
||||
func TestRedactTOML(t *testing.T) {
|
||||
in := `model = "o4"
|
||||
preferred_auth_method = "apikey"
|
||||
mcp_servers.u.env.SECRET_X = 'DUMMY-SQ'
|
||||
|
||||
[model_providers.x]
|
||||
env_key = "OPENAI_API_KEY"
|
||||
http_headers = { "Authorization" = "Bearer DUMMY-CODEX", "X-Org" = "acme" }
|
||||
|
||||
[mcp_servers.s]
|
||||
command = "npx"
|
||||
args = ["srv"]
|
||||
env = { API_KEY = "DUMMY-ENV", MODE = "fast" }
|
||||
|
||||
[mcp_servers.k]
|
||||
args = ["-y", "srv-k", "--api-key", "DUMMY-ARG"]
|
||||
|
||||
[mcp_servers.t.env]
|
||||
GITHUB_TOKEN = "DUMMY-GH" # a comment
|
||||
`
|
||||
out, names := redacted(t, "toml", in)
|
||||
for _, s := range []string{"DUMMY-CODEX", "DUMMY-ENV", "DUMMY-GH", "DUMMY-SQ", "DUMMY-ARG"} {
|
||||
if strings.Contains(out, s) {
|
||||
t.Errorf("copy holds %q:\n%s", s, out)
|
||||
}
|
||||
}
|
||||
for _, s := range []string{
|
||||
`env_key = "OPENAI_API_KEY"`, `"X-Org" = "acme"`, `MODE = "fast"`, `preferred_auth_method = "apikey"`,
|
||||
`GITHUB_TOKEN = "devvm-redacted" # a comment`, `args = ["srv"]`,
|
||||
} {
|
||||
if !strings.Contains(out, s) {
|
||||
t.Errorf("copy lost %q:\n%s", s, out)
|
||||
}
|
||||
}
|
||||
want := "mcp_servers.k.args\nmcp_servers.s.env.API_KEY\nmcp_servers.t.env.GITHUB_TOKEN\nmcp_servers.u.env.SECRET_X\nmodel_providers.x.http_headers.Authorization\n"
|
||||
if names != want {
|
||||
t.Errorf("names = %q, want %q", names, want)
|
||||
}
|
||||
if _, err := redactTOML("x = \"\"\"\nsecret\n\"\"\"\n", new([]string)); err == nil {
|
||||
t.Error("a multi-line string was copied unread")
|
||||
}
|
||||
}
|
||||
|
||||
// opencode.json (JSONC) and Claude Code's settings.json.
|
||||
func TestRedactJSON(t *testing.T) {
|
||||
in := `{
|
||||
// a comment with "quotes"
|
||||
"provider": {"anthropic": {"options": {"apiKey": "DUMMY-OC", "baseURL": "https://x"}}},
|
||||
"other": {"options": {"apiKey": "{env:OTHER_KEY}"}},
|
||||
"mcp": {"m": {"headers": {"Authorization": "Bearer DUMMY-H"}, "command": ["a", "b"]}},
|
||||
"env": {"ANTHROPIC_API_KEY": "DUMMY-CL", "ANTHROPIC_BASE_URL": "https://gw", "N": 1},
|
||||
"apiKeyHelper": "/usr/local/bin/key-helper", /* trailing */
|
||||
}`
|
||||
out, names := redacted(t, "json", in)
|
||||
for _, s := range []string{"DUMMY-OC", "DUMMY-H", "DUMMY-CL"} {
|
||||
if strings.Contains(out, s) {
|
||||
t.Errorf("copy holds %q:\n%s", s, out)
|
||||
}
|
||||
}
|
||||
for _, s := range []string{"{env:OTHER_KEY}", "https://gw", "/usr/local/bin/key-helper", `"baseURL": "https://x"`} {
|
||||
if !strings.Contains(out, s) {
|
||||
t.Errorf("copy lost %q:\n%s", s, out)
|
||||
}
|
||||
}
|
||||
if want := "env.ANTHROPIC_API_KEY\nmcp.m.headers.Authorization\nprovider.anthropic.options.apiKey\n"; names != want {
|
||||
t.Errorf("names = %q, want %q", names, want)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,480 @@
|
||||
package proxy
|
||||
|
||||
// Secrets: the VM only ever holds placeholders. For hosts with a bound secret, the proxy terminates
|
||||
// TLS with a certificate from devvm's own CA (trusted only inside VMs), replaces the placeholder in
|
||||
// the binding's header with the real value, and forwards over a fresh TLS connection. Values come
|
||||
// from `devvm secret get NAME` (the macOS Keychain) on demand and are cached briefly; they're never
|
||||
// logged or written anywhere.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// binding: which hosts get a secret, in which header, and the placeholder the VM sends instead.
|
||||
type binding struct {
|
||||
Name string `json:"name"`
|
||||
Hosts []string `json:"hosts"` // host patterns, as in policy files
|
||||
Header string `json:"header"` // e.g. Authorization; the placeholder is replaced inside its value
|
||||
Placeholder string `json:"placeholder"`
|
||||
}
|
||||
|
||||
var (
|
||||
secretsPath = "" // -secrets: JSON list of bindings (no values), re-read on change
|
||||
secretCmd = "" // -secret-cmd: the devvm script, run as `devvm secret get NAME`
|
||||
upstreamCAs *x509.CertPool // nil: the system roots (tests set their own)
|
||||
// Only HTTPS is intercepted; anything else to a bound host (SSH on :22, …) is tunneled.
|
||||
interceptPorts = map[int]bool{443: true}
|
||||
)
|
||||
|
||||
type bindingFile struct {
|
||||
mu sync.Mutex
|
||||
mtime time.Time
|
||||
list []binding
|
||||
}
|
||||
|
||||
var bindings = &bindingFile{}
|
||||
|
||||
func (b *bindingFile) all() []binding {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
if secretsPath == "" {
|
||||
return nil
|
||||
}
|
||||
st, err := os.Stat(secretsPath)
|
||||
if err != nil {
|
||||
b.list = nil
|
||||
return nil
|
||||
}
|
||||
if !st.ModTime().Equal(b.mtime) {
|
||||
var list []binding
|
||||
if data, err := os.ReadFile(secretsPath); err == nil && json.Unmarshal(data, &list) == nil {
|
||||
b.list, b.mtime = list, st.ModTime()
|
||||
logf("secrets %s: %d bindings", secretsPath, len(list))
|
||||
}
|
||||
// devvm touches the file when a value is set or removed: look values up afresh.
|
||||
valueMu.Lock()
|
||||
values = map[string]cached{}
|
||||
valueMu.Unlock()
|
||||
}
|
||||
return b.list
|
||||
}
|
||||
|
||||
// bindingsFor: the bindings that apply to host.
|
||||
func bindingsFor(host string) []binding {
|
||||
var out []binding
|
||||
for _, b := range bindings.all() {
|
||||
for _, h := range b.Hosts {
|
||||
if r, ok := parseRule(h); ok && !r.deny && r.matchHost(strings.ToLower(host)) {
|
||||
out = append(out, b)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// --- values ---
|
||||
|
||||
type cached struct {
|
||||
value string
|
||||
at time.Time
|
||||
}
|
||||
|
||||
var (
|
||||
valueMu sync.Mutex
|
||||
values = map[string]cached{}
|
||||
)
|
||||
|
||||
// A value is cached for valueTTL; one from an agent's login file (Codex, opencode, Claude MCP) for
|
||||
// loginTTL, since logging out on the host changes nothing devvm sees.
|
||||
const (
|
||||
valueTTL = 5 * time.Minute
|
||||
loginTTL = 30 * time.Second
|
||||
)
|
||||
|
||||
func ttlOf(name string) time.Duration {
|
||||
if name == "codex" || name == "codex-key" || strings.HasPrefix(name, "opencode-") || strings.HasPrefix(name, "claude-mcp-") {
|
||||
return loginTTL
|
||||
}
|
||||
return valueTTL
|
||||
}
|
||||
|
||||
// secretValue runs `devvm secret get NAME` (cached, see ttlOf).
|
||||
var secretValue = func(name string) (string, error) {
|
||||
valueMu.Lock()
|
||||
defer valueMu.Unlock()
|
||||
if c, ok := values[name]; ok && time.Since(c.at) < ttlOf(name) {
|
||||
return c.value, nil
|
||||
}
|
||||
if secretCmd == "" {
|
||||
return "", errors.New("no -secret-cmd")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
out, err := exec.CommandContext(ctx, secretCmd, "secret", "get", name).Output() //nolint:gosec // devvm names itself
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("devvm secret get %s: %w", name, err)
|
||||
}
|
||||
v := strings.TrimSpace(string(out))
|
||||
if v == "" {
|
||||
return "", fmt.Errorf("secret %s is empty", name)
|
||||
}
|
||||
values[name] = cached{v, time.Now()}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// inject replaces each binding's placeholder in its header, also inside "Basic" credentials (git
|
||||
// over HTTPS sends user:token that way). Only the binding's header is touched. It returns the names
|
||||
// of the secrets it put in.
|
||||
func inject(h http.Header, bs []binding) (used []string) {
|
||||
for _, b := range bs {
|
||||
vs := h.Values(b.Header)
|
||||
if len(vs) == 0 {
|
||||
continue
|
||||
}
|
||||
var val string
|
||||
var err error
|
||||
replaced := false
|
||||
for i, v := range vs {
|
||||
nv := v
|
||||
if strings.Contains(nv, b.Placeholder) || basicHas(nv, b.Placeholder) {
|
||||
if val == "" {
|
||||
if val, err = secretValue(b.Name); err != nil {
|
||||
logf("%v", err)
|
||||
return used
|
||||
}
|
||||
}
|
||||
nv = strings.ReplaceAll(nv, b.Placeholder, val)
|
||||
if raw, ok := basic(nv); ok && strings.Contains(raw, b.Placeholder) {
|
||||
nv = "Basic " + base64.StdEncoding.EncodeToString([]byte(strings.ReplaceAll(raw, b.Placeholder, val)))
|
||||
}
|
||||
vs[i], replaced = nv, true
|
||||
}
|
||||
}
|
||||
if replaced {
|
||||
h.Del(b.Header)
|
||||
for _, v := range vs {
|
||||
h.Add(b.Header, v)
|
||||
}
|
||||
used = append(used, b.Name)
|
||||
}
|
||||
}
|
||||
return used
|
||||
}
|
||||
|
||||
func basic(v string) (string, bool) {
|
||||
if len(v) < 6 || !strings.EqualFold(v[:6], "basic ") {
|
||||
return "", false
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(v[6:]))
|
||||
return string(raw), err == nil
|
||||
}
|
||||
|
||||
func basicHas(v, placeholder string) bool {
|
||||
raw, ok := basic(v)
|
||||
return ok && strings.Contains(raw, placeholder)
|
||||
}
|
||||
|
||||
// --- the CA ---
|
||||
|
||||
var (
|
||||
caCert *x509.Certificate
|
||||
caKey *ecdsa.PrivateKey
|
||||
leafKey *ecdsa.PrivateKey
|
||||
leafMu sync.Mutex
|
||||
leaves = map[string]*tls.Certificate{}
|
||||
)
|
||||
|
||||
// The CA lasts caLife and is replaced when it has less than caRenew left: a key that leaks (in a
|
||||
// backup, say) stops working within weeks. VMs trust a new CA from their next launch; a running
|
||||
// proxy keeps the one it started with, which is still valid then.
|
||||
const (
|
||||
caLife = 30 * 24 * time.Hour
|
||||
caRenew = 7 * 24 * time.Hour
|
||||
)
|
||||
|
||||
// initCA writes a new CA into dir (ca.pem, ca.key mode 600) unless a valid one with over caRenew
|
||||
// left is there. One valid for longer than caLife (made before CAs were rotated) is replaced too.
|
||||
func initCA(dir string) error {
|
||||
certPath, keyPath := filepath.Join(dir, "ca.pem"), filepath.Join(dir, "ca.key")
|
||||
if _, err := os.Stat(keyPath); err == nil {
|
||||
if pair, err := tls.LoadX509KeyPair(certPath, keyPath); err == nil {
|
||||
if c, err := x509.ParseCertificate(pair.Certificate[0]); err == nil && time.Until(c.NotAfter) > caRenew &&
|
||||
c.NotAfter.Sub(c.NotBefore) <= caLife+time.Hour {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
serial, _ := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
|
||||
tmpl := &x509.Certificate{
|
||||
SerialNumber: serial,
|
||||
// No host name: every VM sees this certificate.
|
||||
Subject: pkix.Name{CommonName: "devvm proxy CA", Organization: []string{"devvm"}},
|
||||
NotBefore: time.Now().Add(-time.Hour),
|
||||
NotAfter: time.Now().Add(caLife),
|
||||
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
|
||||
BasicConstraintsValid: true,
|
||||
IsCA: true,
|
||||
MaxPathLenZero: true,
|
||||
}
|
||||
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
kder, err := x509.MarshalECPrivateKey(key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
// Each file whole or not at all (temp file, then rename), so a crash halfway leaves no pair that
|
||||
// doesn't match.
|
||||
if err := writeAtomic(keyPath, pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: kder}), 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
return writeAtomic(certPath, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), 0o644)
|
||||
}
|
||||
|
||||
func writeAtomic(path string, data []byte, mode os.FileMode) error {
|
||||
tmp, err := os.CreateTemp(filepath.Dir(path), ".devvm-ca-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.Remove(tmp.Name())
|
||||
if _, err := tmp.Write(data); err != nil {
|
||||
_ = tmp.Close()
|
||||
return err
|
||||
}
|
||||
if err := tmp.Chmod(mode); err != nil {
|
||||
_ = tmp.Close()
|
||||
return err
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmp.Name(), path)
|
||||
}
|
||||
|
||||
func loadCA(certPath, keyPath string) error {
|
||||
pair, err := tls.LoadX509KeyPair(certPath, keyPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
k, ok := pair.PrivateKey.(*ecdsa.PrivateKey)
|
||||
if !ok {
|
||||
return errors.New("the CA key isn't ECDSA")
|
||||
}
|
||||
if caCert, err = x509.ParseCertificate(pair.Certificate[0]); err != nil {
|
||||
return err
|
||||
}
|
||||
caKey = k
|
||||
leafKey, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
return err
|
||||
}
|
||||
|
||||
func caPEM() []byte {
|
||||
if caCert == nil {
|
||||
return nil
|
||||
}
|
||||
return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: caCert.Raw})
|
||||
}
|
||||
|
||||
// leafFor mints (and caches for a day) a certificate for host, signed by the CA.
|
||||
func leafFor(host string) (*tls.Certificate, error) {
|
||||
leafMu.Lock()
|
||||
defer leafMu.Unlock()
|
||||
if c, ok := leaves[host]; ok && time.Until(c.Leaf.NotAfter) > time.Hour {
|
||||
return c, nil
|
||||
}
|
||||
serial, _ := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
|
||||
tmpl := &x509.Certificate{
|
||||
SerialNumber: serial,
|
||||
Subject: pkix.Name{CommonName: host},
|
||||
NotBefore: time.Now().Add(-time.Hour),
|
||||
NotAfter: time.Now().Add(24 * time.Hour),
|
||||
KeyUsage: x509.KeyUsageDigitalSignature,
|
||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||
DNSNames: []string{host},
|
||||
}
|
||||
der, err := x509.CreateCertificate(rand.Reader, tmpl, caCert, &leafKey.PublicKey, caKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
leaf, _ := x509.ParseCertificate(der)
|
||||
c := &tls.Certificate{Certificate: [][]byte{der, caCert.Raw}, PrivateKey: leafKey, Leaf: leaf}
|
||||
leaves[host] = c
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// --- interception ---
|
||||
|
||||
// intercept serves one CONNECT tunnel to host:443 whose host has bindings: TLS with a minted
|
||||
// certificate on the client side, HTTP/1.1 or HTTP/2 inside, and each request forwarded upstream
|
||||
// over a new TLS connection with the secrets put in. Each request must be for host itself: the
|
||||
// secrets are bound to it, so another Host (a site on the same CDN, say) gets 421.
|
||||
func intercept(client net.Conn, host string, port int, e event) {
|
||||
tconn := tls.Server(client, &tls.Config{
|
||||
NextProtos: []string{"h2", "http/1.1"},
|
||||
GetCertificate: func(*tls.ClientHelloInfo) (*tls.Certificate, error) {
|
||||
return leafFor(host)
|
||||
},
|
||||
})
|
||||
if err := tconn.HandshakeContext(context.Background()); err != nil {
|
||||
e.Event, e.Reason = "blocked", "TLS with the VM failed (is the devvm CA installed?): "+err.Error()
|
||||
record(e)
|
||||
_ = client.Close()
|
||||
return
|
||||
}
|
||||
e.Event = "intercept"
|
||||
record(e)
|
||||
cn := &closeNotifyConn{Conn: tconn, done: make(chan struct{})}
|
||||
fwd := forwarder("https", net.JoinHostPort(host, fmt.Sprint(port)), host, port)
|
||||
srv := &http.Server{
|
||||
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if h, _ := splitHostPort(r.Host, port); h != host {
|
||||
http.Error(w, "devvm proxy: this connection is for "+host, http.StatusMisdirectedRequest)
|
||||
return
|
||||
}
|
||||
if what := mintsCredential(host, r.Method, r.URL.Path); what != "" {
|
||||
record(event{
|
||||
Event: "blocked", Host: host, Port: port, Method: r.Method, Path: r.URL.Path, Refused: true,
|
||||
Reason: "makes " + what + " with your token, which would outlast the VM; do it on the host",
|
||||
})
|
||||
http.Error(w, "devvm proxy: refused: this makes "+what+" with your token (do it on the host)", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
fwd.ServeHTTP(w, r)
|
||||
}),
|
||||
Protocols: new(http.Protocols),
|
||||
IdleTimeout: 10 * time.Minute,
|
||||
ReadHeaderTimeout: 30 * time.Second,
|
||||
}
|
||||
// TLS is already done here, so the server sees plain HTTP/1.1, or HTTP/2 with prior knowledge.
|
||||
srv.Protocols.SetHTTP1(true)
|
||||
srv.Protocols.SetUnencryptedHTTP2(true)
|
||||
_ = srv.Serve(&oneConnListener{c: cn, done: cn.done})
|
||||
}
|
||||
|
||||
// GitHub API calls that make a credential of their own with the token the proxy puts in: an SSH or
|
||||
// GPG key on your account, a repo's deploy key, a self-hosted runner's registration, a webhook
|
||||
// (which sends a repo's events anywhere). Each would keep working after devvm secret unuse.
|
||||
var githubMinting = []struct {
|
||||
methods string
|
||||
path *regexp.Regexp
|
||||
what string
|
||||
}{
|
||||
{"POST", regexp.MustCompile(`^/user/(keys|ssh_signing_keys|gpg_keys)$`), "a key on your GitHub account"},
|
||||
{"POST", regexp.MustCompile(`^/repos/[^/]+/[^/]+/keys$`), "a deploy key"},
|
||||
{"POST", regexp.MustCompile(`^/(repos/[^/]+/[^/]+|orgs/[^/]+|enterprises/[^/]+)/actions/runners/(registration-token|generate-jitconfig)$`), "a self-hosted runner"},
|
||||
{"POST PATCH", regexp.MustCompile(`^/(repos/[^/]+/[^/]+|orgs/[^/]+)/hooks(/[^/]+(/config)?)?$`), "a webhook"},
|
||||
}
|
||||
|
||||
// mintsCredential: what the request would make, or "".
|
||||
func mintsCredential(host, method, p string) string {
|
||||
if host != "api.github.com" {
|
||||
return ""
|
||||
}
|
||||
p = strings.ToLower(path.Clean("/" + p))
|
||||
for _, m := range githubMinting {
|
||||
if strings.Contains(" "+m.methods+" ", " "+strings.ToUpper(method)+" ") && m.path.MatchString(p) {
|
||||
return m.what
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// forwarder: a streaming reverse proxy to scheme://target, dialing through the floor, putting
|
||||
// secrets in (HTTPS only), and logging each request. The bindings are read for every request, so
|
||||
// `devvm secret unuse` applies to connections already open.
|
||||
func forwarder(scheme, target, host string, port int) http.Handler {
|
||||
tlsConf := &tls.Config{RootCAs: upstreamCAs, ServerName: host}
|
||||
return &httputil.ReverseProxy{
|
||||
Transport: &http.Transport{
|
||||
DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { return dial(ctx, host, port) },
|
||||
TLSClientConfig: tlsConf, ForceAttemptHTTP2: true,
|
||||
IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 10 * time.Second,
|
||||
},
|
||||
FlushInterval: -1, // stream (SSE) instead of buffering
|
||||
Rewrite: func(pr *httputil.ProxyRequest) {
|
||||
pr.Out.URL.Scheme, pr.Out.URL.Host = scheme, target
|
||||
// The host that was checked (and its secrets bound to), in its canonical form: not the
|
||||
// VM's Host header, which may differ in port or a trailing dot.
|
||||
pr.Out.Host = host
|
||||
if (scheme != "https" || port != 443) && (scheme != "http" || port != 80) {
|
||||
pr.Out.Host = net.JoinHostPort(host, fmt.Sprint(port))
|
||||
}
|
||||
pr.Out.Header.Del("Proxy-Authorization")
|
||||
pr.Out.Header.Del("Proxy-Connection")
|
||||
e := event{Event: "forward", Host: host, Port: port, Method: pr.In.Method, Path: pr.In.URL.Path, Agent: pr.In.UserAgent()}
|
||||
if scheme == "https" && interceptPorts[port] { // secrets only ever go over TLS, to :443
|
||||
if bs := bindingsFor(host); len(bs) > 0 {
|
||||
e.Secrets = inject(pr.Out.Header, bs)
|
||||
}
|
||||
}
|
||||
record(e)
|
||||
},
|
||||
// The error stays in the proxy's own log: it can name addresses the VM shouldn't learn.
|
||||
ErrorHandler: func(w http.ResponseWriter, _ *http.Request, err error) {
|
||||
logf("%s:%d: %v", host, port, err)
|
||||
http.Error(w, "devvm proxy: couldn't reach "+host, http.StatusBadGateway)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// One already-accepted connection as a listener, for http.Server.Serve.
|
||||
type oneConnListener struct {
|
||||
c net.Conn
|
||||
once sync.Once
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
func (l *oneConnListener) Accept() (net.Conn, error) {
|
||||
var c net.Conn
|
||||
l.once.Do(func() { c = l.c })
|
||||
if c != nil {
|
||||
return c, nil
|
||||
}
|
||||
<-l.done
|
||||
return nil, net.ErrClosed
|
||||
}
|
||||
func (l *oneConnListener) Close() error { return nil }
|
||||
func (l *oneConnListener) Addr() net.Addr { return l.c.LocalAddr() }
|
||||
|
||||
type closeNotifyConn struct {
|
||||
net.Conn
|
||||
once sync.Once
|
||||
done chan struct{}
|
||||
}
|
||||
|
||||
func (c *closeNotifyConn) Close() error {
|
||||
c.once.Do(func() { close(c.done) })
|
||||
return c.Conn.Close()
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"crypto/ecdsa"
|
||||
"crypto/rand"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/base64"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/big"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func fakeSecret(t *testing.T, value string) {
|
||||
t.Helper()
|
||||
old := secretValue
|
||||
secretValue = func(string) (string, error) { return value, nil }
|
||||
t.Cleanup(func() { secretValue = old })
|
||||
}
|
||||
|
||||
func TestInject(t *testing.T) {
|
||||
fakeSecret(t, "real")
|
||||
bs := []binding{{Name: "github", Header: "Authorization", Placeholder: "PH"}}
|
||||
h := http.Header{}
|
||||
h.Set("Authorization", "token PH")
|
||||
h.Set("X-Echo", "PH")
|
||||
if used := inject(h, bs); len(used) != 1 || used[0] != "github" {
|
||||
t.Errorf("used = %v", used)
|
||||
}
|
||||
if h.Get("Authorization") != "token real" || h.Get("X-Echo") != "PH" {
|
||||
t.Errorf("headers = %v (only the binding's header may change)", h)
|
||||
}
|
||||
h = http.Header{}
|
||||
h.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("x-access-token:PH")))
|
||||
inject(h, bs)
|
||||
if raw, _ := basic(h.Get("Authorization")); raw != "x-access-token:real" {
|
||||
t.Errorf("basic = %q", raw)
|
||||
}
|
||||
h = http.Header{}
|
||||
h.Set("Authorization", "Bearer something-else")
|
||||
if used := inject(h, bs); len(used) != 0 || h.Get("Authorization") != "Bearer something-else" {
|
||||
t.Error("a header without the placeholder changed")
|
||||
}
|
||||
}
|
||||
|
||||
// interceptSetup: devvm's CA in a temp dir, an upstream HTTPS server for "localhost" (handler h) with a
|
||||
// certificate from it, a policy allowing it, a secret bound to it (placeholder PH, value "real"), and
|
||||
// the proxy. It returns the upstream's port, the bindings file, and a client that goes through the
|
||||
// proxy and trusts the CA, keeping one connection open.
|
||||
func interceptSetup(t *testing.T, h http.HandlerFunc) (int, string, *http.Client) {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
if err := initCA(dir); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := loadCA(filepath.Join(dir, "ca.pem"), filepath.Join(dir, "ca.key")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
leaves = map[string]*tls.Certificate{} // minted by another test's CA
|
||||
pool := x509.NewCertPool()
|
||||
pool.AddCert(caCert)
|
||||
upstreamCAs = pool
|
||||
t.Cleanup(func() { upstreamCAs = nil })
|
||||
up := httptest.NewUnstartedServer(h)
|
||||
cert, _ := leafFor("localhost")
|
||||
up.TLS = &tls.Config{Certificates: []tls.Certificate{*cert}}
|
||||
up.StartTLS()
|
||||
t.Cleanup(up.Close)
|
||||
_, portStr, _ := net.SplitHostPort(up.Listener.Addr().String())
|
||||
port, err := strconv.Atoi(portStr)
|
||||
must(t, err)
|
||||
interceptPorts[port] = true
|
||||
t.Cleanup(func() { delete(interceptPorts, port) })
|
||||
pol = writePolicy(t, fmt.Sprintf("localhost:%d\n127.0.0.1:%d\n", port, port))
|
||||
secretsPath = filepath.Join(dir, "bindings.json")
|
||||
must(t, os.WriteFile(secretsPath, []byte(`[{"name":"t","hosts":["localhost"],"header":"Authorization","placeholder":"PH"}]`), 0o600))
|
||||
t.Cleanup(func() { secretsPath = "" })
|
||||
fakeSecret(t, "real")
|
||||
proxy := httptest.NewServer(http.HandlerFunc(handler))
|
||||
t.Cleanup(proxy.Close)
|
||||
pu, _ := url.Parse(proxy.URL)
|
||||
return port, secretsPath, &http.Client{Transport: &http.Transport{
|
||||
Proxy: http.ProxyURL(pu), TLSClientConfig: &tls.Config{RootCAs: pool}, MaxConnsPerHost: 1,
|
||||
}}
|
||||
}
|
||||
|
||||
func get(t *testing.T, c *http.Client, url, host string) (int, string) {
|
||||
t.Helper()
|
||||
req, _ := http.NewRequestWithContext(t.Context(), http.MethodGet, url, nil)
|
||||
req.Header.Set("Authorization", "Bearer PH")
|
||||
if host != "" {
|
||||
req.Host = host
|
||||
}
|
||||
resp, err := c.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
return resp.StatusCode, string(b)
|
||||
}
|
||||
|
||||
// A secret goes only to the host it's bound to: inside an intercepted tunnel, a request whose Host
|
||||
// names another site (one sharing the bound host's CDN, say) is refused, not forwarded with the token.
|
||||
func TestInterceptRefusesAnotherHost(t *testing.T) {
|
||||
port, _, c := interceptSetup(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprintf(w, "%s|%s", r.Host, r.Header.Get("Authorization")) //nolint:gosec // a test echo server
|
||||
})
|
||||
u := fmt.Sprintf("https://localhost:%d/x", port)
|
||||
if code, body := get(t, c, u, ""); code != 200 || body != fmt.Sprintf("localhost:%d|Bearer real", port) {
|
||||
t.Fatalf("same host: %d %q", code, body)
|
||||
}
|
||||
code, body := get(t, c, u, "other.example")
|
||||
if code != http.StatusMisdirectedRequest || strings.Contains(body, "real") {
|
||||
t.Errorf("another Host: %d %q (want 421 and no secret)", code, body)
|
||||
}
|
||||
}
|
||||
|
||||
// Unbinding a secret applies to tunnels already open: the next request in a kept-alive tunnel gets
|
||||
// no secret.
|
||||
func TestUnbindAppliesToOpenTunnels(t *testing.T) {
|
||||
port, file, c := interceptSetup(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, r.Header.Get("Authorization")) //nolint:gosec // a test echo server
|
||||
})
|
||||
u := fmt.Sprintf("https://localhost:%d/x", port)
|
||||
if _, body := get(t, c, u, ""); body != "Bearer real" {
|
||||
t.Fatalf("bound: %q", body)
|
||||
}
|
||||
must(t, os.WriteFile(file, []byte(`[]`), 0o600))
|
||||
later := time.Now().Add(2 * time.Second)
|
||||
must(t, os.Chtimes(file, later, later))
|
||||
if _, body := get(t, c, u, ""); body != "Bearer PH" {
|
||||
t.Errorf("after unbinding, the open tunnel still got %q", body)
|
||||
}
|
||||
}
|
||||
|
||||
// The CA lasts 30 days, stays while it has over a week left, and is replaced after that.
|
||||
func TestCARotation(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if err := initCA(dir); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
read := func() *x509.Certificate {
|
||||
pair, err := tls.LoadX509KeyPair(filepath.Join(dir, "ca.pem"), filepath.Join(dir, "ca.key"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c, _ := x509.ParseCertificate(pair.Certificate[0])
|
||||
return c
|
||||
}
|
||||
first := read()
|
||||
if life := first.NotAfter.Sub(first.NotBefore); life > 31*24*time.Hour || life < 29*24*time.Hour {
|
||||
t.Errorf("CA valid for %v, want about 30 days", life)
|
||||
}
|
||||
must(t, initCA(dir))
|
||||
if read().SerialNumber.Cmp(first.SerialNumber) != 0 {
|
||||
t.Error("a fresh CA was replaced")
|
||||
}
|
||||
// One that has 3 days left (made here with the same key) is replaced.
|
||||
pair, _ := tls.LoadX509KeyPair(filepath.Join(dir, "ca.pem"), filepath.Join(dir, "ca.key"))
|
||||
key := pair.PrivateKey.(*ecdsa.PrivateKey)
|
||||
tmpl := &x509.Certificate{
|
||||
SerialNumber: big.NewInt(7), Subject: pkix.Name{CommonName: "old"}, NotBefore: time.Now().Add(-27 * 24 * time.Hour),
|
||||
NotAfter: time.Now().Add(3 * 24 * time.Hour), IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign,
|
||||
}
|
||||
der, _ := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
|
||||
must(t, os.WriteFile(filepath.Join(dir, "ca.pem"), pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), 0o600))
|
||||
if err := initCA(dir); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c := read(); c.SerialNumber.Cmp(big.NewInt(7)) == 0 || time.Until(c.NotAfter) < 29*24*time.Hour {
|
||||
t.Errorf("an expiring CA wasn't replaced: %v until %v", c.SerialNumber, c.NotAfter)
|
||||
}
|
||||
if st, _ := os.Stat(filepath.Join(dir, "ca.key")); st.Mode().Perm() != 0o600 {
|
||||
t.Errorf("ca.key mode %v", st.Mode().Perm())
|
||||
}
|
||||
// One valid for longer than caLife (from before the CA was rotated: 10 years) is replaced too.
|
||||
pair, _ = tls.LoadX509KeyPair(filepath.Join(dir, "ca.pem"), filepath.Join(dir, "ca.key"))
|
||||
key = pair.PrivateKey.(*ecdsa.PrivateKey)
|
||||
tmpl = &x509.Certificate{
|
||||
SerialNumber: big.NewInt(8), Subject: pkix.Name{CommonName: "old"}, NotBefore: time.Now().Add(-time.Hour),
|
||||
NotAfter: time.Now().AddDate(10, 0, 0), IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign,
|
||||
}
|
||||
der, _ = x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
|
||||
must(t, os.WriteFile(filepath.Join(dir, "ca.pem"), pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), 0o600))
|
||||
if err := initCA(dir); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c := read(); c.SerialNumber.Cmp(big.NewInt(8)) == 0 || c.NotAfter.Sub(c.NotBefore) > 31*24*time.Hour {
|
||||
t.Errorf("a CA valid for 10 years was kept: %v until %v", c.SerialNumber, c.NotAfter)
|
||||
}
|
||||
}
|
||||
|
||||
// devvm touches the bindings file when a value is set or removed: cached values are dropped.
|
||||
func TestBindingsChangeDropsCachedValues(t *testing.T) {
|
||||
secretsPath = filepath.Join(t.TempDir(), "bindings.json")
|
||||
t.Cleanup(func() { secretsPath = "" })
|
||||
must(t, os.WriteFile(secretsPath, []byte(`[]`), 0o600))
|
||||
bindings.all()
|
||||
valueMu.Lock()
|
||||
values["t"] = cached{"old", time.Now()}
|
||||
valueMu.Unlock()
|
||||
later := time.Now().Add(2 * time.Second)
|
||||
must(t, os.Chtimes(secretsPath, later, later))
|
||||
bindings.all()
|
||||
valueMu.Lock()
|
||||
defer valueMu.Unlock()
|
||||
if _, ok := values["t"]; ok {
|
||||
t.Error("a cached value survived the bindings file changing")
|
||||
}
|
||||
}
|
||||
|
||||
// An intercepted HTTPS request through the proxy: the client trusts only devvm's CA and sends the
|
||||
// placeholder; the upstream server sees the real secret.
|
||||
func TestIntercept(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if err := initCA(dir); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if st, _ := os.Stat(filepath.Join(dir, "ca.key")); st.Mode().Perm() != 0o600 {
|
||||
t.Errorf("ca.key mode %v", st.Mode().Perm())
|
||||
}
|
||||
if err := loadCA(filepath.Join(dir, "ca.pem"), filepath.Join(dir, "ca.key")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
leaves = map[string]*tls.Certificate{} // minted by another test's CA
|
||||
pool := x509.NewCertPool()
|
||||
pool.AddCert(caCert)
|
||||
upstreamCAs = pool
|
||||
t.Cleanup(func() { upstreamCAs = nil })
|
||||
|
||||
// Upstream: echoes what it received, with a certificate for "localhost" from the same CA.
|
||||
up := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprintf(w, "%s|%s|%s", r.Header.Get("Authorization"), r.Header.Get("X-Echo"), r.Host) //nolint:gosec // a test echo server
|
||||
}))
|
||||
cert, _ := leafFor("localhost")
|
||||
up.TLS = &tls.Config{Certificates: []tls.Certificate{*cert}}
|
||||
up.StartTLS()
|
||||
defer up.Close()
|
||||
_, portStr, _ := net.SplitHostPort(up.Listener.Addr().String())
|
||||
port, err := strconv.Atoi(portStr)
|
||||
must(t, err)
|
||||
interceptPorts[port] = true
|
||||
t.Cleanup(func() { delete(interceptPorts, port) })
|
||||
|
||||
pol = writePolicy(t, fmt.Sprintf("localhost:%d\n127.0.0.1:%d\n", port, port))
|
||||
secretsPath = filepath.Join(dir, "bindings.json")
|
||||
must(t, os.WriteFile(secretsPath, []byte(`[{"name":"t","hosts":["localhost"],"header":"Authorization","placeholder":"PH"}]`), 0o600))
|
||||
t.Cleanup(func() { secretsPath = "" })
|
||||
fakeSecret(t, "real-secret")
|
||||
|
||||
proxy := httptest.NewServer(http.HandlerFunc(handler))
|
||||
defer proxy.Close()
|
||||
pu, _ := url.Parse(proxy.URL)
|
||||
client := &http.Client{Transport: &http.Transport{
|
||||
Proxy: http.ProxyURL(pu),
|
||||
TLSClientConfig: &tls.Config{RootCAs: pool},
|
||||
}}
|
||||
req, _ := http.NewRequestWithContext(t.Context(), http.MethodGet, fmt.Sprintf("https://localhost:%d/x", port), nil)
|
||||
req.Header.Set("Authorization", "Bearer PH")
|
||||
req.Header.Set("X-Echo", "PH")
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
_ = resp.Body.Close()
|
||||
if got, want := string(body), fmt.Sprintf("Bearer real-secret|PH|localhost:%d", port); got != want {
|
||||
t.Errorf("upstream saw %q, want %q", got, want)
|
||||
}
|
||||
// The Host upstream gets is the one checked, canonical: not the VM's spelling (a trailing dot).
|
||||
req, _ = http.NewRequestWithContext(t.Context(), http.MethodGet, fmt.Sprintf("https://localhost.:%d/x", port), nil)
|
||||
req.Header.Set("Authorization", "Bearer PH")
|
||||
if resp, err := client.Do(req); err != nil {
|
||||
t.Error(err)
|
||||
} else {
|
||||
body, _ = io.ReadAll(resp.Body)
|
||||
_ = resp.Body.Close()
|
||||
if got := string(body); !strings.HasSuffix(got, fmt.Sprintf("|localhost:%d", port)) {
|
||||
t.Errorf("upstream saw Host %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// The CA is served to the VM; the private key never is.
|
||||
req, _ = http.NewRequestWithContext(t.Context(), http.MethodGet, "http://devvm.proxy/ca.pem", nil)
|
||||
resp, err = client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, _ = io.ReadAll(resp.Body)
|
||||
if !strings.Contains(string(body), "BEGIN CERTIFICATE") || strings.Contains(string(body), "PRIVATE") {
|
||||
t.Errorf("/ca.pem = %q", body)
|
||||
}
|
||||
}
|
||||
|
||||
// Calls that make lasting GitHub credentials with the VM's token are refused; ordinary ones aren't.
|
||||
func TestMintsCredential(t *testing.T) {
|
||||
for _, c := range []struct{ host, method, path, want string }{
|
||||
{"api.github.com", "POST", "/user/keys", "a key on your GitHub account"},
|
||||
{"api.github.com", "post", "/User/SSH_Signing_Keys/", "a key on your GitHub account"},
|
||||
{"api.github.com", "POST", "/repos/o/r/keys", "a deploy key"},
|
||||
{"api.github.com", "POST", "//repos/o/r/./keys", "a deploy key"},
|
||||
{"api.github.com", "POST", "/repos/o/r/x/../keys", "a deploy key"},
|
||||
{"api.github.com", "POST", "/orgs/o/actions/runners/registration-token", "a self-hosted runner"},
|
||||
{"api.github.com", "POST", "/repos/o/r/actions/runners/generate-jitconfig", "a self-hosted runner"},
|
||||
{"api.github.com", "PATCH", "/repos/o/r/hooks/1/config", "a webhook"},
|
||||
{"api.github.com", "POST", "/orgs/o/hooks", "a webhook"},
|
||||
{"api.github.com", "GET", "/user/keys", ""},
|
||||
{"api.github.com", "DELETE", "/repos/o/r/keys/1", ""},
|
||||
{"api.github.com", "POST", "/repos/o/r/pulls", ""},
|
||||
{"api.github.com", "POST", "/repos/o/r/issues/1/comments", ""},
|
||||
{"github.com", "POST", "/user/keys", ""},
|
||||
} {
|
||||
if got := mintsCredential(c.host, c.method, c.path); got != c.want {
|
||||
t.Errorf("%s %s%s = %q, want %q", c.method, c.host, c.path, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package proxy
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"time"
|
||||
)
|
||||
|
||||
var errStop = errors.New("stop after ClientHello")
|
||||
|
||||
// sniOf returns the server name in a TLS ClientHello record ("" if none, or it doesn't parse). It
|
||||
// lets crypto/tls parse the record and stops the handshake at the ClientHello callback.
|
||||
func sniOf(rec []byte) string {
|
||||
var name string
|
||||
c := tls.Server(helloConn{bytes.NewReader(rec)}, &tls.Config{
|
||||
GetConfigForClient: func(h *tls.ClientHelloInfo) (*tls.Config, error) {
|
||||
name = h.ServerName
|
||||
return nil, errStop
|
||||
},
|
||||
})
|
||||
_ = c.HandshakeContext(context.Background())
|
||||
return name
|
||||
}
|
||||
|
||||
// helloConn: a net.Conn that reads the recorded bytes and discards writes.
|
||||
type helloConn struct{ r io.Reader }
|
||||
|
||||
func (c helloConn) Read(b []byte) (int, error) { return c.r.Read(b) }
|
||||
func (c helloConn) Write(b []byte) (int, error) { return len(b), nil }
|
||||
func (c helloConn) Close() error { return nil }
|
||||
func (c helloConn) LocalAddr() net.Addr { return &net.TCPAddr{} }
|
||||
func (c helloConn) RemoteAddr() net.Addr { return &net.TCPAddr{} }
|
||||
func (c helloConn) SetDeadline(time.Time) error { return nil }
|
||||
func (c helloConn) SetReadDeadline(time.Time) error { return nil }
|
||||
func (c helloConn) SetWriteDeadline(time.Time) error { return nil }
|
||||
@@ -48,6 +48,10 @@ func StdinIsTerminal() bool { return stdinTTY() }
|
||||
// go through Say and the rest.
|
||||
func Stdout() io.Writer { return lockedWriter{stdout} }
|
||||
|
||||
// Stderr is where output that isn't a message goes on stderr: the log lines
|
||||
// of a process devvm runs as itself in the background (devvm _proxy).
|
||||
func Stderr() io.Writer { return lockedWriter{stderr} }
|
||||
|
||||
type lockedWriter struct{ w io.Writer }
|
||||
|
||||
func (l lockedWriter) Write(p []byte) (int, error) {
|
||||
|
||||
@@ -180,3 +180,11 @@ func TestStdoutIsForData(t *testing.T) {
|
||||
t.Errorf("got %q", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStderrIsForLogLines(t *testing.T) {
|
||||
out, errOut := sandbox(t, "")
|
||||
_, _ = Stderr().Write([]byte("a log line\n"))
|
||||
if errOut.String() != "a log line\n" || out.Len() != 0 {
|
||||
t.Errorf("got %q, stdout %q", errOut, out)
|
||||
}
|
||||
}
|
||||
@@ -395,3 +395,15 @@ other = "{{.vm}} moves to them on this launch"
|
||||
|
||||
[sync_failed]
|
||||
other = "couldn't set up {{.vm}}'s shared tools"
|
||||
|
||||
[proxy_failed]
|
||||
description = "reason is an error from the system or the flag parser, in English"
|
||||
other = "network policy proxy: {{.reason}}"
|
||||
|
||||
[codex_login_kept]
|
||||
description = "keys lists auth.json's top-level keys, comma-separated"
|
||||
other = "Codex's auth.json {{.keys}} is copied into the VM as it is"
|
||||
|
||||
[opencode_login_kept]
|
||||
description = "providers lists opencode's login providers, comma-separated"
|
||||
other = "opencode's {{.providers}} login is copied into the VM as it is"
|
||||
Vendored
+49
@@ -0,0 +1,49 @@
|
||||
# devvm _proxy: the network policy proxy, hidden. --help lists its flags.
|
||||
exec devvm _proxy --help
|
||||
stdout '-auth-file'
|
||||
stdout '-listen'
|
||||
! stderr .
|
||||
exec devvm --help
|
||||
! stdout _proxy
|
||||
|
||||
# The proxy refuses to run without the VM's password, or with an empty one.
|
||||
env DEVVM_MESSAGES=names
|
||||
! exec devvm _proxy -listen 127.0.0.1:0
|
||||
stderr '^devvm: proxy_failed reason=-auth-file is required$'
|
||||
! exec devvm _proxy --auth-file empty
|
||||
stderr '^devvm: proxy_failed reason=empty is empty$'
|
||||
! exec devvm _proxy -nope
|
||||
stderr '^devvm: proxy_failed reason=flag provided but not defined: -nope$'
|
||||
|
||||
# -init-ca writes the CA and keeps it on the next run.
|
||||
exec devvm _proxy -init-ca ca
|
||||
exists ca/ca.pem ca/ca.key
|
||||
grep 'BEGIN CERTIFICATE' ca/ca.pem
|
||||
cp ca/ca.pem first.pem
|
||||
exec devvm _proxy -init-ca ca
|
||||
cmp ca/ca.pem first.pem
|
||||
|
||||
# -redact: secret-named values replaced, their paths on stderr.
|
||||
stdin settings.json
|
||||
exec devvm _proxy -redact json
|
||||
stdout '"apiKey": "devvm-redacted"'
|
||||
stdout '"baseURL": "https://x"'
|
||||
! stdout dummy-key
|
||||
stderr '^provider.options.apiKey$'
|
||||
|
||||
# -login -login-vm: the VM's copy holds placeholders, and what it copies as
|
||||
# it is is warned about.
|
||||
exec devvm _proxy -login codex -login-file auth.json -login-vm
|
||||
stdout '"OPENAI_API_KEY": "sk-devvm-proxy-managed-codex"'
|
||||
stdout '"extra": "x"'
|
||||
! stdout sk-real
|
||||
stderr '^devvm: codex_login_kept keys=extra$'
|
||||
exec devvm _proxy -login codex -login-file auth.json -login-bindings -login-hosts
|
||||
stdout '^api.openai.com:443$'
|
||||
|
||||
-- empty --
|
||||
|
||||
-- settings.json --
|
||||
{"provider": {"options": {"apiKey": "dummy-key", "baseURL": "https://x"}}}
|
||||
-- auth.json --
|
||||
{"OPENAI_API_KEY": "sk-real", "extra": "x"}
|
||||
Reference in new issue
Block a user