hostedproxy: fronting, expiry and revocation tests over TLS
proxytest.Harness runs the proxy on 127.0.0.1 against a fake controller (signed feed, redeem, renew, revocations, Task 13's cert-report rule) behind a cuttable relay, and two real TLS origins. Harness.Client is the runner transport Task 12 will replace. New end-to-end tests: the fronting matrix, no or foreign certificate, revocation, wrong epoch, socket close at certificate and feed expiry, renewal replay, and cert reports through the bootstrap listener. Fix: a CONNECT that does not parse now answers 400 and logs bad_request instead of closing silently.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
5 files changed,
+1,677
−1
docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md+22 −0internal/hostedproxy/e2e_test.go+538 −0internal/hostedproxy/egress.go+6 −0internal/hostedproxy/policy.go+2 −1internal/hostedproxy/proxytest/harness.go+1,109 −0
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md| index 7434684d..18fb28b5 100644 |
| --- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| +++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| @@ -280,3 +280,25 @@ Mutation check (applied by script, restored and checked with `cmp`): |
| 19. No fallback while an attempt hangs (the stagger timer's `if next < len(addrs)` became `if false && ...`, `origin.go`). Command: `CGO_ENABLED=0 go test ./internal/hostedproxy -run '^TestOriginDialFallsBack$' -count=1`. Observed: FAIL after 15.02 s, `egress_test.go:1080: dialOrigin with the first address stalled: dial tcp 127.0.0.1:35507: i/o timeout` (the second address got the expired context). Restored. |
| Also run: `go test ./internal/hostedproxy ./cmd/equipo-hosted-proxy -count=1 -race` ok (3.8 s and 1.3 s); staticcheck v0.7.0 ok; gofmt clean; `make budget build vet` ok (126 directories within budget). |
| + |
| +## Task 7 |
| + |
| +The proxy end to end over real TLS. New: `internal/hostedproxy/proxytest/harness.go` (package `proxytest`, test-only) and `internal/hostedproxy/e2e_test.go` (package `hostedproxy_test`). One proxy fix (below). No AWS import (TestProviderTypesStayInAdapter passes); default budgets (`internal/hostedproxy` 1882 source and 2108 test lines; `proxytest` 1109 source lines). |
| + |
| +- Harness. `proxytest.New(t)` returns `Harness{Proxy, Origin, Other, Controller, Clock, Log, InterceptPool, InterceptPin, ProxyKey}`, everything on 127.0.0.1. `FakeMono` is the proxy's clock (Mono from an hour, Wall from the real time in whole seconds, so the proxy's leaves also satisfy a real TLS stack such as Task 12's transport); `WaitTimer(at)` waits until a timer is set for exactly `at`, so an `Advance` cannot race the watcher setting it. `FakeController` verifies the proxy's signature on every call and signs every answer for its nonce; it serves the feed (every launch, every revoked or renewed serial, TTL `ctlproxy.FeedLifetime`), redeems a launch's proxy code once, issues real client certificates (SAN `equipo-launch://<launch>/<attempt>/<vm>/<epoch>`, NotAfter the earlier of `ctlproxy.CertLifetime` and the launch deadline, whole seconds), renews a serial once and revokes it, and accepts certification reports by Task 13's rule: a serial it issued, unrevoked, `ecdsa.VerifyASN1` with that certificate's key over SHA-256 of `CertReportMessage`, and no header beyond the signature and transport ones (`identity_header` otherwise). The proxy reaches the controller only through a TCP relay (`Partition`) that starts cut, so the proxy's own first poll fails and the only feed it holds is the one `New` installs; the controller stays reachable directly. Two TLS origins from one origin CA: `Origin` for `instance.example.test` (protocol answer, WebSocket echo) and `Other` for `other.example.test` (never in a manifest); a resolver answers 203.0.113.10 and .20 and the dialer sends each to its origin, so a request that leaked to either is counted. `Harness.Client(vm)` is the one place the runner's transport is built (Task 12 replaces it): no environment proxy, mutual TLS to the egress listener with the intercept CA alone as root and its SPKI pinned, `CONNECT host:443`, then TLS to the host with the intercept CA alone (pinned), ServerName the host, ALPN `http/1.1`, HTTP/2 off, redirects not followed. The client certificate is sent whatever CAs the proxy names (`GetClientCertificate`), as a forger would; with `Certificates`, Go's client silently withheld another CA's certificate and the bootstrap listener saw none. |
| +- Tests (all over real TLS, deterministic on the fake clock): TestFrontingMatrix (19 rows, each refused with its reason in the decision log and neither origin hit: CONNECT to `127.0.0.1:443`, `[::1]:443` `ip_literal`, the host on 8443 `bad_port`, another host and `x@host` `not_in_manifest`, `instance%2Eexample.test:443` `bad_request` (400); inner TLS to the allowed CONNECT with SNI of another host, `x@host`, `host%2Eexample` `sni_mismatch`, no SNI `no_sni`, ALPN `h2` alone and `h2` beside `http/1.1` `alpn`; in the tunnel, another Host, `Host: x@host`, `Host: host%2Eexample`, an absolute-form URI naming another host, a WebSocket upgrade with another Host `host_mismatch`, an absolute-form URI naming the host `bad_path`, a nested CONNECT `nested_tunnel`; positive controls: GET `/api/runner/protocol` and a WebSocket echo, two origin hits, none on the other host). TestNoCertificate (egress handshake refused; `/renew` and `/cert-report` 401 `no_certificate`, nothing forwarded; redemption works without one). TestCertFromOtherCA (the launch's exact URI from another CA: both handshakes refused, nothing forwarded; the controller's certificate then passes). TestReplayedCertAfterRevoke (the revoking feed closes the open socket; CONNECT 403 `revoked`; renewal 403 `revoked`, not forwarded; a live certificate presented with another key fails the handshake; the same certificate with its key passes). TestWrongEpochCert (the launch moves to epoch 3 without revoking: the old socket closes, CONNECT and renewal `wrong_epoch`; an epoch 3 certificate passes). TestOpenSocketClosesAtCertExpiry (a 20 s certificate, so no poll falls inside; the tunnel deadline is the certificate's, not the feed's; an echo 1 ms before NotAfter works, the socket closes at it, then CONNECT `cert_expired`). TestPartitionedProxy (the relay is cut with the controller still accepting; Poll fails; deadline is the feed's 5 min; background polls fail on the way; echo 1 ms before, closed at expiry; CONNECT and renewal `stale_feed`; healed, the next poll lets the VM through). TestRenewalReplayRefused (a captured renewal replayed over the old certificate before the next feed: forwarded, the controller's 403 `already_renewed` relayed; after the feed: the proxy's 403 `revoked`, not forwarded; over the renewed certificate: 403 `serial_mismatch`, not forwarded; the controller got exactly two renewals; the renewed certificate passes). TestCertReportThroughProxy (below). |
| +- Cert report and forged identity headers (interpretation, please confirm). The proxy builds its own request to the controller from the body alone, so identity headers a VM adds (`X-Equipo-Launch`, `X-Equipo-Vm`, `X-Equipo-Serial`, `X-Forwarded-For`, `Equipo-Launch`, a forged `Equipo-Key-Id`) never reach the controller; the test checks the controller saw none of them (only the proxy's own `Equipo-Key-Id`) and that the report was credited by its serial alone to l-1/vm-1. A literal "refused by the controller" for that row would need the proxy to forward VM headers, so the refusal is shown at the controller directly: the same report, proxy-signed, carrying `X-Equipo-Launch` is refused 400 `identity_header`. Another serial: refused by the proxy (403 `serial_mismatch`, not forwarded) and, sent straight to the controller, by the controller (403 `bad_signature`). Another key: the proxy forwards it (it never vouches for a report) and the VM receives the controller's signed 403 `bad_signature`. A revoked serial: the proxy's 403 `revoked` and the controller's 403 `revoked`. The valid report reaches the controller byte for byte. Task 13 must make the real controller (`ctlcert/report.go`) enforce the same rule: serial issued for that live certification launch, unrevoked, signature by that certificate's key (the harness assumes ECDSA P-256, ASN.1, over SHA-256 of `CertReportMessage`; Task 13 fixes the encoding), and no identity taken from or allowed in any header. |
| + |
| +Proxy fix (TDD). A CONNECT whose request line or headers did not parse (for example `CONNECT instance%2Eexample.test:443`, which `net/url` refuses) was closed with no answer and no decision line. It now answers 400 and logs `bad_request` (no method or destination, which did not parse), unless the read ended in EOF, a closed connection or a timeout (`egress.go`, `serveEgress`; `policy.go` comment on `ReasonBadRequest`). Inside a tunnel, bytes that are not HTTP stay `nested_tunnel` (Task 6 ruling). |
| + |
| +RED: `CGO_ENABLED=0 go test ./internal/hostedproxy -run 'TestFronting|TestNoCertificate|TestCertFromOtherCA|TestReplayedCert|TestWrongEpoch|TestOpenSocket|TestPartitioned|TestRenewalReplay|TestCertReportThroughProxy' -count=1` failed: `--- FAIL: TestFrontingMatrix/CONNECT_to_host%2Eexample: e2e_test.go:141: CONNECT instance%2Eexample.test:443 = 0, unexpected EOF; want 400`. (The first run also failed `TestCertFromOtherCA: renewal with another CA's certificate = 401, want the handshake refused`: a harness defect, Go's client withholding a certificate from a CA the server does not name; fixed in the harness with `GetClientCertificate`, no proxy change.) |
| + |
| +GREEN: the same command, `ok internal/hostedproxy 0.153s`; the same tests `-count=20` ok (2.9 s); whole package 1.0 s. |
| + |
| +Mutation checks (each applied by script, the named test run, then restored and checked byte for byte with `cmp`): |
| + |
| +20. Accept `h2` (`decideTLS`: `if p != ALPNHTTP11 && p != "h2"`, `policy.go`). Command: `CGO_ENABLED=0 go test ./internal/hostedproxy -run '^TestFrontingMatrix$' -count=1`. Observed: FAIL, `TestFrontingMatrix/ALPN_h2_only: e2e_test.go:167: no decision line for ALPN h2 only after line 9` (the handshake still failed on Go's own ALPN mismatch, unlogged) and `TestFrontingMatrix/ALPN_h2_beside_http/1.1: e2e_test.go:165: the inner handshake succeeded`. Restored. |
| +21. Skip the tunnel deadline timer (`watch`: `case <-clock.After(deadline - mono):` became `case <-make(chan time.Time):`, `egress.go`). Command: `CGO_ENABLED=0 go test ./internal/hostedproxy -run '^(TestOpenSocketClosesAtCertExpiry|TestPartitionedProxy)$' -count=1`. Observed: FAIL, `e2e_test.go:356: the socket at NotAfter: read = failed to get reader: context deadline exceeded, want the socket closed` and `e2e_test.go:386: the socket at the feed's expiry: read = failed to get reader: context deadline exceeded, want the socket closed` (each after `no timer set for mono ...; going on`: `WaitTimer` logs and goes on, so the socket assertion, not the harness, fails). Restored. |
| +22. (the fix) Close an unparseable CONNECT silently again (`if false && ...` on the new branch, `egress.go`). Command: `CGO_ENABLED=0 go test ./internal/hostedproxy -run '^TestFrontingMatrix$' -count=1`. Observed: FAIL, `TestFrontingMatrix/CONNECT_to_host%2Eexample: e2e_test.go:142: CONNECT instance%2Eexample.test:443 = 0, unexpected EOF; want 400`. Restored. |
| + |
| +Also run: `go test ./internal/hostedproxy/... ./cmd/equipo-hosted-proxy -count=1 -race` once, ok (3.4 s and 1.1 s); `go test ./internal/isolatedjob -run TestProviderTypesStayInAdapter -count=1` ok; staticcheck v0.7.0 on `./internal/hostedproxy/...` clean; gofmt clean; `make budget build vet` ok (127 directories within budget). |
diff --git a/internal/hostedproxy/e2e_test.go b/internal/hostedproxy/e2e_test.go| new file mode 100644 |
| index 00000000..ddb5339c |
| --- /dev/null |
| +++ b/internal/hostedproxy/e2e_test.go |
| @@ -0,0 +1,538 @@ |
| +package hostedproxy_test |
| + |
| +import ( |
| + "context" |
| + "crypto/ecdsa" |
| + "crypto/elliptic" |
| + "crypto/rand" |
| + "crypto/tls" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "net" |
| + "net/http" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/hostedctl/ctlproxy" |
| + "amadan.net/oficina/equipo/internal/hostedproxy" |
| + "amadan.net/oficina/equipo/internal/hostedproxy/proxytest" |
| + "amadan.net/oficina/equipo/internal/hostedwire" |
| + "github.com/coder/websocket" |
| +) |
| + |
| +const ( |
| + host = proxytest.Host |
| + local = proxytest.Host + ":443" |
| + other = proxytest.OtherHost |
| +) |
| + |
| +// noHits fails unless neither origin has seen a request. |
| +func noHits(t *testing.T, h *proxytest.Harness) { |
| + t.Helper() |
| + if origin, otherHits := h.Hits(); origin != 0 || otherHits != 0 { |
| + t.Errorf("the origins saw %d and %d requests, want none", origin, otherHits) |
| + } |
| +} |
| + |
| +// get fetches path from the service host through the proxy as vm. |
| +func get(t *testing.T, h *proxytest.Harness, vm *proxytest.VM, path string) (int, string, error) { |
| + t.Helper() |
| + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| + defer cancel() |
| + req, _ := http.NewRequestWithContext(ctx, http.MethodGet, "https://"+host+path, nil) |
| + c := h.Client(vm) |
| + defer c.CloseIdleConnections() |
| + resp, err := c.Do(req) |
| + if err != nil { |
| + return 0, "", err |
| + } |
| + defer resp.Body.Close() |
| + body, _ := io.ReadAll(resp.Body) |
| + return resp.StatusCode, string(body), nil |
| +} |
| + |
| +// openSocket opens the runner stream through the proxy as vm and checks |
| +// one echo. |
| +func openSocket(t *testing.T, h *proxytest.Harness, vm *proxytest.VM) *websocket.Conn { |
| + t.Helper() |
| + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| + defer cancel() |
| + ws, _, err := websocket.Dial(ctx, "wss://"+host+"/api/runner/stream", &websocket.DialOptions{HTTPClient: h.Client(vm)}) |
| + if err != nil { |
| + t.Fatalf("WebSocket through the proxy: %v", err) |
| + } |
| + t.Cleanup(func() { ws.CloseNow() }) |
| + echo(t, ws, "hello") |
| + return ws |
| +} |
| + |
| +func echo(t *testing.T, ws *websocket.Conn, msg string) { |
| + t.Helper() |
| + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| + defer cancel() |
| + if err := ws.Write(ctx, websocket.MessageText, []byte(msg)); err != nil { |
| + t.Fatalf("write %q: %v", msg, err) |
| + } |
| + if _, got, err := ws.Read(ctx); err != nil || string(got) != msg { |
| + t.Fatalf("echo of %q = %q, %v", msg, got, err) |
| + } |
| +} |
| + |
| +// socketClosed checks that ws is closed now: a read ends with an error |
| +// other than its own deadline. |
| +func socketClosed(t *testing.T, ws *websocket.Conn, what string) { |
| + t.Helper() |
| + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| + defer cancel() |
| + if _, _, err := ws.Read(ctx); err == nil || errors.Is(err, context.DeadlineExceeded) || ctx.Err() != nil { |
| + t.Fatalf("%s: read = %v, want the socket closed", what, err) |
| + } |
| +} |
| + |
| +// refusedConnect checks that CONNECT target as vm is answered 403 (400 |
| +// for bad_request) and logged with reason. |
| +func refusedConnect(t *testing.T, h *proxytest.Harness, vm *proxytest.VM, target, reason string) { |
| + t.Helper() |
| + want := http.StatusForbidden |
| + if reason == hostedproxy.ReasonBadRequest { |
| + want = http.StatusBadRequest |
| + } |
| + from := len(h.Log.Lines(t)) |
| + if c, status, err := h.Connect(context.Background(), vm, target); err != nil || status != want { |
| + if c != nil { |
| + c.Close() |
| + } |
| + t.Errorf("CONNECT %s = %d, %v; want %d", target, status, err, want) |
| + return |
| + } |
| + h.Log.Wait(t, "CONNECT "+target, from, func(l proxytest.LogLine) bool { |
| + // A CONNECT that does not parse has no method to log. |
| + return (l.Method == "CONNECT" || reason == hostedproxy.ReasonBadRequest) && l.Decision == "deny" && l.Reason == reason |
| + }) |
| +} |
| + |
| +// bootCode posts body to the bootstrap listener as vm and returns the |
| +// status and the error code of the answer. |
| +func bootCode(t *testing.T, h *proxytest.Harness, vm *proxytest.VM, path string, body []byte, extra http.Header) (int, string) { |
| + t.Helper() |
| + status, out := h.Boot(t, vm, path, body, extra) |
| + var e hostedwire.ErrorResponse |
| + _ = json.Unmarshal(out, &e) |
| + return status, e.Code |
| +} |
| + |
| +// TestFrontingMatrix: every way of naming one host to the proxy and |
| +// another to the origin is refused with its own reason, and neither |
| +// origin sees a request; the runner's own requests and a WebSocket round |
| +// trip pass. |
| +func TestFrontingMatrix(t *testing.T) { |
| + h := proxytest.New(t) |
| + vm := h.Redeem(t) |
| + |
| + for _, row := range []struct{ name, target, reason string }{ |
| + {"CONNECT to 127.0.0.1:443", "127.0.0.1:443", hostedproxy.ReasonIPLiteral}, |
| + {"CONNECT to [::1]:443", "[::1]:443", hostedproxy.ReasonIPLiteral}, |
| + {"CONNECT to the host on 8443", host + ":8443", hostedproxy.ReasonBadPort}, |
| + {"CONNECT to another host", other + ":443", hostedproxy.ReasonNotInManifest}, |
| + {"CONNECT to x@host", "x@" + local, hostedproxy.ReasonNotInManifest}, |
| + {"CONNECT to host%2Eexample", "instance%2Eexample.test:443", hostedproxy.ReasonBadRequest}, |
| + } { |
| + t.Run(row.name, func(t *testing.T) { refusedConnect(t, h, vm, row.target, row.reason) }) |
| + } |
| + |
| + for _, row := range []struct { |
| + name, sni string |
| + alpn []string |
| + reason string |
| + }{ |
| + {"CONNECT to the host, then SNI of another", other, []string{hostedproxy.ALPNHTTP11}, hostedproxy.ReasonSNIMismatch}, |
| + {"no SNI", "", []string{hostedproxy.ALPNHTTP11}, hostedproxy.ReasonNoSNI}, |
| + {"ALPN h2 only", host, []string{"h2"}, hostedproxy.ReasonALPN}, |
| + {"ALPN h2 beside http/1.1", host, []string{"h2", hostedproxy.ALPNHTTP11}, hostedproxy.ReasonALPN}, |
| + {"SNI x@host", "x@" + host, []string{hostedproxy.ALPNHTTP11}, hostedproxy.ReasonSNIMismatch}, |
| + {"SNI host%2Eexample", "instance%2Eexample.test", []string{hostedproxy.ALPNHTTP11}, hostedproxy.ReasonSNIMismatch}, |
| + } { |
| + t.Run(row.name, func(t *testing.T) { |
| + from := len(h.Log.Lines(t)) |
| + c, status, err := h.Connect(context.Background(), vm, local) |
| + if err != nil || status != http.StatusOK { |
| + t.Fatalf("CONNECT %s = %d, %v", local, status, err) |
| + } |
| + if inner, err := h.Inner(c, row.sni, row.alpn); err == nil { |
| + inner.Close() |
| + t.Fatal("the inner handshake succeeded") |
| + } |
| + h.Log.Wait(t, row.name, from, func(l proxytest.LogLine) bool { |
| + return l.Decision == "deny" && l.Reason == row.reason && l.Destination == local |
| + }) |
| + }) |
| + } |
| + |
| + wsHeaders := "Upgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Version: 13\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n" |
| + for _, row := range []struct{ name, raw, reason string }{ |
| + {"allowed SNI with another Host", "GET /api/runner/protocol HTTP/1.1\r\nHost: " + other + "\r\n\r\n", hostedproxy.ReasonHostMismatch}, |
| + {"Host x@host", "GET /api/runner/protocol HTTP/1.1\r\nHost: x@" + host + "\r\n\r\n", hostedproxy.ReasonHostMismatch}, |
| + {"Host host%2Eexample", "GET /api/runner/protocol HTTP/1.1\r\nHost: instance%2Eexample.test\r\n\r\n", hostedproxy.ReasonHostMismatch}, |
| + {"absolute-form URI naming another host", "GET https://" + other + "/api/runner/protocol HTTP/1.1\r\nHost: " + host + "\r\n\r\n", |
| + hostedproxy.ReasonHostMismatch}, |
| + {"absolute-form URI naming the host", "GET https://" + host + "/api/runner/protocol HTTP/1.1\r\nHost: " + host + "\r\n\r\n", |
| + hostedproxy.ReasonBadPath}, |
| + {"WebSocket upgrade with another Host", "GET /api/runner/stream HTTP/1.1\r\nHost: " + other + "\r\n" + wsHeaders + "\r\n", |
| + hostedproxy.ReasonHostMismatch}, |
| + {"nested CONNECT", "CONNECT " + other + ":443 HTTP/1.1\r\nHost: " + other + ":443\r\n\r\n", hostedproxy.ReasonNestedTunnel}, |
| + } { |
| + t.Run(row.name, func(t *testing.T) { |
| + from := len(h.Log.Lines(t)) |
| + c, status, err := h.Connect(context.Background(), vm, local) |
| + if err != nil || status != http.StatusOK { |
| + t.Fatalf("CONNECT %s = %d, %v", local, status, err) |
| + } |
| + inner, err := h.Inner(c, host, []string{hostedproxy.ALPNHTTP11}) |
| + if err != nil { |
| + t.Fatalf("inner TLS: %v", err) |
| + } |
| + defer inner.Close() |
| + _ = inner.SetDeadline(time.Now().Add(5 * time.Second)) |
| + _, _ = io.WriteString(inner, row.raw) |
| + got, _ := io.ReadAll(inner) |
| + if !strings.HasPrefix(string(got), "HTTP/1.1 403 ") { |
| + t.Errorf("answered %q, want 403", got) |
| + } |
| + h.Log.Wait(t, row.name, from, func(l proxytest.LogLine) bool { |
| + return l.Decision == "deny" && l.Reason == row.reason && l.Destination == local |
| + }) |
| + }) |
| + } |
| + noHits(t, h) |
| + |
| + // Positive control: the runner's own request and its stream. |
| + if status, body, err := get(t, h, vm, "/api/runner/protocol"); err != nil || status != 200 || body != "protocol 39" { |
| + t.Fatalf("GET /api/runner/protocol = %d %q, %v", status, body, err) |
| + } |
| + openSocket(t, h, vm) |
| + if origin, otherHits := h.Hits(); origin != 2 || otherHits != 0 { |
| + t.Errorf("after the positive controls the origins saw %d and %d requests, want 2 and 0", origin, otherHits) |
| + } |
| +} |
| + |
| +// TestNoCertificate: without a client certificate nothing passes the |
| +// egress listener, and the bootstrap listener forwards only a redemption. |
| +func TestNoCertificate(t *testing.T) { |
| + h := proxytest.New(t) |
| + if c, status, err := h.Connect(context.Background(), nil, local); err == nil { |
| + c.Close() |
| + t.Errorf("CONNECT without a certificate answered %d, want the handshake refused", status) |
| + } |
| + vm := h.Redeem(t) // a redemption needs none |
| + for path, body := range map[string][]byte{ |
| + "/renew": func() []byte { _, b := proxytest.RenewBody(t, vm); return b }(), |
| + "/cert-report": proxytest.ReportBody(t, vm.Serial(), []byte("report"), vm.Key), |
| + } { |
| + if status, code := bootCode(t, h, nil, path, body, nil); status != http.StatusUnauthorized || code != "no_certificate" { |
| + t.Errorf("%s without a certificate = %d %s, want 401 no_certificate", path, status, code) |
| + } |
| + } |
| + if n := len(h.Controller.Received("POST /v1/proxy/renew")) + len(h.Controller.Received("POST /v1/proxy/cert-report")); n != 0 { |
| + t.Errorf("the controller got %d requests sent without a certificate", n) |
| + } |
| + noHits(t, h) |
| +} |
| + |
| +// TestCertFromOtherCA: a certificate naming the launch exactly, signed by |
| +// any CA but the controller's, is refused by both listeners' handshakes. |
| +func TestCertFromOtherCA(t *testing.T) { |
| + h := proxytest.New(t) |
| + caKey, ca := proxytest.NewCA(t) |
| + forged := h.IssueClient(t, ca, caKey, proxytest.Epoch) |
| + if c, status, err := h.Connect(context.Background(), forged, local); err == nil { |
| + c.Close() |
| + t.Errorf("CONNECT with another CA's certificate answered %d, want the handshake refused", status) |
| + } |
| + _, body := proxytest.RenewBody(t, forged) |
| + if status, _ := h.Boot(t, forged, "/renew", body, nil); status != 0 { |
| + t.Errorf("renewal with another CA's certificate = %d, want the handshake refused", status) |
| + } |
| + if n := len(h.Controller.Received("POST /v1/proxy/renew")); n != 0 { |
| + t.Errorf("the controller got %d renewals", n) |
| + } |
| + noHits(t, h) |
| + // The same request with the controller's certificate passes. |
| + vm := h.Redeem(t) |
| + if status, _, err := get(t, h, vm, "/api/runner/protocol"); err != nil || status != 200 { |
| + t.Errorf("GET with the controller's certificate = %d, %v", status, err) |
| + } |
| +} |
| + |
| +// TestReplayedCertAfterRevoke: once the controller revokes a serial, the |
| +// next feed closes its open socket and the certificate opens nothing |
| +// more; a certificate presented without its key never completes a |
| +// handshake. |
| +func TestReplayedCertAfterRevoke(t *testing.T) { |
| + h := proxytest.New(t) |
| + ctx := context.Background() |
| + vm := h.Redeem(t) |
| + ws := openSocket(t, h, vm) |
| + h.Controller.Revoke(vm.Serial()) |
| + if err := h.Proxy.Poll(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + socketClosed(t, ws, "the socket after the revoking feed") |
| + refusedConnect(t, h, vm, local, hostedproxy.ReasonRevoked) |
| + _, body := proxytest.RenewBody(t, vm) |
| + if status, code := bootCode(t, h, vm, "/renew", body, nil); status != http.StatusForbidden || code != hostedproxy.ReasonRevoked { |
| + t.Errorf("renewal over the revoked certificate = %d %s, want 403 revoked", status, code) |
| + } |
| + if n := len(h.Controller.Received("POST /v1/proxy/renew")); n != 0 { |
| + t.Errorf("the controller got %d renewals", n) |
| + } |
| + |
| + // Another VM's live certificate, without its key. |
| + live := h.Issue(t, proxytest.LaunchID) |
| + thief, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| + stolen := &proxytest.VM{Key: thief, Cert: tls.Certificate{Certificate: live.Cert.Certificate, PrivateKey: thief, Leaf: live.Cert.Leaf}} |
| + if c, status, err := h.Connect(ctx, stolen, local); err == nil { |
| + c.Close() |
| + t.Errorf("CONNECT with a certificate and another key answered %d, want the handshake refused", status) |
| + } |
| + if status, body, err := get(t, h, live, "/api/runner/protocol"); err != nil || status != 200 { |
| + t.Errorf("GET with the live certificate and its key = %d %q, %v", status, body, err) |
| + } |
| + if origin, _ := h.Hits(); origin != 2 { |
| + t.Errorf("the origin saw %d requests, want the socket and the live GET", origin) |
| + } |
| +} |
| + |
| +// TestWrongEpochCert: after the launch moves to a new epoch, a |
| +// certificate from the old one is refused and its socket closes, even |
| +// when the controller never revoked it; the new epoch's passes. |
| +func TestWrongEpochCert(t *testing.T) { |
| + h := proxytest.New(t) |
| + vm := h.Redeem(t) |
| + ws := openSocket(t, h, vm) |
| + h.Controller.SetEpoch(proxytest.LaunchID, proxytest.Epoch+1) |
| + if err := h.Proxy.Poll(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + socketClosed(t, ws, "the old epoch's socket after the new feed") |
| + refusedConnect(t, h, vm, local, hostedproxy.ReasonWrongEpoch) |
| + _, body := proxytest.RenewBody(t, vm) |
| + if status, code := bootCode(t, h, vm, "/renew", body, nil); status != http.StatusForbidden || code != hostedproxy.ReasonWrongEpoch { |
| + t.Errorf("renewal over the old epoch's certificate = %d %s, want 403 wrong_epoch", status, code) |
| + } |
| + next := h.Issue(t, proxytest.LaunchID) |
| + if got := next.Identity(t).Epoch; got != proxytest.Epoch+1 { |
| + t.Fatalf("new certificate's epoch = %d", got) |
| + } |
| + if status, _, err := get(t, h, next, "/api/runner/protocol"); err != nil || status != 200 { |
| + t.Errorf("GET at the new epoch = %d, %v", status, err) |
| + } |
| +} |
| + |
| +// TestOpenSocketClosesAtCertExpiry: an upgraded WebSocket open across its |
| +// certificate's NotAfter is closed at it, well before the feed expires; |
| +// after it the certificate opens nothing. |
| +func TestOpenSocketClosesAtCertExpiry(t *testing.T) { |
| + h := proxytest.New(t) |
| + const life = 20 * time.Second // the launch deadline caps the certificate, inside one poll interval |
| + h.Controller.SetLaunch(proxytest.Launch{LaunchID: proxytest.LaunchID, AttemptID: proxytest.AttemptID, VMRef: proxytest.VMRef, |
| + Epoch: proxytest.Epoch, Code: strings.Repeat("C", len(ctlproxy.CodePlaceholder)), Deadline: h.Clock.Wall().Add(life), |
| + Services: []hostedwire.Service{{Host: host, Port: 443, Class: hostedwire.ServiceInstance}}}) |
| + vm := h.Redeem(t) |
| + if got := vm.Cert.Leaf.NotAfter.Sub(h.Clock.Wall()); got != life { |
| + t.Fatalf("certificate lifetime %v, want %v", got, life) |
| + } |
| + ws := openSocket(t, h, vm) |
| + mono := h.Clock.Mono() |
| + at := h.Proxy.Feed().Deadline(vm.Identity(t), mono) |
| + if at != mono+life { |
| + t.Fatalf("tunnel deadline %v after now, want the certificate's %v", at-mono, life) |
| + } |
| + h.Clock.WaitTimer(t, at) |
| + h.Clock.Advance(at - mono - time.Millisecond) |
| + echo(t, ws, "a millisecond before NotAfter") |
| + h.Clock.Advance(time.Millisecond) |
| + socketClosed(t, ws, "the socket at NotAfter") |
| + refusedConnect(t, h, vm, local, hostedproxy.ReasonCertExpired) |
| +} |
| + |
| +// TestPartitionedProxy: the controller is up but the proxy cannot reach |
| +// it. Open sockets close at the last feed's expiry and new requests fail |
| +// with stale_feed; once the path heals, the next feed lets them through. |
| +func TestPartitionedProxy(t *testing.T) { |
| + h := proxytest.New(t) |
| + ctx := context.Background() |
| + vm := h.Redeem(t) |
| + ws := openSocket(t, h, vm) |
| + h.Partition(true) |
| + if c, err := net.DialTimeout("tcp", h.Controller.Addr(), 5*time.Second); err != nil { |
| + t.Fatalf("the controller is down: %v", err) |
| + } else { |
| + c.Close() |
| + } |
| + if err := h.Proxy.Poll(ctx); err == nil { |
| + t.Fatal("Poll reached the controller across the partition") |
| + } |
| + mono := h.Clock.Mono() |
| + at := h.Proxy.Feed().Deadline(vm.Identity(t), mono) |
| + if at != mono+ctlproxy.FeedLifetime { |
| + t.Fatalf("tunnel deadline %v after now, want the feed's %v", at-mono, ctlproxy.FeedLifetime) |
| + } |
| + h.Clock.WaitTimer(t, at) |
| + h.Clock.Advance(at - mono - time.Millisecond) // the background polls fail on the way |
| + echo(t, ws, "a millisecond before the feed expires") |
| + h.Clock.Advance(time.Millisecond) |
| + socketClosed(t, ws, "the socket at the feed's expiry") |
| + refusedConnect(t, h, vm, local, hostedproxy.ReasonStaleFeed) |
| + _, body := proxytest.RenewBody(t, vm) |
| + if status, code := bootCode(t, h, vm, "/renew", body, nil); status != http.StatusForbidden || code != hostedproxy.ReasonStaleFeed { |
| + t.Errorf("renewal on a stale feed = %d %s, want 403 stale_feed", status, code) |
| + } |
| + if origin, _ := h.Hits(); origin != 1 { |
| + t.Errorf("the origin saw %d requests, want the socket only", origin) |
| + } |
| + h.Partition(false) |
| + if err := h.Proxy.Poll(ctx); err != nil { |
| + t.Fatalf("Poll after the partition healed: %v", err) |
| + } |
| + if status, _, err := get(t, h, vm, "/api/runner/protocol"); err != nil || status != 200 { |
| + t.Errorf("GET after the partition healed = %d, %v", status, err) |
| + } |
| +} |
| + |
| +// TestRenewalReplayRefused: a renewal captured and replayed through the |
| +// bootstrap listener is refused: by the controller (the serial was |
| +// renewed) while the proxy's feed still lets the old certificate through, |
| +// by the proxy (revoked) once the feed says so, and by the proxy |
| +// (serial_mismatch) over the new certificate. |
| +func TestRenewalReplayRefused(t *testing.T) { |
| + h := proxytest.New(t) |
| + vm := h.Redeem(t) |
| + key, captured := proxytest.RenewBody(t, vm) |
| + status, out := h.Boot(t, vm, "/renew", captured, nil) |
| + if status != http.StatusOK { |
| + t.Fatalf("renewal = %d %s", status, out) |
| + } |
| + var r hostedwire.RedeemResponse |
| + if err := json.Unmarshal(out, &r); err != nil { |
| + t.Fatal(err) |
| + } |
| + renewed := proxytest.VMFromDER(t, key, r.Cert) |
| + |
| + if status, code := bootCode(t, h, vm, "/renew", captured, nil); status != http.StatusForbidden || code != "already_renewed" { |
| + t.Errorf("replay before the next feed = %d %s, want the controller's 403 already_renewed", status, code) |
| + } |
| + if err := h.Proxy.Poll(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + forwarded := len(h.Controller.Received("POST /v1/proxy/renew")) |
| + if status, code := bootCode(t, h, vm, "/renew", captured, nil); status != http.StatusForbidden || code != hostedproxy.ReasonRevoked { |
| + t.Errorf("replay over the old certificate = %d %s, want 403 revoked", status, code) |
| + } |
| + if status, code := bootCode(t, h, renewed, "/renew", captured, nil); status != http.StatusForbidden || code != "serial_mismatch" { |
| + t.Errorf("replay over the new certificate = %d %s, want 403 serial_mismatch", status, code) |
| + } |
| + if n := len(h.Controller.Received("POST /v1/proxy/renew")); n != forwarded || n != 2 { |
| + t.Errorf("the controller got %d renewals, want the renewal and the first replay only", n) |
| + } |
| + refusedConnect(t, h, vm, local, hostedproxy.ReasonRevoked) |
| + if status, _, err := get(t, h, renewed, "/api/runner/protocol"); err != nil || status != 200 { |
| + t.Errorf("GET with the renewed certificate = %d, %v", status, err) |
| + } |
| +} |
| + |
| +// TestCertReportThroughProxy: a report signed with the VM's certificate |
| +// key reaches the controller byte for byte and is credited to the |
| +// launch the serial was issued for. Identity headers the VM adds never |
| +// reach the controller, which refuses any that do; a report for another |
| +// serial, or signed by another key, or for a revoked serial, is refused. |
| +func TestCertReportThroughProxy(t *testing.T) { |
| + h := proxytest.New(t) |
| + vm := h.Redeem(t) |
| + report := []byte(`{"launch_id":"l-1","root":[],"user":[],"sandbox":[]}`) |
| + body := proxytest.ReportBody(t, vm.Serial(), report, vm.Key) |
| + if status, code := bootCode(t, h, vm, "/cert-report", body, nil); status != http.StatusOK { |
| + t.Fatalf("report = %d %s", status, code) |
| + } |
| + got := h.Controller.Received("POST /v1/proxy/cert-report") |
| + if len(got) != 1 || string(got[0].Body) != string(body) { |
| + t.Fatalf("the controller got %d reports, want the VM's body intact", len(got)) |
| + } |
| + if r := h.Controller.Reports(); len(r) != 1 || r[0].Launch.LaunchID != proxytest.LaunchID || r[0].Serial != vm.Serial() || |
| + string(r[0].Body) != string(report) { |
| + t.Fatalf("accepted reports = %+v", r) |
| + } |
| + |
| + // Forged identity headers: the proxy forwards none of them, so the |
| + // report is credited by its serial alone ... |
| + forged := http.Header{"X-Equipo-Launch": {"l-9"}, "X-Equipo-Vm": {"vm-9"}, "X-Equipo-Serial": {"ab"}, |
| + "X-Forwarded-For": {"10.0.0.9"}, hostedwire.HeaderKeyID: {"controller"}, "Equipo-Launch": {"l-9"}} |
| + second := proxytest.ReportBody(t, vm.Serial(), []byte("second"), vm.Key) |
| + if status, code := bootCode(t, h, vm, "/cert-report", second, forged); status != http.StatusOK { |
| + t.Fatalf("report with forged headers = %d %s", status, code) |
| + } |
| + for _, r := range h.Controller.Received("POST /v1/proxy/cert-report") { |
| + for name := range forged { |
| + if v := r.Header.Values(name); name != hostedwire.HeaderKeyID && len(v) != 0 || name == hostedwire.HeaderKeyID && |
| + (len(v) != 1 || v[0] != string(proxytest.ProxyKey)) { |
| + t.Errorf("the controller got %s: %q", name, v) |
| + } |
| + } |
| + } |
| + if r := h.Controller.Reports(); len(r) != 2 || r[1].Launch.LaunchID != proxytest.LaunchID || r[1].Launch.VMRef != proxytest.VMRef { |
| + t.Fatalf("accepted reports = %+v", r) |
| + } |
| + // ... and a request that did carry one is refused by the controller. |
| + direct := http.Header{"X-Equipo-Launch": {"l-9"}} |
| + if status, code := h.Controller.SignedCall(t, h.ProxyKey, "/v1/proxy/cert-report", second, direct); status != 400 || |
| + code != "identity_header" { |
| + t.Errorf("a report with an identity header at the controller = %d %s, want 400 identity_header", status, code) |
| + } |
| + |
| + // Another serial: another launch's VM certificate, signed with this |
| + // VM's key. The proxy refuses it; so does the controller. |
| + h.Controller.SetLaunch(proxytest.Launch{LaunchID: "l-2", AttemptID: "a-2", VMRef: "vm-2", Epoch: 1, Code: "unused", |
| + Services: []hostedwire.Service{{Host: host, Port: 443, Class: hostedwire.ServiceInstance}}}) |
| + otherVM := h.Issue(t, "l-2") |
| + if err := h.Proxy.Poll(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + before := len(h.Controller.Received("POST /v1/proxy/cert-report")) |
| + theirs := proxytest.ReportBody(t, otherVM.Serial(), report, vm.Key) |
| + if status, code := bootCode(t, h, vm, "/cert-report", theirs, nil); status != http.StatusForbidden || code != "serial_mismatch" { |
| + t.Errorf("report for another serial = %d %s, want 403 serial_mismatch", status, code) |
| + } |
| + if n := len(h.Controller.Received("POST /v1/proxy/cert-report")); n != before { |
| + t.Errorf("the controller got the report for another serial") |
| + } |
| + if status, code := h.Controller.SignedCall(t, h.ProxyKey, "/v1/proxy/cert-report", theirs, nil); status != 403 || |
| + code != "bad_signature" { |
| + t.Errorf("report for another serial at the controller = %d %s, want 403 bad_signature", status, code) |
| + } |
| + |
| + // Another key: the proxy forwards it (it never vouches for a report); |
| + // the controller refuses it and the VM gets its signed refusal. |
| + stranger, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| + if status, code := bootCode(t, h, vm, "/cert-report", proxytest.ReportBody(t, vm.Serial(), report, stranger), nil); status != 403 || |
| + code != "bad_signature" { |
| + t.Errorf("report signed by another key = %d %s, want the controller's 403 bad_signature", status, code) |
| + } |
| + |
| + // A revoked serial: refused by the proxy once the feed says so, and |
| + // by the controller. |
| + h.Controller.Revoke(vm.Serial()) |
| + if err := h.Proxy.Poll(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + third := proxytest.ReportBody(t, vm.Serial(), []byte("third"), vm.Key) |
| + if status, code := bootCode(t, h, vm, "/cert-report", third, nil); status != 403 || code != hostedproxy.ReasonRevoked { |
| + t.Errorf("report over a revoked certificate = %d %s, want 403 revoked", status, code) |
| + } |
| + if status, code := h.Controller.SignedCall(t, h.ProxyKey, "/v1/proxy/cert-report", third, nil); status != 403 || code != "revoked" { |
| + t.Errorf("report for a revoked serial at the controller = %d %s, want 403 revoked", status, code) |
| + } |
| + if n := len(h.Controller.Reports()); n != 2 { |
| + t.Errorf("the controller accepted %d reports, want 2", n) |
| + } |
| +} |
diff --git a/internal/hostedproxy/egress.go b/internal/hostedproxy/egress.go| index 0b2aec18..12dde27a 100644 |
| --- a/internal/hostedproxy/egress.go |
| +++ b/internal/hostedproxy/egress.go |
| @@ -279,6 +279,12 @@ func (s *Server) serveEgress(ctx context.Context, raw net.Conn, cfg *tls.Config) |
| writeStatus(outer, http.StatusHTTPVersionNotSupported) |
| return |
| case err != nil: |
| + // A request that does not parse (an escape in the target, a bad |
| + // header) is refused like any other, with a decision line. |
| + if !errors.Is(err, io.EOF) && !errors.Is(err, net.ErrClosed) && !isTimeout(err) && ctx.Err() == nil { |
| + s.log.write(entry{id: id, decision: deny(ReasonBadRequest), status: http.StatusBadRequest}) |
| + writeStatus(outer, http.StatusBadRequest) |
| + } |
| return |
| } |
| _ = raw.SetDeadline(time.Time{}) |
diff --git a/internal/hostedproxy/policy.go b/internal/hostedproxy/policy.go| index b708fa87..14b4bd7e 100644 |
| --- a/internal/hostedproxy/policy.go |
| +++ b/internal/hostedproxy/policy.go |
| @@ -55,7 +55,8 @@ const ( |
| // Reasons outside Decide (review round 1): ReasonBadRequest is a request |
| // line or header past maxHeaderBytes, or a version other than HTTP/1.1, |
| -// at either parse point; ReasonOriginAddress is a service host whose DNS |
| +// at either parse point, or a CONNECT that does not parse (Task 7); |
| +// ReasonOriginAddress is a service host whose DNS |
| // answer holds an address the proxy never dials (allowedOriginAddr). |
| const ( |
| ReasonBadRequest = "bad_request" |
diff --git a/internal/hostedproxy/proxytest/harness.go b/internal/hostedproxy/proxytest/harness.go| new file mode 100644 |
| index 00000000..9bf01d02 |
| --- /dev/null |
| +++ b/internal/hostedproxy/proxytest/harness.go |
| @@ -0,0 +1,1109 @@ |
| +// Package proxytest runs a hosted proxy end to end over real TLS for |
| +// tests: the proxy on 127.0.0.1, a fake controller that signs the feed and |
| +// issues, renews and revokes VM certificates, and two TLS origins, the |
| +// service host and another host that must never be reached. Nothing |
| +// outside tests may import it. |
| +package proxytest |
| + |
| +import ( |
| + "bufio" |
| + "bytes" |
| + "context" |
| + "crypto/ecdsa" |
| + "crypto/ed25519" |
| + "crypto/elliptic" |
| + "crypto/rand" |
| + "crypto/sha256" |
| + "crypto/subtle" |
| + "crypto/tls" |
| + "crypto/x509" |
| + "crypto/x509/pkix" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "maps" |
| + "math/big" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/netip" |
| + "net/url" |
| + "slices" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/hostedctl/ctlproxy" |
| + "amadan.net/oficina/equipo/internal/hostedproxy" |
| + "amadan.net/oficina/equipo/internal/hostedwire" |
| + "amadan.net/oficina/equipo/internal/isolatedjob" |
| + "github.com/coder/websocket" |
| +) |
| + |
| +// The service host and the other host, and the public test addresses the |
| +// harness resolver answers for them (the harness dialer sends each to its |
| +// origin on 127.0.0.1). |
| +const ( |
| + Host = "instance.example.test" |
| + OtherHost = "other.example.test" |
| + hostAddr = "203.0.113.10" |
| + otherAddr = "203.0.113.20" |
| +) |
| + |
| +// The default launch: l-1, attempt a-1, VM vm-1, epoch 2, allowed Host. |
| +const ( |
| + LaunchID = "l-1" |
| + AttemptID = "a-1" |
| + VMRef = isolatedjob.Ref("vm-1") |
| + Epoch = 2 |
| + ProxyKey = hostedwire.KeyID("proxy-1") |
| +) |
| + |
| +// FakeMono is a hostedproxy.Clock tests move by hand. Wall starts at the |
| +// real time (whole seconds), so the proxy's leaves are valid to a real |
| +// TLS stack too; Mono starts at an hour. |
| +type FakeMono struct { |
| + mu sync.Mutex |
| + mono time.Duration |
| + wall time.Time |
| + waiters []waiter |
| +} |
| + |
| +type waiter struct { |
| + at time.Duration |
| + ch chan time.Time |
| +} |
| + |
| +func newFakeMono() *FakeMono { |
| + return &FakeMono{mono: time.Hour, wall: time.Now().UTC().Truncate(time.Second)} |
| +} |
| + |
| +func (c *FakeMono) Mono() time.Duration { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + return c.mono |
| +} |
| + |
| +func (c *FakeMono) Wall() time.Time { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + return c.wall |
| +} |
| + |
| +func (c *FakeMono) After(d time.Duration) <-chan time.Time { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + ch := make(chan time.Time, 1) |
| + if d <= 0 { |
| + ch <- c.wall |
| + return ch |
| + } |
| + c.waiters = append(c.waiters, waiter{at: c.mono + d, ch: ch}) |
| + return ch |
| +} |
| + |
| +// Advance moves both clocks on by d and fires every timer due. |
| +func (c *FakeMono) Advance(d time.Duration) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + c.mono += d |
| + c.wall = c.wall.Add(d) |
| + kept := c.waiters[:0] |
| + for _, w := range c.waiters { |
| + if w.at <= c.mono { |
| + w.ch <- c.wall |
| + continue |
| + } |
| + kept = append(kept, w) |
| + } |
| + c.waiters = kept |
| +} |
| + |
| +// WaitTimer waits (real time, bounded) until a timer is set to fire at |
| +// exactly at, so an Advance past it cannot race the code setting it. It |
| +// does not fail the test when none is set: the caller's own assertions |
| +// judge what the missing timer did not do. |
| +func (c *FakeMono) WaitTimer(t testing.TB, at time.Duration) { |
| + t.Helper() |
| + deadline := time.Now().Add(2 * time.Second) |
| + for time.Now().Before(deadline) { |
| + c.mu.Lock() |
| + found := slices.ContainsFunc(c.waiters, func(w waiter) bool { return w.at == at }) |
| + c.mu.Unlock() |
| + if found { |
| + return |
| + } |
| + time.Sleep(time.Millisecond) |
| + } |
| + t.Logf("no timer set for mono %v; going on", at) |
| +} |
| + |
| +// LogLine is one line of the proxy's decision log. |
| +type LogLine struct { |
| + VM string `json:"vm"` |
| + Launch string `json:"launch"` |
| + Attempt string `json:"attempt"` |
| + Epoch int64 `json:"epoch"` |
| + Destination string `json:"destination"` |
| + Method string `json:"method"` |
| + PathClass string `json:"path_class"` |
| + Route string `json:"route"` |
| + Decision string `json:"decision"` |
| + Reason string `json:"reason"` |
| + Status int `json:"status"` |
| + BytesIn int64 `json:"bytes_in"` |
| + BytesOut int64 `json:"bytes_out"` |
| +} |
| + |
| +// Log is the proxy's decision log. |
| +type Log struct { |
| + mu sync.Mutex |
| + b bytes.Buffer |
| +} |
| + |
| +func (l *Log) Write(p []byte) (int, error) { |
| + l.mu.Lock() |
| + defer l.mu.Unlock() |
| + return l.b.Write(p) |
| +} |
| + |
| +func (l *Log) String() string { |
| + l.mu.Lock() |
| + defer l.mu.Unlock() |
| + return l.b.String() |
| +} |
| + |
| +// Lines decodes the log so far. |
| +func (l *Log) Lines(t testing.TB) []LogLine { |
| + t.Helper() |
| + var out []LogLine |
| + for _, s := range strings.Split(strings.TrimSpace(l.String()), "\n") { |
| + if s == "" { |
| + continue |
| + } |
| + var ll LogLine |
| + if err := json.Unmarshal([]byte(s), &ll); err != nil { |
| + t.Fatalf("decision log line %q: %v", s, err) |
| + } |
| + out = append(out, ll) |
| + } |
| + return out |
| +} |
| + |
| +// Wait waits (real time, bounded) for a line after the first from lines |
| +// that matches fn, and returns it. |
| +func (l *Log) Wait(t testing.TB, what string, from int, fn func(LogLine) bool) LogLine { |
| + t.Helper() |
| + deadline := time.Now().Add(5 * time.Second) |
| + for time.Now().Before(deadline) { |
| + lines := l.Lines(t) |
| + for _, ll := range lines[min(from, len(lines)):] { |
| + if fn(ll) { |
| + return ll |
| + } |
| + } |
| + time.Sleep(5 * time.Millisecond) |
| + } |
| + t.Fatalf("no decision line for %s after line %d in:\n%s", what, from, l.String()) |
| + return LogLine{} |
| +} |
| + |
| +// Launch is one launch the fake controller knows. Deadline (wall) caps the |
| +// certificates it issues, as the controller's launch deadline does. |
| +type Launch struct { |
| + LaunchID, AttemptID string |
| + VMRef isolatedjob.Ref |
| + Epoch int64 |
| + Code string |
| + Deadline time.Time |
| + Services []hostedwire.Service |
| +} |
| + |
| +// issued is one serial the fake controller signed. |
| +type issued struct { |
| + launch ctlproxy.LaunchIdentity |
| + pub *ecdsa.PublicKey |
| + notAfter time.Time |
| + renewed, revoked bool |
| +} |
| + |
| +// Report is a certification report the fake controller accepted, with the |
| +// identity it took from the serial's record. |
| +type Report struct { |
| + Launch ctlproxy.LaunchIdentity |
| + Serial string |
| + Body []byte |
| +} |
| + |
| +// Received is one request the fake controller got, as it arrived. |
| +type Received struct { |
| + Route string |
| + Header http.Header |
| + Body []byte |
| +} |
| + |
| +// FakeController is the controller's proxy side: it verifies the proxy's |
| +// signature on every request, signs every answer for its nonce, serves the |
| +// feed, redeems proxy codes, renews and revokes certificates, and accepts |
| +// certification reports by Task 13's rule (a serial it issued, unrevoked, |
| +// signed by that certificate's key; no identity in any header). |
| +type FakeController struct { |
| + clock *FakeMono |
| + srv *httptest.Server |
| + key ed25519.PrivateKey |
| + verifier *hostedwire.Verifier |
| + ca *x509.Certificate |
| + caKey *ecdsa.PrivateKey |
| + caPool *x509.CertPool |
| + |
| + mu sync.Mutex |
| + launches map[string]*Launch |
| + used map[string]bool // launch -> code redeemed |
| + certs map[string]*issued |
| + feedSer int64 |
| + nonces map[string]bool |
| + reports []Report |
| + received []Received |
| +} |
| + |
| +// identityHeaders are header names a request to the controller may carry: |
| +// the proxy's signature and transport headers. Any other is refused, so no |
| +// header can name a VM, launch or serial (Task 13: headers carry no |
| +// identity). |
| +var identityHeaders = map[string]bool{ |
| + hostedwire.HeaderKeyID: true, hostedwire.HeaderTimestamp: true, hostedwire.HeaderNonce: true, |
| + hostedwire.HeaderSignature: true, "Content-Type": true, "Content-Length": true, "Accept-Encoding": true, |
| + "User-Agent": true, |
| +} |
| + |
| +func newFakeController(t testing.TB, clock *FakeMono, proxyPub ed25519.PublicKey) *FakeController { |
| + _, key, err := ed25519.GenerateKey(rand.Reader) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + caKey, ca, pool := newCA(t, "fake controller client CA") |
| + c := &FakeController{clock: clock, key: key, ca: ca, caKey: caKey, caPool: pool, |
| + launches: map[string]*Launch{}, used: map[string]bool{}, certs: map[string]*issued{}, nonces: map[string]bool{}} |
| + c.verifier = &hostedwire.Verifier{Keys: map[hostedwire.KeyID]hostedwire.VerifyKey{ProxyKey: {Public: proxyPub, Role: hostedwire.RoleProxy}}, |
| + Nonces: c, Now: clock.Wall} |
| + c.srv = httptest.NewUnstartedServer(http.HandlerFunc(c.serve)) |
| + c.srv.Listener.Close() |
| + ln, err := net.Listen("tcp", "127.0.0.1:0") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + c.srv.Listener = ln |
| + c.srv.StartTLS() |
| + t.Cleanup(c.srv.Close) |
| + return c |
| +} |
| + |
| +// Remember is the controller's nonce store. |
| +func (c *FakeController) Remember(_ context.Context, id hostedwire.KeyID, nonce string, _ time.Time) (bool, error) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + k := string(id) + "/" + nonce |
| + if c.nonces[k] { |
| + return false, nil |
| + } |
| + c.nonces[k] = true |
| + return true, nil |
| +} |
| + |
| +// Pool is the client CA: the only issuer of VM certificates. |
| +func (c *FakeController) Pool() *x509.CertPool { return c.caPool } |
| + |
| +// Addr is the controller's own listener (not the proxy's partitioned path |
| +// to it). |
| +func (c *FakeController) Addr() string { return c.srv.Listener.Addr().String() } |
| + |
| +// SetLaunch adds or replaces a launch. |
| +func (c *FakeController) SetLaunch(l Launch) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + c.launches[l.LaunchID] = &l |
| +} |
| + |
| +// SetEpoch moves a launch to epoch without revoking any serial. |
| +func (c *FakeController) SetEpoch(launchID string, epoch int64) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + c.launches[launchID].Epoch = epoch |
| +} |
| + |
| +// Revoke revokes serial, as a stop does. |
| +func (c *FakeController) Revoke(serial string) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + if s, ok := c.certs[serial]; ok { |
| + s.revoked = true |
| + } |
| +} |
| + |
| +// Reports are the certification reports accepted. |
| +func (c *FakeController) Reports() []Report { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + return slices.Clone(c.reports) |
| +} |
| + |
| +// Received are the requests the controller got on route ("" for all). |
| +func (c *FakeController) Received(route string) []Received { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + var out []Received |
| + for _, r := range c.received { |
| + if route == "" || r.Route == route { |
| + out = append(out, r) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// Issue signs a client certificate for launchID's current identity and |
| +// pub, as a redemption or renewal does: NotAfter is the earlier of |
| +// ctlproxy.CertLifetime and the launch's deadline, in whole seconds. |
| +func (c *FakeController) Issue(launchID string, pub *ecdsa.PublicKey) ([]byte, error) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + return c.issueLocked(c.launches[launchID], pub) |
| +} |
| + |
| +func (c *FakeController) issueLocked(l *Launch, pub *ecdsa.PublicKey) ([]byte, error) { |
| + if l == nil { |
| + return nil, errors.New("no such launch") |
| + } |
| + now := c.clock.Wall() |
| + notAfter := now.Add(ctlproxy.CertLifetime) |
| + if !l.Deadline.IsZero() && l.Deadline.Before(notAfter) { |
| + notAfter = l.Deadline |
| + } |
| + notAfter = notAfter.Truncate(time.Second) |
| + if !notAfter.After(now) { |
| + return nil, errors.New("launch past its deadline") |
| + } |
| + n, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128)) |
| + if err != nil { |
| + return nil, err |
| + } |
| + n.Add(n, big.NewInt(1)) |
| + id := ctlproxy.LaunchIdentity{LaunchID: l.LaunchID, AttemptID: l.AttemptID, VMRef: l.VMRef, Epoch: l.Epoch} |
| + der, err := x509.CreateCertificate(rand.Reader, &x509.Certificate{SerialNumber: n, Subject: pkix.Name{CommonName: l.LaunchID}, |
| + NotBefore: now.Add(-time.Minute), NotAfter: notAfter, KeyUsage: x509.KeyUsageDigitalSignature, |
| + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, BasicConstraintsValid: true, URIs: []*url.URL{id.URI()}}, |
| + c.ca, pub, c.caKey) |
| + if err != nil { |
| + return nil, err |
| + } |
| + c.certs[n.Text(16)] = &issued{launch: id, pub: pub, notAfter: notAfter} |
| + return der, nil |
| +} |
| + |
| +// feed is the current feed: every launch, every revoked or renewed serial. |
| +func (c *FakeController) feed() hostedwire.ProxyFeed { |
| + c.feedSer++ |
| + f := hostedwire.ProxyFeed{Version: ctlproxy.FeedVersion, Serial: c.feedSer, IssuedNS: c.clock.Wall().UnixNano(), |
| + TTLMS: ctlproxy.FeedLifetime.Milliseconds(), Launches: []hostedwire.FeedLaunch{}, Revoked: []string{}} |
| + for _, id := range slices.Sorted(maps.Keys(c.launches)) { |
| + l := c.launches[id] |
| + f.Launches = append(f.Launches, hostedwire.FeedLaunch{LaunchID: l.LaunchID, AttemptID: l.AttemptID, VMRef: l.VMRef, |
| + Epoch: l.Epoch, Services: slices.Clone(l.Services), ProxyCodeHash: ctlproxy.CodeHash(l.Code)}) |
| + } |
| + for _, s := range slices.Sorted(maps.Keys(c.certs)) { |
| + if c.certs[s].revoked { |
| + f.Revoked = append(f.Revoked, s) |
| + } |
| + } |
| + return f |
| +} |
| + |
| +// refusal is a controller refusal: a status and a code. |
| +type refusal struct { |
| + status int |
| + code string |
| +} |
| + |
| +func (r refusal) Error() string { return r.code } |
| + |
| +func refuse(code string) error { return refusal{http.StatusForbidden, code} } |
| + |
| +func (c *FakeController) serve(w http.ResponseWriter, r *http.Request) { |
| + body, _ := io.ReadAll(io.LimitReader(r.Body, hostedwire.MaxBody+1)) |
| + if _, _, err := c.verifier.Verify(r, body); err != nil { |
| + http.Error(w, "unsigned", http.StatusUnauthorized) |
| + return |
| + } |
| + nonce := r.Header.Get(hostedwire.HeaderNonce) |
| + c.mu.Lock() |
| + c.received = append(c.received, Received{Route: r.Method + " " + r.URL.Path, Header: r.Header.Clone(), Body: body}) |
| + out, err := c.route(r, body) |
| + c.mu.Unlock() |
| + status := http.StatusOK |
| + if err != nil { |
| + rf, ok := err.(refusal) |
| + if !ok { |
| + rf = refusal{http.StatusBadRequest, "bad_request"} |
| + } |
| + status, out = rf.status, hostedwire.ErrorResponse{Code: rf.code, Message: http.StatusText(rf.status)} |
| + } |
| + raw, _ := json.Marshal(out) |
| + hostedwire.SignResponse(w.Header(), status, nonce, raw, c.key) |
| + w.Header().Set("Content-Type", "application/json") |
| + w.WriteHeader(status) |
| + _, _ = w.Write(raw) |
| +} |
| + |
| +// route answers one verified request; c.mu is held. |
| +func (c *FakeController) route(r *http.Request, body []byte) (any, error) { |
| + for name := range r.Header { |
| + if !identityHeaders[name] { |
| + return nil, refusal{http.StatusBadRequest, "identity_header"} |
| + } |
| + } |
| + switch r.Method + " " + r.URL.Path { |
| + case "GET /v1/proxy/feed": |
| + return c.feed(), nil |
| + case "POST /v1/proxy/redeem": |
| + var q hostedwire.RedeemRequest |
| + if err := hostedwire.DecodeStrict(bytes.NewReader(body), &q); err != nil { |
| + return nil, err |
| + } |
| + l, ok := c.launches[q.LaunchID] |
| + switch { |
| + case !ok || l.VMRef != q.VMRef: |
| + return nil, refuse("not_live") |
| + case subtle.ConstantTimeCompare([]byte(q.ProxyCode), []byte(l.Code)) != 1: |
| + return nil, refuse("wrong_code") |
| + case c.used[q.LaunchID]: |
| + return nil, refuse("code_used") |
| + } |
| + pub, err := csrKey(q.CSR) |
| + if err != nil { |
| + return nil, err |
| + } |
| + c.used[q.LaunchID] = true |
| + return c.answer(l, pub) |
| + case "POST /v1/proxy/renew": |
| + var q hostedwire.RenewCertRequest |
| + if err := hostedwire.DecodeStrict(bytes.NewReader(body), &q); err != nil { |
| + return nil, err |
| + } |
| + old, ok := c.certs[q.Serial] |
| + switch { |
| + case !ok: |
| + return nil, refuse("unknown_serial") |
| + case old.renewed: |
| + return nil, refuse("already_renewed") |
| + case old.revoked: |
| + return nil, refuse("revoked") |
| + case !c.clock.Wall().Before(old.notAfter): |
| + return nil, refuse("cert_expired") |
| + } |
| + l, ok := c.launches[old.launch.LaunchID] |
| + switch { |
| + case !ok || l.VMRef != old.launch.VMRef: |
| + return nil, refuse("not_live") |
| + case l.Epoch != old.launch.Epoch: |
| + return nil, refuse("wrong_epoch") |
| + } |
| + pub, err := csrKey(q.CSR) |
| + if err != nil { |
| + return nil, err |
| + } |
| + old.renewed, old.revoked = true, true |
| + return c.answer(l, pub) |
| + case "POST /v1/proxy/cert-report": |
| + var q hostedwire.CertReport |
| + if err := hostedwire.DecodeStrict(bytes.NewReader(body), &q); err != nil { |
| + return nil, err |
| + } |
| + s, ok := c.certs[q.Serial] |
| + switch { |
| + case !ok: |
| + return nil, refuse("unknown_serial") |
| + case s.revoked: |
| + return nil, refuse("revoked") |
| + } |
| + sum := sha256.Sum256(hostedwire.CertReportMessage(q.Serial, q.Report)) |
| + if !ecdsa.VerifyASN1(s.pub, sum[:], q.Sig) { |
| + return nil, refuse("bad_signature") |
| + } |
| + c.reports = append(c.reports, Report{Launch: s.launch, Serial: q.Serial, Body: slices.Clone(q.Report)}) |
| + return struct{}{}, nil |
| + } |
| + return nil, refusal{http.StatusNotFound, "not_found"} |
| +} |
| + |
| +func (c *FakeController) answer(l *Launch, pub *ecdsa.PublicKey) (any, error) { |
| + der, err := c.issueLocked(l, pub) |
| + if err != nil { |
| + return nil, refuse("not_live") |
| + } |
| + return hostedwire.RedeemResponse{Cert: der, NotAfterNS: 1}, nil |
| +} |
| + |
| +func csrKey(der []byte) (*ecdsa.PublicKey, error) { |
| + r, err := x509.ParseCertificateRequest(der) |
| + if err != nil || r.CheckSignature() != nil { |
| + return nil, refusal{http.StatusBadRequest, "bad_csr"} |
| + } |
| + pub, ok := r.PublicKey.(*ecdsa.PublicKey) |
| + if !ok || pub.Curve != elliptic.P256() { |
| + return nil, refusal{http.StatusBadRequest, "bad_csr"} |
| + } |
| + return pub, nil |
| +} |
| + |
| +// SignedCall sends a request straight to the controller (not through the |
| +// proxy) signed with key as ProxyKey, with extra headers, and returns the |
| +// status and the error code, if any. It stands in for a proxy that would |
| +// forward what the real one does not. |
| +func (c *FakeController) SignedCall(t testing.TB, key ed25519.PrivateKey, path string, body []byte, extra http.Header) (int, string) { |
| + t.Helper() |
| + req, _ := http.NewRequest(http.MethodPost, c.srv.URL+path, bytes.NewReader(body)) |
| + for k, v := range extra { |
| + req.Header[k] = v |
| + } |
| + req.Header.Set("Content-Type", "application/json") |
| + nonce, _ := hostedwire.NewNonce() |
| + if err := hostedwire.SignRequest(req, body, ProxyKey, key, c.clock.Wall(), nonce); err != nil { |
| + t.Fatal(err) |
| + } |
| + resp, err := c.srv.Client().Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer resp.Body.Close() |
| + var e hostedwire.ErrorResponse |
| + _ = json.NewDecoder(resp.Body).Decode(&e) |
| + return resp.StatusCode, e.Code |
| +} |
| + |
| +// partition is the proxy's only path to the controller: a TCP relay on |
| +// 127.0.0.1 that can be cut while the controller stays up. |
| +type partition struct { |
| + ln net.Listener |
| + target string |
| + mu sync.Mutex |
| + cut bool |
| + refused int |
| + conns map[net.Conn]struct{} |
| + accepted sync.WaitGroup |
| +} |
| + |
| +func newPartition(t testing.TB, target string) *partition { |
| + ln, err := net.Listen("tcp", "127.0.0.1:0") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + p := &partition{ln: ln, target: target, cut: true, conns: map[net.Conn]struct{}{}} |
| + p.accepted.Add(1) |
| + go p.run() |
| + t.Cleanup(func() { ln.Close(); p.set(true); p.accepted.Wait() }) |
| + return p |
| +} |
| + |
| +func (p *partition) run() { |
| + defer p.accepted.Done() |
| + for { |
| + c, err := p.ln.Accept() |
| + if err != nil { |
| + return |
| + } |
| + p.mu.Lock() |
| + if p.cut { |
| + p.refused++ |
| + p.mu.Unlock() |
| + c.Close() |
| + continue |
| + } |
| + up, err := net.Dial("tcp", p.target) |
| + if err != nil { |
| + p.mu.Unlock() |
| + c.Close() |
| + continue |
| + } |
| + p.conns[c], p.conns[up] = struct{}{}, struct{}{} |
| + p.mu.Unlock() |
| + go func() { _, _ = io.Copy(up, c); up.Close() }() |
| + go func() { _, _ = io.Copy(c, up); c.Close() }() |
| + } |
| +} |
| + |
| +// set cuts (true) or heals the path; cutting closes every relayed |
| +// connection. |
| +func (p *partition) set(cut bool) { |
| + p.mu.Lock() |
| + defer p.mu.Unlock() |
| + p.cut = cut |
| + if cut { |
| + for c := range p.conns { |
| + c.Close() |
| + } |
| + p.conns = map[net.Conn]struct{}{} |
| + } |
| +} |
| + |
| +func (p *partition) refusals() int { |
| + p.mu.Lock() |
| + defer p.mu.Unlock() |
| + return p.refused |
| +} |
| + |
| +// Harness is one proxy on 127.0.0.1 with its fake controller and origins. |
| +type Harness struct { |
| + Proxy *hostedproxy.Server |
| + Origin *httptest.Server // Host |
| + Other *httptest.Server // OtherHost, never in a manifest |
| + Controller *FakeController |
| + Clock *FakeMono |
| + Log *Log |
| + |
| + // InterceptPool holds only the intercept CA; InterceptPin is the hex |
| + // SHA-256 of its SPKI (the bootstrap's ProxyCAPin). |
| + InterceptPool *x509.CertPool |
| + InterceptPin string |
| + // ProxyKey is the proxy's signing key (role proxy). |
| + ProxyKey ed25519.PrivateKey |
| + |
| + t testing.TB |
| + originHits atomic.Int64 |
| + otherHits atomic.Int64 |
| + part *partition |
| +} |
| + |
| +// New starts a harness: the default launch in the controller's feed, the |
| +// proxy started and holding its first feed, polled once at the current |
| +// Mono. |
| +func New(t testing.TB) *Harness { |
| + t.Helper() |
| + h := &Harness{Clock: newFakeMono(), Log: &Log{}, t: t} |
| + proxyPub, proxyKey, err := ed25519.GenerateKey(rand.Reader) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + h.ProxyKey = proxyKey |
| + h.Controller = newFakeController(t, h.Clock, proxyPub) |
| + h.Controller.SetLaunch(Launch{LaunchID: LaunchID, AttemptID: AttemptID, VMRef: VMRef, Epoch: Epoch, |
| + Code: strings.Repeat("C", len(ctlproxy.CodePlaceholder)), |
| + Services: []hostedwire.Service{{Host: Host, Port: hostedproxy.ServicePort, Class: hostedwire.ServiceInstance}}}) |
| + // The proxy reaches the controller only through the partition, cut |
| + // until its own first poll has failed, so the only feed it holds is |
| + // the one New installs below. |
| + h.part = newPartition(t, h.Controller.Addr()) |
| + |
| + originKey, originCA, originPool := newCA(t, "origin CA") |
| + h.Origin = h.startOrigin(originCA, originKey, Host, &h.originHits) |
| + h.Other = h.startOrigin(originCA, originKey, OtherHost, &h.otherHits) |
| + |
| + icKey, ic, icPool := newCA(t, "intercept CA") |
| + sum := sha256.Sum256(ic.RawSubjectPublicKeyInfo) |
| + h.InterceptPool, h.InterceptPin = icPool, hex.EncodeToString(sum[:]) |
| + |
| + dials := map[string]string{hostAddr + ":443": h.Origin.Listener.Addr().String(), |
| + otherAddr + ":443": h.Other.Listener.Addr().String()} |
| + srv, err := hostedproxy.NewServer(hostedproxy.Config{ |
| + Egress: netip.MustParseAddrPort("127.0.0.1:0"), Boot: netip.MustParseAddrPort("127.0.0.1:0"), |
| + ControllerURL: "https://" + h.part.ln.Addr().String(), ControllerKey: h.Controller.key.Public().(ed25519.PublicKey), |
| + ControllerTLSPin: spkiPin(h.Controller.srv.Certificate()), KeyID: ProxyKey, Key: proxyKey, |
| + ClientCA: h.Controller.Pool(), InterceptCA: tls.Certificate{Certificate: [][]byte{ic.Raw}, PrivateKey: icKey, Leaf: ic}, |
| + OriginRoots: originPool, Log: h.Log, Clock: h.Clock, Resolver: resolver{}, |
| + DialOrigin: func(ctx context.Context, network, addr string) (net.Conn, error) { |
| + to, ok := dials[addr] |
| + if !ok { |
| + return nil, fmt.Errorf("proxytest: dial to %s", addr) |
| + } |
| + var d net.Dialer |
| + return d.DialContext(ctx, network, to) |
| + }, |
| + }) |
| + if err != nil { |
| + t.Fatalf("NewServer: %v", err) |
| + } |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + if err := srv.Start(ctx); err != nil { |
| + cancel() |
| + t.Fatalf("Start: %v", err) |
| + } |
| + t.Cleanup(func() { cancel(); _ = srv.Close() }) |
| + h.Proxy = srv |
| + deadline := time.Now().Add(10 * time.Second) |
| + for h.part.refusals() == 0 { |
| + if time.Now().After(deadline) { |
| + t.Fatal("the proxy's first poll never reached the partition") |
| + } |
| + time.Sleep(time.Millisecond) |
| + } |
| + h.part.set(false) |
| + if err := srv.Poll(ctx); err != nil { |
| + t.Fatalf("Poll: %v", err) |
| + } |
| + return h |
| +} |
| + |
| +// Partition cuts (true) or heals the proxy's path to the controller; the |
| +// controller itself stays up. |
| +func (h *Harness) Partition(cut bool) { h.part.set(cut) } |
| + |
| +// Hits is how many requests reached the service origin and the other |
| +// host's origin. |
| +func (h *Harness) Hits() (origin, other int64) { return h.originHits.Load(), h.otherHits.Load() } |
| + |
| +// startOrigin is a TLS origin for name on 127.0.0.1: GET |
| +// /api/runner/protocol answers "protocol 39", GET /api/runner/stream is a |
| +// WebSocket echo, anything else answers its method and path. |
| +func (h *Harness) startOrigin(caCert *x509.Certificate, caKey *ecdsa.PrivateKey, name string, hits *atomic.Int64) *httptest.Server { |
| + leaf := issueServer(h.t, caCert, caKey, name) |
| + srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + hits.Add(1) |
| + switch r.URL.Path { |
| + case "/api/runner/protocol": |
| + _, _ = io.WriteString(w, "protocol 39") |
| + case "/api/runner/stream": |
| + ws, err := websocket.Accept(w, r, nil) |
| + if err != nil { |
| + return |
| + } |
| + defer ws.CloseNow() |
| + for { |
| + typ, msg, err := ws.Read(r.Context()) |
| + if err != nil { |
| + return |
| + } |
| + if err := ws.Write(r.Context(), typ, msg); err != nil { |
| + return |
| + } |
| + } |
| + default: |
| + _, _ = io.WriteString(w, r.Method+" "+r.URL.Path) |
| + } |
| + })) |
| + srv.Listener.Close() |
| + ln, err := net.Listen("tcp", "127.0.0.1:0") |
| + if err != nil { |
| + h.t.Fatal(err) |
| + } |
| + srv.Listener = ln |
| + srv.TLS = &tls.Config{Certificates: []tls.Certificate{leaf}} |
| + srv.StartTLS() |
| + h.t.Cleanup(srv.Close) |
| + return srv |
| +} |
| + |
| +// resolver answers Host and OtherHost with their public test addresses. |
| +type resolver struct{} |
| + |
| +func (resolver) LookupNetIP(_ context.Context, network, host string) ([]netip.Addr, error) { |
| + switch { |
| + case network != "ip": |
| + case strings.EqualFold(host, Host): |
| + return []netip.Addr{netip.MustParseAddr(hostAddr)}, nil |
| + case strings.EqualFold(host, OtherHost): |
| + return []netip.Addr{netip.MustParseAddr(otherAddr)}, nil |
| + } |
| + return nil, fmt.Errorf("lookup %s %s: no such host", network, host) |
| +} |
| + |
| +// VM is one VM's proxy credential: its key and the certificate the |
| +// controller issued for it. |
| +type VM struct { |
| + Key *ecdsa.PrivateKey |
| + Cert tls.Certificate |
| +} |
| + |
| +// Serial is the certificate's serial as the controller writes it. |
| +func (v *VM) Serial() string { return v.Cert.Leaf.SerialNumber.Text(16) } |
| + |
| +// Identity is what the certificate binds the VM to. |
| +func (v *VM) Identity(t testing.TB) hostedproxy.Identity { |
| + t.Helper() |
| + id, err := hostedproxy.IdentityFromCert(v.Cert.Leaf) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return id |
| +} |
| + |
| +// CSR is a fresh VM key and its certificate request (DER). |
| +func CSR(t testing.TB) (*ecdsa.PrivateKey, []byte) { |
| + t.Helper() |
| + k, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + der, err := x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{Subject: pkix.Name{CommonName: "vm"}}, k) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return k, der |
| +} |
| + |
| +// VMFromDER pairs a certificate (DER) with its key. |
| +func VMFromDER(t testing.TB, key *ecdsa.PrivateKey, der []byte) *VM { |
| + t.Helper() |
| + c, err := x509.ParseCertificate(der) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return &VM{Key: key, Cert: tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key, Leaf: c}} |
| +} |
| + |
| +// Redeem redeems launch l-1's proxy code through the bootstrap listener, |
| +// as a fresh VM does, and returns the VM's credential. |
| +func (h *Harness) Redeem(t testing.TB) *VM { |
| + t.Helper() |
| + key, csr := CSR(t) |
| + body, _ := json.Marshal(hostedwire.RedeemRequest{LaunchID: LaunchID, VMRef: VMRef, |
| + ProxyCode: strings.Repeat("C", len(ctlproxy.CodePlaceholder)), CSR: csr}) |
| + status, out := h.Boot(t, nil, "/redeem", body, nil) |
| + if status != http.StatusOK { |
| + t.Fatalf("redeem: %d %s", status, out) |
| + } |
| + var r hostedwire.RedeemResponse |
| + if err := json.Unmarshal(out, &r); err != nil { |
| + t.Fatal(err) |
| + } |
| + return VMFromDER(t, key, r.Cert) |
| +} |
| + |
| +// Issue has the controller issue a certificate for launchID straight away |
| +// (no proxy code), for a VM key made here. |
| +func (h *Harness) Issue(t testing.TB, launchID string) *VM { |
| + t.Helper() |
| + key, _ := CSR(t) |
| + der, err := h.Controller.Issue(launchID, &key.PublicKey) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return VMFromDER(t, key, der) |
| +} |
| + |
| +// RenewBody is a renewal request for vm's serial with a fresh key. |
| +func RenewBody(t testing.TB, vm *VM) (*ecdsa.PrivateKey, []byte) { |
| + t.Helper() |
| + key, csr := CSR(t) |
| + body, _ := json.Marshal(hostedwire.RenewCertRequest{Serial: vm.Serial(), CSR: csr}) |
| + return key, body |
| +} |
| + |
| +// ReportBody is a certification report for vm's serial, signed with key |
| +// (vm's own key unless another is given) over CertReportMessage: ECDSA |
| +// over SHA-256, ASN.1. |
| +func ReportBody(t testing.TB, serial string, report []byte, key *ecdsa.PrivateKey) []byte { |
| + t.Helper() |
| + sum := sha256.Sum256(hostedwire.CertReportMessage(serial, report)) |
| + sig, err := ecdsa.SignASN1(rand.Reader, key, sum[:]) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + body, _ := json.Marshal(hostedwire.CertReport{Serial: serial, Report: report, Sig: sig}) |
| + return body |
| +} |
| + |
| +// Boot posts body to the bootstrap listener's path over server TLS pinned |
| +// to the intercept CA, with vm's certificate when vm is not nil, and extra |
| +// headers. It returns the status and body. |
| +func (h *Harness) Boot(t testing.TB, vm *VM, path string, body []byte, extra http.Header) (int, []byte) { |
| + t.Helper() |
| + cfg := h.proxyTLS(h.Proxy.BootAddr(), vm) |
| + c := &http.Client{Transport: &http.Transport{TLSClientConfig: cfg, Proxy: nil}, Timeout: 10 * time.Second} |
| + defer c.CloseIdleConnections() |
| + req, _ := http.NewRequest(http.MethodPost, "https://"+h.Proxy.BootAddr().String()+path, bytes.NewReader(body)) |
| + for k, v := range extra { |
| + req.Header[k] = v |
| + } |
| + req.Header.Set("Content-Type", "application/json") |
| + resp, err := c.Do(req) |
| + if err != nil { |
| + return 0, []byte(err.Error()) |
| + } |
| + defer resp.Body.Close() |
| + out, _ := io.ReadAll(resp.Body) |
| + return resp.StatusCode, out |
| +} |
| + |
| +// proxyTLS is the client side of mutual TLS to a proxy listener at addr: |
| +// the intercept CA alone as root, its SPKI pinned, HTTP/1.1. |
| +func (h *Harness) proxyTLS(addr netip.AddrPort, vm *VM) *tls.Config { |
| + cfg := &tls.Config{ServerName: addr.Addr().String(), RootCAs: h.InterceptPool, NextProtos: []string{hostedproxy.ALPNHTTP11}, |
| + MinVersion: tls.VersionTLS12, VerifyConnection: h.pinned} |
| + if vm != nil { |
| + // Sent whatever CAs the proxy names, as a forger would. |
| + cfg.GetClientCertificate = func(*tls.CertificateRequestInfo) (*tls.Certificate, error) { return &vm.Cert, nil } |
| + } |
| + return cfg |
| +} |
| + |
| +// pinned checks that the verified chain ends at the intercept CA whose |
| +// SPKI is InterceptPin. |
| +func (h *Harness) pinned(cs tls.ConnectionState) error { |
| + for _, chain := range cs.VerifiedChains { |
| + root := chain[len(chain)-1] |
| + sum := sha256.Sum256(root.RawSubjectPublicKeyInfo) |
| + if hex.EncodeToString(sum[:]) == h.InterceptPin { |
| + return nil |
| + } |
| + } |
| + return errors.New("proxytest: the proxy's chain does not end at the pinned intercept CA") |
| +} |
| + |
| +// Client is the hosted runner's HTTP client as Task 12 builds it, with |
| +// vm's credential: no environment proxy; each connection is mutual TLS to |
| +// the proxy's egress listener, CONNECT host:443, then TLS to host with the |
| +// intercept CA alone as root (SPKI pinned), ServerName host, ALPN |
| +// http/1.1. Redirects are not followed. Task 12 replaces this with the |
| +// runner's own transport. |
| +func (h *Harness) Client(vm *VM) *http.Client { |
| + return &http.Client{ |
| + Transport: &http.Transport{ |
| + Proxy: nil, ForceAttemptHTTP2: false, TLSNextProto: map[string]func(string, *tls.Conn) http.RoundTripper{}, |
| + DialTLSContext: func(ctx context.Context, _, addr string) (net.Conn, error) { |
| + host, port, err := net.SplitHostPort(addr) |
| + if err != nil || port != "443" { |
| + return nil, fmt.Errorf("proxytest: %s is not host:443", addr) |
| + } |
| + c, status, err := h.Connect(ctx, vm, net.JoinHostPort(host, "443")) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if status != http.StatusOK { |
| + return nil, fmt.Errorf("proxytest: CONNECT %s: %d", addr, status) |
| + } |
| + inner := tls.Client(c, &tls.Config{ServerName: host, RootCAs: h.InterceptPool, |
| + NextProtos: []string{hostedproxy.ALPNHTTP11}, MinVersion: tls.VersionTLS12, VerifyConnection: h.pinned}) |
| + if err := inner.HandshakeContext(ctx); err != nil { |
| + c.Close() |
| + return nil, err |
| + } |
| + return inner, nil |
| + }, |
| + }, |
| + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, |
| + } |
| +} |
| + |
| +// Connect opens mutual TLS to the egress listener with vm's certificate |
| +// (nil: none) and sends CONNECT target. It returns the tunnel after the |
| +// proxy's 200, or the proxy's status. |
| +func (h *Harness) Connect(ctx context.Context, vm *VM, target string) (net.Conn, int, error) { |
| + var d tls.Dialer |
| + d.Config = h.proxyTLS(h.Proxy.EgressAddr(), vm) |
| + raw, err := d.DialContext(ctx, "tcp", h.Proxy.EgressAddr().String()) |
| + if err != nil { |
| + return nil, 0, err |
| + } |
| + c := raw.(*tls.Conn) |
| + _ = c.SetDeadline(time.Now().Add(5 * time.Second)) |
| + if _, err := fmt.Fprintf(c, "CONNECT %s HTTP/1.1\r\nHost: %s\r\n\r\n", target, target); err != nil { |
| + c.Close() |
| + return nil, 0, err |
| + } |
| + br := bufio.NewReader(c) |
| + resp, err := http.ReadResponse(br, nil) |
| + if err != nil { |
| + c.Close() |
| + return nil, 0, err |
| + } |
| + if resp.StatusCode != http.StatusOK { |
| + c.Close() |
| + return nil, resp.StatusCode, nil |
| + } |
| + _ = c.SetDeadline(time.Time{}) |
| + return &bufferedConn{Conn: c, r: br}, http.StatusOK, nil |
| +} |
| + |
| +// Inner runs the inner TLS over a tunnel with sni ("" sends none) and |
| +// alpn offered, trusting only the intercept CA. |
| +func (h *Harness) Inner(c net.Conn, sni string, alpn []string) (*tls.Conn, error) { |
| + cfg := &tls.Config{ServerName: sni, RootCAs: h.InterceptPool, NextProtos: alpn, MinVersion: tls.VersionTLS12} |
| + if sni == "" { |
| + cfg.InsecureSkipVerify = true // no name to check; the handshake is refused anyway |
| + } |
| + inner := tls.Client(c, cfg) |
| + _ = inner.SetDeadline(time.Now().Add(5 * time.Second)) |
| + if err := inner.Handshake(); err != nil { |
| + c.Close() |
| + return nil, err |
| + } |
| + _ = inner.SetDeadline(time.Time{}) |
| + return inner, nil |
| +} |
| + |
| +type bufferedConn struct { |
| + net.Conn |
| + r *bufio.Reader |
| +} |
| + |
| +func (c *bufferedConn) Read(p []byte) (int, error) { return c.r.Read(p) } |
| + |
| +func spkiPin(c *x509.Certificate) string { |
| + sum := sha256.Sum256(c.RawSubjectPublicKeyInfo) |
| + return hex.EncodeToString(sum[:]) |
| +} |
| + |
| +var caSerial atomic.Int64 |
| + |
| +// newCA is a fresh P-256 CA, valid 2020 to 2040. |
| +func newCA(t testing.TB, name string) (*ecdsa.PrivateKey, *x509.Certificate, *x509.CertPool) { |
| + t.Helper() |
| + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + tmpl := &x509.Certificate{SerialNumber: big.NewInt(caSerial.Add(1)), Subject: pkix.Name{CommonName: name}, |
| + NotBefore: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC), NotAfter: time.Date(2040, 1, 1, 0, 0, 0, 0, time.UTC), |
| + BasicConstraintsValid: true, IsCA: true, KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature} |
| + der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + c, _ := x509.ParseCertificate(der) |
| + pool := x509.NewCertPool() |
| + pool.AddCert(c) |
| + return key, c, pool |
| +} |
| + |
| +// NewCA is a CA other than the controller's, for certificates the proxy |
| +// must refuse. |
| +func NewCA(t testing.TB) (*ecdsa.PrivateKey, *x509.Certificate) { |
| + k, c, _ := newCA(t, "another CA") |
| + return k, c |
| +} |
| + |
| +// IssueClient signs a client certificate for the default launch's URI at |
| +// epoch under caCert, valid for ctlproxy.CertLifetime from now. |
| +func (h *Harness) IssueClient(t testing.TB, caCert *x509.Certificate, caKey *ecdsa.PrivateKey, epoch int64) *VM { |
| + t.Helper() |
| + key, _ := CSR(t) |
| + now := h.Clock.Wall() |
| + id := ctlproxy.LaunchIdentity{LaunchID: LaunchID, AttemptID: AttemptID, VMRef: VMRef, Epoch: epoch} |
| + der, err := x509.CreateCertificate(rand.Reader, &x509.Certificate{SerialNumber: big.NewInt(caSerial.Add(1) + 1000), |
| + NotBefore: now.Add(-time.Minute), NotAfter: now.Add(ctlproxy.CertLifetime), URIs: []*url.URL{id.URI()}, |
| + KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}}, |
| + caCert, &key.PublicKey, caKey) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return VMFromDER(t, key, der) |
| +} |
| + |
| +func issueServer(t testing.TB, caCert *x509.Certificate, caKey *ecdsa.PrivateKey, name string) tls.Certificate { |
| + t.Helper() |
| + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + der, err := x509.CreateCertificate(rand.Reader, &x509.Certificate{SerialNumber: big.NewInt(caSerial.Add(1)), |
| + DNSNames: []string{name}, NotBefore: time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC), |
| + NotAfter: time.Date(2040, 1, 1, 0, 0, 0, 0, time.UTC), ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}}, |
| + caCert, &key.PublicKey, caKey) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + c, _ := x509.ParseCertificate(der) |
| + return tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key, Leaf: c} |
| +} |