refactor(proxy): one server struct holds what a proxy runs with and keeps, and a tunnel passes the far end's bytes at once

internal/proxy keeps no package state. newServer makes a server from the
config, as Main starts (it replaces Config.apply, loadPolicies and every
global they set), and each part keeps what it changes under its own lock:
events (the event log and recent blocks), egress (the policy, the host's
addresses in hostAddrs, the company proxies in upstreams), secrets (the
bindings file and the values cache, file lock taken before the values'),
ca (devvm's CA and its leaves), links (the list and the sockets' folder)
and nixCache (the cache's folder, checked narinfos, fetches and slots).
The proxy's own log is a *log.Logger each part is given; Main's lifeline
tick is a const, and run takes it for tests. What's left package-level is
error sentinels and three fixed tables (notPublic, nat64, githubMinting),
now in the structure test's allowedVars; the structure test no longer
leaves internal/proxy out, and its rule case for the proxy fails a var.

Tests make their own server with newServer (testServer, listen, logs,
fakeSecret on a secrets, testCA) and all run in parallel.
TestServersApart checks two servers in one process share no password,
blocks, events, values or CA leaves.

A tunnel to a host the policy allows passes the far end's bytes to the
VM from the start (splice's before), so a server that speaks first gets
its greeting through; the VM's bytes still pass only after the SNI check,
which reads one byte first and the ClientHello only when it starts 0x16.
TestTunnelServerSpeaksFirst failed on the code before.

Docs: the proxy README (the server, files, testing), network.md's
tunnel paragraph, AGENTS.md's test-seams line, Contributing's
package-vars row.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
w3cjandClaude Opus 5.5 committed 2026-11-03 20:10:28 -07:00
1 parent f4ad9c2c3d
commit bcafcda739
22 files changed
+1085 -863

No files matched your search

+1 -1
View File
@@ -84,7 +84,7 @@ Still to come: the release keys (`packaging/minisign.pub`, `packaging/release-si
- **OS-specific code goes behind build tags** in `internal/platform` (`*_darwin.go`, `*_linux.go`, `*_other.go`).
- **Dependencies:** the depguard allowlist (cobra, pflag, cobra/doc, go-i18n, BurntSushi/toml, x/text, x/term, x/sys; go-internal in tests; cobra/doc's own deps never imported directly). `internal/proxy` and `internal/daemon` are stdlib only. Adding one: ask.
- **External tools are commands, never linked** (`limactl`, `docker`, `security`, `git`, `chflags`…); prefer the standard library to shelling out. Strings into a shell are quoted with `shell.Quote`.
- **Test seams are fields** tests set (`Host`, `Exec`, `Runner`, `OS`, `Warn`…), never package vars (reassign: no package sets another's); the one exception is `internal/proxy`'s globals (set by `Main`).
- **Test seams are fields** tests set (`Host`, `Exec`, `Runner`, `OS`, `Warn`…), never package vars (reassign: no package sets another's); `internal/proxy`'s are its `server`'s, which each test makes.
- **The structure test** (`internal/structure`, in `mise run test`) holds types to 24 methods, bans `func init`, allows only constants' kin as package vars, checks the package layers and the owners (host git only in `internal/hostgit`; `DEVVM_` variables only in `readOverrides` and the listed settings; `HOME` only in `internal/paths`, as `Dirs.Home`; shell quoting only in `internal/shell`, the VM-name grammar only in `internal/vmname`): see [Contributing](docs/content/docs/contributing/_index.md#the-structure-test) before raising a limit or listing an exception.
- **The CLI reference is generated:** `TestReferenceIsCurrent` fails on a stale one (`mise run cli-docs`).
- `CGO_ENABLED=0`. `internal/proxy` and `internal/daemon` are unix-only for now (`syscall.Kill`, `Setsid`, `Flock`).
+1 -1
View File
@@ -87,7 +87,7 @@ A fresh context elsewhere, such as for a cleanup that outlives a canceled run, o
| --- | --- |
| `max-methods` | no type has more than 24 methods, value and pointer receivers together; a larger one splits by what its methods do |
| `no-init` | no `func init()` |
| `package-vars` | outside `internal/proxy`, a package-level `var` is a blank interface check, an `Err*`/`err*` sentinel from `errors.New` or `fmt.Errorf`, a `regexp.MustCompile`, `template.Must` or `sync.Once*` result, a `//go:embed` file, or listed in `allowedVars`; anything else becomes a field, a const or a local |
| `package-vars` | a package-level `var` is a blank interface check, an `Err*`/`err*` sentinel from `errors.New` or `fmt.Errorf`, a `regexp.MustCompile`, `template.Must` or `sync.Once*` result, a `//go:embed` file, or listed in `allowedVars`; anything else becomes a field, a const or a local |
| `layers` | which packages import which, in non-test files (tests may wire packages together) |
| `owners` | in non-test files, only its owner runs a host command that `commands` lists, only the files `execSites` lists make a host command, only `guardOwner` asserts a backend package's type, only `envOwner` reads a `DEVVM_` variable, but the settings `envSettings` lists, only its file in `envOwners` reads `HOME`, only its owner's string literals hold a text that `literals` lists, and only `pathsOwner` builds a path in devvm's data or config folder ([details](#the-checks-on-owners)) |
+1 -1
View File
@@ -54,7 +54,7 @@ flowchart TD
named --> swap["the placeholder swapped<br>for the real value"]
```
A tunnel that the proxy doesn't intercept carries the bytes both ways as they are. When the VM finishes sending, the proxy closes its side of the connection to the far end, so the far end sees the end of what the VM sent and can still answer. The tunnel ends when the far end's bytes end, or when the proxy can't pass them on because the VM's connection has gone, and then the proxy closes both connections. In a tunnel to a host the policy allows, the proxy reads the VM's first five bytes to see whether they start a TLS ClientHello before it passes anything on, so with a protocol whose server speaks first, such as SMTP, the VM gets no answer until it has sent five bytes.
A tunnel that the proxy doesn't intercept carries the bytes both ways as they are. When the VM finishes sending, the proxy closes its side of the connection to the far end, so the far end sees the end of what the VM sent and can still answer. The tunnel ends when the far end's bytes end, or when the proxy can't pass them on because the VM's connection has gone, and then the proxy closes both connections. In a tunnel to a host the policy allows, the far end's bytes reach the VM at once, so a protocol whose server speaks first, such as SMTP, gets its greeting before the VM sends anything. The VM's bytes wait until the proxy has checked them: when the first one starts a TLS record, the proxy reads the whole ClientHello and checks its SNI before any of it reaches the far end, and any other first byte passes at once.
### Links through the proxy
+21 -8
View File
@@ -9,7 +9,7 @@ The VM can reach nothing but this proxy. On macOS its Lima hostagent runs under
- with `links` in its config, sends a request for one of the VM's links (`CONNECT db:5432`, `GET http://db:5432/`) to that link's socket on the host before any rule (below);
- checks `CONNECT host:port` and absolute-form requests (`GET http://host/…`) against the VM's policy, which is devvm's built-in policies, read from the binary, and then the user's policy files, and 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; through a company proxy (`upstream`), which resolves names itself, it refuses a name when the host's resolver answers with such an address, and a name the host can't resolve when only `**` allows it (unless `upstream_unresolved`, which builds on Lima get), and it reads at most 64 KiB of the company proxy's answer to `CONNECT`;
- requires a TLS ClientHello in a tunnel to name the CONNECT host (SNI);
- requires a TLS ClientHello in a tunnel to name the CONNECT host (SNI), and passes nothing the VM sends to the far end before it has checked it, while the far end's bytes reach the VM at once, so a server that speaks first, such as SMTP's, sends its greeting before the VM sends anything;
- 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);
- with `nix_cache`, answers `http://devvm.proxy/nix/` itself, as a Nix binary cache that VMs share and only the host fills (below);
- logs every decision as JSON lines.
@@ -25,15 +25,15 @@ Once it listens, it says so with the address it listens on (`daemon.Ready`) in t
| File | What |
| --- | --- |
| `config.go` | `Config`, the one config a VM's proxy and a build's run with (`Encode`, `Sum`, `ReadConfig`, `ConfigVersion`), and the checked reads of the files devvm names to the proxy: `ReadRegular`, which policy files are read with here, in `devvm network` and in doctor, and `readPrivate`, for the config and the links' list (`ErrNotRegular`, `ErrNotPrivate`, `ErrTooLong`) |
| `proxy.go` | `Main` and its one flag, `-config`, the config applied (`apply`, `serve`), the listener, CONNECT and absolute-form handling, the host names it takes (`HostOK`, which `agentlogin` checks MCP servers' hosts with too), the address floor, the log (`Event`, `AllowRule`: `devvm network log` reads it), the `devvm.proxy` endpoints |
| `proxy.go` | `Main` and its one flag, `-config`, the proxy's `server`, which `newServer` makes from the config (below), the listener (`serve`), CONNECT and absolute-form handling, the host names it takes (`HostOK`, which `agentlogin` checks MCP servers' hosts with too), the address floor (`egress`, `hostAddrs`), the log (`Event`, `events`, `AllowRule`: `devvm network log` reads it), the `devvm.proxy` endpoints |
| `policy.go` | the rule syntax and matching (`ValidRule`: `devvm network allow`, `deny` and `rm` take only these); `ParsePolicy`, the one strict parser of policy files, which `devvm network` and doctor use too: each line that holds more than a comment, with its number and whether it's a rule; the built-in policies are read once (`readBuiltins`), every line a rule, and come first in the union; the user's policy files are re-read when they change, each only as a regular file of at most 1 MiB (`ReadRegular`, `PolicyMax`; one that isn't keeps its last rules, logged once), and each line that isn't a rule is logged and skipped, except one that starts with `!` (`BrokenDeny`), which makes the policy deny everything, as refused blocks naming the file and line, until it's fixed |
| `sni.go` | reads a tunnel's ClientHello to check its server name |
| `splice.go` | every tunnel the proxy carries itself: `hijack` takes a `CONNECT`'s connection from the HTTP server and answers `200`, and `splice` passes the bytes both ways as they are, passes on the end of what the client sent, and ends once the server's bytes end or the client has gone |
| `secrets.go` | interception for hosts with a bound secret: certificates from devvm's CA, which devvm makes (`trust.InitCA`) and the proxy only loads (a day each, never past the CA's end; once the CA has ended, `CONNECT`s to be intercepted answered `403` and logged as refused with `caEndedReason`), header substitution; the VM's bindings, `Binding` (`KindSecret` or `KindLogin`, with the login's `Agent`) in a `BindingList` (JSON, version 1), which `internal/secrets` writes and `ReadBindings` reads, and `InterceptLines`, the allowlist's lines for their hosts; values from `IO.Secret`, looked up in the proxy's own process (cached briefly, never logged); `writeAtomic`, the proxy's one writer of whole files |
| `upstream.go` | `upstream`: a company proxy that allowed requests go through (`CONNECT` by name for tunnels and interception, absolute form for plain HTTP), `NO_PROXY`, and the floor for names it resolves (`floorUpstream`) |
| `splice.go` | every tunnel the proxy carries itself: `hijack` takes a `CONNECT`'s connection from the HTTP server and answers `200`, and `splice` passes the bytes both ways as they are, the server's from the start and the client's once a check has passed them (the SNI check, for a tunnel the policy allows), passes on the end of what the client sent, and ends once the server's bytes end or the client has gone |
| `secrets.go` | interception for hosts with a bound secret: certificates from devvm's CA (`ca`), which devvm makes (`trust.InitCA`) and the proxy only loads (a day each, never past the CA's end; once the CA has ended, `CONNECT`s to be intercepted answered `403` and logged as refused with `caEndedReason`), header substitution; the VM's bindings and their values (`secrets`), `Binding` (`KindSecret` or `KindLogin`, with the login's `Agent`) in a `BindingList` (JSON, version 1), which `internal/secrets` writes and `ReadBindings` reads, and `InterceptLines`, the allowlist's lines for their hosts; values from `IO.Secret`, looked up in the proxy's own process (cached briefly, never logged); `writeAtomic`, the proxy's one writer of whole files |
| `upstream.go` | `upstream` and `upstreams`: a company proxy that allowed requests go through (`CONNECT` by name for tunnels and interception, absolute form for plain HTTP), `NO_PROXY`, and the floor for names it resolves (`floorUpstream`) |
| `rotate.go` | the logs' rotation past `LogLimit` (10 MiB): the event log renamed to `<log>.1` under the file's lock, the proxy's own log, which is also its stderr, copied there and emptied; `OpenEventLog`, the event log's writer, which netpolicy's `AppendEvent` uses too, and which opens the log again before a line once the other writer has rotated it |
| `nixcache.go` | `nix_cache`: the shared Nix cache at `http://devvm.proxy/nix/`, its path pattern (`nixPath`), narinfo checks (`parseNarinfo`), NAR checks, the cap and its trim (`NixCacheUsage`, `TrimNixCache`) |
| `links.go` | `links`: the VM's links' list (`LinkList`, `LinkEntry`), their sockets' names (`LinkSocket`, `LinkHash`), their addresses and domain, which devvm's other packages use too (`IsLinkAddr`, `LinkAddr`, `LinkDomain`), matching (`linkFor`), `CONNECT` and absolute-form requests to a link |
| `nixcache.go` | `nix_cache`: the shared Nix cache at `http://devvm.proxy/nix/` (`nixCache`), its path pattern (`nixPath`), narinfo checks (`parseNarinfo`), NAR checks, the cap and its trim (`NixCacheUsage`, `TrimNixCache`) |
| `links.go` | `links`: the VM's links' list (`LinkList`, `LinkEntry`) and the proxy's way to them (`links`), their sockets' names (`LinkSocket`, `LinkHash`), their addresses and domain, which devvm's other packages use too (`IsLinkAddr`, `LinkAddr`, `LinkDomain`), matching (`links.find`), `CONNECT` and absolute-form requests to a link |
| `*_test.go` | unit tests, and fuzz targets for policy rules (`FuzzParseRule`), request targets (`FuzzRequest`), ClientHellos (`FuzzClientHello`) and the Nix cache's paths (`FuzzNixPath`); `testdata/nix/` holds a narinfo and its NAR from cache.nixos.org |
## How devvm runs it
@@ -70,6 +70,19 @@ Flags take one dash or two. The proxy has one, `-config`, and everything it runs
Running the proxy is `Main`'s only mode. What only the host does for network policy runs in devvm itself, never through the proxy's arguments: `trust.InitCA` makes devvm's CA (`ca.pem`, `ca.key`, each written whole; valid 30 days; no host name in it) unless one with over a week left is there, and `internal/agentlogin` makes the VM's copies of agents' login and settings files, their bindings and their values.
## The server
Everything a proxy runs with, and everything it keeps between connections, is in its `server`, which `newServer` makes from the config as the proxy starts. The package keeps no state of its own: its only package-level variables are error sentinels and fixed tables (`notPublic`, `nat64`, `githubMinting`), which the structure test allows. The server holds the VM's name and password, its own log, and these parts, each of which keeps what it changes under a lock of its own:
- `events`: the event log and the last 50 blocks, for `/blocked` and `/blocked/new`;
- `egress`: the policy (`policy`, which reads the user's files again when they change), the host's own addresses (`hostAddrs`, read again every 30 seconds) and the company proxy (`upstreams`, set as the proxy starts and only read after);
- `secrets`: the bindings file, read again when it changes, and the values looked up for it, held through each lookup so lookups go one at a time;
- `ca`: devvm's CA and the certificates the proxy has made with it;
- `links`: the links' list and their sockets' folder, which are only read;
- `nixCache`: the Nix cache's folder, which every proxy shares under its `.lock`, and the narinfos this proxy has checked and the NARs it's fetching.
A test makes a server of its own with `newServer`, as `Main` does, and sets on it whatever else it needs, so no test changes another's proxy and the tests run in parallel.
## Secrets
The bindings file, `secrets.json` in the VM's run folder, is a `BindingList`: `{"version": 1, "bindings": [...]}`, which `secrets.Store` writes whole, mode 600, at each launch and again whenever a secret is saved, deleted, bound or unbound. Each `Binding` has its `name`, its `kind`, its `hosts`, its `header` and its `placeholder`, and never a value. Its kind says where the value comes from: `secret` is one that devvm keeps (`devvm secret set`), in the Keychain or in devvm's secrets folder, and `login` is one of an agent's logins, read from the login file of its `agent` (`codex`, `opencode` or `claude`) on the host each time. Nothing about a binding is worked out from its name. The proxy reads the file with `ReadBindings` when its modification time changes: a regular file, not a symbolic link, owned by the proxy's user and readable and writable by nobody else, at most 1 MiB, of version 1, each binding of a kind it knows. A file it can't read that way has no bindings until devvm writes it again, and the proxy logs why once. A change also drops every value it has cached.
@@ -80,4 +93,4 @@ Inside the VM, `http://devvm.proxy/blocked` lists recent blocks, `/blocked/new`
## 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 and checks that it refuses any flag but `-config`. `nix_cache.txtar` runs it with a config of its own. `internal/agentlogin` and `internal/trust` have the tests of the logins, the redaction and the CA, and `internal/secrets` those of `Store.Get`, the lookup `IO.Secret` runs; the proxy's own tests give it a fake one.
`go test ./internal/proxy` runs the unit tests, in parallel, each with a server of its own ([the server](#the-server)), and the fuzz targets' seeds; `go test -fuzz FuzzRequest ./internal/proxy` fuzzes one. `testdata/script/proxy.txtar` runs `devvm _proxy` itself and checks that it refuses any flag but `-config`. `nix_cache.txtar` runs it with a config of its own. `internal/agentlogin` and `internal/trust` have the tests of the logins, the redaction and the CA, and `internal/secrets` those of `Store.Get`, the lookup `IO.Secret` runs; the proxy's own tests give it a fake one.
+6 -4
View File
@@ -3,7 +3,7 @@ package proxy
import (
"bytes"
"errors"
"io"
"log"
"os"
"path/filepath"
"reflect"
@@ -15,6 +15,7 @@ import (
// A config devvm writes reads back as it was, and Sum tells any change apart.
func TestConfigRoundTrip(t *testing.T) {
t.Parallel()
c := Config{ //nolint:gosec // G101: a test's fake password
Listen: "127.0.0.1:4000", VM: "devvm-x", Password: "k3y",
BuiltinPolicies: []string{"layers/base.policy"}, Policies: []string{"/p/policy"},
@@ -55,6 +56,7 @@ func TestConfigRoundTrip(t *testing.T) {
// ReadConfig refuses a file that isn't devvm's for this proxy alone, of another version, holding a
// field it doesn't know, or one the proxy can't run with: each with an error naming why.
func TestReadConfigRefuses(t *testing.T) {
t.Parallel()
good := Config{Listen: "127.0.0.1:0", Password: "k3y"}
dir := t.TempDir()
write := func(name string, b []byte, mode os.FileMode) string {
@@ -120,6 +122,7 @@ func TestReadConfigRefuses(t *testing.T) {
// ReadRegular, which policy files are read with, follows a link to a regular file, and refuses a
// FIFO, a device and a file past its cap with a named error, without hanging.
func TestReadRegular(t *testing.T) {
t.Parallel()
dir := t.TempDir()
f := filepath.Join(dir, "policy")
must(t, os.WriteFile(f, []byte("a.test\n"), 0o644)) //nolint:gosec // a policy file others may read, as yours may be
@@ -153,12 +156,11 @@ func TestReadRegular(t *testing.T) {
// A policy file that becomes a FIFO or a link to /dev/zero is refused, not read: the proxy keeps
// its last rules, and logs why once.
func TestPolicyFileNotRegular(t *testing.T) {
t.Parallel()
errs := &syncBuffer{}
logger.SetOutput(errs)
t.Cleanup(func() { logger.SetOutput(io.Discard) })
f := filepath.Join(t.TempDir(), "policy")
must(t, os.WriteFile(f, []byte("a.test\n!b.test\n"), 0o600))
p := newPolicy(nil, []string{f})
p := newPolicy(nil, []string{f}, log.New(errs, "", 0))
if ok, _ := p.decide("a.test", 443); !ok {
t.Fatal("a.test isn't allowed")
}
+33 -28
View File
@@ -8,6 +8,7 @@ import (
"encoding/json"
"errors"
"fmt"
"log"
"net"
"net/http"
"net/http/httputil"
@@ -36,10 +37,14 @@ import (
// (LinkSocket), so a list holding anything else is ignored, and no request reaches another VM's
// link or any other socket. Without that folder, no link is reached.
var (
linksFile = "" // Config.Links: the VM's links list, which devvm _links writes; empty: none
linkSockets = "" // Config.LinkSockets: the folder of the links' sockets; empty: none
)
// links is a proxy's way to the VM's links: set once, as it starts, and only read after.
type links struct {
file string // Config.Links: the VM's links list, which devvm _links writes; empty: none
sockets string // Config.LinkSockets: the folder of the links' sockets; empty: none
vm string // Config.VM, whose links' sockets they are
log *log.Logger
events *events
}
// LinkList is the file devvm _links writes for the VM's proxy: the links it carries now.
type LinkList struct {
@@ -93,17 +98,17 @@ func readLinkList(path string) (LinkList, error) {
return l, nil
}
// linkFor returns the VM's link that host and port name, from the list as it is now: its entry,
// find returns the VM's link that host and port name, from the list as it is now: its entry,
// with the socket it must have. A host and port on no entry, an entry whose socket isn't this VM's
// link's, and a list that can't be read give none, so the request is the policy's.
func linkFor(host string, port int) (LinkEntry, bool) {
if linksFile == "" || linkSockets == "" {
func (k links) find(host string, port int) (LinkEntry, bool) {
if k.file == "" || k.sockets == "" {
return LinkEntry{}, false
}
l, err := readLinkList(linksFile)
l, err := readLinkList(k.file)
if err != nil {
if !errors.Is(err, os.ErrNotExist) {
logf("links: %v", err)
k.log.Printf("links: %v", err)
}
return LinkEntry{}, false
}
@@ -113,8 +118,8 @@ func linkFor(host string, port int) (LinkEntry, bool) {
}
a, err := netip.ParseAddr(e.Addr)
if err != nil || a.String() != e.Addr || !IsLinkAddr(a) || a != a.Unmap() || port < 1 || port > 65535 ||
e.Socket != LinkSocket(linkSockets, vmName, a, port) {
logf("links: %s:%d: not this VM's link's socket", host, port)
e.Socket != LinkSocket(k.sockets, k.vm, a, port) {
k.log.Printf("links: %s:%d: not this VM's link's socket", host, port)
continue
}
return e, true
@@ -146,13 +151,13 @@ func LinkAddr(i uint16) netip.Addr {
// internet, and a host under LinkDomain is a link's or nothing.
const LinkDomain = "devvm.internal"
// notALink refuses a host under LinkDomain that's none of the VM's links: such a name is never
// the policy's, so no rule or company proxy sends it anywhere.
func notALink(w http.ResponseWriter, method, host string, port int) bool {
// refuse refuses a host under LinkDomain that's none of the VM's links: such a name is never
// the policy's, so no rule or company proxy sends it anywhere. It reports whether it refused.
func (k links) refuse(w http.ResponseWriter, method, host string, port int) bool {
if !strings.HasSuffix(host, "."+LinkDomain) && host != LinkDomain {
return false
}
record(Event{Event: "blocked", Host: host, Port: port, Method: method, Reason: "not one of this VM's links", Refused: true})
k.events.record(Event{Event: "blocked", Host: host, Port: port, Method: method, Reason: "not one of this VM's links", Refused: true})
http.Error(w, "devvm proxy: "+net.JoinHostPort(host, strconv.Itoa(port))+" isn't one of this VM's links", http.StatusForbidden)
return true
}
@@ -180,22 +185,22 @@ func dialLink(ctx context.Context, sock string) (net.Conn, error) {
}
}
// linkGone answers a request for a link whose socket doesn't answer (its link removed since the
// gone answers a request for a link whose socket doesn't answer (its link removed since the
// list was read, or devvm _links gone) and logs it as devvm _links logs a refusal.
func linkGone(w http.ResponseWriter, host string, port int, e LinkEntry, err error) {
logf("links: %s:%d: %v", host, port, err)
record(Event{Event: "link_refused", Host: host, Port: port, Target: e.Target, Reason: linkNotCarried})
func (k links) gone(w http.ResponseWriter, host string, port int, e LinkEntry, err error) {
k.log.Printf("links: %s:%d: %v", host, port, err)
k.events.record(Event{Event: "link_refused", Host: host, Port: port, Target: e.Target, Reason: linkNotCarried})
http.Error(w, "devvm proxy: the link "+net.JoinHostPort(host, strconv.Itoa(port))+" isn't carried now", http.StatusBadGateway)
}
// linkNotCarried is the reason of a refusal the proxy logs: the link's socket didn't answer.
const linkNotCarried = "not carried"
// connectLink tunnels a CONNECT for a link to its socket, the bytes as they are.
func connectLink(w http.ResponseWriter, r *http.Request, host string, port int, e LinkEntry) {
// connect tunnels a CONNECT for a link to its socket, the bytes as they are.
func (k links) connect(w http.ResponseWriter, r *http.Request, host string, port int, e LinkEntry) {
up, err := dialLink(r.Context(), e.Socket)
if err != nil {
linkGone(w, host, port, e, err)
k.gone(w, host, port, e, err)
return
}
defer func() { _ = up.Close() }()
@@ -203,7 +208,7 @@ func connectLink(w http.ResponseWriter, r *http.Request, host string, port int,
if err != nil {
return
}
splice(client, up)
splice(client, up, nil)
}
// linkDialError: a link's socket didn't answer.
@@ -211,9 +216,9 @@ type linkDialError struct{ err error }
func (e linkDialError) Error() string { return e.err.Error() }
// forwardLink forwards an absolute-form request for a link (plain HTTP) to its socket, a new
// forward forwards an absolute-form request for a link (plain HTTP) to its socket, a new
// connection for each request, so devvm _links checks each one, and none of the proxy's headers.
func forwardLink(w http.ResponseWriter, r *http.Request, host string, port int, e LinkEntry) {
func (k links) forward(w http.ResponseWriter, r *http.Request, host string, port int, e LinkEntry) {
tr := &http.Transport{
DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
c, err := dialLink(ctx, e.Socket)
@@ -227,7 +232,7 @@ func forwardLink(w http.ResponseWriter, r *http.Request, host string, port int,
defer tr.CloseIdleConnections()
rp := &httputil.ReverseProxy{
Transport: tr,
ErrorLog: logger,
ErrorLog: k.log,
FlushInterval: -1,
Rewrite: func(pr *httputil.ProxyRequest) {
pr.Out.URL.Scheme, pr.Out.URL.Host = "http", r.URL.Host
@@ -236,10 +241,10 @@ func forwardLink(w http.ResponseWriter, r *http.Request, host string, port int,
},
ErrorHandler: func(w http.ResponseWriter, _ *http.Request, err error) {
if de := (linkDialError{}); errors.As(err, &de) {
linkGone(w, host, port, e, de.err)
k.gone(w, host, port, e, de.err)
return
}
logf("links: %s:%d: %v", host, port, err)
k.log.Printf("links: %s:%d: %v", host, port, err)
http.Error(w, "devvm proxy: the link "+net.JoinHostPort(host, strconv.Itoa(port))+" didn't answer", http.StatusBadGateway)
},
}
+47 -43
View File
@@ -8,7 +8,6 @@ import (
"io"
"net"
"net/http"
"net/http/httptest"
"net/netip"
"os"
"path/filepath"
@@ -109,26 +108,23 @@ func linkEntry(dir, addr string, port int, hosts ...string) LinkEntry {
}
}
// linkProxy is the proxy for linkVM with the list in a short folder (sockets' paths are at most 104
// characters), a policy that allows nothing, and its events in a buffer.
func linkProxy(t *testing.T) (dir string, events *syncBuffer, addr string) {
// linkProxy is a proxy for linkVM with the list in a short folder (sockets' paths are at most 104
// characters), a policy that allows nothing, and its events in a buffer, and the address it
// listens on.
func linkProxy(t *testing.T) (s *server, dir string, events *syncBuffer, addr string) {
t.Helper()
dir, err := os.MkdirTemp("/tmp", "pl")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = os.RemoveAll(dir) })
oldVM, oldOut, oldAuth := vmName, logOut, proxyAuth
events = &syncBuffer{}
// The list is in the VM's own run folder; the sockets are in devvm's.
list := filepath.Join(dir, "vm", "run", "links.json")
must(t, os.MkdirAll(filepath.Dir(list), 0o700))
vmName, linksFile, linkSockets, logOut, proxyAuth = linkVM, list, dir, events, ""
pol = writePolicy(t, "")
t.Cleanup(func() { vmName, linksFile, linkSockets, logOut, proxyAuth = oldVM, "", "", oldOut, oldAuth })
p := httptest.NewServer(http.HandlerFunc(handler))
t.Cleanup(p.Close)
return dir, events, p.Listener.Addr().String()
s = testServer(t, Config{VM: linkVM, Links: list, LinkSockets: dir}, "")
events = &syncBuffer{}
s.events.out = events
return s, dir, events, listen(t, s)
}
// tunnel sends a CONNECT for hostPort, then data, and returns the status and what came back.
@@ -164,9 +160,10 @@ func tunnel(t *testing.T, addr, hostPort string, data []byte) (int, string) {
// anything else is the policy's, and blocked. The proxy logs nothing of a link it carried: its
// socket's server, devvm _links, does.
func TestLinkConnect(t *testing.T) {
dir, events, addr := linkProxy(t)
t.Parallel()
s, dir, events, addr := linkProxy(t)
db := serveLink(t, dir, "127.77.0.1", 5432)
writeLinkList(t, linksFile, linkEntry(dir, "127.77.0.1", 5432, "db", "db.devvm.internal"))
writeLinkList(t, s.links.file, linkEntry(dir, "127.77.0.1", 5432, "db", "db.devvm.internal"))
for _, hp := range []string{"db:5432", "DB:5432", "db.:5432", "db.devvm.internal:5432", "Db.Devvm.Internal.:5432"} {
if code, got := tunnel(t, addr, hp, []byte("ping "+hp)); code != http.StatusOK || got != "ping "+hp {
t.Errorf("%s: %d %q", hp, code, got)
@@ -195,18 +192,20 @@ func TestLinkConnect(t *testing.T) {
// and a secret bound to the link's name (or to every host) isn't put in, its port intercepted or
// not.
func TestLinkConnectUntouched(t *testing.T) {
dir, _, addr := linkProxy(t)
t.Parallel()
s, dir, _, addr := linkProxy(t)
db := serveLink(t, dir, "127.77.0.1", 443)
writeLinkList(t, linksFile, linkEntry(dir, "127.77.0.1", 443, "db", "db.devvm.internal"))
writeLinkList(t, s.links.file, linkEntry(dir, "127.77.0.1", 443, "db", "db.devvm.internal"))
ca := t.TempDir()
writeCA(t, ca)
must(t, loadCA(filepath.Join(ca, "ca.pem"), filepath.Join(ca, "ca.key")))
secretsPath = filepath.Join(ca, "bindings.json")
writeBindings(t, secretsPath, bound("db", "**"))
t.Cleanup(func() { secretsPath = "" })
fakeSecret(t, "real-secret")
var err error
s.ca, err = loadCA(filepath.Join(ca, "ca.pem"), filepath.Join(ca, "ca.key"))
must(t, err)
s.secrets.path = filepath.Join(ca, "bindings.json")
writeBindings(t, s.secrets.path, bound("db", "**"))
fakeSecret(s.secrets, "real-secret")
// A rule that allows the name too: the link still comes first, never intercepted.
pol = writePolicy(t, "db\n")
s.egress.pol = writePolicy(t, "db\n")
hello := clientHello(t, "evil.example")
if code, got := tunnel(t, addr, "db:443", hello); code != http.StatusOK || got != string(hello) {
t.Errorf("a ClientHello for another host: %d, %d bytes back", code, len(got))
@@ -224,11 +223,11 @@ func TestLinkConnectUntouched(t *testing.T) {
// and then one for another host are each handled as they are: the link's carried, the other host
// blocked by the policy. HTTPS to a link is refused in absolute form: CONNECT carries it.
func TestLinkForward(t *testing.T) {
dir, events, addr := linkProxy(t)
proxyAuth = "k3y"
t.Cleanup(func() { proxyAuth = "" })
t.Parallel()
s, dir, events, addr := linkProxy(t)
s.password = "k3y"
db := serveLink(t, dir, "127.77.0.1", 8080)
writeLinkList(t, linksFile, linkEntry(dir, "127.77.0.1", 8080, "db", "db.devvm.internal"))
writeLinkList(t, s.links.file, linkEntry(dir, "127.77.0.1", 8080, "db", "db.devvm.internal"))
c, err := new(net.Dialer).DialContext(t.Context(), "tcp", addr)
if err != nil {
t.Fatal(err)
@@ -260,11 +259,11 @@ func TestLinkForward(t *testing.T) {
if code, _ := get("https://db:8080/", "db:8080"); code != http.StatusBadRequest {
t.Errorf("https in absolute form: %d", code)
}
s := db.seen()
if len(s) != 2 {
t.Fatalf("the link's socket saw %d connections, want 2: %q", len(s), s)
seen := db.seen()
if len(seen) != 2 {
t.Fatalf("the link's socket saw %d connections, want 2: %q", len(seen), seen)
}
for _, req := range s {
for _, req := range seen {
if !strings.HasPrefix(req, "GET /") || strings.Contains(req, "Proxy-") || strings.Contains(req, "k3y") || strings.Contains(req, "ZGV2dm06azN5") {
t.Errorf("the link got %q", req)
}
@@ -277,8 +276,9 @@ func TestLinkForward(t *testing.T) {
// A link on the list whose socket doesn't answer (removed since, or devvm _links gone) is refused
// with 502 and logged once as a refused link.
func TestLinkGone(t *testing.T) {
dir, events, addr := linkProxy(t)
writeLinkList(t, linksFile, linkEntry(dir, "127.77.0.1", 5432, "db", "db.devvm.internal"))
t.Parallel()
s, dir, events, addr := linkProxy(t)
writeLinkList(t, s.links.file, linkEntry(dir, "127.77.0.1", 5432, "db", "db.devvm.internal"))
if code, _ := tunnel(t, addr, "db:5432", nil); code != http.StatusBadGateway {
t.Errorf("CONNECT: %d", code)
}
@@ -297,7 +297,9 @@ func TestLinkGone(t *testing.T) {
// ignored, as is a list that's a symbolic link, that others may write, of another version, or not
// JSON. A request never names a socket: a host with a slash isn't one.
func TestLinkListRefused(t *testing.T) {
dir, _, addr := linkProxy(t)
t.Parallel()
s, dir, _, addr := linkProxy(t)
linksFile := s.links.file
serveLink(t, dir, "127.77.0.1", 5432)
other := LinkSocket(dir, "devvm-other-0123456789abcd", netip.MustParseAddr("127.77.0.1"), 5432)
ln, err := new(net.ListenConfig).Listen(t.Context(), "unix", other)
@@ -364,12 +366,11 @@ func TestLinkListRefused(t *testing.T) {
}
// Without the sockets' folder, no link is reached.
must(t, os.Chmod(linksFile, 0o600))
old := linkSockets
linkSockets = ""
s.links.sockets = ""
if code, _ := tunnel(t, addr, "db:5432", nil); code != http.StatusForbidden {
t.Errorf("without -link-sockets: %d", code)
t.Errorf("without link_sockets: %d", code)
}
linkSockets = old
s.links.sockets = dir
for name, data := range map[string]string{
"another version": `{"version":2,"links":[{"hosts":["db"],"addr":"127.77.0.1","port":5432,"socket":"` + good.Socket + `"}]}`,
"not JSON": "db 5432 " + good.Socket,
@@ -398,8 +399,9 @@ func TestLinkListRefused(t *testing.T) {
// allow: it's never asked of the policy, a resolver or a company proxy. A short name that's no
// link is the policy's.
func TestLinkDomainRefused(t *testing.T) {
_, events, addr := linkProxy(t)
pol = writePolicy(t, "**\n**:5432\n")
t.Parallel()
s, _, events, addr := linkProxy(t)
s.egress.pol = writePolicy(t, "**\n**:5432\n")
for _, hp := range []string{"db.devvm.internal:5432", "devvm.internal:443", "x.y.devvm.internal.:5432"} {
if code, _ := tunnel(t, addr, hp, nil); code != http.StatusForbidden {
t.Errorf("CONNECT %s: %d", hp, code)
@@ -413,12 +415,13 @@ func TestLinkDomainRefused(t *testing.T) {
}
}
// Without -links, the proxy has no links: a name that would be one is the policy's.
// Without links, the proxy has no links: a name that would be one is the policy's.
func TestNoLinksFile(t *testing.T) {
dir, _, addr := linkProxy(t)
t.Parallel()
s, dir, _, addr := linkProxy(t)
serveLink(t, dir, "127.77.0.1", 5432)
writeLinkList(t, linksFile, linkEntry(dir, "127.77.0.1", 5432, "db"))
linksFile = ""
writeLinkList(t, s.links.file, linkEntry(dir, "127.77.0.1", 5432, "db"))
s.links.file = ""
if code, _ := tunnel(t, addr, "db:5432", nil); code != http.StatusForbidden {
t.Errorf("CONNECT: %d", code)
}
@@ -427,6 +430,7 @@ func TestNoLinksFile(t *testing.T) {
// A link's socket is named by a hash of the VM, "socket", its address and its port, each after a
// NUL: what devvm _links listens on and the e2e checks look for.
func TestLinkSocket(t *testing.T) {
t.Parallel()
got := LinkSocket("/run", "vm", netip.MustParseAddr("127.77.0.1"), 5432)
if got != "/run/link-"+LinkHash("vm", "socket", "127.77.0.1", "5432")+".sock" || len(filepath.Base(got)) != len("link-0123456789abcdef.sock") {
t.Errorf("LinkSocket = %q", got)
+124 -100
View File
@@ -17,11 +17,13 @@ import (
"crypto/ed25519"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"errors"
"fmt"
"io"
"io/fs"
"log"
"net"
"net/http"
"os"
@@ -52,38 +54,61 @@ const (
nixTmpAge = time.Hour
)
var (
nixCacheDir = "" // Config.NixCache: the cache's folder; "": no cache
nixCacheMax = NixCacheDefault // Config.NixCacheMax: its cap, in bytes
nixBase = "https://" + nixHost
nixDial = func(ctx context.Context) (net.Conn, error) { return dialOut(ctx, nixHost, 443) }
nixFloor = upstreamAllowed // tests: no DNS
nixClient = newNixClient()
nixMu sync.Mutex
nixKnown = map[string]narMeta{} // NAR path (nar/…) → what a checked narinfo says of it
nixKnownMax = 1 << 16
nixFetching = map[string]chan struct{}{} // NARs this proxy is fetching, by path
nixSlots = make(chan struct{}, nixFetchMax)
errNixUnsupported = errors.New("not a narinfo devvm reads")
)
var errNixUnsupported = errors.New("not a narinfo devvm reads")
// nixFetchMax is how many NARs one proxy fetches at once.
const nixFetchMax = 4
// nixKnownMax is how many checked narinfos' NARs a proxy remembers.
const nixKnownMax = 1 << 16
// narMeta is what a checked narinfo says of its NAR's file.
type narMeta struct {
fileHash string // sha256:<nix32>
fileSize int64
}
// newNixClient makes the client the cache fetches with: to cache.nixos.org only, through the floor
// or the company proxy (dialOut), with the system's roots and the user's CAs, never following a
// redirect.
func newNixClient() *http.Client {
// nixCache is a proxy's way to the shared Nix cache (Config.NixCache): the folder, which every
// proxy shares under its lock (.lock), and what this proxy keeps of it, under mu.
type nixCache struct {
dir string // Config.NixCache: the cache's folder; "": no cache
max int64 // Config.NixCacheMax: its cap, in bytes
// base, dial and floor are cache.nixos.org's URL, how it's reached (through the floor or the
// company proxy, dialOut) and the check that it may be (the floor's, as for any request).
base string
dial func(ctx context.Context) (net.Conn, error)
floor func(ctx context.Context) error
client *http.Client
egress *egress // the VM's policy decides whether cache.nixos.org may be asked
events *events
log *log.Logger
mu sync.Mutex
known map[string]narMeta // NAR path (nar/…) → what a checked narinfo says of it
fetching map[string]chan struct{} // NARs this proxy is fetching, by path
slots chan struct{} // nixFetchMax
}
// newNixCache is the cache in dir, capped at maxSize, which fetches from cache.nixos.org through e,
// trusting roots (nil: the system's) besides the system's.
func newNixCache(dir string, maxSize int64, e *egress, ev *events, l *log.Logger, roots *x509.CertPool) *nixCache {
n := &nixCache{
dir: dir, max: maxSize, base: "https://" + nixHost, egress: e, events: ev, log: l,
known: map[string]narMeta{}, fetching: map[string]chan struct{}{}, slots: make(chan struct{}, nixFetchMax),
}
n.dial = func(ctx context.Context) (net.Conn, error) { return e.dialOut(ctx, nixHost, 443) }
n.floor = n.upstreamAllowed
n.client = n.newClient(roots)
return n
}
// newClient makes the client the cache fetches with: to cache.nixos.org only, through n.dial, with
// the system's roots and the user's CAs (roots), never following a redirect.
func (n *nixCache) newClient(roots *x509.CertPool) *http.Client {
return &http.Client{
Transport: &http.Transport{
DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { return nixDial(ctx) },
TLSClientConfig: &tls.Config{RootCAs: upstreamCAs, ServerName: nixHost}, ForceAttemptHTTP2: true,
DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { return n.dial(ctx) },
TLSClientConfig: &tls.Config{RootCAs: roots, ServerName: nixHost}, ForceAttemptHTTP2: true,
IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ResponseHeaderTimeout: 30 * time.Second,
},
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
@@ -267,44 +292,44 @@ func parseNarinfo(data []byte, hash string) (narinfo, error) {
}
// remember what a checked narinfo says of its NAR, for the VM's request for it next.
func remember(ni narinfo) {
nixMu.Lock()
defer nixMu.Unlock()
if len(nixKnown) >= nixKnownMax {
clear(nixKnown)
func (n *nixCache) remember(ni narinfo) {
n.mu.Lock()
defer n.mu.Unlock()
if len(n.known) >= nixKnownMax {
clear(n.known)
}
nixKnown[ni.url] = narMeta{ni.fileHash, ni.fileSize}
n.known[ni.url] = narMeta{ni.fileHash, ni.fileSize}
}
func known(p string) (narMeta, bool) {
nixMu.Lock()
defer nixMu.Unlock()
m, ok := nixKnown[p]
func (n *nixCache) lookup(p string) (narMeta, bool) {
n.mu.Lock()
defer n.mu.Unlock()
m, ok := n.known[p]
return m, ok
}
// --- serving ---
// serveNix answers a request under http://devvm.proxy/nix/. Its event says what came of it: a hit,
// serve answers a request under http://devvm.proxy/nix/. Its event says what came of it: a hit,
// fetched, or not found and why (logged, never kept).
func serveNix(w http.ResponseWriter, r *http.Request) {
func (n *nixCache) serve(w http.ResponseWriter, r *http.Request) {
p := strings.TrimPrefix(r.URL.Path, "/nix/")
kind := nixPath(p)
e := Event{Event: "nix-cache", Host: nixHost, Port: 443, Method: r.Method, Path: r.URL.Path, Agent: r.UserAgent()}
if (r.Method != http.MethodGet && r.Method != http.MethodHead) || r.URL.RawQuery != "" || r.URL.ForceQuery ||
r.URL.EscapedPath() != r.URL.Path || kind == nixNone {
e.Reason = "refused: not a request the Nix cache takes"
record(e)
n.events.record(e)
http.Error(w, "devvm proxy: not a request the Nix cache takes", http.StatusBadRequest)
return
}
if nixCacheDir == "" {
if n.dir == "" {
http.Error(w, "devvm proxy: no Nix cache", http.StatusNotFound)
return
}
if ok, why := pol.decide(nixHost, 443); !ok {
if ok, why := n.egress.pol.decide(nixHost, 443); !ok {
e.Reason = "not found: " + nixHost + " isn't allowed (" + why + ")"
record(e)
n.events.record(e)
http.Error(w, "devvm proxy: "+nixHost+" isn't allowed", http.StatusNotFound)
return
}
@@ -314,16 +339,16 @@ func serveNix(w http.ResponseWriter, r *http.Request) {
e.Reason = "served"
serveBytes(w, r, []byte(nixCacheInfo), "text/x-nix-cache-info", time.Time{})
case nixNarinfo:
err = serveNarinfo(w, r, p, &e)
err = n.serveNarinfo(w, r, p, &e)
case nixNar:
err = serveNar(w, r, p, &e)
err = n.serveNar(w, r, p, &e)
case nixNone: // refused above
}
if err != nil {
e.Reason = "not found: " + err.Error()
http.Error(w, "devvm proxy: not in the Nix cache", http.StatusNotFound)
}
record(e)
n.events.record(e)
}
func serveBytes(w http.ResponseWriter, r *http.Request, data []byte, ctype string, mod time.Time) {
@@ -333,25 +358,25 @@ func serveBytes(w http.ResponseWriter, r *http.Request, data []byte, ctype strin
// serveNarinfo answers a narinfo: the cache's copy when it still checks, else cache.nixos.org's,
// checked, then kept.
func serveNarinfo(w http.ResponseWriter, r *http.Request, p string, e *Event) error {
func (n *nixCache) serveNarinfo(w http.ResponseWriter, r *http.Request, p string, e *Event) error {
hash := p[:32]
file := filepath.Join(nixCacheDir, p)
file := filepath.Join(n.dir, p)
if data, err := readUpTo(file, nixInfoMax); err == nil {
if ni, err := parseNarinfo(data, hash); err == nil {
touch(file)
remember(ni)
n.remember(ni)
e.Reason = "hit"
serveBytes(w, r, data, "text/x-nix-narinfo", time.Time{})
return nil
}
_ = os.Remove(file) //nolint:gosec // a name nixPath checked, in the cache's folder
}
if err := nixFloor(r.Context()); err != nil {
if err := n.floor(r.Context()); err != nil {
return err
}
ctx, cancel := context.WithTimeout(r.Context(), time.Minute)
defer cancel()
resp, err := nixGet(ctx, p)
resp, err := n.get(ctx, p)
if err != nil {
return err
}
@@ -367,10 +392,10 @@ func serveNarinfo(w http.ResponseWriter, r *http.Request, p string, e *Event) er
if err != nil {
return fmt.Errorf("its narinfo is refused: %w", err)
}
if err := keepBytes(file, data); err != nil {
logf("nix cache: %v", err)
if err := n.keepBytes(file, data); err != nil {
n.log.Printf("nix cache: %v", err)
}
remember(ni)
n.remember(ni)
e.Reason = "fetched"
serveBytes(w, r, data, "text/x-nix-narinfo", time.Time{})
return nil
@@ -378,9 +403,9 @@ func serveNarinfo(w http.ResponseWriter, r *http.Request, p string, e *Event) er
// serveNar answers a NAR: the cache's copy, else cache.nixos.org's when a checked narinfo names it,
// its SHA-256 and size checked against that narinfo's before it's kept and served.
func serveNar(w http.ResponseWriter, r *http.Request, p string, e *Event) error {
file := filepath.Join(nixCacheDir, filepath.FromSlash(p))
m, ok := known(p)
func (n *nixCache) serveNar(w http.ResponseWriter, r *http.Request, p string, e *Event) error {
file := filepath.Join(n.dir, filepath.FromSlash(p))
m, ok := n.lookup(p)
if serveCachedNar(w, r, file, m, ok) {
e.Reason = "hit"
return nil
@@ -388,15 +413,15 @@ func serveNar(w http.ResponseWriter, r *http.Request, p string, e *Event) error
switch {
case !ok:
return errors.New("no checked narinfo names it")
case m.fileSize > nixCacheMax:
case m.fileSize > n.max:
return errors.New("it's larger than the cache's cap")
case r.Method == http.MethodHead:
return errors.New("a HEAD fetches nothing")
}
if err := nixFloor(r.Context()); err != nil {
if err := n.floor(r.Context()); err != nil {
return err
}
if err := fetchOnce(r.Context(), p, file, m); err != nil {
if err := n.fetchOnce(r.Context(), p, file, m); err != nil {
return err
}
if !serveCachedNar(w, r, file, m, ok) {
@@ -426,10 +451,10 @@ func serveCachedNar(w http.ResponseWriter, r *http.Request, file string, m narMe
// fetchOnce fetches a NAR into the cache: one fetch of each at a time in this proxy, which other
// requests for it wait for, and at most nixFetchMax at once.
func fetchOnce(ctx context.Context, p, file string, m narMeta) error {
nixMu.Lock()
if ch, busy := nixFetching[p]; busy {
nixMu.Unlock()
func (n *nixCache) fetchOnce(ctx context.Context, p, file string, m narMeta) error {
n.mu.Lock()
if ch, busy := n.fetching[p]; busy {
n.mu.Unlock()
select {
case <-ch:
case <-ctx.Done():
@@ -438,42 +463,42 @@ func fetchOnce(ctx context.Context, p, file string, m narMeta) error {
return nil // whether it's there, the caller sees
}
ch := make(chan struct{})
nixFetching[p] = ch
nixMu.Unlock()
n.fetching[p] = ch
n.mu.Unlock()
defer func() {
nixMu.Lock()
delete(nixFetching, p)
nixMu.Unlock()
n.mu.Lock()
delete(n.fetching, p)
n.mu.Unlock()
close(ch)
}()
select {
case nixSlots <- struct{}{}:
case n.slots <- struct{}{}:
case <-ctx.Done():
return ctx.Err()
}
defer func() { <-nixSlots }()
return fetchNar(ctx, p, file, m)
defer func() { <-n.slots }()
return n.fetchNar(ctx, p, file, m)
}
// upstreamAllowed: the floor (or the company proxy's) for cache.nixos.org, as for any request.
func upstreamAllowed(ctx context.Context) error {
if _, why := check(ctx, nixHost, 443, false); why != "" {
func (n *nixCache) upstreamAllowed(ctx context.Context) error {
if _, why := n.egress.check(ctx, nixHost, 443, false); why != "" {
return errors.New(nixHost + " is blocked: " + why)
}
return nil
}
// nixGet fetches p from cache.nixos.org: its answer when that's 200. Nothing of the VM's request
// get fetches p from cache.nixos.org: its answer when that's 200. Nothing of the VM's request
// goes with it.
func nixGet(ctx context.Context, p string) (*http.Response, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, nixBase+"/"+p, nil) //nolint:gosec // cache.nixos.org alone, a path nixPath checked
func (n *nixCache) get(ctx context.Context, p string) (*http.Response, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, n.base+"/"+p, nil) //nolint:gosec // cache.nixos.org alone, a path nixPath checked
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", "devvm-nix-cache")
resp, err := nixClient.Do(req) //nolint:gosec // as above; its dialer reaches cache.nixos.org alone
resp, err := n.client.Do(req) //nolint:gosec // as above; its dialer reaches cache.nixos.org alone
if err != nil {
logf("nix cache: %s: %v", p, err) // can name addresses the VM shouldn't learn
n.log.Printf("nix cache: %s: %v", p, err) // can name addresses the VM shouldn't learn
return nil, errors.New(nixHost + " couldn't be reached")
}
if resp.StatusCode != http.StatusOK {
@@ -486,12 +511,12 @@ func nixGet(ctx context.Context, p string) (*http.Response, error) {
// fetchNar downloads p into a file of its own in the cache's folder, checks it against m, and
// renames it to file. Its room under the cap is taken first, and the file is made its full size
// at once, so what's being fetched counts against the cap as it's written.
func fetchNar(ctx context.Context, p, file string, m narMeta) error {
func (n *nixCache) fetchNar(ctx context.Context, p, file string, m narMeta) error {
var tmp *os.File
room := onDisk(m.fileSize)
err := reserve(room, func() error {
err := n.reserve(room, func() error {
var err error
if tmp, err = os.CreateTemp(nixCacheDir, ".tmp-*"); err == nil {
if tmp, err = os.CreateTemp(n.dir, ".tmp-*"); err == nil {
err = tmp.Truncate(m.fileSize)
}
return err
@@ -506,23 +531,23 @@ func fetchNar(ctx context.Context, p, file string, m narMeta) error {
kept := false
defer func() {
if !kept {
release(room)
n.release(room)
}
}()
resp, err := nixGet(ctx, p)
resp, err := n.get(ctx, p)
if err != nil {
return err
}
defer func() { _ = resp.Body.Close() }()
h := sha256.New()
n, err := io.Copy(io.MultiWriter(tmp, h), io.LimitReader(resp.Body, m.fileSize+1))
got, err := io.Copy(io.MultiWriter(tmp, h), io.LimitReader(resp.Body, m.fileSize+1))
if cerr := tmp.Close(); err == nil {
err = cerr
}
if err != nil {
return err
}
if n != m.fileSize || "sha256:"+nix32(h.Sum(nil)) != m.fileHash {
if got != m.fileSize || "sha256:"+nix32(h.Sum(nil)) != m.fileHash {
return errors.New("its NAR doesn't match the narinfo's FileHash and FileSize")
}
if err := os.Rename(tmp.Name(), file); err != nil { //nolint:gosec // a name nixPath checked, in the cache's folder
@@ -534,12 +559,12 @@ func fetchNar(ctx context.Context, p, file string, m narMeta) error {
// keepBytes writes data, a narinfo, whole into the cache as file, all under the cache's lock: it's
// small, and no file of it is left for other proxies to count meanwhile.
func keepBytes(file string, data []byte) error {
n := onDisk(int64(len(data)))
return reserve(n, func() error {
func (n *nixCache) keepBytes(file string, data []byte) error {
room := onDisk(int64(len(data)))
return n.reserve(room, func() error {
err := writeAtomic(file, data, 0o600)
if err != nil {
addSize(nixCacheDir, -n)
addSize(n.dir, -room)
}
return err
})
@@ -562,15 +587,15 @@ func touch(file string) {
// --- the folder, its size and its cap ---
// openNixCache makes the cache's folders, the user's alone, and the client it fetches with.
func openNixCache() error {
if nixCacheDir == "" {
// open makes the cache's folders, the user's alone.
func (n *nixCache) open() error {
if n.dir == "" {
return nil
}
if nixCacheMax < 0 {
if n.max < 0 {
return errors.New("nix_cache_max is below 0")
}
for _, d := range []string{nixCacheDir, filepath.Join(nixCacheDir, "nar")} {
for _, d := range []string{n.dir, filepath.Join(n.dir, "nar")} {
if err := os.MkdirAll(d, 0o700); err != nil {
return err
}
@@ -578,7 +603,6 @@ func openNixCache() error {
return err
}
}
nixClient = newNixClient()
return nil
}
@@ -618,34 +642,34 @@ var errNixFull = errors.New("the cache is full of files being fetched")
// lock. When the cache would pass its cap, it first deletes the least recently used files, down
// to nine tenths of it, so most writes count nothing. Files being fetched count but never go, so
// a fetch that would pass the cap with them is refused.
func reserve(n int64, then func() error) error {
unlock, err := lockNix(nixCacheDir)
func (n *nixCache) reserve(room int64, then func() error) error {
unlock, err := lockNix(n.dir)
if err != nil {
return err
}
defer unlock()
total, ok := readSize(nixCacheDir)
if !ok || total+n > nixCacheMax {
if total, _, _, err = trim(nixCacheDir, nixCacheMax-n, max(nixCacheMax/10*9-n, 0)); err != nil {
total, ok := readSize(n.dir)
if !ok || total+room > n.max {
if total, _, _, err = trim(n.dir, n.max-room, max(n.max/10*9-room, 0)); err != nil {
return err
}
if total+n > nixCacheMax {
writeSize(nixCacheDir, total)
if total+room > n.max {
writeSize(n.dir, total)
return errNixFull
}
}
writeSize(nixCacheDir, total+n)
writeSize(n.dir, total+room)
return then()
}
// release gives back room reserve took for a file that wasn't kept.
func release(n int64) {
unlock, err := lockNix(nixCacheDir)
func (n *nixCache) release(room int64) {
unlock, err := lockNix(n.dir)
if err != nil {
return
}
defer unlock()
addSize(nixCacheDir, -n)
addSize(n.dir, -room)
}
// addSize changes the running total by n; the caller holds the lock.
+57 -55
View File
@@ -3,6 +3,7 @@ package proxy
import (
"context"
"crypto/sha256"
"errors"
"fmt"
"net"
"net/http"
@@ -33,6 +34,7 @@ func fixture(t *testing.T, name string) []byte {
}
func TestNixPath(t *testing.T) {
t.Parallel()
h32, h52 := strings.Repeat("a", 32), strings.Repeat("0", 52)
for p, want := range map[string]nixKind{
"nix-cache-info": nixInfo,
@@ -63,6 +65,7 @@ func TestNixPath(t *testing.T) {
}
func TestNix32(t *testing.T) {
t.Parallel()
sum := sha256.Sum256(fixture(t, fixNar))
if got, want := nix32(sum[:]), "1jrm0rjd3i5vxv2sjm6zgqqi87ikb3fjqg3myg7wj0x4q5psb550"; got != want {
t.Errorf("nix32 = %s, want %s (the narinfo's FileHash)", got, want)
@@ -70,6 +73,7 @@ func TestNix32(t *testing.T) {
}
func TestParseNarinfo(t *testing.T) {
t.Parallel()
good := string(fixture(t, fixHash+".narinfo"))
ni, err := parseNarinfo([]byte(good), fixHash)
if err != nil {
@@ -132,9 +136,9 @@ func (f *fakeNixCache) requests() []string {
return append([]string(nil), f.got...)
}
// useNixCache points the proxy's cache at a temp folder and a fake cache.nixos.org, with policy
// useNixCache is a proxy whose cache is a temp folder and a fake cache.nixos.org, with policy
// rules.
func useNixCache(t *testing.T, rules string) (*fakeNixCache, string) {
func useNixCache(t *testing.T, rules string) (*server, *fakeNixCache, string) {
t.Helper()
f := &fakeNixCache{files: map[string][]byte{
"/" + fixHash + ".narinfo": fixture(t, fixHash+".narinfo"),
@@ -157,61 +161,54 @@ func useNixCache(t *testing.T, rules string) (*fakeNixCache, string) {
}))
t.Cleanup(f.srv.Close)
dir := filepath.Join(t.TempDir(), "nix-cache")
oldDir, oldMax, oldBase, oldDial, oldFloor, oldPol := nixCacheDir, nixCacheMax, nixBase, nixDial, nixFloor, pol
t.Cleanup(func() {
nixCacheDir, nixCacheMax, nixBase, nixDial, nixFloor, pol = oldDir, oldMax, oldBase, oldDial, oldFloor, oldPol
clear(nixKnown)
})
nixCacheDir, nixCacheMax, nixBase = dir, NixCacheDefault, "http://"+nixHost
s := testServer(t, Config{NixCache: dir}, rules)
s.nix.base = "http://" + nixHost
addr := f.srv.Listener.Addr().String()
nixDial = func(ctx context.Context) (net.Conn, error) {
s.nix.dial = func(ctx context.Context) (net.Conn, error) {
var d net.Dialer
return d.DialContext(ctx, "tcp", addr)
}
nixFloor = func(context.Context) error { return nil }
pol = writePolicy(t, rules)
clear(nixKnown)
if err := openNixCache(); err != nil {
t.Fatal(err)
}
return f, dir
s.nix.floor = func(context.Context) error { return nil }
return s, f, dir
}
func nixReq(t *testing.T, method, target string) (int, []byte) {
func nixReq(t *testing.T, s *server, method, target string) (int, []byte) {
t.Helper()
r := httptest.NewRequestWithContext(t.Context(), method, target, nil)
r.Header.Set("Proxy-Authorization", "Basic secret")
r.Header.Set("Cookie", "vm=1")
w := httptest.NewRecorder()
serveReserved(w, r)
s.serveReserved(w, r)
return w.Code, w.Body.Bytes()
}
func TestNixCacheServes(t *testing.T) {
f, dir := useNixCache(t, nixHost)
log := logs(t)
if code, body := nixReq(t, "GET", "http://devvm.proxy/nix/nix-cache-info"); code != 200 || string(body) != nixCacheInfo {
t.Parallel()
s, f, dir := useNixCache(t, nixHost)
log := logs(s)
if code, body := nixReq(t, s, "GET", "http://devvm.proxy/nix/nix-cache-info"); code != 200 || string(body) != nixCacheInfo {
t.Fatalf("nix-cache-info: %d %q", code, body)
}
// A NAR no checked narinfo names isn't fetched.
if code, _ := nixReq(t, "GET", "http://devvm.proxy/nix/"+fixNar); code != 404 || len(f.requests()) != 0 {
if code, _ := nixReq(t, s, "GET", "http://devvm.proxy/nix/"+fixNar); code != 404 || len(f.requests()) != 0 {
t.Fatalf("a NAR before its narinfo: %d, upstream got %q", code, f.requests())
}
narinfo := "http://devvm.proxy/nix/" + fixHash + ".narinfo"
if code, body := nixReq(t, "GET", narinfo); code != 200 || string(body) != string(fixture(t, fixHash+".narinfo")) {
if code, body := nixReq(t, s, "GET", narinfo); code != 200 || string(body) != string(fixture(t, fixHash+".narinfo")) {
t.Fatalf("narinfo: %d %q", code, body)
}
if code, body := nixReq(t, "GET", "http://devvm.proxy/nix/"+fixNar); code != 200 || string(body) != string(fixture(t, fixNar)) {
if code, body := nixReq(t, s, "GET", "http://devvm.proxy/nix/"+fixNar); code != 200 || string(body) != string(fixture(t, fixNar)) {
t.Fatalf("NAR: %d, %d bytes", code, len(body))
}
// Again, from the cache alone, as another VM's proxy would serve them.
clear(nixKnown)
other := testServer(t, Config{NixCache: dir}, nixHost)
other.nix.floor = func(context.Context) error { return errors.New("asked cache.nixos.org") }
for _, p := range []string{fixHash + ".narinfo", fixNar} {
if code, _ := nixReq(t, "GET", "http://devvm.proxy/nix/"+p); code != 200 {
if code, _ := nixReq(t, other, "GET", "http://devvm.proxy/nix/"+p); code != 200 {
t.Errorf("%s again: %d", p, code)
}
}
if code, body := nixReq(t, "HEAD", narinfo); code != 200 || len(body) != 0 {
if code, body := nixReq(t, s, "HEAD", narinfo); code != 200 || len(body) != 0 {
t.Errorf("HEAD: %d %q", code, body)
}
got := f.requests()
@@ -236,7 +233,8 @@ func TestNixCacheServes(t *testing.T) {
}
func TestNixCacheRefuses(t *testing.T) {
f, dir := useNixCache(t, nixHost)
t.Parallel()
s, f, dir := useNixCache(t, nixHost)
h32 := strings.Repeat("a", 32)
for _, c := range []struct{ method, target string }{
{"POST", "http://devvm.proxy/nix/" + fixHash + ".narinfo"},
@@ -251,7 +249,7 @@ func TestNixCacheRefuses(t *testing.T) {
{"GET", "http://devvm.proxy/nix/"},
{"GET", "http://devvm.proxy/nix/nar/x"},
} {
if code, _ := nixReq(t, c.method, c.target); code != http.StatusBadRequest {
if code, _ := nixReq(t, s, c.method, c.target); code != http.StatusBadRequest {
t.Errorf("%s %s: %d, want 400", c.method, c.target, code)
}
}
@@ -260,7 +258,7 @@ func TestNixCacheRefuses(t *testing.T) {
}
// What upstream doesn't have, or answers otherwise, isn't kept: Nix goes direct.
for _, p := range []string{h32 + ".narinfo", "redirect.narinfo"} {
if code, _ := nixReq(t, "GET", "http://devvm.proxy/nix/"+p); code != 404 && code != 400 {
if code, _ := nixReq(t, s, "GET", "http://devvm.proxy/nix/"+p); code != 404 && code != 400 {
t.Errorf("%s: %d", p, code)
}
}
@@ -268,7 +266,7 @@ func TestNixCacheRefuses(t *testing.T) {
f.mu.Lock()
f.files["/"+fixHash+".narinfo"] = []byte(strings.Replace(string(fixture(t, fixHash+".narinfo")), "NarSize: 8848", "NarSize: 8849", 1))
f.mu.Unlock()
if code, _ := nixReq(t, "GET", "http://devvm.proxy/nix/"+fixHash+".narinfo"); code != 404 {
if code, _ := nixReq(t, s, "GET", "http://devvm.proxy/nix/"+fixHash+".narinfo"); code != 404 {
t.Errorf("a forged narinfo: %d", code)
}
f.mu.Lock()
@@ -277,16 +275,16 @@ func TestNixCacheRefuses(t *testing.T) {
nar[100] ^= 1
f.files["/"+fixNar] = nar
f.mu.Unlock()
if code, _ := nixReq(t, "GET", "http://devvm.proxy/nix/"+fixHash+".narinfo"); code != 200 {
if code, _ := nixReq(t, s, "GET", "http://devvm.proxy/nix/"+fixHash+".narinfo"); code != 200 {
t.Fatalf("narinfo: %d", code)
}
if code, _ := nixReq(t, "GET", "http://devvm.proxy/nix/"+fixNar); code != 404 {
if code, _ := nixReq(t, s, "GET", "http://devvm.proxy/nix/"+fixNar); code != 404 {
t.Errorf("a corrupted NAR: %d", code)
}
f.mu.Lock()
f.files["/"+fixNar] = append(fixture(t, fixNar), 0)
f.mu.Unlock()
if code, _ := nixReq(t, "GET", "http://devvm.proxy/nix/"+fixNar); code != 404 {
if code, _ := nixReq(t, s, "GET", "http://devvm.proxy/nix/"+fixNar); code != 404 {
t.Errorf("a NAR longer than its FileSize: %d", code)
}
if n, _, _ := NixCacheUsage(dir); n != 1 {
@@ -298,20 +296,21 @@ func TestNixCacheRefuses(t *testing.T) {
}
func TestNixCachePolicy(t *testing.T) {
f, _ := useNixCache(t, "github.com\n")
if code, _ := nixReq(t, "GET", "http://devvm.proxy/nix/"+fixHash+".narinfo"); code != 404 {
t.Parallel()
s, f, _ := useNixCache(t, "github.com\n")
if code, _ := nixReq(t, s, "GET", "http://devvm.proxy/nix/"+fixHash+".narinfo"); code != 404 {
t.Errorf("without %s in the policy: %d", nixHost, code)
}
nixFloor = func(context.Context) error { return fmt.Errorf("%s is blocked", nixHost) }
pol = writePolicy(t, nixHost)
if code, _ := nixReq(t, "GET", "http://devvm.proxy/nix/"+fixHash+".narinfo"); code != 404 {
s.nix.floor = func(context.Context) error { return fmt.Errorf("%s is blocked", nixHost) }
s.egress.pol = writePolicy(t, nixHost)
if code, _ := nixReq(t, s, "GET", "http://devvm.proxy/nix/"+fixHash+".narinfo"); code != 404 {
t.Errorf("below the floor: %d", code)
}
if got := f.requests(); len(got) != 0 {
t.Errorf("upstream got %q", got)
}
nixCacheDir = ""
if code, _ := nixReq(t, "GET", "http://devvm.proxy/nix/nix-cache-info"); code != 404 {
s.nix.dir = ""
if code, _ := nixReq(t, s, "GET", "http://devvm.proxy/nix/nix-cache-info"); code != 404 {
t.Errorf("no -nix-cache: %d", code)
}
}
@@ -319,18 +318,19 @@ func TestNixCachePolicy(t *testing.T) {
// A NAR is fetched once however many ask for it at once, a HEAD fetches nothing, a copy that
// isn't the size its narinfo says goes, and files being fetched never take the cache past its cap.
func TestNixCacheFetches(t *testing.T) {
f, dir := useNixCache(t, nixHost)
t.Parallel()
s, f, dir := useNixCache(t, nixHost)
nar := "http://devvm.proxy/nix/" + fixNar
if code, _ := nixReq(t, "GET", "http://devvm.proxy/nix/"+fixHash+".narinfo"); code != 200 {
if code, _ := nixReq(t, s, "GET", "http://devvm.proxy/nix/"+fixHash+".narinfo"); code != 200 {
t.Fatalf("narinfo: %d", code)
}
if code, _ := nixReq(t, "HEAD", nar); code != 404 || len(f.requests()) != 1 {
if code, _ := nixReq(t, s, "HEAD", nar); code != 404 || len(f.requests()) != 1 {
t.Errorf("HEAD of a NAR not in the cache: %d, upstream got %q", code, f.requests())
}
var wg sync.WaitGroup
for range 8 {
wg.Go(func() {
if code, body := nixReq(t, "GET", nar); code != 200 || len(body) != 958 {
if code, body := nixReq(t, s, "GET", nar); code != 200 || len(body) != 958 {
t.Errorf("GET: %d, %d bytes", code, len(body))
}
})
@@ -339,26 +339,26 @@ func TestNixCacheFetches(t *testing.T) {
if got := f.requests(); len(got) != 2 {
t.Errorf("upstream got %q, want the narinfo and the NAR once", got)
}
if code, _ := nixReq(t, "HEAD", nar); code != 200 {
if code, _ := nixReq(t, s, "HEAD", nar); code != 200 {
t.Errorf("HEAD of a NAR in the cache: %d", code)
}
// A copy of another size is dropped and fetched again.
must(t, os.WriteFile(filepath.Join(dir, fixNar), []byte("short"), 0o600))
if code, body := nixReq(t, "GET", nar); code != 200 || len(body) != 958 || len(f.requests()) != 3 {
if code, body := nixReq(t, s, "GET", nar); code != 200 || len(body) != 958 || len(f.requests()) != 3 {
t.Errorf("a short copy: %d, %d bytes, upstream got %q", code, len(body), f.requests())
}
// Files being fetched that fill the cap leave no room, and nothing is kept.
must(t, os.Remove(filepath.Join(dir, fixNar)))
nixCacheMax = 128 << 10
s.nix.max = 128 << 10
writeCached(t, dir, ".tmp-busy", 128<<10, time.Now())
must(t, os.Remove(sizeFile(dir)))
if code, _ := nixReq(t, "GET", nar); code != 404 {
if code, _ := nixReq(t, s, "GET", nar); code != 404 {
t.Errorf("a full cache: %d", code)
}
if _, err := os.Stat(filepath.Join(dir, fixNar)); err == nil {
t.Error("a NAR was kept in a full cache")
}
if n, _ := readSize(dir); n > nixCacheMax {
if n, _ := readSize(dir); n > s.nix.max {
t.Errorf("the running total is %d, over the cap", n)
}
}
@@ -372,6 +372,7 @@ func writeCached(t *testing.T, dir, name string, size int, at time.Time) {
}
func TestTrimNixCache(t *testing.T) {
t.Parallel()
dir := t.TempDir()
must(t, os.Mkdir(filepath.Join(dir, "nar"), 0o700))
now := time.Now()
@@ -413,13 +414,14 @@ func TestTrimNixCache(t *testing.T) {
// Many proxies keeping files at once never leave the cache over its cap.
func TestNixCacheCap(t *testing.T) {
_, dir := useNixCache(t, nixHost)
nixCacheMax = 64 << 10
t.Parallel()
s, _, dir := useNixCache(t, nixHost)
s.nix.max = 64 << 10
var wg sync.WaitGroup
var failed atomic.Int32
for i := range 40 {
wg.Go(func() {
if keepBytes(filepath.Join(dir, fmt.Sprintf("%032d.narinfo", i)), make([]byte, 900)) != nil {
if s.nix.keepBytes(filepath.Join(dir, fmt.Sprintf("%032d.narinfo", i)), make([]byte, 900)) != nil {
failed.Add(1)
}
})
@@ -428,8 +430,8 @@ func TestNixCacheCap(t *testing.T) {
if failed.Load() > 0 {
t.Fatalf("%d writes failed", failed.Load())
}
if _, size, _ := NixCacheUsage(dir); size > nixCacheMax || size == 0 {
t.Errorf("the cache takes %d, its cap is %d", size, nixCacheMax)
if _, size, _ := NixCacheUsage(dir); size > s.nix.max || size == 0 {
t.Errorf("the cache takes %d, its cap is %d", size, s.nix.max)
}
entries, _ := os.ReadDir(dir)
for _, e := range entries {
+14 -11
View File
@@ -4,6 +4,7 @@ import (
"errors"
"fmt"
"io/fs"
"log"
"net"
"net/netip"
"os"
@@ -199,22 +200,24 @@ type policy struct {
broken map[string]PolicyLine
// failed is, for each file whose last read failed, why: logged once, not at every request.
failed map[string]string
log *log.Logger // the proxy's own log: what was read, what was skipped
}
// PolicyMax bounds a policy file that the proxy, devvm network and devvm doctor read.
const PolicyMax = 1 << 20
func newPolicy(builtin []rule, files []string) *policy {
func newPolicy(builtin []rule, files []string, l *log.Logger) *policy {
return &policy{
builtin: builtin, files: files, mtime: map[string]time.Time{}, rules: map[string][]rule{}, broken: map[string]PolicyLine{},
failed: map[string]string{},
failed: map[string]string{}, log: l,
}
}
// readBuiltins reads the built-in policies names, paths in devvm's own files own, once, in order.
// Each is devvm's own, so one that's missing or holds a line that isn't a rule is devvm's bug: an
// error, and the proxy refuses to start, rather than run with fewer rules than devvm meant.
func readBuiltins(own fs.FS, names []string) ([]rule, error) {
// readBuiltins reads the built-in policies names, paths in devvm's own files own, once, in order,
// logging each to l. Each is devvm's own, so one that's missing or holds a line that isn't a rule
// is devvm's bug: an error, and the proxy refuses to start, rather than run with fewer rules than
// devvm meant.
func readBuiltins(own fs.FS, names []string, l *log.Logger) ([]rule, error) {
if len(names) > 0 && own == nil {
return nil, errors.New("built-in policies need devvm's own files")
}
@@ -230,7 +233,7 @@ func readBuiltins(own fs.FS, names []string) ([]rule, error) {
return nil, fmt.Errorf("built-in policy %s:%d isn't a rule: %q", n, l.N, l.Text)
}
}
logf("built-in policy %s: %d rules", n, len(rs))
l.Printf("built-in policy %s: %d rules", n, len(rs))
out = append(out, rs...)
}
return out, nil
@@ -266,7 +269,7 @@ func (p *policy) all() ([]rule, string) {
if err != nil { // keep its last rules (a deny dropped for a moment would let through)
if why := err.Error(); p.failed[f] != why {
p.failed[f] = why
logf("policy %v; its last rules kept", err)
p.log.Printf("policy %v; its last rules kept", err)
}
out = append(out, p.rules[f]...)
continue
@@ -293,16 +296,16 @@ func (p *policy) load(f, b string) {
for _, l := range lines {
switch {
case BrokenDeny(l):
logf("%s:%d: not a rule but reads as a deny, so everything is denied: %q", f, l.N, l.Text)
p.log.Printf("%s:%d: not a rule but reads as a deny, so everything is denied: %q", f, l.N, l.Text)
if _, ok := p.broken[f]; !ok {
p.broken[f] = l
}
case !l.OK:
logf("%s:%d: not a rule, skipped: %q", f, l.N, l.Text)
p.log.Printf("%s:%d: not a rule, skipped: %q", f, l.N, l.Text)
}
}
p.rules[f] = rs
logf("policy %s: %d rules", f, len(rs))
p.log.Printf("policy %s: %d rules", f, len(rs))
}
// decide whether host:port may be reached. host is a name or an address literal. It returns the
+243 -188
View File
@@ -23,6 +23,10 @@
//
// It exits when the VM's hostagent does (Config.Lifeline). Standard library only, and internal/daemon,
// which is too: it prints nothing itself, but writes to the streams devvm hands Main.
//
// Everything one proxy runs with and keeps between connections is in its server, which Main makes
// from the config (newServer): the package keeps no state of its own, so each test makes a server
// of its own, and none sees another's.
package proxy
import (
@@ -30,6 +34,7 @@ import (
"bytes"
"context"
"crypto/subtle"
"crypto/x509"
"encoding/base64"
"encoding/json"
"errors"
@@ -50,8 +55,6 @@ import (
"github.com/w3cj/devvm/internal/daemon"
)
var vmName = "vm"
// newFlags defines devvm _proxy's one flag, -config, on a flag set of its own, writing into path. It
// takes one dash or two.
func newFlags(path *string) *flag.FlagSet {
@@ -60,9 +63,78 @@ func newFlags(path *string) *flag.FlagSet {
return fs
}
// --- who may use the proxy ---
// --- the server ---
var proxyAuth = "" // the VM's password (Config.Password); empty: no check
// server is one proxy: what its config gave it, and what it keeps between connections, each part
// under a lock of its own. newServer makes it from a Config.
type server struct {
vm string // Config.VM, for the log
password string // the VM's password (Config.Password); empty: no check
log *log.Logger // its own log lines (what it loaded, what failed), not events
events *events
egress *egress // where a connection may go: the policy, the floor, the company proxy
secrets *secrets // Config.Secrets: the bindings and their values
ca *ca // Config.CA, for interception; nil: none
// upstreamCAs is what the proxy's own TLS connections trust: nil, the system roots;
// Config.UpstreamCAs, the user's CAs besides them.
upstreamCAs *x509.CertPool
// interceptPorts are the ports a host with a bound secret is intercepted on: HTTPS's alone, so
// anything else to a bound host (SSH on :22, …) is tunneled.
interceptPorts map[int]bool
links links
nix *nixCache
}
// newServer makes the server c describes, logging to l and its events to out: it reads its CA,
// the company proxy's settings, the built-in policies (from std.FS) and the user's policy files,
// and opens the Nix cache. Values come from std.Secret.
func newServer(c Config, std IO, l *log.Logger, out io.Writer) (*server, error) {
ev := &events{vm: c.VM, out: out}
s := &server{
vm: c.VM, password: c.Password, log: l, events: ev,
secrets: newSecrets(c.Secrets, std.Secret, l),
interceptPorts: map[int]bool{443: true},
links: links{file: c.Links, sockets: c.LinkSockets, vm: c.VM, log: l, events: ev},
}
var err error
if c.CA != "" {
if s.ca, err = loadCA(c.CA, c.CAKey); err != nil {
return nil, err
}
}
if c.UpstreamCAs != "" {
if s.upstreamCAs, err = upstreamPool([]byte(c.UpstreamCAs)); err != nil {
return nil, err
}
}
var up upstreams
if c.Upstream != nil {
if up, err = newUpstreams(*c.Upstream); err != nil {
return nil, err
}
l.Printf("%s", up.names())
}
up.unresolved = c.UpstreamUnresolved
rs, err := readBuiltins(std.FS, c.BuiltinPolicies, l)
if err != nil {
return nil, err
}
own := &hostAddrs{}
own.load()
s.egress = &egress{pol: newPolicy(rs, c.Policies, l), own: own, up: up}
s.egress.pol.all()
maxSize := c.NixCacheMax
if maxSize == 0 {
maxSize = NixCacheDefault
}
s.nix = newNixCache(c.NixCache, maxSize, s.egress, ev, l, s.upstreamCAs)
if err := s.nix.open(); err != nil {
return nil, err
}
return s, nil
}
// --- who may use the proxy ---
// ProxyUser is the user every request names with its password, a VM's or a build's own, as devvm's
// backends put it in a guest's proxy settings.
@@ -72,8 +144,8 @@ const ProxyUser = "devvm"
// 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 == "" {
func (s *server) authorized(r *http.Request) bool {
if s.password == "" {
return true
}
v := r.Header.Get("Proxy-Authorization")
@@ -81,11 +153,9 @@ func authorized(r *http.Request) bool {
return false
}
raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(v[6:]))
return err == nil && subtle.ConstantTimeCompare(raw, []byte(ProxyUser+":"+proxyAuth)) == 1
return err == nil && subtle.ConstantTimeCompare(raw, []byte(ProxyUser+":"+s.password)) == 1
}
var pol *policy
// --- events ---
// Event is one line of the event log, as JSON: a decision about a
@@ -115,28 +185,40 @@ type numbered struct {
e Event
}
var (
logMu sync.Mutex
logOut io.Writer = io.Discard // Main sets it: Config.Log, else stdout
recent []numbered // the last blocks, for /blocked
blocks int // blocks so far
)
// events is a proxy's event log (Config.Log, else IO.Stdout) and the blocks it keeps for
// /blocked, all under its lock.
type events struct {
vm string // Config.VM: every event's
mu sync.Mutex
out io.Writer
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
// record writes e to the log, as the VM's, now, and keeps it among the recent blocks when it's one.
func (ev *events) record(e Event) {
e.Time, e.VM = time.Now().UTC().Format(time.RFC3339), ev.vm
b, _ := json.Marshal(e)
logMu.Lock()
defer logMu.Unlock()
fmt.Fprintln(logOut, string(b))
ev.mu.Lock()
defer ev.mu.Unlock()
fmt.Fprintln(ev.out, string(b))
if e.Event == "blocked" {
blocks++
recent = append(recent, numbered{blocks, e})
if len(recent) > 50 {
recent = recent[len(recent)-50:]
ev.blocks++
ev.recent = append(ev.recent, numbered{ev.blocks, e})
if len(ev.recent) > 50 {
ev.recent = ev.recent[len(ev.recent)-50:]
}
}
}
// blocked is a copy of the recent blocks, and how many blocks there have been, for /blocked and
// /blocked/new.
func (ev *events) blocked() ([]numbered, int) {
ev.mu.Lock()
defer ev.mu.Unlock()
return slices.Clone(ev.recent), ev.blocks
}
// 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.
@@ -174,23 +256,17 @@ func newBlocks(rs []numbered, count int, after string) string {
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
)
// hostAddrs is the host's own addresses, read again every 30 seconds: they change (a new network,
// IPv6 temporary addresses).
type hostAddrs struct {
mu sync.Mutex
addrs map[netip.Addr]bool
at time.Time
}
func loadOwnAddrs() {
func (h *hostAddrs) load() {
addrs, _ := net.InterfaceAddrs()
own := map[netip.Addr]bool{}
for _, a := range addrs {
@@ -198,21 +274,21 @@ func loadOwnAddrs() {
own[p.Addr().Unmap()] = true
}
}
ownMu.Lock()
ownAddrs, ownAt = own, time.Now()
ownMu.Unlock()
h.mu.Lock()
h.addrs, h.at = own, time.Now()
h.mu.Unlock()
}
func isOwn(a netip.Addr) bool {
ownMu.Lock()
stale := time.Since(ownAt) > 30*time.Second
ownMu.Unlock()
func (h *hostAddrs) has(a netip.Addr) bool {
h.mu.Lock()
stale := time.Since(h.at) > 30*time.Second
h.mu.Unlock()
if stale {
loadOwnAddrs()
h.load()
}
ownMu.Lock()
defer ownMu.Unlock()
return ownAddrs[a]
h.mu.Lock()
defer h.mu.Unlock()
return h.addrs[a]
}
// Ranges that aren't the public internet beyond what netip's predicates cover: CGNAT, "this network",
@@ -224,6 +300,7 @@ var notPublic = []netip.Prefix{
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).
@@ -235,12 +312,13 @@ func nat64IPv4(a netip.Addr) (netip.Addr, bool) {
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 {
// internal: addresses a VM must not reach without an explicit rule: the host itself (h) 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 (h *hostAddrs) internal(a netip.Addr) bool {
a = a.Unmap()
if v4, ok := nat64IPv4(a); ok {
return internal(v4)
return h.internal(v4)
}
for _, p := range notPublic {
if p.Contains(a) {
@@ -248,14 +326,22 @@ func internal(a netip.Addr) bool {
}
}
return a.IsLoopback() || a.IsPrivate() || a.IsLinkLocalUnicast() || a.IsLinkLocalMulticast() ||
a.IsMulticast() || a.IsUnspecified() || a.IsInterfaceLocalMulticast() || isOwn(a)
a.IsMulticast() || a.IsUnspecified() || a.IsInterfaceLocalMulticast() || h.has(a)
}
// egress decides where a connection may go, and makes it: the policy, the floor of internal
// addresses (the host's own among them), and the company proxy.
type egress struct {
pol *policy
own *hostAddrs
up upstreams
}
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) {
func (e *egress) 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()}
@@ -270,7 +356,7 @@ func resolve(ctx context.Context, host string, port int) ([]netip.Addr, error) {
}
var ok []netip.Addr
for _, a := range addrs {
if !pol.addrDenied(a, port) && (!internal(a) || pol.addrAllowed(a, port)) {
if !e.pol.addrDenied(a, port) && (!e.own.internal(a) || e.pol.addrAllowed(a, port)) {
ok = append(ok, a)
}
}
@@ -280,8 +366,8 @@ func resolve(ctx context.Context, host string, port int) ([]netip.Addr, error) {
return ok, nil
}
func dial(ctx context.Context, host string, port int) (net.Conn, error) {
addrs, err := resolve(ctx, host, port)
func (e *egress) dial(ctx context.Context, host string, port int) (net.Conn, error) {
addrs, err := e.resolve(ctx, host, port)
if err != nil {
return nil, err
}
@@ -290,11 +376,11 @@ func dial(ctx context.Context, host string, port int) (net.Conn, error) {
}
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 {
c, err2 := d.DialContext(ctx, "tcp", netip.AddrPortFrom(a, uint16(port)).String())
if err2 == nil {
return c, nil
}
err = e
err = err2
}
return nil, err
}
@@ -344,9 +430,9 @@ func splitHostPort(hp string, def int) (string, int) {
return norm(h), n
}
func block(w http.ResponseWriter, e Event) {
func (s *server) block(w http.ResponseWriter, e Event) {
e.Event = "blocked"
record(e)
s.events.record(e)
w.Header().Set("X-Devvm-Blocked", e.Host)
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusForbidden)
@@ -377,19 +463,19 @@ func AllowRule(host string, port int) (string, bool) {
// check runs the policy and the floor; on success it returns the rule that allowed host:port. plain
// is a plain HTTP request, which goes through HTTP_PROXY's upstream rather than HTTPS_PROXY's.
func check(ctx context.Context, host string, port int, plain bool) (string, string) {
rule, why, _ := checkRefused(ctx, host, port, plain)
func (e *egress) check(ctx context.Context, host string, port int, plain bool) (string, string) {
rule, why, _ := e.checkRefused(ctx, host, port, plain)
return rule, why
}
// checkRefused is check, and whether a refusal is one no allow rule would lift (a broken deny's),
// which its event marks Refused.
func checkRefused(ctx context.Context, host string, port int, plain bool) (string, string, bool) {
ok, rule, refused := pol.verdict(host, port) // rule: the allowing rule, or why not
func (e *egress) checkRefused(ctx context.Context, host string, port int, plain bool) (string, string, bool) {
ok, rule, refused := e.pol.verdict(host, port) // rule: the allowing rule, or why not
if !ok {
return "", rule, refused
}
if why := floorCheck(ctx, host, port, plain); why != "" {
if why := e.floorCheck(ctx, host, port, plain); why != "" {
return "", why, false
}
return rule, "", false
@@ -397,10 +483,10 @@ func checkRefused(ctx context.Context, host string, port int, plain bool) (strin
// floorCheck is check past the rules for an allowed host: the address floor, or the company
// proxy's. It returns why not, or "".
func floorCheck(ctx context.Context, host string, port int, plain bool) string {
floor := func() error { _, err := resolve(ctx, host, port); return err }
if upstreamFor(host, port, plain) != nil {
floor = func() error { return floorUpstream(ctx, host, port) }
func (e *egress) floorCheck(ctx context.Context, host string, port int, plain bool) string {
floor := func() error { _, err := e.resolve(ctx, host, port); return err }
if e.up.route(host, port, plain) != nil {
floor = func() error { return e.floorUpstream(ctx, host, port) }
}
err := floor()
switch {
@@ -415,46 +501,56 @@ func floorCheck(ctx context.Context, host string, port int, plain bool) string {
}
}
func handleConnect(w http.ResponseWriter, r *http.Request) {
func (s *server) 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
}
// One of the VM's links: its socket, before any rule (links.go).
if l, ok := linkFor(host, port); ok {
connectLink(w, r, host, port, l)
if l, ok := s.links.find(host, port); ok {
s.links.connect(w, r, host, port, l)
return
}
if notALink(w, "CONNECT", host, port) {
if s.links.refuse(w, "CONNECT", host, port) {
return
}
e := Event{Host: host, Port: port, Method: "CONNECT"}
rule, why, refused := checkRefused(r.Context(), host, port, false)
rule, why, refused := s.egress.checkRefused(r.Context(), host, port, false)
if why != "" {
e.Reason, e.Refused = why, refused
block(w, e)
s.block(w, e)
return
}
e.Rule = rule
if up := upstreamFor(host, port, false); up != nil {
if up := s.egress.up.route(host, port, false); up != nil {
e.Upstream = up.addr
}
if bs := bindingsFor(host); interceptPorts[port] && len(bs) > 0 && caCert != nil {
if caEndedRefusal(w, e) {
if bs := s.secrets.forHost(host); s.interceptPorts[port] && len(bs) > 0 && s.ca != nil {
if s.caEndedRefusal(w, e) {
return
}
client, err := hijack(w)
if err != nil {
return
}
intercept(r.Context(), client, host, port, e)
s.intercept(r.Context(), client, host, port, e)
return
}
up, err := dialOut(r.Context(), host, port)
s.tunnel(w, r, host, port, e)
}
// tunnel carries a CONNECT to host:port that the policy allows, e its event. The far end's bytes
// go to the client at once, so a protocol whose server speaks first (SMTP) gets its greeting
// before the client sends anything. The client's go on only once they're checked: when they start
// a TLS ClientHello, its SNI must be the host that was checked (which blunts domain fronting), and
// nothing of the client's reaches the far end before that. Other protocols (SSH on :22, …) pass as
// they are.
func (s *server) tunnel(w http.ResponseWriter, r *http.Request, host string, port int, e Event) {
up, err := s.egress.dialOut(r.Context(), host, port)
if err != nil {
e.Reason = "connect failed: " + err.Error()
block(w, e)
s.block(w, e)
return
}
defer func() { _ = up.Close() }()
@@ -463,19 +559,18 @@ func handleConnect(w http.ResponseWriter, r *http.Request) {
return
}
defer func() { _ = client.Close() }()
// 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(client.r)
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)
splice(client, up)
splice(client, up, func() bool {
first, sni, isTLS := peekClientHello(client.r)
if isTLS && !sniMatches(sni, host) {
e.Event, e.Reason = "blocked", fmt.Sprintf("TLS name %q doesn't match %s", sni, host)
s.events.record(e)
return false
}
e.Event = "tunnel"
s.events.record(e)
_, err := up.Write(first)
return err == nil
})
}
func sniMatches(sni, host string) bool {
@@ -486,10 +581,15 @@ func sniMatches(sni, host string) bool {
}
// 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.
// read (to replay upstream), the SNI, and whether it was TLS. It looks at one byte first: only a
// TLS record starts with 0x16, so a client that sends fewer than a record header's five bytes of
// anything else isn't held.
func peekClientHello(r *bufio.Reader) ([]byte, string, bool) {
if b, err := r.Peek(1); err != nil || b[0] != 0x16 {
return nil, "", false
}
hdr, err := r.Peek(5)
if err != nil || hdr[0] != 0x16 || hdr[1] != 3 {
if err != nil || hdr[1] != 3 {
return nil, "", false
}
n := int(hdr[3])<<8 | int(hdr[4])
@@ -502,7 +602,7 @@ func peekClientHello(r *bufio.Reader) ([]byte, string, bool) {
// 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) {
func (s *server) handleHTTP(w http.ResponseWriter, r *http.Request) {
if r.URL.Host == "" {
http.Error(w, "devvm proxy: not a proxy request", http.StatusBadRequest)
return
@@ -521,47 +621,45 @@ func handleHTTP(w http.ResponseWriter, r *http.Request) {
return
}
if host == "devvm.proxy" {
serveReserved(w, r)
s.serveReserved(w, r)
return
}
// One of the VM's links: its socket, before any rule (links.go). HTTPS to a link goes through
// CONNECT, so its TLS stays the client's: the proxy makes none of its own to a link.
if l, ok := linkFor(host, port); ok {
if l, ok := s.links.find(host, port); ok {
if scheme == "https" {
http.Error(w, "devvm proxy: reach a link over HTTPS through CONNECT", http.StatusBadRequest)
return
}
forwardLink(w, r, host, port, l)
s.links.forward(w, r, host, port, l)
return
}
if notALink(w, r.Method, host, port) {
if s.links.refuse(w, r.Method, host, port) {
return
}
e := Event{Host: host, Port: port, Method: r.Method, Path: r.URL.Path, Agent: r.UserAgent()}
if _, why, refused := checkRefused(r.Context(), host, port, scheme == "http"); why != "" {
if _, why, refused := s.egress.checkRefused(r.Context(), host, port, scheme == "http"); why != "" {
e.Reason, e.Refused = why, refused
block(w, e)
s.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())))
s.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) {
func (s *server) serveReserved(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, "/nix/") {
serveNix(w, r)
s.nix.serve(w, r)
return
}
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()
rs, _ := s.events.blocked()
if len(rs) == 0 {
fmt.Fprintln(w, "devvm: nothing blocked recently")
return
@@ -577,12 +675,10 @@ func serveReserved(w http.ResponseWriter, r *http.Request) {
}
_, _ = w.Write(b.Bytes())
case "/blocked/new":
logMu.Lock()
s := newBlocks(recent, blocks, r.URL.Query().Get("after"))
logMu.Unlock()
fmt.Fprint(w, s)
rs, count := s.events.blocked()
fmt.Fprint(w, newBlocks(rs, count, r.URL.Query().Get("after")))
case "/ca.pem":
if p := caPEM(); p != nil {
if p := s.ca.pem(); p != nil {
_, _ = w.Write(p)
return
}
@@ -592,50 +688,36 @@ func serveReserved(w http.ResponseWriter, r *http.Request) {
}
}
func handler(w http.ResponseWriter, r *http.Request) {
if !authorized(r) {
func (s *server) handler(w http.ResponseWriter, r *http.Request) {
if !s.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)
s.handleConnect(w, r)
return
}
handleHTTP(w, r)
s.handleHTTP(w, r)
}
// lifelineTick: how often watchLifeline looks (tests shorten it).
var lifelineTick = 3 * time.Second
// lifelineTick: how often the proxy looks at its VM's lifeline.
const lifelineTick = 3 * time.Second
// lifelineWait bounds how long the proxy waits for its VM's lifeline: it starts before the VM does.
const lifelineWait = 15 * time.Minute
// watchLifeline returns once the VM's lifeline (daemon.Lifeline) no longer holds, or never names a
// process that runs. It follows the start it first sees running, not later ones: a restarted VM
// gets a new proxy. A lifeline a start writes whose process is already gone (the VM stopped
// between two looks) ends it too; what the file held when the proxy started is an earlier
// start's, and waited past.
func watchLifeline(path string) {
if l, ok := daemon.FollowLifeline(path, lifelineWait, lifelineTick); ok {
l.Wait(lifelineTick)
// process that runs, looking every tick. It follows the start it first sees running, not later
// ones: a restarted VM gets a new proxy. A lifeline a start writes whose process is already gone
// (the VM stopped between two looks) ends it too; what the file held when the proxy started is an
// earlier start's, and waited past.
func watchLifeline(path string, tick time.Duration) {
if l, ok := daemon.FollowLifeline(path, lifelineWait, tick); ok {
l.Wait(tick)
}
}
// loadPolicies reads the built-in policies (Config.BuiltinPolicies) from devvm's files, the user's
// policy files (Config.Policies) and the host's own addresses, and opens the Nix cache
// (Config.NixCache).
func loadPolicies(c Config, own fs.FS) error {
rs, err := readBuiltins(own, c.BuiltinPolicies)
if err != nil {
return err
}
pol = newPolicy(rs, c.Policies)
pol.all()
loadOwnAddrs()
return openNixCache()
}
// IO is what devvm _proxy reads and writes: devvm's own streams.
type IO struct {
// Stdout gets data: the event log without Config.Log, and what -help prints.
@@ -651,7 +733,10 @@ type IO struct {
// Main runs devvm _proxy with args (its flags): the proxy itself, with -config's file, until the
// VM's hostagent is gone. -help prints the flags to std.Stdout. Errors are returned, not printed.
func Main(args []string, std IO) error {
func Main(args []string, std IO) error { return run(args, std, lifelineTick) }
// run is Main, looking at the VM's lifeline every tick.
func run(args []string, std IO, tick time.Duration) error {
var configPath string
fs := newFlags(&configPath)
fs.SetOutput(io.Discard)
@@ -666,7 +751,6 @@ func Main(args []string, std IO) error {
if fs.NArg() > 0 {
return fmt.Errorf("unexpected argument %q", fs.Arg(0))
}
logger.SetOutput(std.Stderr)
// Without a config, and the password in it, any program on the host could use the proxy, and
// the VM's tokens with it.
if configPath == "" {
@@ -679,75 +763,46 @@ func Main(args []string, std IO) error {
if c.Secrets != "" && std.Secret == nil {
return errors.New("secrets without a lookup")
}
return serve(c, std)
}
// apply sets what the proxy runs with from c, reading its CA and the company proxy's settings.
func (c Config) apply() error {
vmName, proxyAuth, upUnresolved = c.VM, c.Password, c.UpstreamUnresolved
secretsPath = c.Secrets
linksFile, linkSockets = c.Links, c.LinkSockets
nixCacheDir, nixCacheMax = c.NixCache, c.NixCacheMax
if nixCacheMax == 0 {
nixCacheMax = NixCacheDefault
}
if c.CA != "" {
if err := loadCA(c.CA, c.CAKey); err != nil {
return err
}
}
if c.UpstreamCAs != "" {
if err := loadUpstreamCAs([]byte(c.UpstreamCAs)); err != nil {
return err
}
}
if c.Upstream != nil {
if err := loadUpstream(*c.Upstream); err != nil {
return err
}
logf("%s", upstreamNames())
}
return nil
return serve(c, std, tick)
}
// serve runs the proxy with c until the VM's hostagent is gone (c.Lifeline).
func serve(c Config, std IO) error {
func serve(c Config, std IO, tick time.Duration) error {
l := log.New(std.Stderr, "devvm proxy: ", log.LstdFlags)
if c.ProxyLog != "" {
f, err := copyRotating(c.ProxyLog, std.Stderr, LogLimit)
if err != nil {
return err
}
logger.SetOutput(f)
l.SetOutput(f)
}
if err := c.apply(); err != nil {
return err
}
secretLookup, logOut = std.Secret, std.Stdout
out := std.Stdout
if c.Log != "" {
f, err := OpenEventLog(c.Log)
if err != nil {
return err
}
defer func() { _ = f.Close() }()
logOut = f
out = f
}
if err := loadPolicies(c, std.FS); err != nil {
s, err := newServer(c, std, l, out)
if err != nil {
return err
}
ln, err := net.Listen("tcp", c.Listen) //nolint:noctx // listens for the proxy's whole life
if err != nil {
return err
}
srv := &http.Server{Handler: http.HandlerFunc(handler), ReadHeaderTimeout: 30 * time.Second}
logf("listening on %s for %s", ln.Addr(), vmName)
srv := &http.Server{Handler: http.HandlerFunc(s.handler), ReadHeaderTimeout: 30 * time.Second}
l.Printf("listening on %s for %s", ln.Addr(), s.vm)
// What devvm waits for as it starts the proxy: the address it listens on.
if err := daemon.Ready(ln.Addr().String()); err != nil {
logf("%v", err)
l.Printf("%v", err)
}
if c.Lifeline != "" {
go func() {
watchLifeline(c.Lifeline)
logf("the VM's hostagent is gone; exiting")
watchLifeline(c.Lifeline, tick)
l.Printf("the VM's hostagent is gone; exiting")
_ = srv.Close()
}()
}
+155 -61
View File
@@ -8,6 +8,7 @@ import (
"errors"
"io"
"io/fs"
"log"
"net"
"net/http"
"net/http/httptest"
@@ -25,16 +26,57 @@ import (
"time"
)
func writePolicy(t *testing.T, rules string) *policy {
// quiet is a log that keeps nothing.
func quiet() *log.Logger { return log.New(io.Discard, "devvm proxy: ", 0) }
// policyFiles writes rules to a policy file of the test's own, and returns it and a file that's
// missing, which has no rules.
func policyFiles(t *testing.T, rules string) []string {
t.Helper()
f := filepath.Join(t.TempDir(), "policy")
if err := os.WriteFile(f, []byte(rules), 0o600); err != nil {
t.Fatal(err)
must(t, os.WriteFile(f, []byte(rules), 0o600))
return []string{f, filepath.Join(t.TempDir(), "missing")}
}
func writePolicy(t *testing.T, rules string) *policy {
t.Helper()
return newPolicy(nil, policyFiles(t, rules), quiet())
}
// testServer is a proxy of the test's own, made as Main makes one (newServer), from c with a
// policy of rules (and the VM's name "vm" when c has none): it logs nothing, and nothing of it is
// any other test's.
func testServer(t *testing.T, c Config, rules string) *server {
t.Helper()
c.Policies = append(c.Policies, policyFiles(t, rules)...)
if c.VM == "" {
c.VM = "vm"
}
return newPolicy(nil, []string{f, filepath.Join(t.TempDir(), "missing")})
s, err := newServer(c, IO{}, quiet(), io.Discard)
must(t, err)
return s
}
// listen serves s for the test, on a port of its own, and returns its address.
func listen(t *testing.T, s *server) string {
t.Helper()
p := httptest.NewServer(http.HandlerFunc(s.handler))
t.Cleanup(p.Close)
return p.Listener.Addr().String()
}
// logs captures s's event log and its own log lines.
func logs(s *server) *syncBuffer {
b := &syncBuffer{}
s.events.mu.Lock()
s.events.out = b
s.events.mu.Unlock()
s.log.SetOutput(b)
return b
}
func TestNewBlocks(t *testing.T) {
t.Parallel()
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"}},
@@ -72,6 +114,7 @@ func TestNewBlocks(t *testing.T) {
}
func TestDecide(t *testing.T) {
t.Parallel()
p := writePolicy(t, `
# comment
example.com
@@ -114,6 +157,7 @@ github.com:22
// ParsePolicy is strict: a line holds one rule, as devvm network allow takes it, a comment, or
// nothing. Every other line is returned as not a rule, with its number, and the proxy skips it.
func TestParsePolicy(t *testing.T) {
t.Parallel()
text := "# a comment\n" +
"\n" +
"example.com\n" +
@@ -179,13 +223,11 @@ func TestParsePolicy(t *testing.T) {
// logging the file, the line's number and its text, and keeps the file's rules. A trailing dot
// in a rule names the same host.
func TestPolicySkipsBadLines(t *testing.T) {
t.Parallel()
var logged strings.Builder
old := logger.Writer()
logger.SetOutput(&logged)
t.Cleanup(func() { logger.SetOutput(old) })
f := filepath.Join(t.TempDir(), "policy")
must(t, os.WriteFile(f, []byte("**\nexample.com:x\n!example.org.\n!::ffff:10.0.0.0/104\n"), 0o600))
p := newPolicy(nil, []string{f})
p := newPolicy(nil, []string{f}, log.New(&logged, "", 0))
if ok, why := p.decide("example.org", 443); ok {
t.Errorf("example.org allowed (%s): the deny with a trailing dot was skipped", why)
}
@@ -206,15 +248,13 @@ func TestPolicySkipsBadLines(t *testing.T) {
// everything, by name and by address, as a refusal no allow rule would lift, naming the file and
// line; fixing the line lifts it.
func TestPolicyBrokenDeny(t *testing.T) {
t.Parallel()
var logged strings.Builder
old := logger.Writer()
logger.SetOutput(&logged)
t.Cleanup(func() { logger.SetOutput(old) })
dir := t.TempDir()
good, f := filepath.Join(dir, "good"), filepath.Join(dir, "policy")
must(t, os.WriteFile(good, []byte("**\n10.0.0.0/8\n"), 0o600))
must(t, os.WriteFile(f, []byte("ok.test\n! bad.example.com # a space after the !\n"), 0o600))
p := newPolicy(nil, []string{good, f})
p := newPolicy(nil, []string{good, f}, log.New(&logged, "", 0))
for _, h := range []string{"bad.example.com", "other.test", "10.0.0.1"} {
ok, why, refused := p.verdict(h, 443)
if ok || !refused || !strings.Contains(why, f+":2 isn't a rule but reads as a deny") {
@@ -228,14 +268,13 @@ func TestPolicyBrokenDeny(t *testing.T) {
t.Errorf("the log has no %q:\n%s", want, logged.String())
}
// Through the proxy: 403, refused, with no allow command.
oldPol, oldOut, oldAuth := pol, logOut, proxyAuth
var events strings.Builder
pol, logOut, proxyAuth = p, &events, ""
t.Cleanup(func() { pol, logOut, proxyAuth = oldPol, oldOut, oldAuth })
s := testServer(t, Config{}, "")
s.egress.pol = p
events := logs(s)
req := httptest.NewRequestWithContext(t.Context(), http.MethodConnect, "http://other.test:443", nil)
req.Host = "other.test:443"
w := httptest.NewRecorder()
handler(w, req)
s.handler(w, req)
if w.Code != http.StatusForbidden || strings.Contains(w.Body.String(), "network allow") || !strings.Contains(w.Body.String(), "refused") {
t.Errorf("answered %d %q", w.Code, w.Body.String())
}
@@ -245,7 +284,7 @@ func TestPolicyBrokenDeny(t *testing.T) {
// An absolute-form request too.
req = httptest.NewRequestWithContext(t.Context(), http.MethodGet, "http://other.test/x", nil)
w = httptest.NewRecorder()
handler(w, req)
s.handler(w, req)
if w.Code != http.StatusForbidden || strings.Contains(w.Body.String(), "network allow") {
t.Errorf("absolute form: answered %d %q", w.Code, w.Body.String())
}
@@ -268,10 +307,11 @@ func TestPolicyBrokenDeny(t *testing.T) {
// times) is read again: its denies, a broken one too, hold again. A leading byte-order mark is
// no part of the first line.
func TestPolicyFileBack(t *testing.T) {
t.Parallel()
dir := t.TempDir()
f, away := filepath.Join(dir, "policy"), filepath.Join(dir, "away")
must(t, os.WriteFile(f, []byte("\xef\xbb\xbf!bad.test\n**\n"), 0o600))
p := newPolicy(nil, []string{f})
p := newPolicy(nil, []string{f}, quiet())
if ok, _ := p.decide("bad.test", 443); ok {
t.Fatal("bad.test allowed: the byte-order mark hid its deny")
}
@@ -299,9 +339,10 @@ func TestPolicyFileBack(t *testing.T) {
}
func TestPolicyReload(t *testing.T) {
t.Parallel()
f := filepath.Join(t.TempDir(), "policy")
must(t, os.WriteFile(f, []byte("a.test\n"), 0o600))
p := newPolicy(nil, []string{f})
p := newPolicy(nil, []string{f}, quiet())
if ok, _ := p.decide("b.test", 443); ok {
t.Fatal("b.test allowed before it was added")
}
@@ -327,18 +368,19 @@ func TestPolicyReload(t *testing.T) {
// beats a built-in allow. One that's missing, or holds a line that isn't a rule, or with no files
// to read it from, is an error.
func TestBuiltinPolicies(t *testing.T) {
t.Parallel()
own := fstest.MapFS{
"layers/base.policy": {Data: []byte("# devvm's\nbase.test\n")},
"shared-tools/node.policy": {Data: []byte("node.test\n*.node.test:8443\n")},
"layers/bad.policy": {Data: []byte("ok.test\nnot a rule\n")},
}
rs, err := readBuiltins(own, []string{"layers/base.policy", "shared-tools/node.policy"})
rs, err := readBuiltins(own, []string{"layers/base.policy", "shared-tools/node.policy"}, quiet())
if err != nil || len(rs) != 3 {
t.Fatalf("readBuiltins = %v, %v", rs, err)
}
f := filepath.Join(t.TempDir(), "policy")
must(t, os.WriteFile(f, []byte("mine.test\n!node.test\n"), 0o600))
p := newPolicy(rs, []string{f})
p := newPolicy(rs, []string{f}, quiet())
all, _ := p.all()
var texts []string
for _, r := range all {
@@ -367,45 +409,48 @@ func TestBuiltinPolicies(t *testing.T) {
{own, []string{"../policy"}, "built-in policy ../policy: "},
{nil, []string{"layers/base.policy"}, "built-in policies need devvm's own files"},
} {
if _, err := readBuiltins(c.own, c.names); err == nil || !strings.HasPrefix(err.Error(), c.want) {
if _, err := readBuiltins(c.own, c.names, quiet()); err == nil || !strings.HasPrefix(err.Error(), c.want) {
t.Errorf("readBuiltins(%q) = %v, want %q", c.names, err, c.want)
}
}
if rs, err := readBuiltins(nil, nil); err != nil || rs != nil {
if rs, err := readBuiltins(nil, nil, quiet()); err != nil || rs != nil {
t.Errorf("no built-ins: %v, %v", rs, err)
}
}
func TestInternal(t *testing.T) {
t.Parallel()
own := &hostAddrs{}
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)) {
if !own.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)) {
if own.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.Parallel()
e := testServer(t, Config{}, "**\n10.9.8.7\n").egress
if _, err := e.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) {
if _, err := e.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 {
if a, err := e.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, false); why == "" {
if _, why := e.check(t.Context(), "localhost", 443, false); why == "" {
t.Error("localhost passed the floor through '**'")
}
}
@@ -413,39 +458,37 @@ func TestFloor(t *testing.T) {
// 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.Parallel()
e := testServer(t, Config{}, "localhost:8080\n127.0.0.0/8:8080\n::1:8080\n!127.0.0.1:8080\n!::1:8080\n").egress
if ok, _ := e.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) {
if e.pol.addrAllowed(netip.MustParseAddr("127.0.0.1"), 8080) {
t.Error("addrAllowed ignores the deny")
}
if _, why := check(t.Context(), "localhost", 8080, false); why == "" {
if _, why := e.check(t.Context(), "localhost", 8080, false); 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 {
e.pol = writePolicy(t, "**\n!1.1.1.1\n")
if a, err := e.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")
e.pol = writePolicy(t, "**\n!203.0.113.0/24\n")
n := netip.MustParseAddr("64:ff9b::cb00:7105")
if !pol.addrDenied(n, 443) {
if !e.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 {
if a, err := e.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()
t.Parallel()
addr := listen(t, testServer(t, Config{Password: "k3y"}, ""))
basic := func(s string) string { return "Basic " + base64.StdEncoding.EncodeToString([]byte(s)) }
for _, c := range []struct {
auth string
@@ -461,7 +504,7 @@ func TestProxyAuth(t *testing.T) {
if c.auth != "" {
h += "Proxy-Authorization: " + c.auth + "\r\n"
}
got, _ := roundTrip(t, proxy.Listener.Addr().String(), h+"\r\n")
got, _ := roundTrip(t, addr, 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 {
@@ -476,13 +519,60 @@ func TestProxyAuth(t *testing.T) {
}
}
// Two proxies in one process share nothing of a VM's: each takes only its own password, logs and
// lists only its own blocks, as its own VM, and keeps its own values, looked up with its own
// lookup, and its own CA's leaves.
func TestServersApart(t *testing.T) {
t.Parallel()
dir := t.TempDir()
writeCA(t, dir)
other := filepath.Join(dir, "other")
must(t, os.Mkdir(other, 0o700))
writeCA(t, other)
a := testServer(t, Config{VM: "devvm-a", Password: "pa", CA: filepath.Join(dir, "ca.pem"), CAKey: filepath.Join(dir, "ca.key")}, "")
b := testServer(t, Config{VM: "devvm-b", Password: "pb", CA: filepath.Join(other, "ca.pem"), CAKey: filepath.Join(other, "ca.key")}, "")
aEvents, bEvents := logs(a), logs(b)
aAddr, bAddr := listen(t, a), listen(t, b)
auth := func(pw string) string { return "Proxy-Authorization: " + authOf(ProxyUser, pw) + "\r\n" }
if code, _ := roundTrip(t, bAddr, "GET http://devvm.proxy/blocked HTTP/1.1\r\nHost: devvm.proxy\r\n"+auth("pa")+"\r\n"); code != http.StatusProxyAuthRequired {
t.Errorf("b took a's password: %d", code)
}
if code, _ := roundTrip(t, bAddr, "CONNECT blocked.test:443 HTTP/1.1\r\nHost: blocked.test:443\r\n"+auth("pb")+"\r\n"); code != http.StatusForbidden {
t.Errorf("b's block: %d", code)
}
if _, body := roundTrip(t, aAddr, "GET http://devvm.proxy/blocked HTTP/1.1\r\nHost: devvm.proxy\r\n"+auth("pa")+"\r\n"); !strings.Contains(body, "nothing blocked") {
t.Errorf("a lists b's block: %q", body)
}
if _, body := roundTrip(t, bAddr, "GET http://devvm.proxy/blocked/new?after=0 HTTP/1.1\r\nHost: devvm.proxy\r\n"+auth("pb")+"\r\n"); !strings.Contains(body, "blocked.test") {
t.Errorf("b doesn't list its block: %q", body)
}
if aEvents.String() != "" || !strings.Contains(bEvents.String(), `"vm":"devvm-b","event":"blocked","host":"blocked.test"`) {
t.Errorf("events: a %q, b %q", aEvents.String(), bEvents.String())
}
fakeSecret(a.secrets, "a-value")
fakeSecret(b.secrets, "b-value")
bind := Binding{Name: "t", Kind: KindSecret}
if v, err := a.secrets.value(bind); v != "a-value" || err != nil {
t.Errorf("a's value: %q, %v", v, err)
}
if v, err := b.secrets.value(bind); v != "b-value" || err != nil {
t.Errorf("b's value: %q, %v", v, err)
}
la, err := a.ca.leafFor("api.example.com")
must(t, err)
lb, err := b.ca.leafFor("api.example.com")
must(t, err)
if la == lb || la.Leaf.CheckSignatureFrom(a.ca.cert) != nil || lb.Leaf.CheckSignatureFrom(a.ca.cert) == nil {
t.Error("a leaf of one proxy's CA is the other's")
}
}
// 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()
t.Parallel()
s := testServer(t, Config{}, "")
addr := listen(t, s)
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",
@@ -495,7 +585,7 @@ func TestOddHostsRefused(t *testing.T) {
"CONNECT evil..test:443 HTTP/1.1\r\nHost: x\r\n\r\n",
"CONNECT .evil.test:443 HTTP/1.1\r\nHost: x\r\n\r\n",
} {
code, body := roundTrip(t, proxy.Listener.Addr().String(), req)
code, body := roundTrip(t, addr, req)
if code != http.StatusBadRequest || strings.Contains(body, "network allow") {
t.Errorf("%q: %d %q (want 400, no allow command)", strings.SplitN(req, "\r\n", 2)[0], code, body)
}
@@ -519,18 +609,19 @@ func TestOddHostsRefused(t *testing.T) {
}
// Under ** with a deny of evil.test, every form with more dots gets 400: the policy trims one
// dot of its own, so evil.test.. alone (evil.test. to it) would pass the deny.
pol = writePolicy(t, "**\n!evil.test\n")
if ok, _, _ := pol.verdict("evil.test..", 443); !ok {
s.egress.pol = writePolicy(t, "**\n!evil.test\n")
if ok, _, _ := s.egress.pol.verdict("evil.test..", 443); !ok {
t.Errorf("the policy denies evil.test..: then this test doesn't show HostOK refusing it")
}
for _, h := range []string{"evil.test..", "evil.test...", "evil.test...."} {
if code, body := roundTrip(t, proxy.Listener.Addr().String(), "CONNECT "+h+":443 HTTP/1.1\r\nHost: x\r\n\r\n"); code != http.StatusBadRequest {
if code, body := roundTrip(t, addr, "CONNECT "+h+":443 HTTP/1.1\r\nHost: x\r\n\r\n"); code != http.StatusBadRequest {
t.Errorf("%s under **: %d %q, want 400", h, code, body)
}
}
}
func TestAllowRule(t *testing.T) {
t.Parallel()
for _, c := range []struct {
host string
port int
@@ -553,6 +644,7 @@ func TestAllowRule(t *testing.T) {
}
func TestValidRule(t *testing.T) {
t.Parallel()
for _, c := range []struct {
rule string
ok bool
@@ -657,6 +749,7 @@ func clientHello(t *testing.T, name string) []byte {
}
func TestClientHello(t *testing.T) {
t.Parallel()
if rec := clientHello(t, "api.example.com"); len(rec) < 50 || rec[0] != 0x16 {
t.Errorf("record not returned for replay: %d bytes", len(rec))
}
@@ -667,6 +760,7 @@ func TestClientHello(t *testing.T) {
}
func TestSNIMatches(t *testing.T) {
t.Parallel()
if !sniMatches("API.example.com", "api.example.com") || sniMatches("other.com", "api.example.com") {
t.Error("name check")
}
@@ -687,6 +781,7 @@ func writeConfig(t *testing.T, c Config) string {
// are errors, and nothing is served then. The proxy has no other mode: what the host does alone
// (the CA, agents' logins, redaction) isn't reachable from its arguments.
func TestMainRefuses(t *testing.T) {
t.Parallel()
var out, errs bytes.Buffer
std := IO{Stdout: &out, Stderr: &errs}
if err := Main([]string{"--help"}, std); err != nil || strings.Count("\n"+out.String(), "\n -") != 1 || !strings.Contains(out.String(), "-config") {
@@ -713,7 +808,6 @@ func TestMainRefuses(t *testing.T) {
// A built-in policy devvm's files lack: a devvm bug, so the proxy never listens.
std.FS = fstest.MapFS{"layers/base.policy": {Data: []byte("base.test\n")}}
c := Config{Listen: "127.0.0.1:0", Password: "k3y", BuiltinPolicies: []string{"layers/base.policy", "layers/gone.policy"}}
t.Cleanup(func() { proxyAuth = "" })
if err := Main([]string{"-config", writeConfig(t, c)}, std); err == nil || !strings.Contains(err.Error(), "built-in policy layers/gone.policy") {
t.Errorf("a missing built-in: %v", err)
}
@@ -725,8 +819,8 @@ func TestMainRefuses(t *testing.T) {
// 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, linksFile = "", "" })
t.Parallel()
const tick = 50 * time.Millisecond
dir := t.TempDir()
pidFile, logFile := filepath.Join(dir, "ha.pid"), filepath.Join(dir, "log.jsonl")
sleep := exec.CommandContext(t.Context(), "sleep", "60")
@@ -749,11 +843,11 @@ func TestMainRuns(t *testing.T) {
errs := &syncBuffer{}
done := make(chan error)
go func() {
done <- Main([]string{"--config", writeConfig(t, Config{
done <- run([]string{"--config", writeConfig(t, Config{
Listen: addr, VM: "devvm-x", Password: "k3y", Lifeline: pidFile, Log: logFile,
Policies: []string{filepath.Join(dir, "missing")}, Links: filepath.Join(dir, "devvm-x.links.json"),
BuiltinPolicies: []string{"layers/base.policy"},
})}, IO{Stdout: io.Discard, Stderr: errs, FS: fstest.MapFS{"layers/base.policy": {Data: []byte("base.test:8443\n")}}})
})}, IO{Stdout: io.Discard, Stderr: errs, FS: fstest.MapFS{"layers/base.policy": {Data: []byte("base.test:8443\n")}}}, tick)
}()
pu, _ := url.Parse("http://devvm:k3y@" + addr)
client := &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(pu)}}
@@ -788,7 +882,7 @@ func TestMainRuns(t *testing.T) {
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
time.Sleep(5 * tick) // the proxy has seen the hostagent
_ = sleep.Process.Kill()
_ = sleep.Wait()
select {
@@ -912,7 +1006,7 @@ func FuzzRequest(f *testing.F) {
if err := os.WriteFile(file, []byte(ruleFor(host, port)+"\n"), 0o600); err != nil {
t.Fatal(err)
}
if ok, why := newPolicy(nil, []string{file}).decide(host, port); !ok {
if ok, why := newPolicy(nil, []string{file}, quiet()).decide(host, port); !ok {
t.Fatalf("%q: the rule %q doesn't allow %s port %d: %s", raw, ruleFor(host, port), host, port, why)
}
})
+4
View File
@@ -31,6 +31,7 @@ func modeOf(t *testing.T, path string) os.FileMode {
// one there, and a new one starts; no line spans two files, and every
// file is the user's alone, whatever mode the log had.
func TestRotateRenames(t *testing.T) {
t.Parallel()
path := filepath.Join(t.TempDir(), "vm.jsonl")
if err := os.WriteFile(path, []byte("old 0123456789\n"), 0o644); err != nil { //nolint:gosec // a log left open to others
t.Fatal(err)
@@ -87,6 +88,7 @@ func TestRotateRenames(t *testing.T) {
// new log, whose size counts from its own, and the next rotation keeps
// the renamed one's lines.
func TestRotateFollowsTheOtherWriter(t *testing.T) {
t.Parallel()
path := filepath.Join(t.TempDir(), "vm.jsonl")
r, err := openRotating(path, 30)
if err != nil {
@@ -123,6 +125,7 @@ func TestRotateFollowsTheOtherWriter(t *testing.T) {
// Writes from many connections at once during a rotation: each line
// whole, once, in one of the two files.
func TestRotateConcurrent(t *testing.T) {
t.Parallel()
const writers, each = 16, 50
line := func(w, i int) string { return fmt.Sprintf(`{"writer":%02d,"line":%03d,"pad":"0123456789"}`+"\n", w, i) }
total := int64(writers * each * len(line(0, 0)))
@@ -173,6 +176,7 @@ func TestRotateConcurrent(t *testing.T) {
// its last error goes to: it's copied to <log>.1 and emptied, so writes
// that bypass the rotation still reach the current log.
func TestRotateCopies(t *testing.T) {
t.Parallel()
path := filepath.Join(t.TempDir(), "vm.proxy.log")
if err := os.WriteFile(path, []byte("started 0123\n"), 0o644); err != nil { //nolint:gosec // a log left open to others
t.Fatal(err)
+117 -107
View File
@@ -20,6 +20,7 @@ import (
"encoding/pem"
"errors"
"fmt"
"log"
"math/big"
"net"
"net/http"
@@ -121,56 +122,59 @@ func InterceptLines(hosts []string) []string {
// Lookup returns a binding's value: IO.Secret, which devvm sets to its secrets' store.
type Lookup func(ctx context.Context, b Binding) (string, error)
var (
secretsPath = "" // Config.Secrets: the bindings file (no values), re-read on change
secretLookup Lookup // IO.Secret: each binding's value
upstreamCAs *x509.CertPool // nil: the system roots; Config.UpstreamCAs: the user's CAs besides them
// Only HTTPS is intercepted; anything else to a bound host (SSH on :22, …) is tunneled.
interceptPorts = map[int]bool{443: true}
)
type bindingFile struct {
// secrets is a proxy's bindings (Config.Secrets) and the values it has looked up for them.
type secrets struct {
path string // Config.Secrets: the bindings file (no values), re-read on change; "": none
lookup Lookup // IO.Secret: each binding's value
log *log.Logger
// mu holds the bindings as the file had them at mtime. It's taken before valueMu, never after.
mu sync.Mutex
mtime time.Time
list []Binding
// valueMu holds the values, by binding name, and is held through a lookup, so lookups go one
// at a time.
valueMu sync.Mutex
values map[string]cached
}
var bindings = &bindingFile{}
func newSecrets(path string, lookup Lookup, l *log.Logger) *secrets {
return &secrets{path: path, lookup: lookup, log: l, values: map[string]cached{}}
}
// all returns the bindings as the file has them now. A file that's gone, or that can't be read as
// ReadBindings reads it, has none: no value goes in until devvm writes it again.
func (b *bindingFile) all() []Binding {
b.mu.Lock()
defer b.mu.Unlock()
if secretsPath == "" {
func (s *secrets) all() []Binding {
s.mu.Lock()
defer s.mu.Unlock()
if s.path == "" {
return nil
}
st, err := os.Lstat(secretsPath)
st, err := os.Lstat(s.path)
if err != nil {
b.list, b.mtime = nil, time.Time{}
s.list, s.mtime = nil, time.Time{}
return nil
}
if !st.ModTime().Equal(b.mtime) {
b.mtime = st.ModTime()
l, err := ReadBindings(secretsPath)
if !st.ModTime().Equal(s.mtime) {
s.mtime = st.ModTime()
l, err := ReadBindings(s.path)
if err != nil {
logf("secrets: %v", err)
s.log.Printf("secrets: %v", err)
} else {
logf("secrets %s: %d bindings", secretsPath, len(l.Bindings))
s.log.Printf("secrets %s: %d bindings", s.path, len(l.Bindings))
}
b.list = l.Bindings
s.list = l.Bindings
// devvm touches the file when a value is set or removed: look values up afresh.
valueMu.Lock()
values = map[string]cached{}
valueMu.Unlock()
s.valueMu.Lock()
s.values = map[string]cached{}
s.valueMu.Unlock()
}
return b.list
return s.list
}
// bindingsFor: the bindings that apply to host.
func bindingsFor(host string) []Binding {
// forHost: the bindings that apply to host.
func (s *secrets) forHost(host string) []Binding {
var out []Binding
for _, b := range bindings.all() {
for _, b := range s.all() {
for _, h := range b.Hosts {
if r, ok := parseRule(h); ok && !r.deny && r.matchHost(strings.ToLower(host)) {
out = append(out, b)
@@ -188,11 +192,6 @@ type cached struct {
at time.Time
}
var (
valueMu sync.Mutex
values = map[string]cached{}
)
// A value is cached for valueTTL; a login's (KindLogin: Codex, opencode, Claude MCP) for loginTTL,
// since logging out on the host changes nothing devvm sees.
const (
@@ -210,35 +209,35 @@ func ttlOf(b Binding) time.Duration {
return valueTTL
}
// secretValue returns b's value from secretLookup, cached (see ttlOf). Lookups go one at a time,
// so two requests never refresh a login at once.
func secretValue(b Binding) (string, error) {
valueMu.Lock()
defer valueMu.Unlock()
if c, ok := values[b.Name]; ok && time.Since(c.at) < ttlOf(b) {
// value returns b's value from the lookup, cached (see ttlOf). Lookups go one at a time, so two
// requests never refresh a login at once.
func (s *secrets) value(b Binding) (string, error) {
s.valueMu.Lock()
defer s.valueMu.Unlock()
if c, ok := s.values[b.Name]; ok && time.Since(c.at) < ttlOf(b) {
return c.value, nil
}
if secretLookup == nil {
if s.lookup == nil {
return "", errors.New("no secret lookup")
}
// The value is cached for every request: no one request's end cancels it.
ctx, cancel := context.WithTimeout(context.Background(), lookupTimeout) //nolint:forbidigo // shared by every request
defer cancel()
v, err := secretLookup(ctx, b)
v, err := s.lookup(ctx, b)
if err != nil {
return "", fmt.Errorf("secret %s: %w", b.Name, err)
}
if v = strings.TrimSpace(v); v == "" {
return "", fmt.Errorf("secret %s is empty", b.Name)
}
values[b.Name] = cached{v, time.Now()}
s.values[b.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) {
func (s *secrets) inject(h http.Header, bs []Binding) (used []string) {
for _, b := range bs {
vs := h.Values(b.Header)
if len(vs) == 0 {
@@ -251,8 +250,8 @@ func inject(h http.Header, bs []Binding) (used []string) {
nv := v
if strings.Contains(nv, b.Placeholder) || basicHas(nv, b.Placeholder) {
if val == "" {
if val, err = secretValue(b); err != nil {
logf("%v", err)
if val, err = s.value(b); err != nil {
s.log.Printf("%v", err)
return used
}
}
@@ -289,13 +288,15 @@ func basicHas(v, placeholder string) bool {
// --- the CA ---
var (
caCert *x509.Certificate
caKey *ecdsa.PrivateKey
// ca is devvm's CA as a proxy has it (Config.CA): the certificate and key it signs leaves with, the
// one key every leaf has, and the leaves it has minted, by host, under mu.
type ca struct {
cert *x509.Certificate
key *ecdsa.PrivateKey
leafKey *ecdsa.PrivateKey
leafMu sync.Mutex
leaves = map[string]*tls.Certificate{}
)
mu sync.Mutex
leaves map[string]*tls.Certificate
}
// devvm makes its CA (trust.InitCA) and replaces it before it ends; VMs trust a new CA from their
// next launch, which starts their proxy again with it. A proxy keeps the CA it started with, as its
@@ -328,42 +329,51 @@ func writeAtomic(path string, data []byte, mode os.FileMode) error {
return os.Rename(tmp.Name(), path) //nolint:gosec // devvm's own files, or a Nix cache file nixPath named
}
func loadCA(certPath, keyPath string) error {
// loadCA reads the CA's certificate and key files (Config.CA, Config.CAKey).
func loadCA(certPath, keyPath string) (*ca, error) {
pair, err := tls.LoadX509KeyPair(certPath, keyPath)
if err != nil {
return err
return nil, err
}
k, ok := pair.PrivateKey.(*ecdsa.PrivateKey)
if !ok {
return errors.New("the CA key isn't ECDSA")
return nil, errors.New("the CA key isn't ECDSA")
}
if caCert, err = x509.ParseCertificate(pair.Certificate[0]); err != nil {
return err
cert, err := x509.ParseCertificate(pair.Certificate[0])
if err != nil {
return nil, err
}
caKey = k
leafKey, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
return err
return newCA(cert, k)
}
// loadUpstreamCAs makes the proxy's own TLS connections trust the CA certificates in pem
// newCA is the CA cert, signing with key, with a leaf key of its own and no leaves yet.
func newCA(cert *x509.Certificate, key *ecdsa.PrivateKey) (*ca, error) {
leafKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return nil, err
}
return &ca{cert: cert, key: key, leafKey: leafKey, leaves: map[string]*tls.Certificate{}}, nil
}
// upstreamPool is what the proxy's own TLS connections trust: the CA certificates in pem
// (Config.UpstreamCAs: the user's, checked by devvm) as well as the system roots.
func loadUpstreamCAs(pem []byte) error {
func upstreamPool(pem []byte) (*x509.CertPool, error) {
pool, err := x509.SystemCertPool()
if err != nil {
return err
return nil, err
}
if !pool.AppendCertsFromPEM(pem) {
return errors.New("upstream_cas holds no certificates")
return nil, errors.New("upstream_cas holds no certificates")
}
upstreamCAs = pool
return nil
return pool, nil
}
func caPEM() []byte {
if caCert == nil {
// pem is the CA's certificate, for /ca.pem; nil for no CA.
func (c *ca) pem() []byte {
if c == nil {
return nil
}
return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: caCert.Raw})
return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: c.cert.Raw})
}
// errCAEnded: the CA is past its NotAfter, so a leaf it signed would verify nowhere.
@@ -372,18 +382,18 @@ var errCAEnded = errors.New("devvm's CA has ended")
// caEndedReason is the log's reason for a tunnel refused because the CA has ended.
const caEndedReason = "devvm's CA has ended: open the VM again (devvm in its folder) for a new one"
// caEnded reports whether the CA is past its NotAfter at now.
func caEnded(now time.Time) bool { return !now.Before(caCert.NotAfter) }
// ended reports whether the CA is past its NotAfter at now.
func (c *ca) ended(now time.Time) bool { return !now.Before(c.cert.NotAfter) }
// caEndedRefusal refuses a CONNECT to be intercepted (e) once the CA has ended, before the tunnel
// opens: 403, with the reason and no allow command, since no rule would help, and logged as a
// refused block. It reports whether it refused.
func caEndedRefusal(w http.ResponseWriter, e Event) bool {
if !caEnded(time.Now()) {
func (s *server) caEndedRefusal(w http.ResponseWriter, e Event) bool {
if !s.ca.ended(time.Now()) {
return false
}
e.Event, e.Reason, e.Refused = "blocked", caEndedReason, true
record(e)
s.events.record(e)
w.Header().Set("X-Devvm-Blocked", e.Host)
http.Error(w, "devvm proxy: "+net.JoinHostPort(e.Host, strconv.Itoa(e.Port))+" is refused: "+caEndedReason, http.StatusForbidden)
return true
@@ -392,23 +402,23 @@ func caEndedRefusal(w http.ResponseWriter, e Event) bool {
// leafFor mints (and caches) a certificate for host, signed by the CA: for a day, and never past
// the CA's own NotAfter or before its NotBefore, since a client checks the whole chain. One that
// ends with the CA is kept until then. Once the CA has ended there's none (errCAEnded).
func leafFor(host string) (*tls.Certificate, error) {
leafMu.Lock()
defer leafMu.Unlock()
func (c *ca) leafFor(host string) (*tls.Certificate, error) {
c.mu.Lock()
defer c.mu.Unlock()
now := time.Now()
if caEnded(now) {
if c.ended(now) {
return nil, errCAEnded
}
if c, ok := leaves[host]; ok && now.Before(c.Leaf.NotAfter) &&
(c.Leaf.NotAfter.Sub(now) > time.Hour || c.Leaf.NotAfter.Equal(caCert.NotAfter)) {
return c, nil
if l, ok := c.leaves[host]; ok && now.Before(l.Leaf.NotAfter) &&
(l.Leaf.NotAfter.Sub(now) > time.Hour || l.Leaf.NotAfter.Equal(c.cert.NotAfter)) {
return l, nil
}
notBefore, notAfter := now.Add(-time.Hour), now.Add(24*time.Hour)
if notBefore.Before(caCert.NotBefore) {
notBefore = caCert.NotBefore
if notBefore.Before(c.cert.NotBefore) {
notBefore = c.cert.NotBefore
}
if notAfter.After(caCert.NotAfter) {
notAfter = caCert.NotAfter
if notAfter.After(c.cert.NotAfter) {
notAfter = c.cert.NotAfter
}
serial, _ := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
tmpl := &x509.Certificate{
@@ -420,14 +430,14 @@ func leafFor(host string) (*tls.Certificate, error) {
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
DNSNames: []string{host},
}
der, err := x509.CreateCertificate(rand.Reader, tmpl, caCert, &leafKey.PublicKey, caKey)
der, err := x509.CreateCertificate(rand.Reader, tmpl, c.cert, &c.leafKey.PublicKey, c.key)
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
l := &tls.Certificate{Certificate: [][]byte{der, c.cert.Raw}, PrivateKey: c.leafKey, Leaf: leaf}
c.leaves[host] = l
return l, nil
}
// --- interception ---
@@ -437,11 +447,11 @@ func leafFor(host string) (*tls.Certificate, error) {
// 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. The handshake
// with the VM gets 30 seconds.
func intercept(ctx context.Context, client net.Conn, host string, port int, e Event) {
func (s *server) intercept(ctx context.Context, 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)
return s.ca.leafFor(host)
},
})
hctx, cancel := context.WithTimeout(ctx, 30*time.Second)
@@ -449,14 +459,14 @@ func intercept(ctx context.Context, client net.Conn, host string, port int, e Ev
cancel()
if err != nil {
e.Event, e.Reason = "blocked", "TLS with the VM failed (is the devvm CA installed?): "+err.Error()
record(e)
s.events.record(e)
_ = client.Close()
return
}
e.Event = "intercept"
record(e)
s.events.record(e)
cn := &closeNotifyConn{Conn: tconn, done: make(chan struct{})}
fwd := forwarder("https", net.JoinHostPort(host, fmt.Sprint(port)), host, port)
fwd := s.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 {
@@ -464,7 +474,7 @@ func intercept(ctx context.Context, client net.Conn, host string, port int, e Ev
return
}
if what := mintsCredential(host, r.Method, r.URL.Path); what != "" {
record(Event{
s.events.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",
})
@@ -476,7 +486,7 @@ func intercept(ctx context.Context, client net.Conn, host string, port int, e Ev
Protocols: new(http.Protocols),
IdleTimeout: 10 * time.Minute,
ReadHeaderTimeout: 30 * time.Second,
ErrorLog: logger,
ErrorLog: s.log,
}
// TLS is already done here, so the server sees plain HTTP/1.1, or HTTP/2 with prior knowledge.
srv.Protocols.SetHTTP1(true)
@@ -517,16 +527,16 @@ func mintsCredential(host, method, p string) string {
// for every request, so `devvm secret unuse` applies to connections already open. HTTPS goes over
// TLS with the system's roots and the user's CAs, through an upstream's CONNECT tunnel when one
// applies; plain HTTP through an upstream is sent to it in absolute form, with its credentials.
func forwarder(scheme, target, host string, port int) http.Handler {
tlsConf := &tls.Config{RootCAs: upstreamCAs, ServerName: host}
func (s *server) forwarder(scheme, target, host string, port int) http.Handler {
tlsConf := &tls.Config{RootCAs: s.upstreamCAs, ServerName: host}
tr := &http.Transport{
DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { return dialOut(ctx, host, port) },
DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { return s.egress.dialOut(ctx, host, port) },
TLSClientConfig: tlsConf, ForceAttemptHTTP2: true,
IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 10 * time.Second,
}
up := upstreamFor(host, port, scheme == "http")
up := s.egress.up.route(host, port, scheme == "http")
if scheme == "http" {
tr.DialContext = func(ctx context.Context, _, _ string) (net.Conn, error) { return dial(ctx, host, port) }
tr.DialContext = func(ctx context.Context, _, _ string) (net.Conn, error) { return s.egress.dial(ctx, host, port) }
if up != nil {
// The upstream connects to what the request line names: the host that was checked,
// in its canonical form, never the VM's spelling of it.
@@ -545,7 +555,7 @@ func forwarder(scheme, target, host string, port int) http.Handler {
}
return &httputil.ReverseProxy{
Transport: tr,
ErrorLog: logger,
ErrorLog: s.log,
FlushInterval: -1, // stream (SSE) instead of buffering
Rewrite: func(pr *httputil.ProxyRequest) {
pr.Out.URL.Scheme, pr.Out.URL.Host = scheme, target
@@ -565,16 +575,16 @@ func forwarder(scheme, target, host string, port int) http.Handler {
pr.Out.Header.Set("Proxy-Authorization", up.auth)
}
}
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)
if scheme == "https" && s.interceptPorts[port] { // secrets only ever go over TLS, to :443
if bs := s.secrets.forHost(host); len(bs) > 0 {
e.Secrets = s.secrets.inject(pr.Out.Header, bs)
}
}
record(e)
s.events.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)
s.log.Printf("%s:%d: %v", host, port, err)
http.Error(w, "devvm proxy: couldn't reach "+host, http.StatusBadGateway)
},
}
+96 -129
View File
@@ -32,6 +32,7 @@ import (
// with another mode included, and leaves nothing else; one it can't write
// leaves nothing either.
func TestWriteAtomic(t *testing.T) {
t.Parallel()
dir := t.TempDir()
path := filepath.Join(dir, "ca.crt")
for _, tc := range []struct {
@@ -72,25 +73,26 @@ func bound(hosts ...string) Binding {
return Binding{Name: "t", Kind: KindSecret, Hosts: hosts, Header: "Authorization", Placeholder: "PH"}
}
// fakeSecret makes every lookup give value, with nothing cached yet, and returns the bindings
// fakeSecret makes every lookup of s give value, with nothing cached yet, and returns the bindings
// looked up, in order.
func fakeSecret(t *testing.T, value string) *[]Binding {
t.Helper()
func fakeSecret(s *secrets, value string) *[]Binding {
var asked []Binding
old := secretLookup
secretLookup = func(_ context.Context, b Binding) (string, error) { asked = append(asked, b); return value, nil }
values = map[string]cached{}
t.Cleanup(func() { secretLookup, values = old, map[string]cached{} })
s.valueMu.Lock()
defer s.valueMu.Unlock()
s.lookup = func(_ context.Context, b Binding) (string, error) { asked = append(asked, b); return value, nil }
s.values = map[string]cached{}
return &asked
}
func TestInject(t *testing.T) {
fakeSecret(t, "real")
t.Parallel()
s := newSecrets("", nil, quiet())
fakeSecret(s, "real")
bs := []Binding{{Name: "github", Kind: KindSecret, 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" {
if used := s.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" {
@@ -98,52 +100,44 @@ func TestInject(t *testing.T) {
}
h = http.Header{}
h.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("x-access-token:PH")))
inject(h, bs)
s.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" {
if used := s.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) {
// interceptSetup: a proxy with devvm's CA, which a temp dir holds, 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"). It returns the proxy, 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) (*server, int, string, *http.Client) {
t.Helper()
dir := t.TempDir()
writeCA(t, dir)
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
file := filepath.Join(dir, "bindings.json")
s := testServer(t, Config{CA: filepath.Join(dir, "ca.pem"), CAKey: filepath.Join(dir, "ca.key"), Secrets: file}, "")
pool := x509.NewCertPool()
pool.AddCert(caCert)
upstreamCAs = pool
t.Cleanup(func() { upstreamCAs = nil })
pool.AddCert(s.ca.cert)
s.upstreamCAs = pool
up := httptest.NewUnstartedServer(h)
cert, _ := leafFor("localhost")
cert, _ := s.ca.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")
writeBindings(t, secretsPath, bound("localhost"))
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{
s.interceptPorts[port] = true
s.egress.pol = writePolicy(t, fmt.Sprintf("localhost:%d\n127.0.0.1:%d\n", port, port))
writeBindings(t, file, bound("localhost"))
fakeSecret(s.secrets, "real")
pu, _ := url.Parse("http://" + listen(t, s))
return s, port, file, &http.Client{Transport: &http.Transport{
Proxy: http.ProxyURL(pu), TLSClientConfig: &tls.Config{RootCAs: pool}, MaxConnsPerHost: 1,
}}
}
@@ -167,7 +161,8 @@ func get(t *testing.T, c *http.Client, url, host string) (int, string) {
// 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) {
t.Parallel()
_, 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)
@@ -183,7 +178,8 @@ func TestInterceptRefusesAnotherHost(t *testing.T) {
// 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) {
t.Parallel()
_, 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)
@@ -220,6 +216,7 @@ func writeCA(t *testing.T, dir string) {
// Values from agents' login files are cached briefly: a logout on the host stops them soon. The
// binding's kind decides, never its name.
func TestLoginValuesCacheBriefly(t *testing.T) {
t.Parallel()
for _, tc := range []struct {
b Binding
want time.Duration
@@ -240,45 +237,48 @@ func TestLoginValuesCacheBriefly(t *testing.T) {
// A value is looked up in this process, with the binding the file has, once, then cached until its
// time is up; a lookup that fails, or gives nothing, isn't cached, and puts nothing in.
func TestSecretValueLooksUpInProcess(t *testing.T) {
asked := fakeSecret(t, " real\n")
t.Parallel()
s := newSecrets("", nil, quiet())
asked := fakeSecret(s, " real\n")
b := Binding{Name: "codex", Kind: KindLogin, Agent: "codex"}
for range 2 {
if v, err := secretValue(b); v != "real" || err != nil {
t.Fatalf("secretValue = %q, %v", v, err)
if v, err := s.value(b); v != "real" || err != nil {
t.Fatalf("value = %q, %v", v, err)
}
}
if len(*asked) != 1 || !reflect.DeepEqual((*asked)[0], b) {
t.Errorf("looked up %+v, want %+v once", *asked, b)
}
values[b.Name] = cached{"real", time.Now().Add(-loginTTL)}
if _, err := secretValue(b); err != nil || len(*asked) != 2 {
s.values[b.Name] = cached{"real", time.Now().Add(-loginTTL)}
if _, err := s.value(b); err != nil || len(*asked) != 2 {
t.Errorf("an expired value: %v, %d lookups", err, len(*asked))
}
values = map[string]cached{}
secretLookup = func(context.Context, Binding) (string, error) { return "", errors.New("locked") }
if _, err := secretValue(b); err == nil || !strings.Contains(err.Error(), "codex: locked") {
s.values = map[string]cached{}
s.lookup = func(context.Context, Binding) (string, error) { return "", errors.New("locked") }
if _, err := s.value(b); err == nil || !strings.Contains(err.Error(), "codex: locked") {
t.Errorf("a failed lookup: %v", err)
}
secretLookup = func(context.Context, Binding) (string, error) { return " ", nil }
if _, err := secretValue(b); err == nil {
s.lookup = func(context.Context, Binding) (string, error) { return " ", nil }
if _, err := s.value(b); err == nil {
t.Error("an empty value was taken")
}
if _, ok := values[b.Name]; ok {
if _, ok := s.values[b.Name]; ok {
t.Error("a failed lookup was cached")
}
secretLookup = nil
if _, err := secretValue(b); err == nil {
s.lookup = nil
if _, err := s.value(b); err == nil {
t.Error("a value without a lookup")
}
h := http.Header{}
h.Set("Authorization", "Bearer PH")
if used := inject(h, []Binding{{Name: "codex", Kind: KindLogin, Header: "Authorization", Placeholder: "PH"}}); used != nil || h.Get("Authorization") != "Bearer PH" {
if used := s.inject(h, []Binding{{Name: "codex", Kind: KindLogin, Header: "Authorization", Placeholder: "PH"}}); used != nil || h.Get("Authorization") != "Bearer PH" {
t.Errorf("without a value: used %v, %q", used, h.Get("Authorization"))
}
}
// The bindings file: versioned, private, of known kinds; InterceptLines gives its hosts on 443.
func TestReadBindings(t *testing.T) {
t.Parallel()
dir := t.TempDir()
path := filepath.Join(dir, "secrets.json")
l := BindingList{Bindings: []Binding{
@@ -327,30 +327,28 @@ func TestReadBindings(t *testing.T) {
// A bindings file the proxy can't read, or that's gone, has no bindings: nothing goes in.
func TestBindingsUnreadableHaveNone(t *testing.T) {
secretsPath = filepath.Join(t.TempDir(), "bindings.json")
t.Cleanup(func() { secretsPath = "" })
must(t, os.WriteFile(secretsPath, BindingList{Bindings: []Binding{{Name: "t", Kind: KindSecret, Hosts: []string{"localhost"}}}}.Encode(), 0o600))
if bs := bindingsFor("localhost"); len(bs) != 1 {
t.Parallel()
path := filepath.Join(t.TempDir(), "bindings.json")
s := newSecrets(path, nil, quiet())
must(t, os.WriteFile(path, BindingList{Bindings: []Binding{{Name: "t", Kind: KindSecret, Hosts: []string{"localhost"}}}}.Encode(), 0o600))
if bs := s.forHost("localhost"); len(bs) != 1 {
t.Fatalf("bindings = %+v", bs)
}
must(t, os.Chmod(secretsPath, 0o644)) //nolint:gosec // G302: the file others may read is what's tested
must(t, os.Chmod(path, 0o644)) //nolint:gosec // G302: the file others may read is what's tested
later := time.Now().Add(2 * time.Second)
must(t, os.Chtimes(secretsPath, later, later))
if bs := bindingsFor("localhost"); bs != nil {
must(t, os.Chtimes(path, later, later))
if bs := s.forHost("localhost"); bs != nil {
t.Errorf("a file others may read gave %+v", bs)
}
must(t, os.Remove(secretsPath))
if bs := bindingsFor("localhost"); bs != nil {
must(t, os.Remove(path))
if bs := s.forHost("localhost"); bs != nil {
t.Errorf("a file that's gone gave %+v", bs)
}
}
// useCA makes the proxy's CA one valid from notBefore to notAfter, for this test, with no leaves
// minted yet.
func useCA(t *testing.T, notBefore, notAfter time.Time) {
// testCA is a CA valid from notBefore to notAfter, with no leaves minted yet.
func testCA(t *testing.T, notBefore, notAfter time.Time) *ca {
t.Helper()
oldCert, oldKey, oldLeafKey, oldLeaves := caCert, caKey, leafKey, leaves
t.Cleanup(func() { caCert, caKey, leafKey, leaves = oldCert, oldKey, oldLeafKey, oldLeaves })
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
must(t, err)
tmpl := &x509.Certificate{
@@ -359,35 +357,35 @@ func useCA(t *testing.T, notBefore, notAfter time.Time) {
}
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
must(t, err)
caCert, err = x509.ParseCertificate(der)
cert, err := x509.ParseCertificate(der)
must(t, err)
caKey = key
leafKey, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
c, err := newCA(cert, key)
must(t, err)
leaves = map[string]*tls.Certificate{}
return c
}
// A leaf never outlives the CA that signed it, or starts before it: a VM left running near the CA's
// end gets leaves that end with it, kept until then, and none once it has ended.
func TestLeafWithinCA(t *testing.T) {
t.Parallel()
start, end := time.Now().Add(-time.Minute).Truncate(time.Second), time.Now().Add(30*time.Minute).Truncate(time.Second)
useCA(t, start, end)
c, err := leafFor("api.example.com")
authority := testCA(t, start, end)
c, err := authority.leafFor("api.example.com")
must(t, err)
if c.Leaf.NotAfter.After(end) || c.Leaf.NotBefore.Before(start) {
t.Errorf("a leaf valid %v to %v, from a CA valid %v to %v", c.Leaf.NotBefore, c.Leaf.NotAfter, start, end)
}
if again, err := leafFor("api.example.com"); err != nil || again != c {
if again, err := authority.leafFor("api.example.com"); err != nil || again != c {
t.Errorf("a leaf that ends with its CA was minted again (%v)", err)
}
pool := x509.NewCertPool()
pool.AddCert(caCert)
pool.AddCert(authority.cert)
if _, err := c.Leaf.Verify(x509.VerifyOptions{DNSName: "api.example.com", Roots: pool}); err != nil {
t.Errorf("the leaf doesn't verify: %v", err)
}
useCA(t, time.Now().Add(-30*24*time.Hour), time.Now().Add(-time.Minute))
if c, err := leafFor("api.example.com"); !errors.Is(err, errCAEnded) || c != nil {
authority = testCA(t, time.Now().Add(-30*24*time.Hour), time.Now().Add(-time.Minute))
if c, err := authority.leafFor("api.example.com"); !errors.Is(err, errCAEnded) || c != nil {
t.Errorf("a leaf from a CA that has ended: %v, %v", c != nil, err)
}
}
@@ -395,17 +393,16 @@ func TestLeafWithinCA(t *testing.T) {
// A tunnel to a host with a bound secret, once the proxy's CA has ended, is refused before it
// opens: 403 with the reason and no allow command, logged as a refused block.
func TestInterceptCAEnded(t *testing.T) {
port, _, _ := interceptSetup(t, func(http.ResponseWriter, *http.Request) {})
t.Parallel()
s, port, _, _ := interceptSetup(t, func(http.ResponseWriter, *http.Request) {})
var events strings.Builder
oldOut := logOut
logOut = &events
t.Cleanup(func() { logOut = oldOut })
useCA(t, time.Now().Add(-30*24*time.Hour), time.Now().Add(-time.Minute))
s.events.out = &events // the handler runs here, alone
s.ca = testCA(t, time.Now().Add(-30*24*time.Hour), time.Now().Add(-time.Minute))
target := net.JoinHostPort("localhost", strconv.Itoa(port))
req := httptest.NewRequestWithContext(t.Context(), http.MethodConnect, "http://"+target, nil)
req.Host = target
w := httptest.NewRecorder()
handler(w, req)
s.handler(w, req)
if w.Code != http.StatusForbidden || !strings.Contains(w.Body.String(), caEndedReason) ||
strings.Contains(w.Body.String(), "network allow") || w.Header().Get("X-Devvm-Blocked") != "localhost" {
t.Errorf("answered %d %q", w.Code, w.Body.String())
@@ -419,19 +416,20 @@ func TestInterceptCAEnded(t *testing.T) {
// 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 = "" })
writeBindings(t, secretsPath)
bindings.all()
valueMu.Lock()
values["t"] = cached{"old", time.Now()}
valueMu.Unlock()
t.Parallel()
path := filepath.Join(t.TempDir(), "bindings.json")
s := newSecrets(path, nil, quiet())
writeBindings(t, path)
s.all()
s.valueMu.Lock()
s.values["t"] = cached{"old", time.Now()}
s.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 {
must(t, os.Chtimes(path, later, later))
s.all()
s.valueMu.Lock()
defer s.valueMu.Unlock()
if _, ok := s.values["t"]; ok {
t.Error("a cached value survived the bindings file changing")
}
}
@@ -439,44 +437,12 @@ func TestBindingsChangeDropsCachedValues(t *testing.T) {
// 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()
writeCA(t, dir)
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 })
t.Parallel()
// 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) {
s, port, _, client := interceptSetup(t, 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")
writeBindings(t, secretsPath, bound("localhost"))
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},
}}
})
fakeSecret(s.secrets, "real-secret")
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")
@@ -517,6 +483,7 @@ func TestIntercept(t *testing.T) {
// Calls that make lasting GitHub credentials with the VM's token are refused; ordinary ones aren't.
func TestMintsCredential(t *testing.T) {
t.Parallel()
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"},
+11 -3
View File
@@ -2,7 +2,8 @@ package proxy
// Tunnels: a CONNECT the proxy carries itself (to a host the policy allows, or to one of the VM's
// links) and each connection the relay passes on are spliced, their bytes passed as they are both
// ways (splice); a CONNECT's connection is first taken from the HTTP server (hijack).
// ways (splice), the far end's from the start; a CONNECT's connection is first taken from the HTTP
// server (hijack).
import (
"bufio"
@@ -29,11 +30,18 @@ func hijack(w http.ResponseWriter) (bufConn, error) {
// splice passes client's bytes to server and server's to client, as they are. The end of what
// client sends ends what server reads (closeWrite), and server can still answer. Once server's
// bytes end, or client can't be written to (it went away), splice closes both connections and
// returns.
func splice(client, server net.Conn) {
// returns. Server's bytes pass from the start; client's only once before, when there's one, has
// returned true (it may read client's first bytes and pass them on itself), and when it returns
// false, none do, and both connections close.
func splice(client, server net.Conn, before func() bool) {
done := make(chan struct{})
go func() {
defer close(done)
if before != nil && !before() {
_ = client.Close()
_ = server.Close()
return
}
_, _ = io.Copy(server, client)
closeWrite(server)
}()
+48 -7
View File
@@ -87,8 +87,7 @@ func checkTunnel(t *testing.T, f *farEnd, open func() (net.Conn, io.Reader)) {
c, r = open()
_ = c.SetDeadline(time.Now().Add(20 * time.Second))
// Five bytes: a tunnel the policy allows reads that many, to see whether they start TLS.
_, _ = c.Write([]byte("s----"))
_, _ = c.Write([]byte("s"))
if _, err := io.ReadFull(r, make([]byte, 64<<10)); err != nil {
t.Fatalf("the far end's bytes: %v", err)
}
@@ -120,33 +119,73 @@ func connectTo(t *testing.T, addr, hostPort string) (net.Conn, io.Reader) {
// A tunnel to a host the policy allows.
func TestTunnelSplices(t *testing.T) {
_, _, addr := linkProxy(t)
t.Parallel()
s, _, _, addr := linkProxy(t)
ln, err := new(net.ListenConfig).Listen(t.Context(), "tcp", "127.0.0.1:0")
must(t, err)
f := serveFarEnd(t, ln)
port := strconv.Itoa(ln.Addr().(*net.TCPAddr).Port)
pol = writePolicy(t, "127.0.0.1:"+port+"\n")
s.egress.pol = writePolicy(t, "127.0.0.1:"+port+"\n")
checkTunnel(t, f, func() (net.Conn, io.Reader) { return connectTo(t, addr, "127.0.0.1:"+port) })
}
// A tunnel to a host the policy allows passes the far end's bytes on at once: a protocol whose
// server speaks first (SMTP) gets its greeting before the client sends anything, and a client that
// sends fewer than five bytes that aren't TLS gets its answer.
func TestTunnelServerSpeaksFirst(t *testing.T) {
t.Parallel()
s, _, _, addr := linkProxy(t)
ln, err := new(net.ListenConfig).Listen(t.Context(), "tcp", "127.0.0.1:0")
must(t, err)
t.Cleanup(func() { _ = ln.Close() })
go func() {
c, err := ln.Accept()
if err != nil {
return
}
defer func() { _ = c.Close() }()
_, _ = io.WriteString(c, "220 hello\r\n")
b := make([]byte, 2)
if _, err := io.ReadFull(c, b); err == nil {
_, _ = c.Write(append([]byte("got:"), b...))
}
}()
port := strconv.Itoa(ln.Addr().(*net.TCPAddr).Port)
s.egress.pol = writePolicy(t, "127.0.0.1:"+port+"\n")
c, r := connectTo(t, addr, "127.0.0.1:"+port)
defer func() { _ = c.Close() }()
_ = c.SetDeadline(time.Now().Add(5 * time.Second))
greeting := make([]byte, len("220 hello\r\n"))
if _, err := io.ReadFull(r, greeting); err != nil || string(greeting) != "220 hello\r\n" {
t.Fatalf("the greeting before the client spoke: %q, %v", greeting, err)
}
_, _ = c.Write([]byte("hi"))
answer := make([]byte, len("got:hi"))
if _, err := io.ReadFull(r, answer); err != nil || string(answer) != "got:hi" {
t.Errorf("two bytes that aren't TLS: %q, %v", answer, err)
}
}
// A tunnel to one of the VM's links.
func TestLinkTunnelSplices(t *testing.T) {
dir, _, addr := linkProxy(t)
t.Parallel()
s, dir, _, addr := linkProxy(t)
sock := LinkSocket(dir, linkVM, netip.MustParseAddr("127.77.0.1"), 5432)
ln, err := new(net.ListenConfig).Listen(t.Context(), "unix", sock)
must(t, err)
f := serveFarEnd(t, ln)
writeLinkList(t, linksFile, linkEntry(dir, "127.77.0.1", 5432, "db"))
writeLinkList(t, s.links.file, linkEntry(dir, "127.77.0.1", 5432, "db"))
checkTunnel(t, f, func() (net.Conn, io.Reader) { return connectTo(t, addr, "db:5432") })
}
// splice closes a connection with no writing side of its own to close at the end of what the
// client sent, and returns once the server's bytes end, both connections closed.
func TestSpliceEnds(t *testing.T) {
t.Parallel()
client, vm := net.Pipe()
server, far := net.Pipe()
done := make(chan struct{})
go func() { splice(client, server); close(done) }()
go func() { splice(client, server, nil); close(done) }()
go func() { _, _ = vm.Write([]byte("hi")); _ = vm.Close() }()
_ = far.SetDeadline(time.Now().Add(10 * time.Second))
if b, err := io.ReadAll(far); string(b) != "hi" || err != nil {
@@ -166,6 +205,7 @@ func TestSpliceEnds(t *testing.T) {
// hijack answers that the tunnel is open, and the bytes the client sent along with its request
// are the connection's first.
func TestHijack(t *testing.T) {
t.Parallel()
ln, err := new(net.ListenConfig).Listen(t.Context(), "tcp", "127.0.0.1:0")
must(t, err)
srv := &http.Server{ReadHeaderTimeout: 5 * time.Second, Handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
@@ -194,6 +234,7 @@ func TestHijack(t *testing.T) {
// The links' addresses are 127.77.0.0/16, as themselves or mapped into IPv6, and LinkAddr gives
// each of them.
func TestIsLinkAddr(t *testing.T) {
t.Parallel()
for s, want := range map[string]bool{
"127.77.0.1": true, "127.77.255.254": true, "127.77.0.0": true, "127.77.255.255": true, "::ffff:127.77.0.1": true,
"127.0.0.1": false, "127.78.0.0": false, "127.76.255.255": false, "::1": false, "::ffff:127.0.0.1": false,
+34 -29
View File
@@ -33,12 +33,16 @@ type upstream struct {
auth string
}
var (
upUnresolved = false // Config.UpstreamUnresolved: names the host can't resolve go upstream even when only ** allows them
upHTTPS *upstream // tunnels and the connections that put secrets in; nil: direct
upHTTP *upstream // plain HTTP requests; nil: direct
noProxy []noProxyRule
)
// upstreams is a proxy's company proxies (Config.Upstream): set once, as it starts, and only read
// after.
type upstreams struct {
https *upstream // tunnels and the connections that put secrets in; nil: direct
http *upstream // plain HTTP requests; nil: direct
noProxy []noProxyRule
// unresolved is Config.UpstreamUnresolved: names the host can't resolve go upstream even when
// only ** allows them.
unresolved bool
}
// ErrUpstreamScheme is ParseUpstream's error for a proxy that isn't http://.
var ErrUpstreamScheme = errors.New("only http:// proxies can be an upstream")
@@ -96,29 +100,30 @@ func newUpstream(raw string) (*upstream, error) {
return up, nil
}
// loadUpstream takes the config's company proxy (Config.Upstream): the host's HTTPS_PROXY,
// newUpstreams takes the config's company proxy (Config.Upstream): the host's HTTPS_PROXY,
// HTTP_PROXY and NO_PROXY.
func loadUpstream(u Upstream) error {
func newUpstreams(u Upstream) (upstreams, error) {
var ups upstreams
var err error
if upHTTPS, err = newUpstream(u.HTTPS); err != nil {
return fmt.Errorf("upstream: HTTPS_PROXY: %w", err)
if ups.https, err = newUpstream(u.HTTPS); err != nil {
return upstreams{}, fmt.Errorf("upstream: HTTPS_PROXY: %w", err)
}
if upHTTP, err = newUpstream(u.HTTP); err != nil {
return fmt.Errorf("upstream: HTTP_PROXY: %w", err)
if ups.http, err = newUpstream(u.HTTP); err != nil {
return upstreams{}, fmt.Errorf("upstream: HTTP_PROXY: %w", err)
}
noProxy = parseNoProxy(u.NoProxy)
return nil
ups.noProxy = parseNoProxy(u.NoProxy)
return ups, nil
}
// upstreamNames: the upstreams, by host:port only, for the proxy's log.
func upstreamNames() string {
// names: the upstreams, by host:port only, for the proxy's log.
func (ups upstreams) names() string {
name := func(u *upstream) string {
if u == nil {
return "none"
}
return u.addr
}
return "https through " + name(upHTTPS) + ", http through " + name(upHTTP)
return "https through " + name(ups.https) + ", http through " + name(ups.http)
}
// --- NO_PROXY ---
@@ -198,17 +203,17 @@ func local(host string) bool {
return host == "localhost" || strings.HasSuffix(host, ".localhost")
}
// upstreamFor: the upstream host:port goes through, nil for direct. plain is a plain HTTP request
// route: the upstream host:port goes through, nil for direct. plain is a plain HTTP request
// (HTTP_PROXY's); anything else is a tunnel (HTTPS_PROXY's). host is canonical (splitHostPort).
func upstreamFor(host string, port int, plain bool) *upstream {
up := upHTTPS
func (ups upstreams) route(host string, port int, plain bool) *upstream {
up := ups.https
if plain {
up = upHTTP
up = ups.http
}
if up == nil || local(host) {
return nil
}
for _, r := range noProxy {
for _, r := range ups.noProxy {
if r.matches(host, port) {
return nil
}
@@ -228,9 +233,9 @@ var errUnresolved = errors.New("this machine can't resolve it, and only ** allow
// or under *.domain: one that only ** allows is refused (errUnresolved), so ** alone never sends
// the company proxy a name it may resolve to its own network's hosts. With Config.UpstreamUnresolved
// (a build whose VM reaches internal addresses anyway), any such name goes upstream.
func floorUpstream(ctx context.Context, host string, port int) error {
func (e *egress) floorUpstream(ctx context.Context, host string, port int) error {
if _, err := netip.ParseAddr(strings.Trim(host, "[]")); err == nil {
_, err := resolve(ctx, host, port)
_, err := e.resolve(ctx, host, port)
return err
}
lctx, cancel := context.WithTimeout(ctx, 3*time.Second)
@@ -240,14 +245,14 @@ func floorUpstream(ctx context.Context, host string, port int) error {
if ctx.Err() != nil {
return ctx.Err()
}
if !upUnresolved && !pol.byName(host, port) {
if !e.up.unresolved && !e.pol.byName(host, port) {
return errUnresolved
}
return nil
}
for _, a := range ips {
a = a.Unmap()
if pol.addrDenied(a, port) || internal(a) && !pol.addrAllowed(a, port) {
if e.pol.addrDenied(a, port) || e.own.internal(a) && !e.pol.addrAllowed(a, port) {
return errFloor
}
}
@@ -318,9 +323,9 @@ const maxConnectReply = 64 << 10
// dialOut connects to host:port for a tunnel or a TLS connection: through the upstream when one
// applies, else directly to an address the floor allows.
func dialOut(ctx context.Context, host string, port int) (net.Conn, error) {
if up := upstreamFor(host, port, false); up != nil {
func (e *egress) dialOut(ctx context.Context, host string, port int) (net.Conn, error) {
if up := e.up.route(host, port, false); up != nil {
return up.connect(ctx, host, port)
}
return dial(ctx, host, port)
return e.dial(ctx, host, port)
}
+67 -82
View File
@@ -83,27 +83,14 @@ func (f *fakeUpstream) requests() []string {
return append([]string(nil), f.seen...)
}
// useUpstream points both upstreams at f, with the test's credentials, and NO_PROXY at noProxyList.
func useUpstream(t *testing.T, f *fakeUpstream, noProxyList string) {
// useUpstream points both of s's upstreams at f, with the test's credentials, and NO_PROXY at
// noProxyList.
func useUpstream(t *testing.T, s *server, f *fakeUpstream, noProxyList string) {
t.Helper()
u := "http://corp-user:" + upPassword + "@" + f.ln.Addr().String()
must(t, loadUpstream(Upstream{HTTPS: u, HTTP: u, NoProxy: noProxyList}))
t.Cleanup(func() { upHTTPS, upHTTP, noProxy = nil, nil, nil })
}
// logs captures the event log and the proxy's own log lines.
func logs(t *testing.T) *syncBuffer {
t.Helper()
b := &syncBuffer{}
set := func(w io.Writer) { // a tunnel still open may log as the test ends
logMu.Lock()
logOut = w
logMu.Unlock()
logger.SetOutput(w)
}
set(b)
t.Cleanup(func() { set(io.Discard) })
return b
ups, err := newUpstreams(Upstream{HTTPS: u, HTTP: u, NoProxy: noProxyList})
must(t, err)
s.egress.up = ups
}
func authOf(user, pass string) string {
@@ -111,6 +98,7 @@ func authOf(user, pass string) string {
}
func TestParseUpstream(t *testing.T) {
t.Parallel()
for _, c := range []struct {
raw, host string
scheme bool // ErrUpstreamScheme
@@ -154,9 +142,11 @@ func TestParseUpstream(t *testing.T) {
}
func TestNoProxy(t *testing.T) {
upHTTPS, upHTTP = &upstream{addr: "https.corp:8080"}, &upstream{addr: "http.corp:8080"}
noProxy = parseNoProxy(" Corp.Example , .internal.test,*.wild.test, 10.0.0.0/8, 192.0.2.7, git.test:22, [2001:db8::1]")
t.Cleanup(func() { upHTTPS, upHTTP, noProxy = nil, nil, nil })
t.Parallel()
ups := upstreams{
https: &upstream{addr: "https.corp:8080"}, http: &upstream{addr: "http.corp:8080"},
noProxy: parseNoProxy(" Corp.Example , .internal.test,*.wild.test, 10.0.0.0/8, 192.0.2.7, git.test:22, [2001:db8::1]"),
}
for _, c := range []struct {
host string
port int
@@ -183,21 +173,21 @@ func TestNoProxy(t *testing.T) {
{"127.0.0.1", 8080, true, true},
{"::1", 8080, false, true},
} {
up := upstreamFor(c.host, c.port, c.plain)
up := ups.route(c.host, c.port, c.plain)
if (up == nil) != c.direct {
t.Errorf("%s:%d (plain %v): upstream %v, want direct %v", c.host, c.port, c.plain, up, c.direct)
}
if up != nil && c.plain != (up == upHTTP) {
if up != nil && c.plain != (up == ups.http) {
t.Errorf("%s:%d (plain %v): the wrong upstream, %s", c.host, c.port, c.plain, up.addr)
}
}
noProxy = parseNoProxy("*")
if upstreamFor("github.com", 443, false) != nil {
ups.noProxy = parseNoProxy("*")
if ups.route("github.com", 443, false) != nil {
t.Error("NO_PROXY=* sent a host upstream")
}
// Without HTTP_PROXY, plain HTTP goes direct; tunnels still go upstream.
noProxy, upHTTP = nil, nil
if upstreamFor("github.com", 80, true) != nil || upstreamFor("github.com", 80, false) == nil {
ups.noProxy, ups.http = nil, nil
if ups.route("github.com", 80, true) != nil || ups.route("github.com", 80, false) == nil {
t.Error("HTTPS_PROXY alone: plain HTTP should go direct, tunnels upstream")
}
}
@@ -205,6 +195,7 @@ func TestNoProxy(t *testing.T) {
// A tunnel to an allowed host goes through the upstream: CONNECT by the name the VM asked for, with
// the upstream's credentials, never the VM's; a denied host, or a private address, never reaches it.
func TestUpstreamTunnel(t *testing.T) {
t.Parallel()
echo, err := new(net.ListenConfig).Listen(t.Context(), "tcp", "127.0.0.1:0")
must(t, err)
t.Cleanup(func() { _ = echo.Close() })
@@ -218,16 +209,13 @@ func TestUpstreamTunnel(t *testing.T) {
}
}()
f := newFakeUpstream(t, echo.Addr().String(), http.StatusOK)
useUpstream(t, f, "")
out := logs(t)
pol = writePolicy(t, "allowed.test\n**:5432\n!denied.test\n10.1.2.3\n")
proxyAuth = "k3y"
t.Cleanup(func() { proxyAuth = "" })
proxy := httptest.NewServer(http.HandlerFunc(handler))
t.Cleanup(proxy.Close)
s := testServer(t, Config{Password: "k3y"}, "allowed.test\n**:5432\n!denied.test\n10.1.2.3\n")
useUpstream(t, s, f, "")
out := logs(s)
addr := listen(t, s)
vmAuth := "Proxy-Authorization: " + authOf("devvm", "k3y") + "\r\n"
c, err := new(net.Dialer).DialContext(t.Context(), "tcp", proxy.Listener.Addr().String())
c, err := new(net.Dialer).DialContext(t.Context(), "tcp", addr)
must(t, err)
defer c.Close()
fmt.Fprintf(c, "CONNECT allowed.test:443 HTTP/1.1\r\nHost: allowed.test:443\r\n%s\r\n", vmAuth)
@@ -250,7 +238,7 @@ func TestUpstreamTunnel(t *testing.T) {
// Refused before the upstream: a denied host, a host the policy doesn't allow, and a private
// address the policy allows but the floor still judges.
for _, target := range []string{"denied.test:443", "other.test:443", "10.1.2.4:5432", "127.0.0.1:5432"} {
code, _ := roundTrip(t, proxy.Listener.Addr().String(), "CONNECT "+target+" HTTP/1.1\r\nHost: "+target+"\r\n"+vmAuth+"\r\n")
code, _ := roundTrip(t, addr, "CONNECT "+target+" HTTP/1.1\r\nHost: "+target+"\r\n"+vmAuth+"\r\n")
if code != http.StatusForbidden {
t.Errorf("%s: %d, want 403", target, code)
}
@@ -259,7 +247,7 @@ func TestUpstreamTunnel(t *testing.T) {
t.Errorf("refused hosts reached the upstream: %q", f.requests())
}
// An allowed address goes upstream too, by its address.
c2, err := new(net.Dialer).DialContext(t.Context(), "tcp", proxy.Listener.Addr().String())
c2, err := new(net.Dialer).DialContext(t.Context(), "tcp", addr)
must(t, err)
fmt.Fprintf(c2, "CONNECT 10.1.2.3:443 HTTP/1.1\r\nHost: 10.1.2.3:443\r\n%s\r\n", vmAuth)
resp, err = http.ReadResponse(bufio.NewReader(c2), &http.Request{Method: http.MethodConnect})
@@ -273,12 +261,12 @@ func TestUpstreamTunnel(t *testing.T) {
if reqs := f.requests(); len(reqs) != 2 || !strings.HasPrefix(reqs[1], "CONNECT 10.1.2.3:443 ") {
t.Errorf("the allowed address: %q", reqs)
}
s := out.String()
if strings.Contains(s, upPassword) || strings.Contains(s, authOf("corp-user", upPassword)) {
t.Errorf("the logs hold the upstream's credentials: %s", s)
l := out.String()
if strings.Contains(l, upPassword) || strings.Contains(l, authOf("corp-user", upPassword)) {
t.Errorf("the logs hold the upstream's credentials: %s", l)
}
if !strings.Contains(s, `"event":"tunnel","host":"allowed.test","port":443`) || !strings.Contains(s, `"upstream":"`+f.ln.Addr().String()+`"`) {
t.Errorf("the event log doesn't name the upstream: %s", s)
if !strings.Contains(l, `"event":"tunnel","host":"allowed.test","port":443`) || !strings.Contains(l, `"upstream":"`+f.ln.Addr().String()+`"`) {
t.Errorf("the event log doesn't name the upstream: %s", l)
}
}
@@ -286,6 +274,7 @@ func TestUpstreamTunnel(t *testing.T) {
// under *.domain; one that only ** allows is refused before the upstream sees it. (.test names
// never resolve.)
func TestUpstreamUnresolved(t *testing.T) {
t.Parallel()
echo, err := new(net.ListenConfig).Listen(t.Context(), "tcp", "127.0.0.1:0")
must(t, err)
t.Cleanup(func() { _ = echo.Close() })
@@ -299,11 +288,10 @@ func TestUpstreamUnresolved(t *testing.T) {
}
}()
f := newFakeUpstream(t, echo.Addr().String(), http.StatusOK)
useUpstream(t, f, "")
out := logs(t)
pol = writePolicy(t, "**\nnamed.test\n*.wild.test\n!denied.wild.test\n")
proxy := httptest.NewServer(http.HandlerFunc(handler))
t.Cleanup(proxy.Close)
s := testServer(t, Config{}, "**\nnamed.test\n*.wild.test\n!denied.wild.test\n")
useUpstream(t, s, f, "")
out := logs(s)
addr := listen(t, s)
for _, tc := range []struct {
target string
code int
@@ -316,7 +304,7 @@ func TestUpstreamUnresolved(t *testing.T) {
{"named.test:8443", http.StatusForbidden}, // named for 443 and 80 only
} {
// Only the answer: an open tunnel waits for a ClientHello.
c, err := new(net.Dialer).DialContext(t.Context(), "tcp", proxy.Listener.Addr().String())
c, err := new(net.Dialer).DialContext(t.Context(), "tcp", addr)
must(t, err)
fmt.Fprintf(c, "CONNECT %s HTTP/1.1\r\nHost: %s\r\n\r\n", tc.target, tc.target)
resp, err := http.ReadResponse(bufio.NewReader(c), &http.Request{Method: http.MethodConnect})
@@ -337,13 +325,12 @@ func TestUpstreamUnresolved(t *testing.T) {
t.Errorf("the refusal isn't logged: %s", out.String())
}
// Plain HTTP the same.
code, _ := roundTrip(t, proxy.Listener.Addr().String(), "GET http://only-star.test/ HTTP/1.1\r\nHost: only-star.test\r\n\r\n")
code, _ := roundTrip(t, addr, "GET http://only-star.test/ HTTP/1.1\r\nHost: only-star.test\r\n\r\n")
if code != http.StatusForbidden || strings.Contains(strings.Join(f.requests(), "\n"), "only-star") {
t.Errorf("plain HTTP: %d, the upstream saw %q", code, f.requests())
}
// -upstream-unresolved (a build's proxy): ** sends it upstream; a denied name stays refused.
upUnresolved = true
t.Cleanup(func() { upUnresolved = false })
// upstream_unresolved (a build's proxy): ** sends it upstream; a denied name stays refused.
s.egress.up.unresolved = true
for _, tc := range []struct {
target string
code int
@@ -351,12 +338,12 @@ func TestUpstreamUnresolved(t *testing.T) {
{"only-star.test:443", http.StatusOK},
{"denied.wild.test:443", http.StatusForbidden},
} {
c, err := new(net.Dialer).DialContext(t.Context(), "tcp", proxy.Listener.Addr().String())
c, err := new(net.Dialer).DialContext(t.Context(), "tcp", addr)
must(t, err)
fmt.Fprintf(c, "CONNECT %s HTTP/1.1\r\nHost: %s\r\n\r\n", tc.target, tc.target)
resp, err := http.ReadResponse(bufio.NewReader(c), &http.Request{Method: http.MethodConnect})
if err != nil || resp.StatusCode != tc.code {
t.Errorf("-upstream-unresolved %s: %v %v, want %d", tc.target, resp, err, tc.code)
t.Errorf("upstream_unresolved %s: %v %v, want %d", tc.target, resp, err, tc.code)
}
if resp != nil {
_ = resp.Body.Close()
@@ -368,6 +355,7 @@ func TestUpstreamUnresolved(t *testing.T) {
// The upstream's answer to CONNECT is read only so far: headers that never end fail the tunnel.
// What follows an answer that ends is the tunnel's, past the limit too.
func TestUpstreamConnectReplyLimit(t *testing.T) {
t.Parallel()
serve := func(answer func(net.Conn)) *upstream {
ln, err := new(net.ListenConfig).Listen(t.Context(), "tcp", "127.0.0.1:0")
must(t, err)
@@ -413,14 +401,12 @@ func TestUpstreamConnectReplyLimit(t *testing.T) {
// NO_PROXY's hosts are reached directly: the upstream never sees them.
func TestUpstreamNoProxyDirect(t *testing.T) {
t.Parallel()
f := newFakeUpstream(t, "127.0.0.1:9", http.StatusOK)
useUpstream(t, f, "*")
logs(t)
pol = writePolicy(t, "allowed.test\n")
proxy := httptest.NewServer(http.HandlerFunc(handler))
t.Cleanup(proxy.Close)
s := testServer(t, Config{}, "allowed.test\n")
useUpstream(t, s, f, "*")
// Direct, it's resolved here: .test names don't resolve, so it's refused, unseen upstream.
code, body := roundTrip(t, proxy.Listener.Addr().String(), "CONNECT allowed.test:443 HTTP/1.1\r\nHost: allowed.test:443\r\n\r\n")
code, body := roundTrip(t, listen(t, s), "CONNECT allowed.test:443 HTTP/1.1\r\nHost: allowed.test:443\r\n\r\n")
if code != http.StatusForbidden || !strings.Contains(body, "can't resolve") || len(f.requests()) != 0 {
t.Errorf("NO_PROXY=*: %d %q, upstream saw %q", code, body, f.requests())
}
@@ -429,15 +415,13 @@ func TestUpstreamNoProxyDirect(t *testing.T) {
// Plain HTTP goes to HTTP_PROXY's upstream in absolute form, with its credentials in place of the
// VM's; an upstream that refuses is reported to the VM without them.
func TestUpstreamPlainHTTP(t *testing.T) {
t.Parallel()
f := newFakeUpstream(t, "", http.StatusOK)
useUpstream(t, f, "")
out := logs(t)
pol = writePolicy(t, "allowed.test\n")
proxyAuth = "k3y"
t.Cleanup(func() { proxyAuth = "" })
proxy := httptest.NewServer(http.HandlerFunc(handler))
t.Cleanup(proxy.Close)
pu, _ := url.Parse("http://devvm:k3y@" + proxy.Listener.Addr().String())
s := testServer(t, Config{Password: "k3y"}, "allowed.test\n")
useUpstream(t, s, f, "")
out := logs(s)
addr := listen(t, s)
pu, _ := url.Parse("http://devvm:k3y@" + addr)
client := &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(pu)}}
req, _ := http.NewRequestWithContext(t.Context(), http.MethodGet, "http://allowed.test/x?y=1", nil)
resp, err := client.Do(req)
@@ -450,16 +434,16 @@ func TestUpstreamPlainHTTP(t *testing.T) {
if reqs := f.requests(); len(reqs) != 1 || reqs[0] != "GET http://allowed.test/x?y=1 "+authOf("corp-user", upPassword) {
t.Errorf("the upstream saw %q", reqs)
}
if s := out.String(); strings.Contains(s, upPassword) || !strings.Contains(s, `"upstream":"`+f.ln.Addr().String()+`"`) {
t.Errorf("the log: %s", s)
if l := out.String(); strings.Contains(l, upPassword) || !strings.Contains(l, `"upstream":"`+f.ln.Addr().String()+`"`) {
t.Errorf("the log: %s", l)
}
// The upstream gets the host that was checked, canonical, whatever the VM's spelling.
if c, _ := roundTrip(t, proxy.Listener.Addr().String(),
if c, _ := roundTrip(t, addr,
"GET http://ALLOWED.test.:8080/y HTTP/1.1\r\nHost: x\r\nProxy-Authorization: "+authOf("devvm", "k3y")+"\r\nConnection: close\r\n\r\n"); c != http.StatusForbidden {
t.Errorf("a port the policy doesn't allow: %d", c)
}
pol = writePolicy(t, "allowed.test\nallowed.test:8080\n")
code, _ := roundTrip(t, proxy.Listener.Addr().String(),
s.egress.pol = writePolicy(t, "allowed.test\nallowed.test:8080\n")
code, _ := roundTrip(t, addr,
"GET http://ALLOWED.test.:8080/y HTTP/1.1\r\nHost: x\r\nProxy-Authorization: "+authOf("devvm", "k3y")+"\r\nConnection: close\r\n\r\n")
if reqs := f.requests(); code != http.StatusOK || len(reqs) != 2 || !strings.HasPrefix(reqs[1], "GET http://allowed.test:8080/y ") {
t.Errorf("an odd spelling: %d, the upstream saw %q", code, reqs)
@@ -467,7 +451,7 @@ func TestUpstreamPlainHTTP(t *testing.T) {
// An upstream that refuses: the tunnel is refused, naming it by host:port alone.
f.status = http.StatusProxyAuthRequired
code, body := roundTrip(t, proxy.Listener.Addr().String(),
code, body := roundTrip(t, addr,
"CONNECT allowed.test:443 HTTP/1.1\r\nHost: allowed.test:443\r\nProxy-Authorization: "+authOf("devvm", "k3y")+"\r\n\r\n")
if code != http.StatusForbidden || !strings.Contains(body, "answered 407") || strings.Contains(body, upPassword) {
t.Errorf("refused upstream: %d %q", code, body)
@@ -477,10 +461,11 @@ func TestUpstreamPlainHTTP(t *testing.T) {
// A host with a bound secret is intercepted, and its request goes on through the upstream's tunnel
// over TLS checked against the user's CAs, with the secret put in.
func TestUpstreamIntercept(t *testing.T) {
_, _, c := interceptSetup(t, func(http.ResponseWriter, *http.Request) {})
t.Parallel()
s, _, file, c := interceptSetup(t, func(http.ResponseWriter, *http.Request) {})
// The fake upstream sends every tunnel to a TLS server whose certificate, from the same CA as
// the user's, names "intercepted.test", which the VM asks for, bound and allowed.
srvCert, _ := leafFor("intercepted.test")
srvCert, _ := s.ca.leafFor("intercepted.test")
tlsSrv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "%s|%s", r.Host, r.Header.Get("Authorization")) //nolint:gosec // a test echo server
}))
@@ -488,11 +473,11 @@ func TestUpstreamIntercept(t *testing.T) {
tlsSrv.StartTLS()
t.Cleanup(tlsSrv.Close)
f := newFakeUpstream(t, tlsSrv.Listener.Addr().String(), http.StatusOK)
useUpstream(t, f, "")
pol = writePolicy(t, "intercepted.test\n")
writeBindings(t, secretsPath, bound("intercepted.test"))
useUpstream(t, s, f, "")
s.egress.pol = writePolicy(t, "intercepted.test\n")
writeBindings(t, file, bound("intercepted.test"))
later := time.Now().Add(time.Second)
must(t, os.Chtimes(secretsPath, later, later))
must(t, os.Chtimes(file, later, later))
code, body := get(t, c, "https://intercepted.test/x", "")
if code != http.StatusOK || body != "intercepted.test|Bearer real" {
t.Errorf("through the upstream: %d %q", code, body)
@@ -501,7 +486,7 @@ func TestUpstreamIntercept(t *testing.T) {
t.Errorf("the upstream saw %q", reqs)
}
// Without the user's CA, the upstream's certificate isn't trusted: nothing is sent.
upstreamCAs = x509.NewCertPool()
s.upstreamCAs = x509.NewCertPool()
f.mu.Lock()
f.seen = nil
f.mu.Unlock()
+1 -5
View File
@@ -318,15 +318,11 @@ func varAllowed(name string, value ast.Expr, embed bool) bool {
}
// checkVars: package-level vars, tests' too, are constants' kin: what
// varAllowed allows, or what allowedVars lists. internal/proxy is left
// out: its state is globals its Main sets.
// varAllowed allows, or what allowedVars lists.
func checkVars(m *module, r rules) []violation {
var vs []violation
seen := map[string]bool{}
for _, f := range m.files {
if matches(f.dir, []string{"internal/proxy/..."}) {
continue
}
for _, d := range f.ast.Decls {
gd, ok := d.(*ast.GenDecl)
if !ok || gd.Tok != token.VAR {
+1
View File
@@ -130,6 +130,7 @@ func varCases() []ruleCase {
{
name: "internal/proxy's state",
files: map[string]string{"internal/proxy/a.go": "package proxy\nvar port int\n"},
want: &want{ruleVars, "var port"},
},
{
name: "an allowed var",
+3
View File
@@ -175,6 +175,9 @@ func devvmVars() map[string]string {
"internal/netpolicy.Env": table,
"internal/netpolicy.directArgv": table,
"internal/project.markers": table,
"internal/proxy.notPublic": table,
"internal/proxy.nat64": table,
"internal/proxy.githubMinting": table,
"internal/secrets.Known": table,
"internal/secrets.loginKinds": table,
"internal/sshagent.Modes": table,