hostedproxy: authenticated CONNECT proxy with origin TLS
Slice 2 Task 6. The egress proxy's policy core and data path: mTLS identity from the controller's CA, exact-host CONNECT, inner TLS terminated with a leaf for that host, CONNECT/SNI/Host/path-class checks per request, origin TLS to the exact host, redirects to other authorities refused, tunnels closed at the certificate or feed deadline or on revocation. The bootstrap listener forwards redeem, renew and cert-report under the proxy's signature. Feed freshness is judged on the monotonic clock from receipt.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
12 files changed,
+3,050
−0
cmd/equipo-hosted-proxy/config.go+180 −0cmd/equipo-hosted-proxy/config_test.go+170 −0cmd/equipo-hosted-proxy/main.go+39 −0docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md+30 −0internal/hostedproxy/boot.go+245 −0internal/hostedproxy/egress.go+596 −0internal/hostedproxy/egress_test.go+679 −0internal/hostedproxy/feed.go+186 −0internal/hostedproxy/log.go+79 −0internal/hostedproxy/origin.go+134 −0internal/hostedproxy/policy.go+283 −0internal/hostedproxy/policy_test.go+429 −0
diff --git a/cmd/equipo-hosted-proxy/config.go b/cmd/equipo-hosted-proxy/config.go| new file mode 100644 |
| index 00000000..dcc79b05 |
| --- /dev/null |
| +++ b/cmd/equipo-hosted-proxy/config.go |
| @@ -0,0 +1,180 @@ |
| +package main |
| + |
| +import ( |
| + "crypto/ed25519" |
| + "crypto/tls" |
| + "crypto/x509" |
| + "encoding/base64" |
| + "errors" |
| + "fmt" |
| + "net" |
| + "net/netip" |
| + "os" |
| + "strconv" |
| + "strings" |
| + |
| + "amadan.net/oficina/equipo/internal/hostedproxy" |
| + "amadan.net/oficina/equipo/internal/hostedwire" |
| +) |
| + |
| +// fileConfig is the -config file: one JSON object read with |
| +// hostedwire.DecodeStrict, so an unknown or repeated key is refused. Every |
| +// field is required. |
| +type fileConfig struct { |
| + // EgressListen is the CONNECT listener and BootListen the bootstrap |
| + // listener: one specific IP address (the same for both, as a VM's |
| + // bootstrap names them) and two ports. Never a wildcard. |
| + EgressListen string `json:"egress_listen"` |
| + BootListen string `json:"boot_listen"` |
| + // ControllerURL is the controller's https origin; ControllerPublicKey |
| + // its ed25519 public key in standard base64; ControllerTLSPin the hex |
| + // SHA-256 of its TLS certificate's SubjectPublicKeyInfo. |
| + ControllerURL string `json:"controller_url"` |
| + ControllerPublicKey string `json:"controller_public_key"` |
| + ControllerTLSPin string `json:"controller_tls_pin"` |
| + // KeyID is this proxy's key in the controller's table (role proxy); |
| + // SigningKeyFile holds its ed25519 seed in standard base64, readable |
| + // by no one but the owner. |
| + KeyID string `json:"key_id"` |
| + SigningKeyFile string `json:"signing_key_file"` |
| + // ClientCAFile is the controller's proxy client CA certificate (PEM). |
| + ClientCAFile string `json:"client_ca_file"` |
| + // InterceptCACertFile and InterceptCAKeyFile are the CA the proxy's |
| + // server leaves are minted from (PEM); the key readable by no one but |
| + // the owner. |
| + InterceptCACertFile string `json:"intercept_ca_cert_file"` |
| + InterceptCAKeyFile string `json:"intercept_ca_key_file"` |
| +} |
| + |
| +// loadConfig reads and checks the config file at path. The decision log |
| +// goes to standard output; origins are checked against the system roots. |
| +func loadConfig(path string) (hostedproxy.Config, error) { |
| + if path == "" { |
| + return hostedproxy.Config{}, errors.New("no -config file given") |
| + } |
| + f, err := os.Open(path) |
| + if err != nil { |
| + return hostedproxy.Config{}, err |
| + } |
| + defer f.Close() |
| + var fc fileConfig |
| + if err := hostedwire.DecodeStrict(f, &fc); err != nil { |
| + return hostedproxy.Config{}, fmt.Errorf("config %s: %w", path, err) |
| + } |
| + c, err := fc.check() |
| + if err != nil { |
| + return hostedproxy.Config{}, fmt.Errorf("config %s: %w", path, err) |
| + } |
| + return c, nil |
| +} |
| + |
| +func (fc fileConfig) check() (hostedproxy.Config, error) { |
| + var c hostedproxy.Config |
| + var err error |
| + if c.Egress, err = checkListen("egress_listen", fc.EgressListen); err != nil { |
| + return c, err |
| + } |
| + if c.Boot, err = checkListen("boot_listen", fc.BootListen); err != nil { |
| + return c, err |
| + } |
| + if c.Egress.Addr() != c.Boot.Addr() || c.Egress.Port() == c.Boot.Port() { |
| + return c, errors.New("egress_listen and boot_listen must be one address on two ports") |
| + } |
| + for name, v := range map[string]string{"controller_url": fc.ControllerURL, "controller_public_key": fc.ControllerPublicKey, |
| + "controller_tls_pin": fc.ControllerTLSPin, "key_id": fc.KeyID, "signing_key_file": fc.SigningKeyFile, |
| + "client_ca_file": fc.ClientCAFile, "intercept_ca_cert_file": fc.InterceptCACertFile, |
| + "intercept_ca_key_file": fc.InterceptCAKeyFile} { |
| + if v == "" { |
| + return c, fmt.Errorf("%s is required", name) |
| + } |
| + } |
| + c.ControllerURL, c.ControllerTLSPin, c.KeyID = fc.ControllerURL, fc.ControllerTLSPin, hostedwire.KeyID(fc.KeyID) |
| + pub, err := base64.StdEncoding.Strict().DecodeString(fc.ControllerPublicKey) |
| + if err != nil || len(pub) != ed25519.PublicKeySize { |
| + return c, errors.New("controller_public_key must be an ed25519 public key in base64") |
| + } |
| + c.ControllerKey = pub |
| + if c.Key, err = readSigningKey(fc.SigningKeyFile); err != nil { |
| + return c, err |
| + } |
| + caPEM, err := os.ReadFile(fc.ClientCAFile) |
| + if err != nil { |
| + return c, fmt.Errorf("client CA: %w", err) |
| + } |
| + c.ClientCA = x509.NewCertPool() |
| + if !c.ClientCA.AppendCertsFromPEM(caPEM) { |
| + return c, fmt.Errorf("client CA %s holds no certificate", fc.ClientCAFile) |
| + } |
| + certPEM, err := os.ReadFile(fc.InterceptCACertFile) |
| + if err != nil { |
| + return c, fmt.Errorf("intercept CA: %w", err) |
| + } |
| + keyPEM, err := readPrivate(fc.InterceptCAKeyFile, "intercept CA key") |
| + if err != nil { |
| + return c, err |
| + } |
| + if c.InterceptCA, err = tls.X509KeyPair(certPEM, keyPEM); err != nil { |
| + return c, fmt.Errorf("intercept CA %s (key %s): %w", fc.InterceptCACertFile, fc.InterceptCAKeyFile, err) |
| + } |
| + // NewServer checks the rest (the URL, pin, and that the intercept |
| + // certificate is a CA), so the command refuses what the library would. |
| + if _, err := hostedproxy.NewServer(c); err != nil { |
| + return c, err |
| + } |
| + return c, nil |
| +} |
| + |
| +// checkListen accepts only "IP:port" with one specific IP and a port: a |
| +// wildcard (0.0.0.0, ::) or an empty host (":port") would listen on every |
| +// interface, and a host name could resolve to anything. |
| +func checkListen(name, addr string) (netip.AddrPort, error) { |
| + if addr == "" { |
| + return netip.AddrPort{}, fmt.Errorf("%s is required", name) |
| + } |
| + host, port, err := net.SplitHostPort(addr) |
| + if err != nil { |
| + return netip.AddrPort{}, fmt.Errorf("%s %q is not host:port", name, addr) |
| + } |
| + ip, err := netip.ParseAddr(host) |
| + if err != nil || ip.Zone() != "" { |
| + return netip.AddrPort{}, fmt.Errorf("%s %q must name one IP address, not %q", name, addr, host) |
| + } |
| + if ip.Unmap().IsUnspecified() { |
| + return netip.AddrPort{}, fmt.Errorf("%s %q listens on every interface; name one address", name, addr) |
| + } |
| + n, err := strconv.ParseUint(port, 10, 16) |
| + if err != nil || n == 0 || strconv.FormatUint(n, 10) != port { |
| + return netip.AddrPort{}, fmt.Errorf("%s %q has no valid port", name, addr) |
| + } |
| + return netip.AddrPortFrom(ip.Unmap(), uint16(n)), nil |
| +} |
| + |
| +// readPrivate reads the secret file at path, refusing one that group or |
| +// others may read. what names it in errors. |
| +func readPrivate(path, what string) ([]byte, error) { |
| + info, err := os.Stat(path) |
| + if err != nil { |
| + return nil, fmt.Errorf("%s: %w", what, err) |
| + } |
| + if info.Mode().Perm()&0o077 != 0 { |
| + return nil, fmt.Errorf("%s %s is readable by group or others (mode %v)", what, path, info.Mode().Perm()) |
| + } |
| + raw, err := os.ReadFile(path) |
| + if err != nil { |
| + return nil, fmt.Errorf("%s: %w", what, err) |
| + } |
| + return raw, nil |
| +} |
| + |
| +// readSigningKey reads the base64 ed25519 seed in path. |
| +func readSigningKey(path string) (ed25519.PrivateKey, error) { |
| + raw, err := readPrivate(path, "signing key") |
| + if err != nil { |
| + return nil, err |
| + } |
| + seed, err := base64.StdEncoding.Strict().DecodeString(strings.TrimSpace(string(raw))) |
| + if err != nil || len(seed) != ed25519.SeedSize { |
| + return nil, fmt.Errorf("signing key %s must hold a %d-byte ed25519 seed in base64", path, ed25519.SeedSize) |
| + } |
| + return ed25519.NewKeyFromSeed(seed), nil |
| +} |
diff --git a/cmd/equipo-hosted-proxy/config_test.go b/cmd/equipo-hosted-proxy/config_test.go| new file mode 100644 |
| index 00000000..7ace0519 |
| --- /dev/null |
| +++ b/cmd/equipo-hosted-proxy/config_test.go |
| @@ -0,0 +1,170 @@ |
| +package main |
| + |
| +import ( |
| + "crypto/ecdsa" |
| + "crypto/ed25519" |
| + "crypto/elliptic" |
| + "crypto/rand" |
| + "crypto/x509" |
| + "crypto/x509/pkix" |
| + "encoding/base64" |
| + "encoding/json" |
| + "encoding/pem" |
| + "math/big" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/rastrillo/rastrillo/budget" |
| +) |
| + |
| +func TestMain(m *testing.M) { os.Exit(budget.Main(m)) } |
| + |
| +// writeCA writes a fresh P-256 CA certificate and key to dir. |
| +func writeCA(t *testing.T, dir, name string) (certPath, keyPath string) { |
| + t.Helper() |
| + k, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + tmpl := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: name}, |
| + NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), |
| + BasicConstraintsValid: true, IsCA: true, KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature} |
| + der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &k.PublicKey, k) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + pk, _ := x509.MarshalPKCS8PrivateKey(k) |
| + certPath, keyPath = filepath.Join(dir, name+".pem"), filepath.Join(dir, name+".key") |
| + if err := os.WriteFile(certPath, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(keyPath, pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pk}), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + return certPath, keyPath |
| +} |
| + |
| +// validConfig writes a valid config's files to a temporary directory and |
| +// returns the config as a map, for tests to change one field. |
| +func validConfig(t *testing.T) (string, map[string]string) { |
| + t.Helper() |
| + dir := t.TempDir() |
| + clientCA, _ := writeCA(t, dir, "client-ca") |
| + interceptCert, interceptKey := writeCA(t, dir, "intercept-ca") |
| + seed := make([]byte, ed25519.SeedSize) |
| + _, _ = rand.Read(seed) |
| + keyPath := filepath.Join(dir, "proxy.key") |
| + if err := os.WriteFile(keyPath, []byte(base64.StdEncoding.EncodeToString(seed)+"\n"), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + pub, _, _ := ed25519.GenerateKey(rand.Reader) |
| + return dir, map[string]string{ |
| + "egress_listen": "10.20.0.5:3128", |
| + "boot_listen": "10.20.0.5:3129", |
| + "controller_url": "https://controller.example.test:8443", |
| + "controller_public_key": base64.StdEncoding.EncodeToString(pub), |
| + "controller_tls_pin": strings.Repeat("ab", 32), |
| + "key_id": "proxy-1", |
| + "signing_key_file": keyPath, |
| + "client_ca_file": clientCA, |
| + "intercept_ca_cert_file": interceptCert, |
| + "intercept_ca_key_file": interceptKey, |
| + } |
| +} |
| + |
| +func writeConfig(t *testing.T, dir string, fields map[string]string) string { |
| + t.Helper() |
| + raw, err := json.Marshal(fields) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + path := filepath.Join(dir, "proxy.json") |
| + if err := os.WriteFile(path, raw, 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + return path |
| +} |
| + |
| +func TestConfigLoads(t *testing.T) { |
| + dir, fields := validConfig(t) |
| + cfg, err := loadConfig(writeConfig(t, dir, fields)) |
| + if err != nil { |
| + t.Fatalf("loadConfig: %v", err) |
| + } |
| + if cfg.Egress.String() != "10.20.0.5:3128" || cfg.Boot.String() != "10.20.0.5:3129" || cfg.KeyID != "proxy-1" || |
| + cfg.ClientCA == nil || len(cfg.Key) != ed25519.PrivateKeySize || cfg.OriginRoots != nil { |
| + t.Errorf("loaded config = %+v", cfg) |
| + } |
| +} |
| + |
| +func TestConfigRefusesWildcardListen(t *testing.T) { |
| + // Each host is given to both listeners (ports 3128 and 3129), so only |
| + // the host itself can be the reason for a refusal. |
| + for _, host := range []string{"0.0.0.0", "[::]", "", "*", "[::ffff:0.0.0.0]", "localhost", "proxy.example.test", |
| + "[fe80::1%eth0]"} { |
| + dir, fields := validConfig(t) |
| + fields["egress_listen"], fields["boot_listen"] = host+":3128", host+":3129" |
| + if _, err := loadConfig(writeConfig(t, dir, fields)); err == nil { |
| + t.Errorf("listeners on %q were accepted", host) |
| + } |
| + } |
| + for _, field := range []string{"egress_listen", "boot_listen"} { |
| + for _, addr := range []string{"", "10.20.0.5", "10.20.0.5:0", "10.20.0.5:http"} { |
| + dir, fields := validConfig(t) |
| + fields[field] = addr |
| + if _, err := loadConfig(writeConfig(t, dir, fields)); err == nil { |
| + t.Errorf("%s %q was accepted", field, addr) |
| + } |
| + } |
| + } |
| +} |
| + |
| +func TestConfigRefuses(t *testing.T) { |
| + for name, change := range map[string]func(dir string, f map[string]string){ |
| + "the same address twice": func(_ string, f map[string]string) { f["boot_listen"] = f["egress_listen"] }, |
| + "listeners on two addresses": func(_ string, f map[string]string) { f["boot_listen"] = "10.20.0.6:3129" }, |
| + "an http controller": func(_ string, f map[string]string) { f["controller_url"] = "http://controller.example.test" }, |
| + "a controller URL with a path": func(_ string, f map[string]string) { f["controller_url"] += "/v1" }, |
| + "a short pin": func(_ string, f map[string]string) { f["controller_tls_pin"] = "abcd" }, |
| + "an upper-case pin": func(_ string, f map[string]string) { f["controller_tls_pin"] = strings.Repeat("AB", 32) }, |
| + "a short controller key": func(_ string, f map[string]string) { f["controller_public_key"] = "AAAA" }, |
| + "no key ID": func(_ string, f map[string]string) { f["key_id"] = "" }, |
| + "a signing key others can read": func(_ string, f map[string]string) { _ = os.Chmod(f["signing_key_file"], 0o644) }, |
| + "an intercept key others can read": func(_ string, f map[string]string) { _ = os.Chmod(f["intercept_ca_key_file"], 0o640) }, |
| + "an intercept certificate that is not a CA": func(dir string, f map[string]string) { |
| + f["intercept_ca_cert_file"], f["intercept_ca_key_file"] = writeLeaf(t, dir) |
| + }, |
| + } { |
| + dir, fields := validConfig(t) |
| + change(dir, fields) |
| + if _, err := loadConfig(writeConfig(t, dir, fields)); err == nil { |
| + t.Errorf("%s: accepted", name) |
| + } |
| + } |
| + dir, fields := validConfig(t) |
| + path := writeConfig(t, dir, fields) |
| + raw, _ := os.ReadFile(path) |
| + if err := os.WriteFile(path, append(raw[:len(raw)-1], []byte(`,"listen":"10.0.0.1:1"}`)...), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := loadConfig(path); err == nil { |
| + t.Error("an unknown key was accepted") |
| + } |
| +} |
| + |
| +// writeLeaf writes a certificate that is not a CA, with its key. |
| +func writeLeaf(t *testing.T, dir string) (string, string) { |
| + t.Helper() |
| + k, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| + tmpl := &x509.Certificate{SerialNumber: big.NewInt(2), Subject: pkix.Name{CommonName: "leaf"}, |
| + NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), KeyUsage: x509.KeyUsageDigitalSignature} |
| + der, _ := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &k.PublicKey, k) |
| + pk, _ := x509.MarshalPKCS8PrivateKey(k) |
| + c, kp := filepath.Join(dir, "leaf.pem"), filepath.Join(dir, "leaf.key") |
| + _ = os.WriteFile(c, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), 0o644) |
| + _ = os.WriteFile(kp, pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pk}), 0o600) |
| + return c, kp |
| +} |
diff --git a/cmd/equipo-hosted-proxy/main.go b/cmd/equipo-hosted-proxy/main.go| new file mode 100644 |
| index 00000000..cf145044 |
| --- /dev/null |
| +++ b/cmd/equipo-hosted-proxy/main.go |
| @@ -0,0 +1,39 @@ |
| +// Command equipo-hosted-proxy runs one authenticated egress proxy for |
| +// hosted VMs (spec §6): the CONNECT listener VMs reach their services |
| +// through, the bootstrap listener that forwards certificate redemption, |
| +// renewal and certification reports to the controller, and the poll of |
| +// the controller's signed launch feed. It imports no AWS package. |
| +// |
| +// equipo-hosted-proxy -config /etc/equipo-hosted/proxy.json |
| +// |
| +// The decision log is written to standard output, one JSON line per |
| +// decision. |
| +package main |
| + |
| +import ( |
| + "context" |
| + "flag" |
| + "log" |
| + "os" |
| + "os/signal" |
| + "syscall" |
| + |
| + "amadan.net/oficina/equipo/internal/hostedproxy" |
| +) |
| + |
| +func main() { |
| + path := flag.String("config", "", "path of the proxy's JSON config file") |
| + flag.Parse() |
| + cfg, err := loadConfig(*path) |
| + if err != nil { |
| + log.Printf("equipo-hosted-proxy: %v", err) |
| + os.Exit(1) |
| + } |
| + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) |
| + defer stop() |
| + log.Printf("equipo-hosted-proxy: egress on %s, bootstrap on %s", cfg.Egress, cfg.Boot) |
| + if err := hostedproxy.Serve(ctx, cfg); err != nil { |
| + log.Printf("equipo-hosted-proxy: %v", err) |
| + os.Exit(1) |
| + } |
| +} |
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md| index 33afbccc..d0186f13 100644 |
| --- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| +++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| @@ -214,3 +214,33 @@ Mutation checks (each applied by script, the named test run, then restored and c |
| 24. No timeout (`context.WithCancel`). Same command. Observed: FAIL, `fetcher_test.go:48: ... owner "123456789012", deadline false; want ... a deadline`. Restored. |
| Also run: `go test ./internal/hostedcert ./internal/hostedctl/... ./internal/hostedclient ./internal/hostedwire ./cmd/equipo-hosted-controller ./internal/isolatedjob -count=1` ok (TestProviderTypesStayInAdapter included; hostedctl 23.4 s at load average 102 to 116); `go test -race` of the touched tests ok; `go vet -tags hostedlive` and staticcheck v0.7.0 (plain and `-tags hostedlive`) ok; `make budget build vet` ok after raising the `internal/hostedctl` record to 5954/9907. govulncheck was not run on the new s3 module (it needs the network). |
| + |
| +## Task 6 |
| + |
| +The authenticated egress proxy: new package `internal/hostedproxy` (`policy.go`, `feed.go`, `egress.go`, `boot.go`, `origin.go`, `log.go`; tests in `policy_test.go`, `egress_test.go`) and command `cmd/equipo-hosted-proxy` (`main.go`, `config.go`, `config_test.go`). No AWS import (TestProviderTypesStayInAdapter passes); default budgets (1523 source and 1108 test lines in `internal/hostedproxy`). |
| + |
| +- Policy. `IdentityFromCert` (exactly one URI SAN read with `ctlproxy.ParseLaunchURI`, no other name, serial as lower-case hex as the controller writes it). `Feed.Decide` judges, in order: the identity (`stale_feed`, `cert_expired`, `revoked`, `unknown_launch` for an unknown launch or another attempt or VM, `wrong_epoch`), a CONNECT inside the tunnel (`nested_tunnel`), the CONNECT target (`ip_literal`, `bad_port` for anything but 443, `not_in_manifest` unless a launch service names the host exactly, ASCII case aside), the inner hello (`ech`, `no_sni`, `ip_literal`, `sni_mismatch`, `alpn` for any offered protocol but `http/1.1`), `Host` (`host_mismatch`: the CONNECT host, port 443 or none), and the path class (`bad_path` unless the request target is exactly one of the five instance routes, so no query and no absolute form; `bad_method`; `GET /api/runner/stream` only as an upgrade, an upgrade anywhere else `nested_tunnel`). `redirect_refused` is judged on the origin's answer: a 3xx whose `Location` names another host, a port but 443, a scheme but https, user info, or more than one value becomes a bare 502. |
| +- Clocks (ruling). Freshness is the monotonic clock only: a feed is usable from its receipt (`Install`) for its TTL, capped at `ctlproxy.FeedLifetime`. The receipt also records the wall clock beside the monotonic one, and a certificate's `NotAfter` is turned into monotonic time through that pair, so `Decide` and `Deadline` never read the wall clock and a jump after receipt moves nothing. `Clock` (`Mono`, `Wall`, `After`) is injectable; `SystemClock` is the real one. |
| +- Data path. Egress listener: TLS requiring a client certificate from `ClientCA`, one `CONNECT` per connection, judged on target and identity before the 200; the inner TLS is terminated with a leaf for exactly the manifest host from `InterceptCA` (ALPN `http/1.1` only; a hello that fails `decideTLS` aborts the handshake and is logged by reason); each request is judged with `Decide` and forwarded through a per-tunnel `http.Transport` whose only dial is the proxy's own TLS to that exact host on 443 (SNI set, `OriginRoots` or the system roots, HTTP/1.1 only), hop-by-hop headers dropped. A refusal answers 403 and ends the tunnel; bytes that are not HTTP are `nested_tunnel`. A WebSocket upgrade (only `Upgrade: websocket`) is piped only after the same check and a 101 from the origin. A watcher closes each tunnel, and any piped socket, at `Feed.Deadline` (the earlier of certificate expiry and feed expiry) or as soon as a fresher feed no longer lets the identity through. |
| +- Bootstrap listener: server TLS only (a client certificate is verified when sent); `POST /redeem` (no certificate), `POST /renew` and `POST /cert-report` (each needs a certificate the current feed lets through, whose serial equals the body's), each body checked with `DecodeStrict` and forwarded byte for byte, signed with the proxy key, to `/v1/proxy/redeem`, `/v1/proxy/renew`, `/v1/proxy/cert-report`; the answer is relayed only when the controller signed it for that request. The feed (`GET /v1/proxy/feed`) is polled at start and every 30 s; the controller's TLS certificate is trusted only by `ControllerTLSPin`, the hex SHA-256 of its SubjectPublicKeyInfo (the format `ProxyCAPin` uses), and each answer only under `ControllerKey` for that request's nonce. |
| +- Decision log: one JSON line per decision with time, VM, launch, attempt, epoch, destination (the CONNECT target), method (a known method or `other`), path class (`instance` or `none`, never the path), decision, reason, origin status, bytes in and out. No header, body, query, path or token. |
| +- `config.go`: one strict JSON file; both listeners one specific IP (the same for both, as a bootstrap names them) on two ports; wildcards, empty hosts, names, zones and port 0 refused; key files readable by the owner only; it then builds the server through `hostedproxy.NewServer`, which refuses an unspecified listener too. |
| +- Interface additions beyond the brief, for tests and Task 7's harness: `Config.Clock`, `Config.DialOrigin`, `Server` (`NewServer`, `Start`, `Close`, `Poll`, `Feed`, `EgressAddr`, `BootAddr`), `Feed.Install`, `NewFeed`, `SystemClock`. |
| + |
| +RED: `CGO_ENABLED=0 go test ./internal/hostedproxy ./cmd/equipo-hosted-proxy -run 'TestDecide|TestStaleFeed|TestConfig|TestLogHasNoSecrets|TestPathClass' -count=1` failed to build: `config_test.go:93:14: undefined: loadConfig`; `egress_test.go:57:44: undefined: logLine`, `undefined: Clock`, `undefined: Server`, `undefined: NewServer`, `undefined: Config`, `policy_test.go:124:45: undefined: Feed`. |
| + |
| +GREEN: the same command: `ok internal/hostedproxy`, `ok cmd/equipo-hosted-proxy` (TestDecideTable, TestDecideDeadline, TestStaleFeedDeniesAll, TestLogHasNoSecrets, TestPathClassCoversRunner, TestConfigLoads, TestConfigRefusesWildcardListen, TestConfigRefuses). Also new and passing: TestEgressForwardsAllowedRequests, TestEgressRefusesAndTheOriginSeesNothing, TestEgressRedirectRefused, TestEgressNeedsClientCertFromTheCA, TestEgressWebSocketClosesWhenRevoked (a real coder/websocket echo through the proxy, closed by a revoking feed), TestPollVerifiesTheFeed (another signer; a wrong pin sends nothing), TestBootForwardsUnderTheProxySignature (redeem, renew and cert-report against a fake controller that verifies the proxy's signature; no certificate, another serial, an unknown field and a revoked serial are not forwarded). TestPathClassCoversRunner finds `wire.StreamPath` (thin/link.go) and `wire.RunnerProtocolPath` (runner/enrol.go) today; it also takes every whole `/api/` literal under `internal/runner/hosted/`, and any `/api/` literal or wire constant with a `/hosted/` segment, so Task 12's paths join it, and fails on a hosted path written as a fragment (`"/hosted/..."`). |
| + |
| +Mutation checks (each applied by script, the named test run, then restored and checked byte for byte with `cmp`): |
| + |
| +1. Compare hosts by suffix (`sameHost` became a case-folded `HasSuffix` either way, `policy.go`). Command: `CGO_ENABLED=0 go test ./internal/hostedproxy -run 'TestDecideTable' -count=1`. Observed: FAIL, `policy_test.go:232: a name ending in the allowed host: Decide = {Allow:true ...}, want refused not_in_manifest` (also a name under the host, its parent, user info in the target, `SNI ending in the host ... want refused sni_mismatch`, `Host ending in the host ... want refused host_mismatch`, Host with user info), and `policy_test.go:261: decideResponse(302, ["https://evil-instance.example.test/x"]) = {Allow:true ...}, want allowed false`. Restored. |
| +2. Measure freshness on the wall clock (`Feed.current`'s `mono-f.received >= f.ttl` became `f.clock.Wall().Sub(f.anchorWall) >= f.ttl`). Command: `... -run 'TestStaleFeedDeniesAll|TestDecideTable' -count=1`. Observed: FAIL, `policy_test.go:325: 1 min on, wall clock an hour ahead: GET /api/runner/protocol = {Allow:false Reason:stale_feed ...}, want allowed true` and `policy_test.go:331: lifetime and 1 ms, wall clock an hour behind: GET /api/runner/protocol = {Allow:true ...}, want allowed false (else stale_feed)` for every route; `policy_test.go:232: stale feed: Decide = {Allow:true ...}, want refused stale_feed`. Restored. |
| +3. Log the `Authorization` header (`logLine` gained `authorization`, filled from the request for forwarded requests, `log.go` and `egress.go`). Command: `... -run 'TestLogHasNoSecrets' -count=1`. Observed: FAIL, `egress_test.go:555: the decision log holds SECRET-AUTHORIZATION: {"time":...,"method":"POST","path_class":"instance","decision":"allow",...,"authorization":"Bearer SECRET-AUTHORIZATION"}` (and `holds Bearer`). Restored. |
| +4. (extra) No Host check (`decideHost` returned ""). Command: `... -run 'TestDecideTable|TestEgressRefuses' -count=1`. Observed: FAIL, `policy_test.go:232: Host of another host: Decide = {Allow:true ...}, want refused host_mismatch` (six rows), and `egress_test.go:443: "GET /api/runner/protocol HTTP/1.1\r\nHost: other.example.test\r\n\r\n" answered "HTTP/1.1 200 OK ... protocol 39", want 403`. Restored. (The first run of this mutation took 125 s: the forwarded request kept the tunnel open to the 2-minute idle timeout. The test now sets a 5 s deadline; the rerun failed the same way in 10 s.) |
| +5. (extra) No redirect check (`if true || status < 300 ...`, `decideResponse`). Command: `... -run 'TestDecideTable|TestEgressRedirectRefused' -count=1`. Observed: FAIL, `egress_test.go:464: redirect to another host answered 302 map[... Location:[https://other.example.test/steal]] ..., want a bare 502`, and ten `decideResponse(...) = {Allow:true ...}, want allowed false` rows. Restored. |
| +6. (extra) No tunnel watcher (`go t.watch()` became `_ = t.watch`). Command: `... -run 'TestEgressWebSocketClosesWhenRevoked' -count=1`. Observed: FAIL, `egress_test.go:520: read after the revocation = failed to get reader: context deadline exceeded, want the socket closed`. Restored. |
| +7. (extra) The bootstrap listener skips the serial match (`if false && serial != id.Serial`, `boot.go`). Command: `... -run 'TestBootForwardsUnderTheProxySignature' -count=1`. Observed: FAIL, `egress_test.go:649: renewal for another serial: forwarded (200)`, `report for another serial: forwarded (200)`, `egress_test.go:653: controller got 2 refused requests`. Restored. |
| +8. (extra) `GET /api/runner/protocol` left out of the instance class. Command: `... -run 'TestPathClassCoversRunner' -count=1`. Observed: FAIL, `policy_test.go:426: /api/runner/protocol (../runner/enrol.go: wire.RunnerProtocolPath) is outside the proxy's instance path class`. Restored. |
| +9. (extra) Wildcard listeners allowed, in both layers (`checkListen`'s `IsUnspecified` check and `NewServer`'s). Command: `CGO_ENABLED=0 go test ./cmd/equipo-hosted-proxy -run 'TestConfigRefusesWildcardListen' -count=1`. Observed: FAIL, `config_test.go:111: listeners on "0.0.0.0" were accepted`, `"[::]"`, `"[::ffff:0.0.0.0]"`. Restored. (Either layer alone still refuses; the test first gave the wildcard to one listener only, where the one-address rule refused it, and now gives it to both.) |
| + |
| +Also run: `go test ./internal/hostedproxy ./cmd/equipo-hosted-proxy -count=1 -race` once, ok (2.3 s and 1.1 s); `go test ./internal/isolatedjob -run TestProviderTypesStayInAdapter -count=1` ok; staticcheck v0.7.0 on both packages ok; gofmt clean; `make budget build vet` ok (126 directories within budget). |
diff --git a/internal/hostedproxy/boot.go b/internal/hostedproxy/boot.go| new file mode 100644 |
| index 00000000..dbc12b25 |
| --- /dev/null |
| +++ b/internal/hostedproxy/boot.go |
| @@ -0,0 +1,245 @@ |
| +package hostedproxy |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/ed25519" |
| + "crypto/sha256" |
| + "crypto/subtle" |
| + "crypto/tls" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "log" |
| + "net" |
| + "net/http" |
| + "net/url" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/hostedwire" |
| +) |
| + |
| +// Controller routes the proxy calls (role proxy). |
| +const ( |
| + routeFeed = "/v1/proxy/feed" |
| + routeRedeem = "/v1/proxy/redeem" |
| + routeRenew = "/v1/proxy/renew" |
| + routeCertReport = "/v1/proxy/cert-report" |
| +) |
| + |
| +// controllerTimeout bounds one call to the controller, the body included. |
| +const controllerTimeout = 15 * time.Second |
| + |
| +// ErrController is a controller answer the proxy cannot use: unreachable, |
| +// unsigned, signed by another key or for another request. |
| +var ErrController = errors.New("hostedproxy: no usable answer from the controller") |
| + |
| +// controllerClient sends signed requests to the controller and verifies |
| +// that each answer is signed for that request. |
| +type controllerClient struct { |
| + origin string |
| + keyID hostedwire.KeyID |
| + key ed25519.PrivateKey |
| + pub ed25519.PublicKey |
| + rt http.RoundTripper |
| + clock Clock |
| +} |
| + |
| +func newControllerClient(cfg Config) (*controllerClient, error) { |
| + u, err := url.Parse(cfg.ControllerURL) |
| + if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || (u.Path != "" && u.Path != "/") || |
| + u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || u.Opaque != "" { |
| + return nil, errors.New("hostedproxy: the controller URL must be an https origin with no path, query or user info") |
| + } |
| + if !validPin(cfg.ControllerTLSPin) { |
| + return nil, errors.New("hostedproxy: the controller TLS pin must be 64 lower-case hex digits") |
| + } |
| + want, _ := hex.DecodeString(cfg.ControllerTLSPin) |
| + tlsCfg := &tls.Config{ |
| + MinVersion: tls.VersionTLS12, |
| + // The pin is the controller's identity, not a CA: the chain is not |
| + // checked, the leaf's key must be the pinned one. VerifyConnection |
| + // runs either way. |
| + InsecureSkipVerify: true, |
| + VerifyConnection: func(cs tls.ConnectionState) error { |
| + if len(cs.PeerCertificates) == 0 { |
| + return errors.New("hostedproxy: the controller sent no certificate") |
| + } |
| + got := sha256.Sum256(cs.PeerCertificates[0].RawSubjectPublicKeyInfo) |
| + if subtle.ConstantTimeCompare(got[:], want) != 1 { |
| + return errors.New("hostedproxy: the controller's certificate is not the pinned one") |
| + } |
| + return nil |
| + }, |
| + } |
| + return &controllerClient{origin: "https://" + u.Host, keyID: cfg.KeyID, key: cfg.Key, pub: cfg.ControllerKey, |
| + clock: cfg.Clock, rt: &http.Transport{TLSClientConfig: tlsCfg, Proxy: nil, ResponseHeaderTimeout: controllerTimeout, |
| + MaxIdleConnsPerHost: 2, IdleConnTimeout: time.Minute}}, nil |
| +} |
| + |
| +// call sends one signed request and returns the verified answer. The |
| +// answer is never redirected, and nothing of one that fails verification |
| +// is returned. |
| +func (c *controllerClient) call(ctx context.Context, method, path string, body []byte) (int, []byte, error) { |
| + ctx, cancel := context.WithTimeout(ctx, controllerTimeout) |
| + defer cancel() |
| + req, err := http.NewRequestWithContext(ctx, method, c.origin+path, bytes.NewReader(body)) |
| + if err != nil { |
| + return 0, nil, fmt.Errorf("%w: build request", ErrController) |
| + } |
| + if body != nil { |
| + req.Header.Set("Content-Type", "application/json") |
| + } |
| + nonce, err := hostedwire.NewNonce() |
| + if err != nil { |
| + return 0, nil, err |
| + } |
| + if err := hostedwire.SignRequest(req, body, c.keyID, c.key, c.clock.Wall(), nonce); err != nil { |
| + return 0, nil, fmt.Errorf("%w: sign: %w", ErrController, err) |
| + } |
| + resp, err := c.rt.RoundTrip(req) |
| + if err != nil { |
| + return 0, nil, fmt.Errorf("%w: %s %s: sending failed", ErrController, method, path) |
| + } |
| + defer resp.Body.Close() |
| + got, err := io.ReadAll(io.LimitReader(resp.Body, hostedwire.MaxBody+1)) |
| + if err != nil { |
| + return 0, nil, fmt.Errorf("%w: %s %s: reading failed", ErrController, method, path) |
| + } |
| + if err := hostedwire.VerifyResponse(resp, got, nonce, c.pub); err != nil { |
| + return 0, nil, fmt.Errorf("%w: %s %s: %w", ErrController, method, path, err) |
| + } |
| + return resp.StatusCode, got, nil |
| +} |
| + |
| +// Poll fetches the feed once and installs it when the controller signed |
| +// it for this request. |
| +func (s *Server) Poll(ctx context.Context) error { |
| + status, body, err := s.ctl.call(ctx, http.MethodGet, routeFeed, nil) |
| + if err != nil { |
| + return err |
| + } |
| + if status != http.StatusOK { |
| + return fmt.Errorf("%w: feed answered %d", ErrController, status) |
| + } |
| + var pf hostedwire.ProxyFeed |
| + if err := hostedwire.DecodeStrict(bytes.NewReader(body), &pf); err != nil { |
| + return fmt.Errorf("%w: feed: %w", ErrController, err) |
| + } |
| + return s.feed.Install(pf) |
| +} |
| + |
| +func (s *Server) pollLoop(ctx context.Context) { |
| + for { |
| + if err := s.Poll(ctx); err != nil && ctx.Err() == nil { |
| + log.Printf("equipo-hosted-proxy: feed: %v", err) |
| + } |
| + select { |
| + case <-ctx.Done(): |
| + return |
| + case <-s.clock.After(PollInterval): |
| + } |
| + } |
| +} |
| + |
| +// newBootServer is the bootstrap listener: server TLS only (a client |
| +// certificate is checked when sent, and required by /renew and |
| +// /cert-report), and three routes, each forwarded to the controller under |
| +// the proxy's signature: |
| +// |
| +// POST /redeem hostedwire.RedeemRequest -> POST /v1/proxy/redeem |
| +// POST /renew hostedwire.RenewCertRequest -> POST /v1/proxy/renew |
| +// POST /cert-report hostedwire.CertReport -> POST /v1/proxy/cert-report |
| +// |
| +// The proxy adds no identity of its own: a renewal binds to the serial the |
| +// controller issued, and a report carries the VM key's signature. It only |
| +// refuses to forward a renewal or report whose body names another serial |
| +// than the certificate it came over, or over a certificate the feed no |
| +// longer lets through. |
| +func (s *Server) newBootServer(ctx context.Context) *http.Server { |
| + mux := http.NewServeMux() |
| + mux.HandleFunc("POST /redeem", func(w http.ResponseWriter, r *http.Request) { |
| + s.forwardBoot(w, r, routeRedeem, false, func(b []byte) (string, error) { |
| + var q hostedwire.RedeemRequest |
| + return "", hostedwire.DecodeStrict(bytes.NewReader(b), &q) |
| + }) |
| + }) |
| + mux.HandleFunc("POST /renew", func(w http.ResponseWriter, r *http.Request) { |
| + s.forwardBoot(w, r, routeRenew, true, func(b []byte) (string, error) { |
| + var q hostedwire.RenewCertRequest |
| + err := hostedwire.DecodeStrict(bytes.NewReader(b), &q) |
| + return q.Serial, err |
| + }) |
| + }) |
| + mux.HandleFunc("POST /cert-report", func(w http.ResponseWriter, r *http.Request) { |
| + s.forwardBoot(w, r, routeCertReport, true, func(b []byte) (string, error) { |
| + var q hostedwire.CertReport |
| + err := hostedwire.DecodeStrict(bytes.NewReader(b), &q) |
| + return q.Serial, err |
| + }) |
| + }) |
| + return &http.Server{ |
| + Handler: mux, DisableGeneralOptionsHandler: true, |
| + BaseContext: func(net.Listener) context.Context { return ctx }, |
| + ReadHeaderTimeout: handshakeTimeout, ReadTimeout: 30 * time.Second, WriteTimeout: time.Minute, |
| + IdleTimeout: time.Minute, MaxHeaderBytes: 16 << 10, |
| + TLSNextProto: map[string]func(*http.Server, *tls.Conn, http.Handler){}, |
| + ErrorLog: log.New(io.Discard, "", 0), |
| + TLSConfig: &tls.Config{MinVersion: tls.VersionTLS12, ClientAuth: tls.VerifyClientCertIfGiven, |
| + ClientCAs: s.cfg.ClientCA, Time: s.clock.Wall, NextProtos: []string{ALPNHTTP11}, |
| + GetCertificate: func(*tls.ClientHelloInfo) (*tls.Certificate, error) { return s.ca.ipLeaf(s.cfg.Boot.Addr()) }}, |
| + } |
| +} |
| + |
| +// forwardBoot reads and checks one bootstrap request and forwards it. |
| +// check decodes the body strictly and returns the serial it names; when |
| +// needCert, that serial must be the current certificate's. |
| +func (s *Server) forwardBoot(w http.ResponseWriter, r *http.Request, route string, needCert bool, |
| + check func([]byte) (string, error)) { |
| + body, err := io.ReadAll(io.LimitReader(r.Body, hostedwire.MaxBody+1)) |
| + if err != nil || len(body) > hostedwire.MaxBody { |
| + bootError(w, http.StatusBadRequest, "bad_request") |
| + return |
| + } |
| + serial, err := check(body) |
| + if err != nil { |
| + bootError(w, http.StatusBadRequest, "bad_request") |
| + return |
| + } |
| + if needCert { |
| + if r.TLS == nil || len(r.TLS.VerifiedChains) == 0 || len(r.TLS.VerifiedChains[0]) == 0 { |
| + bootError(w, http.StatusUnauthorized, "no_certificate") |
| + return |
| + } |
| + id, err := IdentityFromCert(r.TLS.VerifiedChains[0][0]) |
| + if err != nil { |
| + bootError(w, http.StatusForbidden, "bad_certificate") |
| + return |
| + } |
| + if _, reason := s.feed.current(id, s.clock.Mono()); reason != "" { |
| + bootError(w, http.StatusForbidden, reason) |
| + return |
| + } |
| + if serial != id.Serial { |
| + bootError(w, http.StatusForbidden, "serial_mismatch") |
| + return |
| + } |
| + } |
| + status, out, err := s.ctl.call(r.Context(), http.MethodPost, route, body) |
| + if err != nil { |
| + bootError(w, http.StatusBadGateway, "controller_unavailable") |
| + return |
| + } |
| + w.Header().Set("Content-Type", "application/json") |
| + w.WriteHeader(status) |
| + _, _ = w.Write(out) |
| +} |
| + |
| +func bootError(w http.ResponseWriter, status int, code string) { |
| + raw, _ := json.Marshal(hostedwire.ErrorResponse{Code: code, Message: http.StatusText(status)}) |
| + w.Header().Set("Content-Type", "application/json") |
| + w.WriteHeader(status) |
| + _, _ = w.Write(raw) |
| +} |
diff --git a/internal/hostedproxy/egress.go b/internal/hostedproxy/egress.go| new file mode 100644 |
| index 00000000..935039a2 |
| --- /dev/null |
| +++ b/internal/hostedproxy/egress.go |
| @@ -0,0 +1,596 @@ |
| +package hostedproxy |
| + |
| +import ( |
| + "bufio" |
| + "context" |
| + "crypto/ed25519" |
| + "crypto/tls" |
| + "crypto/x509" |
| + "encoding/hex" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net" |
| + "net/http" |
| + "net/netip" |
| + "net/textproto" |
| + "net/url" |
| + "os" |
| + "slices" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/hostedwire" |
| +) |
| + |
| +// Config is one proxy's configuration. Every field is required but |
| +// OriginRoots, Log, Clock and DialOrigin. |
| +type Config struct { |
| + // Egress is the CONNECT listener, Boot the bootstrap listener: each a |
| + // specific address (never a wildcard), port 0 only in tests. |
| + Egress, Boot netip.AddrPort |
| + // ControllerURL is the controller's https origin. Its TLS certificate |
| + // is trusted only by ControllerTLSPin, the hex SHA-256 of its |
| + // SubjectPublicKeyInfo, and its answers only when signed by |
| + // ControllerKey for the proxy's request. |
| + ControllerURL string |
| + ControllerKey ed25519.PublicKey |
| + ControllerTLSPin string |
| + // KeyID and Key are the proxy's entry (role proxy) in the |
| + // controller's key table. |
| + KeyID hostedwire.KeyID |
| + Key ed25519.PrivateKey |
| + // ClientCA is the controller's client CA: the only issuer of VM |
| + // certificates. |
| + ClientCA *x509.CertPool |
| + // InterceptCA signs the proxy's server leaves; VMs pin its SPKI. |
| + InterceptCA tls.Certificate |
| + // OriginRoots verify service hosts; nil means the system roots. Only |
| + // tests set it. |
| + OriginRoots *x509.CertPool |
| + // Log receives the decision log, one JSON line per decision; nil |
| + // means standard output. |
| + Log io.Writer |
| + // Clock is the proxy's time; nil means SystemClock. DialOrigin opens |
| + // the TCP connection to a service host ("host:443"); nil means a |
| + // plain net.Dialer. Tests set both. |
| + Clock Clock |
| + DialOrigin func(ctx context.Context, network, addr string) (net.Conn, error) |
| +} |
| + |
| +// PollInterval is how often the proxy asks the controller for the feed. |
| +const PollInterval = 30 * time.Second |
| + |
| +// Bounds on a VM's connections. |
| +const ( |
| + handshakeTimeout = 10 * time.Second |
| + idleTimeout = 2 * time.Minute |
| +) |
| + |
| +// Server is one running proxy: the egress and bootstrap listeners and the |
| +// feed poll. |
| +type Server struct { |
| + cfg Config |
| + clock Clock |
| + feed *Feed |
| + ca *interceptCA |
| + log *decisionLog |
| + ctl *controllerClient |
| + |
| + egressLn, bootLn net.Listener |
| + bootSrv *http.Server |
| + cancel context.CancelFunc |
| + wg sync.WaitGroup |
| + |
| + mu sync.Mutex |
| + conns map[net.Conn]struct{} |
| + closed bool |
| +} |
| + |
| +// NewServer checks cfg and builds a proxy; Start binds and runs it. |
| +func NewServer(cfg Config) (*Server, error) { |
| + for name, a := range map[string]netip.AddrPort{"egress": cfg.Egress, "boot": cfg.Boot} { |
| + if !a.IsValid() || a.Addr().Unmap().IsUnspecified() || a.Addr().Zone() != "" { |
| + return nil, fmt.Errorf("hostedproxy: %s listener %s must be one specific address", name, a) |
| + } |
| + } |
| + switch { |
| + case cfg.KeyID == "": |
| + return nil, errors.New("hostedproxy: no key ID") |
| + case len(cfg.Key) != ed25519.PrivateKeySize: |
| + return nil, errors.New("hostedproxy: the signing key is missing or the wrong length") |
| + case len(cfg.ControllerKey) != ed25519.PublicKeySize: |
| + return nil, errors.New("hostedproxy: the controller key is missing or the wrong length") |
| + case cfg.ClientCA == nil: |
| + return nil, errors.New("hostedproxy: no client CA") |
| + } |
| + if cfg.Clock == nil { |
| + cfg.Clock = SystemClock() |
| + } |
| + if cfg.Log == nil { |
| + cfg.Log = os.Stdout |
| + } |
| + ca, err := newInterceptCA(cfg.InterceptCA, cfg.Clock) |
| + if err != nil { |
| + return nil, err |
| + } |
| + ctl, err := newControllerClient(cfg) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return &Server{cfg: cfg, clock: cfg.Clock, feed: NewFeed(cfg.Clock), ca: ca, ctl: ctl, |
| + log: &decisionLog{w: cfg.Log, clock: cfg.Clock}, conns: map[net.Conn]struct{}{}}, nil |
| +} |
| + |
| +// Feed is the proxy's current feed. |
| +func (s *Server) Feed() *Feed { return s.feed } |
| + |
| +// EgressAddr and BootAddr are the bound listeners' addresses. |
| +func (s *Server) EgressAddr() netip.AddrPort { return s.egressLn.Addr().(*net.TCPAddr).AddrPort() } |
| +func (s *Server) BootAddr() netip.AddrPort { return s.bootLn.Addr().(*net.TCPAddr).AddrPort() } |
| + |
| +// Start binds both listeners and runs the listeners and the feed poll |
| +// (at once, then every PollInterval) until ctx ends or Close. |
| +func (s *Server) Start(ctx context.Context) error { |
| + egress, err := net.Listen("tcp", s.cfg.Egress.String()) |
| + if err != nil { |
| + return fmt.Errorf("hostedproxy: egress listener: %w", err) |
| + } |
| + boot, err := net.Listen("tcp", s.cfg.Boot.String()) |
| + if err != nil { |
| + egress.Close() |
| + return fmt.Errorf("hostedproxy: bootstrap listener: %w", err) |
| + } |
| + ctx, s.cancel = context.WithCancel(ctx) |
| + s.egressLn, s.bootLn = egress, boot |
| + s.bootSrv = s.newBootServer(ctx) |
| + s.wg.Add(3) |
| + go func() { defer s.wg.Done(); s.acceptEgress(ctx) }() |
| + go func() { defer s.wg.Done(); _ = s.bootSrv.ServeTLS(boot, "", "") }() |
| + go func() { defer s.wg.Done(); s.pollLoop(ctx) }() |
| + go func() { <-ctx.Done(); s.shut() }() |
| + return nil |
| +} |
| + |
| +// Close stops the proxy, closes every tunnel and waits for them. |
| +func (s *Server) Close() error { |
| + s.shut() |
| + s.wg.Wait() |
| + return nil |
| +} |
| + |
| +func (s *Server) shut() { |
| + s.mu.Lock() |
| + if s.closed { |
| + s.mu.Unlock() |
| + return |
| + } |
| + s.closed = true |
| + conns := s.conns |
| + s.conns = map[net.Conn]struct{}{} |
| + s.mu.Unlock() |
| + if s.cancel != nil { |
| + s.cancel() |
| + } |
| + if s.egressLn != nil { |
| + s.egressLn.Close() |
| + } |
| + if s.bootSrv != nil { |
| + s.bootSrv.Close() |
| + } |
| + for c := range conns { |
| + c.Close() |
| + } |
| +} |
| + |
| +// Serve runs a proxy for cfg until ctx ends. |
| +func Serve(ctx context.Context, cfg Config) error { |
| + s, err := NewServer(cfg) |
| + if err != nil { |
| + return err |
| + } |
| + if err := s.Start(ctx); err != nil { |
| + return err |
| + } |
| + <-ctx.Done() |
| + return s.Close() |
| +} |
| + |
| +func (s *Server) track(c net.Conn) bool { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + if s.closed { |
| + return false |
| + } |
| + s.conns[c] = struct{}{} |
| + return true |
| +} |
| + |
| +func (s *Server) untrack(c net.Conn) { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + delete(s.conns, c) |
| +} |
| + |
| +func (s *Server) acceptEgress(ctx context.Context) { |
| + cfg := &tls.Config{ |
| + MinVersion: tls.VersionTLS12, ClientAuth: tls.RequireAndVerifyClientCert, ClientCAs: s.cfg.ClientCA, |
| + NextProtos: []string{ALPNHTTP11}, Time: s.clock.Wall, |
| + GetCertificate: func(*tls.ClientHelloInfo) (*tls.Certificate, error) { return s.ca.ipLeaf(s.cfg.Egress.Addr()) }, |
| + } |
| + for { |
| + raw, err := s.egressLn.Accept() |
| + if err != nil { |
| + if ctx.Err() != nil || errors.Is(err, net.ErrClosed) { |
| + return |
| + } |
| + time.Sleep(50 * time.Millisecond) |
| + continue |
| + } |
| + if !s.track(raw) { |
| + raw.Close() |
| + return |
| + } |
| + s.wg.Add(1) |
| + go func() { |
| + defer s.wg.Done() |
| + defer s.untrack(raw) |
| + defer raw.Close() |
| + s.serveEgress(ctx, raw, cfg) |
| + }() |
| + } |
| +} |
| + |
| +// serveEgress runs one VM connection: mutual TLS, one CONNECT, then the |
| +// tunnel. |
| +func (s *Server) serveEgress(ctx context.Context, raw net.Conn, cfg *tls.Config) { |
| + _ = raw.SetDeadline(time.Now().Add(handshakeTimeout)) |
| + outer := tls.Server(raw, cfg) |
| + if err := outer.HandshakeContext(ctx); err != nil { |
| + return |
| + } |
| + chains := outer.ConnectionState().VerifiedChains |
| + if len(chains) == 0 || len(chains[0]) == 0 { |
| + return |
| + } |
| + id, err := IdentityFromCert(chains[0][0]) |
| + if err != nil { |
| + return |
| + } |
| + br := bufio.NewReader(outer) |
| + req, err := http.ReadRequest(br) |
| + if err != nil { |
| + return |
| + } |
| + _ = raw.SetDeadline(time.Time{}) |
| + target := req.RequestURI |
| + if req.Method != http.MethodConnect { |
| + s.log.write(entry{id: id, method: req.Method, decision: deny(ReasonBadMethod)}) |
| + writeStatus(outer, http.StatusMethodNotAllowed) |
| + return |
| + } |
| + d := s.feed.decideTarget(id, target, s.clock.Mono()) |
| + if !d.Allow { |
| + s.log.write(entry{id: id, destination: target, method: req.Method, decision: d}) |
| + writeStatus(outer, http.StatusForbidden) |
| + return |
| + } |
| + if _, err := io.WriteString(outer, "HTTP/1.1 200 Connection established\r\n\r\n"); err != nil { |
| + return |
| + } |
| + t := &tunnel{s: s, id: id, target: target, svc: d.Service, raw: raw} |
| + t.ctx, t.cancel = context.WithCancel(ctx) |
| + defer t.close() |
| + go t.watch() |
| + t.serve(&bufferedConn{Conn: outer, r: br}) |
| +} |
| + |
| +// writeStatus answers with a bare status and closes the exchange. |
| +func writeStatus(w io.Writer, code int) { |
| + _, _ = fmt.Fprintf(w, "HTTP/1.1 %d %s\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", code, http.StatusText(code)) |
| +} |
| + |
| +// bufferedConn reads through r, which may hold bytes already read from |
| +// Conn. |
| +type bufferedConn struct { |
| + net.Conn |
| + r *bufio.Reader |
| +} |
| + |
| +func (c *bufferedConn) Read(p []byte) (int, error) { return c.r.Read(p) } |
| + |
| +// countConn counts the bytes read from and written to Conn. |
| +type countConn struct { |
| + net.Conn |
| + in, out *atomic.Int64 |
| +} |
| + |
| +func (c *countConn) Read(p []byte) (int, error) { |
| + n, err := c.Conn.Read(p) |
| + c.in.Add(int64(n)) |
| + return n, err |
| +} |
| + |
| +func (c *countConn) Write(p []byte) (int, error) { |
| + n, err := c.Conn.Write(p) |
| + c.out.Add(int64(n)) |
| + return n, err |
| +} |
| + |
| +// tunnel is one CONNECT tunnel to one service. |
| +type tunnel struct { |
| + s *Server |
| + id Identity |
| + target string |
| + svc hostedwire.Service |
| + raw net.Conn |
| + ctx context.Context |
| + cancel context.CancelFunc |
| + |
| + in, out atomic.Int64 |
| + |
| + mu sync.Mutex |
| + done bool |
| + closers []func() |
| +} |
| + |
| +// onClose runs fn when the tunnel closes (now, if it has). |
| +func (t *tunnel) onClose(fn func()) { |
| + t.mu.Lock() |
| + if !t.done { |
| + t.closers = append(t.closers, fn) |
| + t.mu.Unlock() |
| + return |
| + } |
| + t.mu.Unlock() |
| + fn() |
| +} |
| + |
| +func (t *tunnel) close() { |
| + t.mu.Lock() |
| + if t.done { |
| + t.mu.Unlock() |
| + return |
| + } |
| + t.done = true |
| + closers := t.closers |
| + t.mu.Unlock() |
| + t.cancel() |
| + t.raw.Close() |
| + for _, fn := range closers { |
| + fn() |
| + } |
| +} |
| + |
| +// watch closes the tunnel at its deadline (Feed.Deadline), or as soon as |
| +// a fresher feed no longer lets its identity through. |
| +func (t *tunnel) watch() { |
| + feed, clock := t.s.feed, t.s.clock |
| + for { |
| + changes := feed.changes() |
| + mono := clock.Mono() |
| + deadline := feed.Deadline(t.id, mono) |
| + if _, reason := feed.current(t.id, mono); reason != "" || mono >= deadline { |
| + t.close() |
| + return |
| + } |
| + select { |
| + case <-clock.After(deadline - mono): |
| + case <-changes: |
| + case <-t.ctx.Done(): |
| + return |
| + } |
| + } |
| +} |
| + |
| +// hello is what the inner ClientHello said. |
| +type hello struct { |
| + seen bool |
| + sni string |
| + alpn []string |
| + ech bool |
| + reason string // decideTLS's refusal, if any |
| +} |
| + |
| +// extECH is the encrypted_client_hello extension's code point. |
| +const extECH = 0xfe0d |
| + |
| +var errHelloRefused = errors.New("hostedproxy: client hello refused") |
| + |
| +// serve terminates the inner TLS with a leaf for exactly the service |
| +// host, then judges and forwards each request in turn. |
| +func (t *tunnel) serve(c net.Conn) { |
| + var h hello |
| + cfg := &tls.Config{MinVersion: tls.VersionTLS12, |
| + GetConfigForClient: func(chi *tls.ClientHelloInfo) (*tls.Config, error) { |
| + h = hello{seen: true, sni: chi.ServerName, alpn: slices.Clone(chi.SupportedProtos), ech: slices.Contains(chi.Extensions, extECH)} |
| + if h.reason = decideTLS(t.svc.Host, h.sni, h.alpn, h.ech); h.reason != "" { |
| + return nil, errHelloRefused |
| + } |
| + leaf, err := t.s.ca.hostLeaf(t.svc.Host) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return &tls.Config{MinVersion: tls.VersionTLS12, Certificates: []tls.Certificate{*leaf}, NextProtos: []string{ALPNHTTP11}}, nil |
| + }} |
| + _ = c.SetDeadline(time.Now().Add(handshakeTimeout)) |
| + inner := tls.Server(c, cfg) |
| + if err := inner.HandshakeContext(t.ctx); err != nil { |
| + switch { |
| + case h.reason != "": |
| + t.logDecision("", "", deny(h.reason), 0, 0, 0) |
| + case !h.seen && t.ctx.Err() == nil: |
| + t.logDecision("", "", deny(ReasonNestedTunnel), 0, 0, 0) |
| + } |
| + return |
| + } |
| + _ = c.SetDeadline(time.Time{}) |
| + t.onClose(func() { inner.Close() }) |
| + ic := &countConn{Conn: inner, in: &t.in, out: &t.out} |
| + br := bufio.NewReader(ic) |
| + transport := &http.Transport{ |
| + DialTLSContext: func(ctx context.Context, _, _ string) (net.Conn, error) { return t.s.dialOrigin(ctx, t.svc.Host) }, |
| + TLSNextProto: map[string]func(string, *tls.Conn) http.RoundTripper{}, |
| + DisableCompression: true, MaxIdleConnsPerHost: 1, IdleConnTimeout: idleTimeout, |
| + ResponseHeaderTimeout: time.Minute, |
| + } |
| + t.onClose(transport.CloseIdleConnections) |
| + for { |
| + in0, out0 := t.in.Load(), t.out.Load() |
| + _ = inner.SetReadDeadline(time.Now().Add(idleTimeout)) |
| + req, err := http.ReadRequest(br) |
| + if err != nil { |
| + if !errors.Is(err, io.EOF) && !errors.Is(err, net.ErrClosed) && !isTimeout(err) && t.ctx.Err() == nil { |
| + t.logDecision("", "", deny(ReasonNestedTunnel), 0, t.in.Load()-in0, t.out.Load()-out0) |
| + } |
| + return |
| + } |
| + _ = inner.SetReadDeadline(time.Time{}) |
| + r := Request{Connect: t.target, SNI: h.sni, Host: req.Host, Method: req.Method, Path: req.RequestURI, |
| + ALPN: h.alpn, ECH: h.ech, Upgrade: upgradeAsked(req.Header)} |
| + d := t.s.feed.Decide(t.id, r, t.s.clock.Mono()) |
| + if d.Allow && r.Upgrade && !websocketAsked(req.Header) { |
| + d = deny(ReasonNestedTunnel) |
| + } |
| + class := pathClassOf(t.svc.Class, req.RequestURI) |
| + if !d.Allow { |
| + writeStatus(ic, http.StatusForbidden) |
| + t.logDecision(req.Method, class, d, 0, t.in.Load()-in0, t.out.Load()-out0) |
| + return |
| + } |
| + status, keep := t.forward(transport, req, ic, br, r.Upgrade) |
| + rd := d |
| + if status == -http.StatusBadGateway { |
| + rd, status = Decision{Reason: ReasonRedirectRefused, Service: t.svc}, http.StatusBadGateway |
| + } |
| + t.logDecision(req.Method, class, rd, status, t.in.Load()-in0, t.out.Load()-out0) |
| + if !keep { |
| + return |
| + } |
| + } |
| +} |
| + |
| +func isTimeout(err error) bool { |
| + var ne net.Error |
| + return errors.As(err, &ne) && ne.Timeout() |
| +} |
| + |
| +func (t *tunnel) logDecision(method, class string, d Decision, status int, in, out int64) { |
| + if class == "" { |
| + class = "none" |
| + } |
| + t.s.log.write(entry{id: t.id, destination: t.target, method: method, pathClass: class, decision: d, |
| + status: status, in: in, out: out}) |
| +} |
| + |
| +// hopHeaders are dropped in both directions; Connection also names more. |
| +var hopHeaders = []string{"Connection", "Proxy-Connection", "Keep-Alive", "Proxy-Authenticate", "Proxy-Authorization", |
| + "Te", "Trailer", "Transfer-Encoding", "Upgrade"} |
| + |
| +func dropHop(h http.Header) http.Header { |
| + h = h.Clone() |
| + for _, v := range h.Values("Connection") { |
| + for _, name := range strings.Split(v, ",") { |
| + h.Del(textproto.TrimString(name)) |
| + } |
| + } |
| + for _, name := range hopHeaders { |
| + h.Del(name) |
| + } |
| + return h |
| +} |
| + |
| +// upgradeAsked: the request names any upgrade. |
| +func upgradeAsked(h http.Header) bool { |
| + if len(h.Values("Upgrade")) > 0 { |
| + return true |
| + } |
| + for _, v := range h.Values("Connection") { |
| + for _, name := range strings.Split(v, ",") { |
| + if strings.EqualFold(textproto.TrimString(name), "upgrade") { |
| + return true |
| + } |
| + } |
| + } |
| + return false |
| +} |
| + |
| +// websocketAsked: the upgrade asked for is exactly one, websocket. |
| +func websocketAsked(h http.Header) bool { |
| + v := h.Values("Upgrade") |
| + return len(v) == 1 && strings.EqualFold(strings.TrimSpace(v[0]), "websocket") |
| +} |
| + |
| +// forward sends req to the service host over the proxy's own TLS and |
| +// writes the answer to the VM. It returns the status written and whether |
| +// the tunnel may carry another request; -502 means a redirect to another |
| +// authority was refused (and a bare 502 written). |
| +func (t *tunnel) forward(rt http.RoundTripper, req *http.Request, ic net.Conn, br *bufio.Reader, upgrade bool) (int, bool) { |
| + header := dropHop(req.Header) |
| + if upgrade { |
| + header.Set("Connection", "Upgrade") |
| + header.Set("Upgrade", "websocket") |
| + } |
| + out := (&http.Request{Method: req.Method, Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1, Header: header, |
| + URL: &url.URL{Scheme: "https", Host: t.svc.Host, Path: req.URL.Path, RawPath: req.URL.RawPath}, |
| + Host: t.svc.Host, Body: req.Body, ContentLength: req.ContentLength}).WithContext(t.ctx) |
| + if req.ContentLength == 0 { |
| + out.Body = nil |
| + } |
| + resp, err := rt.RoundTrip(out) |
| + if err != nil { |
| + writeStatus(ic, http.StatusBadGateway) |
| + return http.StatusBadGateway, false |
| + } |
| + defer resp.Body.Close() |
| + if rd := decideResponse(t.svc, resp.StatusCode, resp.Header.Values("Location")); !rd.Allow { |
| + writeStatus(ic, http.StatusBadGateway) |
| + return -http.StatusBadGateway, false |
| + } |
| + if resp.StatusCode == http.StatusSwitchingProtocols { |
| + return t.pipe(resp, ic, br, upgrade), false |
| + } |
| + resp.Header = dropHop(resp.Header) |
| + if err := resp.Write(ic); err != nil { |
| + return resp.StatusCode, false |
| + } |
| + // A body that ends only when the connection does ends the tunnel too. |
| + framed := resp.ContentLength >= 0 || slices.Contains(resp.TransferEncoding, "chunked") |
| + return resp.StatusCode, framed && !req.Close && !resp.Close |
| +} |
| + |
| +// pipe joins an upgraded connection to the VM until either side ends or |
| +// the tunnel closes. |
| +func (t *tunnel) pipe(resp *http.Response, ic net.Conn, br *bufio.Reader, upgrade bool) int { |
| + origin, ok := resp.Body.(io.ReadWriteCloser) |
| + if !ok || !upgrade || !websocketAsked(resp.Header) { |
| + writeStatus(ic, http.StatusBadGateway) |
| + return http.StatusBadGateway |
| + } |
| + t.onClose(func() { origin.Close() }) |
| + var head strings.Builder |
| + head.WriteString("HTTP/1.1 101 Switching Protocols\r\n") |
| + _ = resp.Header.Write(&head) |
| + head.WriteString("\r\n") |
| + if _, err := io.WriteString(ic, head.String()); err != nil { |
| + return http.StatusSwitchingProtocols |
| + } |
| + done := make(chan struct{}, 2) |
| + go func() { _, _ = io.Copy(origin, br); done <- struct{}{} }() |
| + go func() { _, _ = io.Copy(ic, origin); done <- struct{}{} }() |
| + <-done |
| + t.close() |
| + <-done |
| + return http.StatusSwitchingProtocols |
| +} |
| + |
| +// validPin is the form ControllerTLSPin takes: 64 lower-case hex digits. |
| +func validPin(s string) bool { |
| + if len(s) != 64 { |
| + return false |
| + } |
| + _, err := hex.DecodeString(s) |
| + return err == nil && strings.ToLower(s) == s |
| +} |
diff --git a/internal/hostedproxy/egress_test.go b/internal/hostedproxy/egress_test.go| new file mode 100644 |
| index 00000000..700eeead |
| --- /dev/null |
| +++ b/internal/hostedproxy/egress_test.go |
| @@ -0,0 +1,679 @@ |
| +package hostedproxy |
| + |
| +import ( |
| + "bufio" |
| + "bytes" |
| + "context" |
| + "crypto/ecdsa" |
| + "crypto/ed25519" |
| + "crypto/elliptic" |
| + "crypto/rand" |
| + "crypto/sha256" |
| + "crypto/tls" |
| + "crypto/x509" |
| + "crypto/x509/pkix" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "math/big" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/netip" |
| + "net/url" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/hostedctl/ctlproxy" |
| + "amadan.net/oficina/equipo/internal/hostedwire" |
| + "amadan.net/oficina/equipo/internal/isolatedjob" |
| + "github.com/coder/websocket" |
| +) |
| + |
| +// syncBuffer is a decision log tests can read while the proxy writes. |
| +type syncBuffer struct { |
| + mu sync.Mutex |
| + b bytes.Buffer |
| +} |
| + |
| +func (s *syncBuffer) Write(p []byte) (int, error) { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + return s.b.Write(p) |
| +} |
| + |
| +func (s *syncBuffer) String() string { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + return s.b.String() |
| +} |
| + |
| +// lines decodes the decision log. |
| +func (s *syncBuffer) lines(t *testing.T) []logLine { |
| + t.Helper() |
| + var out []logLine |
| + for _, l := range strings.Split(strings.TrimSpace(s.String()), "\n") { |
| + if l == "" { |
| + continue |
| + } |
| + var ll logLine |
| + if err := json.Unmarshal([]byte(l), &ll); err != nil { |
| + t.Fatalf("decision log line %q: %v", l, err) |
| + } |
| + out = append(out, ll) |
| + } |
| + return out |
| +} |
| + |
| +// waitLog waits (real time, bounded) for a decision line matching fn. |
| +func (s *syncBuffer) waitLog(t *testing.T, what string, fn func(logLine) bool) logLine { |
| + t.Helper() |
| + deadline := time.Now().Add(5 * time.Second) |
| + for time.Now().Before(deadline) { |
| + for _, l := range s.lines(t) { |
| + if fn(l) { |
| + return l |
| + } |
| + } |
| + time.Sleep(10 * time.Millisecond) |
| + } |
| + t.Fatalf("no decision line for %s in:\n%s", what, s.String()) |
| + return logLine{} |
| +} |
| + |
| +// testCA is a CA tests mint certificates under. |
| +type testCA struct { |
| + cert *x509.Certificate |
| + key *ecdsa.PrivateKey |
| + pair tls.Certificate |
| + pool *x509.CertPool |
| +} |
| + |
| +var testSerial atomic.Int64 |
| + |
| +func newTestCA(t *testing.T, name string) *testCA { |
| + t.Helper() |
| + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + tmpl := &x509.Certificate{SerialNumber: big.NewInt(testSerial.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 &testCA{cert: c, key: key, pair: tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key, Leaf: c}, pool: pool} |
| +} |
| + |
| +func (ca *testCA) issue(t *testing.T, tmpl *x509.Certificate) tls.Certificate { |
| + t.Helper() |
| + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if tmpl.SerialNumber == nil { |
| + tmpl.SerialNumber = big.NewInt(testSerial.Add(1)) |
| + } |
| + der, err := x509.CreateCertificate(rand.Reader, tmpl, ca.cert, &key.PublicKey, ca.key) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + c, _ := x509.ParseCertificate(der) |
| + return tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key, Leaf: c} |
| +} |
| + |
| +// fakeController answers the proxy routes, verifying the proxy's |
| +// signature and signing each answer for its nonce. |
| +type fakeController struct { |
| + t *testing.T |
| + srv *httptest.Server |
| + key ed25519.PrivateKey |
| + signer ed25519.PrivateKey // signs answers; key unless a test swaps it |
| + mu sync.Mutex |
| + feed hostedwire.ProxyFeed |
| + got map[string][][]byte // route -> bodies received |
| + nonces map[string]bool |
| +} |
| + |
| +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 |
| +} |
| + |
| +func (c *fakeController) bodies(route string) [][]byte { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + return c.got[route] |
| +} |
| + |
| +func (c *fakeController) setFeed(f hostedwire.ProxyFeed) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + c.feed = f |
| +} |
| + |
| +func newFakeController(t *testing.T, clock Clock, proxyPub ed25519.PublicKey) *fakeController { |
| + _, key, _ := ed25519.GenerateKey(rand.Reader) |
| + c := &fakeController{t: t, key: key, signer: key, got: map[string][][]byte{}, nonces: map[string]bool{}} |
| + v := &hostedwire.Verifier{Keys: map[hostedwire.KeyID]hostedwire.VerifyKey{"proxy-1": {Public: proxyPub, Role: hostedwire.RoleProxy}}, |
| + Nonces: c, Now: clock.Wall} |
| + c.srv = httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + body, _ := io.ReadAll(r.Body) |
| + if _, _, err := v.Verify(r, body); err != nil { |
| + http.Error(w, "unsigned", http.StatusUnauthorized) |
| + return |
| + } |
| + var out any |
| + c.mu.Lock() |
| + switch r.Method + " " + r.URL.Path { |
| + case "GET /v1/proxy/feed": |
| + out = c.feed |
| + case "POST /v1/proxy/redeem", "POST /v1/proxy/renew": |
| + out = hostedwire.RedeemResponse{Cert: []byte("issued"), NotAfterNS: 42} |
| + case "POST /v1/proxy/cert-report": |
| + out = struct{}{} |
| + } |
| + c.got[r.URL.Path] = append(c.got[r.URL.Path], body) |
| + signer := c.signer |
| + c.mu.Unlock() |
| + if out == nil { |
| + http.NotFound(w, r) |
| + return |
| + } |
| + raw, _ := json.Marshal(out) |
| + hostedwire.SignResponse(w.Header(), http.StatusOK, r.Header.Get(hostedwire.HeaderNonce), raw, signer) |
| + w.Header().Set("Content-Type", "application/json") |
| + _, _ = w.Write(raw) |
| + })) |
| + c.srv.StartTLS() |
| + t.Cleanup(c.srv.Close) |
| + return c |
| +} |
| + |
| +// spkiPin is the hex SHA-256 of c's SubjectPublicKeyInfo. |
| +func spkiPin(c *x509.Certificate) string { |
| + sum := sha256.Sum256(c.RawSubjectPublicKeyInfo) |
| + return hex.EncodeToString(sum[:]) |
| +} |
| + |
| +// env is one proxy on 127.0.0.1 with a fake controller and an origin |
| +// that answers as testHost. |
| +type env struct { |
| + t *testing.T |
| + clock *fakeClock |
| + clientCA *testCA |
| + intercept *testCA |
| + ctl *fakeController |
| + origin *httptest.Server |
| + hits atomic.Int64 // requests the origin saw |
| + handler atomic.Value // http.Handler for the origin |
| + srv *Server |
| + log *syncBuffer |
| +} |
| + |
| +func newEnv(t *testing.T) *env { |
| + t.Helper() |
| + e := &env{t: t, clock: newFakeClock(), clientCA: newTestCA(t, "client CA"), intercept: newTestCA(t, "intercept CA"), |
| + log: &syncBuffer{}} |
| + pub, key, _ := ed25519.GenerateKey(rand.Reader) |
| + e.ctl = newFakeController(t, e.clock, pub) |
| + e.ctl.setFeed(testFeed()) |
| + |
| + originCA := newTestCA(t, "origin CA") |
| + leaf := originCA.issue(t, &x509.Certificate{DNSNames: []string{testHost}, 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}}) |
| + e.handler.Store(http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + _, _ = io.WriteString(w, "protocol 39") |
| + }))) |
| + e.origin = httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + e.hits.Add(1) |
| + e.handler.Load().(http.Handler).ServeHTTP(w, r) |
| + })) |
| + e.origin.TLS = &tls.Config{Certificates: []tls.Certificate{leaf}} |
| + e.origin.StartTLS() |
| + t.Cleanup(e.origin.Close) |
| + originAddr := e.origin.Listener.Addr().String() |
| + |
| + srv, err := NewServer(Config{ |
| + Egress: netip.MustParseAddrPort("127.0.0.1:0"), Boot: netip.MustParseAddrPort("127.0.0.1:0"), |
| + ControllerURL: e.ctl.srv.URL, ControllerKey: e.ctl.key.Public().(ed25519.PublicKey), |
| + ControllerTLSPin: spkiPin(e.ctl.srv.Certificate()), KeyID: "proxy-1", Key: key, |
| + ClientCA: e.clientCA.pool, InterceptCA: e.intercept.pair, OriginRoots: originCA.pool, Log: e.log, |
| + Clock: e.clock, |
| + DialOrigin: func(ctx context.Context, network, addr string) (net.Conn, error) { |
| + if addr != testLocal { |
| + return nil, fmt.Errorf("test origin dial to %s", addr) |
| + } |
| + var d net.Dialer |
| + return d.DialContext(ctx, network, originAddr) |
| + }, |
| + }) |
| + 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() |
| + if err := srv.Close(); err != nil { |
| + t.Errorf("Close: %v", err) |
| + } |
| + }) |
| + e.srv = srv |
| + if err := srv.Poll(ctx); err != nil { |
| + t.Fatalf("Poll: %v", err) |
| + } |
| + return e |
| +} |
| + |
| +// vmCert is a client certificate for l-1 under the controller's CA, or |
| +// under ca when given. |
| +func (e *env) vmCert(serial int64, ca *testCA) tls.Certificate { |
| + if ca == nil { |
| + ca = e.clientCA |
| + } |
| + u := ctlproxy.LaunchIdentity{LaunchID: "l-1", AttemptID: "a-1", VMRef: isolatedjob.Ref("vm-1"), Epoch: 2}.URI() |
| + wall := e.clock.Wall() |
| + return ca.issue(e.t, &x509.Certificate{SerialNumber: big.NewInt(serial), NotBefore: wall.Add(-time.Minute), |
| + NotAfter: wall.Add(ctlproxy.CertLifetime), URIs: []*url.URL{u}, KeyUsage: x509.KeyUsageDigitalSignature, |
| + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}}) |
| +} |
| + |
| +// outer opens mutual TLS to addr with cert (nil: none). |
| +func (e *env) outer(addr netip.AddrPort, cert *tls.Certificate) (*tls.Conn, error) { |
| + cfg := &tls.Config{ServerName: addr.Addr().String(), RootCAs: e.intercept.pool, Time: e.clock.Wall, |
| + NextProtos: []string{ALPNHTTP11}} |
| + if cert != nil { |
| + cfg.Certificates = []tls.Certificate{*cert} |
| + } |
| + c, err := tls.Dial("tcp", addr.String(), cfg) |
| + if err != nil { |
| + return nil, err |
| + } |
| + // TLS 1.3 reports a refused client certificate on the first read. |
| + return c, nil |
| +} |
| + |
| +// connect opens a tunnel to target and returns the connection after the |
| +// proxy's 200, or the proxy's status. |
| +func (e *env) connect(cert *tls.Certificate, target string) (net.Conn, int, error) { |
| + c, err := e.outer(e.srv.EgressAddr(), cert) |
| + if err != nil { |
| + return nil, 0, err |
| + } |
| + _ = c.SetDeadline(time.Now().Add(5 * time.Second)) |
| + if _, err := fmt.Fprintf(c, "CONNECT %s HTTP/1.1\r\nHost: %s\r\nProxy-Authorization: Bearer SECRET-PROXY-AUTH\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 |
| +} |
| + |
| +// tunnel opens a tunnel to target and the inner TLS with sni and alpn. |
| +func (e *env) tunnel(cert *tls.Certificate, target, sni string, alpn []string) (*tls.Conn, error) { |
| + c, status, err := e.connect(cert, target) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if status != http.StatusOK { |
| + return nil, fmt.Errorf("CONNECT %s: status %d", target, status) |
| + } |
| + inner := tls.Client(c, &tls.Config{ServerName: sni, RootCAs: e.intercept.pool, NextProtos: alpn, Time: e.clock.Wall}) |
| + if err := inner.Handshake(); err != nil { |
| + c.Close() |
| + return nil, err |
| + } |
| + return inner, nil |
| +} |
| + |
| +// client is an HTTP client whose every connection is a tunnel through the |
| +// proxy, as the hosted runner's transport (Task 12) makes them. |
| +func (e *env) client(cert *tls.Certificate) *http.Client { |
| + return &http.Client{ |
| + Transport: &http.Transport{DialTLSContext: func(_ context.Context, _, addr string) (net.Conn, error) { |
| + host, _, _ := net.SplitHostPort(addr) |
| + return e.tunnel(cert, addr, host, []string{ALPNHTTP11}) |
| + }}, |
| + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, |
| + } |
| +} |
| + |
| +func TestEgressForwardsAllowedRequests(t *testing.T) { |
| + e := newEnv(t) |
| + var seen sync.Map |
| + e.handler.Store(http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + body, _ := io.ReadAll(r.Body) |
| + seen.Store(r.Method+" "+r.URL.RequestURI(), r.Host+" "+string(body)) |
| + _, _ = io.WriteString(w, "ok "+r.URL.Path) |
| + }))) |
| + cert := e.vmCert(0x51, nil) |
| + c := e.client(&cert) |
| + resp, err := c.Get("https://" + testHost + "/api/runner/protocol") |
| + if err != nil { |
| + t.Fatalf("GET protocol through the proxy: %v", err) |
| + } |
| + body, _ := io.ReadAll(resp.Body) |
| + resp.Body.Close() |
| + if resp.StatusCode != 200 || string(body) != "ok /api/runner/protocol" { |
| + t.Fatalf("GET protocol = %d %q", resp.StatusCode, body) |
| + } |
| + resp, err = c.Post("https://"+testHost+"/api/hosted/enrol", "application/json", strings.NewReader(`{"vm":"vm-1"}`)) |
| + if err != nil { |
| + t.Fatalf("POST enrol: %v", err) |
| + } |
| + resp.Body.Close() |
| + if got, _ := seen.Load("POST /api/hosted/enrol"); got != testHost+` {"vm":"vm-1"}` { |
| + t.Errorf("origin saw enrol as %q", got) |
| + } |
| + l := e.log.waitLog(t, "the enrol", func(l logLine) bool { return l.Method == "POST" && l.Decision == "allow" }) |
| + if l.VM != "vm-1" || l.Launch != "l-1" || l.Attempt != "a-1" || l.Destination != testLocal || |
| + l.PathClass != hostedwire.ServiceInstance || l.Reason != "" || l.BytesIn == 0 || l.BytesOut == 0 || l.Status != 200 { |
| + t.Errorf("decision line for the enrol = %+v", l) |
| + } |
| +} |
| + |
| +func TestEgressRefusesAndTheOriginSeesNothing(t *testing.T) { |
| + e := newEnv(t) |
| + cert := e.vmCert(0x52, nil) |
| + // A CONNECT to an IP literal or a host off the manifest: 403, no tunnel. |
| + for target, reason := range map[string]string{"127.0.0.1:443": ReasonIPLiteral, "other.example.test:443": ReasonNotInManifest, |
| + testHost + ":8443": ReasonBadPort} { |
| + if _, status, err := e.connect(&cert, target); err != nil || status != http.StatusForbidden { |
| + t.Errorf("CONNECT %s = %d, %v; want 403", target, status, err) |
| + } |
| + e.log.waitLog(t, target, func(l logLine) bool { return l.Destination == target && l.Reason == reason }) |
| + } |
| + // SNI of another host and h2 only: the inner handshake is refused. |
| + if c, err := e.tunnel(&cert, testLocal, "other.example.test", []string{ALPNHTTP11}); err == nil { |
| + c.Close() |
| + t.Error("inner TLS with another SNI succeeded") |
| + } |
| + e.log.waitLog(t, "sni", func(l logLine) bool { return l.Reason == ReasonSNIMismatch }) |
| + if c, err := e.tunnel(&cert, testLocal, testHost, []string{"h2"}); err == nil { |
| + c.Close() |
| + t.Error("inner TLS offering only h2 succeeded") |
| + } |
| + e.log.waitLog(t, "alpn", func(l logLine) bool { return l.Reason == ReasonALPN }) |
| + // Another Host, a path off the class, a nested CONNECT, opaque bytes. |
| + for raw, reason := range map[string]string{ |
| + "GET /api/runner/protocol HTTP/1.1\r\nHost: other.example.test\r\n\r\n": ReasonHostMismatch, |
| + "GET /api/runner/v2/leases HTTP/1.1\r\nHost: " + testHost + "\r\n\r\n": ReasonBadPath, |
| + "CONNECT other.example.test:443 HTTP/1.1\r\nHost: other.example.test:443\r\n\r\n": ReasonNestedTunnel, |
| + "\x16\x03\x01 opaque bytes, not HTTP\r\n\r\n": ReasonNestedTunnel, |
| + } { |
| + inner, err := e.tunnel(&cert, testLocal, testHost, []string{ALPNHTTP11}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + _ = inner.SetDeadline(time.Now().Add(5 * time.Second)) |
| + _, _ = io.WriteString(inner, raw) |
| + got, _ := io.ReadAll(inner) |
| + inner.Close() |
| + if reason != ReasonNestedTunnel && !strings.HasPrefix(string(got), "HTTP/1.1 403") { |
| + t.Errorf("%q answered %q, want 403", raw, got) |
| + } |
| + e.log.waitLog(t, reason, func(l logLine) bool { return l.Reason == reason && l.Destination == testLocal }) |
| + } |
| + if n := e.hits.Load(); n != 0 { |
| + t.Errorf("the origin saw %d requests, want 0", n) |
| + } |
| +} |
| + |
| +func TestEgressRedirectRefused(t *testing.T) { |
| + e := newEnv(t) |
| + e.handler.Store(http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + http.Redirect(w, r, "https://other.example.test/steal", http.StatusFound) |
| + }))) |
| + cert := e.vmCert(0x53, nil) |
| + resp, err := e.client(&cert).Get("https://" + testHost + "/api/runner/protocol") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + body, _ := io.ReadAll(resp.Body) |
| + resp.Body.Close() |
| + if resp.StatusCode != http.StatusBadGateway || resp.Header.Get("Location") != "" || strings.Contains(string(body), "other.example") { |
| + t.Errorf("redirect to another host answered %d %v %q, want a bare 502", resp.StatusCode, resp.Header, body) |
| + } |
| + e.log.waitLog(t, "the redirect", func(l logLine) bool { return l.Reason == ReasonRedirectRefused && l.Decision == "deny" }) |
| +} |
| + |
| +func TestEgressNeedsClientCertFromTheCA(t *testing.T) { |
| + e := newEnv(t) |
| + other := newTestCA(t, "other CA") |
| + cert := e.vmCert(0x54, other) |
| + for name, c := range map[string]*tls.Certificate{"no certificate": nil, "another CA's certificate": &cert} { |
| + if _, status, err := e.connect(c, testLocal); err == nil { |
| + t.Errorf("%s: CONNECT answered %d, want the handshake refused", name, status) |
| + } |
| + } |
| +} |
| + |
| +func TestEgressWebSocketClosesWhenRevoked(t *testing.T) { |
| + e := newEnv(t) |
| + e.handler.Store(http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + 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 |
| + } |
| + } |
| + }))) |
| + cert := e.vmCert(0x55, nil) |
| + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| + defer cancel() |
| + ws, _, err := websocket.Dial(ctx, "wss://"+testHost+"/api/runner/stream", &websocket.DialOptions{HTTPClient: e.client(&cert)}) |
| + if err != nil { |
| + t.Fatalf("WebSocket through the proxy: %v", err) |
| + } |
| + defer ws.CloseNow() |
| + if err := ws.Write(ctx, websocket.MessageText, []byte("ping")); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, msg, err := ws.Read(ctx); err != nil || string(msg) != "ping" { |
| + t.Fatalf("echo = %q, %v", msg, err) |
| + } |
| + // A fresher feed revokes the serial: the socket closes. |
| + f := testFeed() |
| + f.Revoked = append(f.Revoked, "55") |
| + e.ctl.setFeed(f) |
| + if err := e.srv.Poll(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, _, err := ws.Read(ctx); err == nil || errors.Is(err, context.DeadlineExceeded) { |
| + t.Fatalf("read after the revocation = %v, want the socket closed", err) |
| + } |
| + e.log.waitLog(t, "the socket", func(l logLine) bool { return l.Decision == "allow" && l.BytesIn > 0 && l.Status == 101 }) |
| +} |
| + |
| +func TestLogHasNoSecrets(t *testing.T) { |
| + e := newEnv(t) |
| + e.handler.Store(http.Handler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Set-Cookie", "session=SECRET-SET-COOKIE") |
| + _, _ = io.WriteString(w, "SECRET-RESPONSE-BODY") |
| + }))) |
| + cert := e.vmCert(0x56, nil) |
| + c := e.client(&cert) |
| + send := func(method, target, body string) { |
| + req, _ := http.NewRequest(method, "https://"+testHost+target, strings.NewReader(body)) |
| + req.Header.Set("Authorization", "Bearer SECRET-AUTHORIZATION") |
| + req.Header.Set("Cookie", "token=SECRET-COOKIE") |
| + req.Header.Set("X-Equipo-Token", "SECRET-HEADER") |
| + resp, err := c.Do(req) |
| + if err != nil { |
| + t.Fatalf("%s %s: %v", method, target, err) |
| + } |
| + _, _ = io.Copy(io.Discard, resp.Body) |
| + resp.Body.Close() |
| + } |
| + send("POST", "/api/hosted/enrol", `{"code":"SECRET-BODY"}`) |
| + send("GET", "/api/runner/protocol?token=SECRET-QUERY", "") |
| + send("POST", "/api/runner/v2/leases/SECRET-PATH", `SECRET-DENIED-BODY`) |
| + e.log.waitLog(t, "the enrol", func(l logLine) bool { return l.Decision == "allow" && l.Method == "POST" }) |
| + e.log.waitLog(t, "the query", func(l logLine) bool { return l.Reason == ReasonBadPath && l.Method == "GET" }) |
| + e.log.waitLog(t, "the leases path", func(l logLine) bool { return l.Reason == ReasonBadPath && l.Method == "POST" }) |
| + got := e.log.String() |
| + for _, secret := range []string{"SECRET-AUTHORIZATION", "SECRET-COOKIE", "SECRET-HEADER", "SECRET-BODY", "SECRET-QUERY", |
| + "SECRET-PATH", "SECRET-DENIED-BODY", "SECRET-SET-COOKIE", "SECRET-RESPONSE-BODY", "SECRET-PROXY-AUTH", "Bearer"} { |
| + if strings.Contains(got, secret) { |
| + t.Errorf("the decision log holds %s:\n%s", secret, got) |
| + } |
| + } |
| +} |
| + |
| +func TestPollVerifiesTheFeed(t *testing.T) { |
| + e := newEnv(t) |
| + ctx := context.Background() |
| + // The signer changes before the feed, so the background poll never |
| + // gets the revocation under the right key either. |
| + _, other, _ := ed25519.GenerateKey(rand.Reader) |
| + e.ctl.mu.Lock() |
| + e.ctl.signer = other |
| + e.ctl.mu.Unlock() |
| + f := testFeed() |
| + f.Revoked = []string{"77"} |
| + e.ctl.setFeed(f) |
| + if err := e.srv.Poll(ctx); err == nil { |
| + t.Error("Poll accepted a feed signed by another key") |
| + } |
| + id := testIdentity(e.clock.Wall()) |
| + id.Serial = "77" |
| + if d := e.srv.Feed().Decide(id, okRequest(), e.clock.Mono()); !d.Allow { |
| + t.Errorf("a feed under another key was installed: %+v", d) |
| + } |
| + e.ctl.mu.Lock() |
| + e.ctl.signer = e.ctl.key |
| + e.ctl.mu.Unlock() |
| + if err := e.srv.Poll(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + if d := e.srv.Feed().Decide(id, okRequest(), e.clock.Mono()); d.Reason != ReasonRevoked { |
| + t.Errorf("after a verified feed: %+v, want %s", d, ReasonRevoked) |
| + } |
| + // A controller whose certificate is not the pinned one is not asked. |
| + cfg := e.srv.cfg |
| + cfg.ControllerTLSPin = strings.Repeat("0", 64) |
| + s2, err := NewServer(cfg) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + before := len(e.ctl.bodies("/v1/proxy/feed")) |
| + if err := s2.Poll(ctx); err == nil { |
| + t.Error("Poll trusted a controller certificate that is not the pinned one") |
| + } |
| + if n := len(e.ctl.bodies("/v1/proxy/feed")); n != before { |
| + t.Errorf("the controller saw %d more feed requests, want 0", n-before) |
| + } |
| +} |
| + |
| +// boot posts body to the bootstrap listener's path, with cert (nil: none). |
| +func (e *env) boot(path string, cert *tls.Certificate, body string) (int, string) { |
| + e.t.Helper() |
| + cfg := &tls.Config{ServerName: e.srv.BootAddr().Addr().String(), RootCAs: e.intercept.pool, Time: e.clock.Wall} |
| + if cert != nil { |
| + cfg.Certificates = []tls.Certificate{*cert} |
| + } |
| + c := &http.Client{Transport: &http.Transport{TLSClientConfig: cfg}, Timeout: 10 * time.Second} |
| + resp, err := c.Post("https://"+e.srv.BootAddr().String()+path, "application/json", strings.NewReader(body)) |
| + if err != nil { |
| + e.t.Fatalf("POST %s: %v", path, err) |
| + } |
| + defer resp.Body.Close() |
| + got, _ := io.ReadAll(resp.Body) |
| + return resp.StatusCode, string(got) |
| +} |
| + |
| +func TestBootForwardsUnderTheProxySignature(t *testing.T) { |
| + e := newEnv(t) |
| + redeem := `{"launch_id":"l-1","vm_ref":"vm-1","proxy_code":"` + ctlproxy.CodePlaceholder + `","csr":"AAAA"}` |
| + if status, body := e.boot("/redeem", nil, redeem); status != 200 || !strings.Contains(body, `"not_after_ns":42`) { |
| + t.Errorf("redeem = %d %s", status, body) |
| + } |
| + if got := e.ctl.bodies("/v1/proxy/redeem"); len(got) != 1 || string(got[0]) != redeem { |
| + t.Errorf("controller got redemptions %q, want the VM's body once", got) |
| + } |
| + cert := e.vmCert(0x57, nil) |
| + other := e.vmCert(0x58, nil) |
| + renew := `{"serial":"57","csr":"AAAA"}` |
| + for name, tc := range map[string]struct { |
| + cert *tls.Certificate |
| + body string |
| + }{ |
| + "renewal without a certificate": {nil, renew}, |
| + "renewal for another serial": {&other, renew}, |
| + "report without a certificate": {nil, `{"serial":"57","report":"AAAA","sig":"AAAA"}`}, |
| + "report for another serial": {&other, `{"serial":"57","report":"AAAA","sig":"AAAA"}`}, |
| + "renewal with a field the type does not have": {&cert, `{"serial":"57","csr":"AAAA","vm_ref":"vm-9"}`}, |
| + } { |
| + path := "/renew" |
| + if strings.HasPrefix(name, "report") { |
| + path = "/cert-report" |
| + } |
| + if status, _ := e.boot(path, tc.cert, tc.body); status == 200 { |
| + t.Errorf("%s: forwarded (200)", name) |
| + } |
| + } |
| + if n := len(e.ctl.bodies("/v1/proxy/renew")) + len(e.ctl.bodies("/v1/proxy/cert-report")); n != 0 { |
| + t.Fatalf("controller got %d refused requests", n) |
| + } |
| + if status, body := e.boot("/renew", &cert, renew); status != 200 { |
| + t.Errorf("renewal = %d %s", status, body) |
| + } |
| + report := `{"serial":"57","report":"cmVwb3J0","sig":"c2ln"}` |
| + if status, body := e.boot("/cert-report", &cert, report); status != 200 { |
| + t.Errorf("report = %d %s", status, body) |
| + } |
| + if got := e.ctl.bodies("/v1/proxy/cert-report"); len(got) != 1 || string(got[0]) != report { |
| + t.Errorf("controller got reports %q, want the VM's body once", got) |
| + } |
| + // A revoked serial is not current: its renewal is not forwarded. |
| + f := testFeed() |
| + f.Revoked = append(f.Revoked, "57") |
| + e.ctl.setFeed(f) |
| + if err := e.srv.Poll(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if status, _ := e.boot("/renew", &cert, renew); status == 200 { |
| + t.Error("renewal over a revoked certificate was forwarded") |
| + } |
| + if got := e.ctl.bodies("/v1/proxy/renew"); len(got) != 1 { |
| + t.Errorf("controller got %d renewals, want 1", len(got)) |
| + } |
| +} |
diff --git a/internal/hostedproxy/feed.go b/internal/hostedproxy/feed.go| new file mode 100644 |
| index 00000000..2b4d66b4 |
| --- /dev/null |
| +++ b/internal/hostedproxy/feed.go |
| @@ -0,0 +1,186 @@ |
| +package hostedproxy |
| + |
| +import ( |
| + "errors" |
| + "fmt" |
| + "sync" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/hostedctl/ctlproxy" |
| + "amadan.net/oficina/equipo/internal/hostedwire" |
| +) |
| + |
| +// Clock is the proxy's time. Mono is a monotonic reading (any origin) |
| +// that wall clock changes never move; every freshness and expiry rule is |
| +// judged on it. Wall dates certificates and signatures. After fires once |
| +// Mono has moved on by d. |
| +type Clock interface { |
| + Mono() time.Duration |
| + Wall() time.Time |
| + After(d time.Duration) <-chan time.Time |
| +} |
| + |
| +// SystemClock is the real clock: Mono counts from the process's first |
| +// reading on Go's monotonic clock. |
| +func SystemClock() Clock { return systemClock{} } |
| + |
| +var processStart = time.Now() |
| + |
| +type systemClock struct{} |
| + |
| +func (systemClock) Mono() time.Duration { return time.Since(processStart) } |
| +func (systemClock) Wall() time.Time { return time.Now() } |
| +func (systemClock) After(d time.Duration) <-chan time.Time { return time.After(d) } |
| + |
| +// ErrFeed is a feed Install will not take. |
| +var ErrFeed = errors.New("hostedproxy: feed is not valid") |
| + |
| +// Feed holds the newest launch feed the controller signed. It is safe for |
| +// concurrent use. |
| +// |
| +// A feed is usable from its receipt (Install) until its TTL has passed on |
| +// the monotonic clock, and never longer than ctlproxy.FeedLifetime (plan |
| +// decision S2-3). At receipt the feed also records the wall clock beside |
| +// the monotonic one; a certificate's NotAfter is turned into monotonic |
| +// time through that pair, so a later wall clock jump moves no deadline. |
| +type Feed struct { |
| + clock Clock |
| + |
| + mu sync.RWMutex |
| + have bool |
| + received time.Duration // Mono at receipt |
| + ttl time.Duration |
| + anchorWall time.Time // Wall at receipt |
| + launches map[string]hostedwire.FeedLaunch |
| + revoked map[string]bool |
| + changed chan struct{} // closed by the next Install |
| +} |
| + |
| +// NewFeed returns an empty feed: until a feed is installed every request |
| +// is refused as stale_feed. |
| +func NewFeed(c Clock) *Feed { |
| + if c == nil { |
| + c = SystemClock() |
| + } |
| + return &Feed{clock: c, changed: make(chan struct{})} |
| +} |
| + |
| +// Install takes pf, which the caller has verified as the controller's |
| +// signed answer to its own request, as the current feed, received now. |
| +func (f *Feed) Install(pf hostedwire.ProxyFeed) error { |
| + if pf.Version != ctlproxy.FeedVersion || pf.TTLMS <= 0 { |
| + return fmt.Errorf("%w: version %d, ttl %d ms", ErrFeed, pf.Version, pf.TTLMS) |
| + } |
| + launches := make(map[string]hostedwire.FeedLaunch, len(pf.Launches)) |
| + for _, l := range pf.Launches { |
| + if l.LaunchID == "" { |
| + return fmt.Errorf("%w: a launch without an ID", ErrFeed) |
| + } |
| + if _, dup := launches[l.LaunchID]; dup { |
| + return fmt.Errorf("%w: launch %s listed twice", ErrFeed, l.LaunchID) |
| + } |
| + launches[l.LaunchID] = l |
| + } |
| + revoked := make(map[string]bool, len(pf.Revoked)) |
| + for _, s := range pf.Revoked { |
| + revoked[s] = true |
| + } |
| + ttl := ctlproxy.FeedLifetime |
| + if pf.TTLMS < ttl.Milliseconds() { |
| + ttl = time.Duration(pf.TTLMS) * time.Millisecond |
| + } |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.have, f.ttl, f.launches, f.revoked = true, ttl, launches, revoked |
| + f.received, f.anchorWall = f.clock.Mono(), f.clock.Wall() |
| + close(f.changed) |
| + f.changed = make(chan struct{}) |
| + return nil |
| +} |
| + |
| +// changes returns a channel closed when the next feed is installed. |
| +func (f *Feed) changes() <-chan struct{} { |
| + f.mu.RLock() |
| + defer f.mu.RUnlock() |
| + return f.changed |
| +} |
| + |
| +// current judges id alone at mono: a fresh feed, an unexpired and |
| +// unrevoked certificate, and a live launch with the same attempt, VM and |
| +// epoch. It returns that launch, or the reason id is refused. |
| +func (f *Feed) current(id Identity, mono time.Duration) (hostedwire.FeedLaunch, string) { |
| + f.mu.RLock() |
| + defer f.mu.RUnlock() |
| + if !f.have || mono-f.received >= f.ttl || mono < f.received { |
| + return hostedwire.FeedLaunch{}, ReasonStaleFeed |
| + } |
| + if mono >= f.certEnd(id) { |
| + return hostedwire.FeedLaunch{}, ReasonCertExpired |
| + } |
| + if f.revoked[id.Serial] { |
| + return hostedwire.FeedLaunch{}, ReasonRevoked |
| + } |
| + l, ok := f.launches[id.LaunchID] |
| + if !ok || l.AttemptID != id.AttemptID || l.VMRef != id.VMRef { |
| + return hostedwire.FeedLaunch{}, ReasonUnknownLaunch |
| + } |
| + if l.Epoch != id.Epoch { |
| + return hostedwire.FeedLaunch{}, ReasonWrongEpoch |
| + } |
| + return l, "" |
| +} |
| + |
| +// certEnd is id's NotAfter on the monotonic clock, through the receipt's |
| +// clock pair. f.mu must be held. |
| +func (f *Feed) certEnd(id Identity) time.Duration { |
| + return f.received + id.NotAfter.Sub(f.anchorWall) |
| +} |
| + |
| +// Decide judges one request in a tunnel at mono: the identity (current), |
| +// then the CONNECT target, the inner TLS, the Host header and the path |
| +// class, in that order. Only an allowed decision names a Service. |
| +func (f *Feed) Decide(id Identity, r Request, mono time.Duration) Decision { |
| + l, reason := f.current(id, mono) |
| + if reason != "" { |
| + return deny(reason) |
| + } |
| + if r.Method == "CONNECT" { |
| + return deny(ReasonNestedTunnel) |
| + } |
| + d := decideConnect(l, r.Connect) |
| + if !d.Allow { |
| + return d |
| + } |
| + if reason := decideTLS(d.Service.Host, r.SNI, r.ALPN, r.ECH); reason != "" { |
| + return deny(reason) |
| + } |
| + if reason := decideHost(d.Service.Host, r.Host); reason != "" { |
| + return deny(reason) |
| + } |
| + if reason := classRoute(d.Service.Class, r.Method, r.Path, r.Upgrade); reason != "" { |
| + return deny(reason) |
| + } |
| + return d |
| +} |
| + |
| +// decideTarget judges id and a CONNECT target alone, before any tunnel |
| +// is opened. |
| +func (f *Feed) decideTarget(id Identity, connect string, mono time.Duration) Decision { |
| + l, reason := f.current(id, mono) |
| + if reason != "" { |
| + return deny(reason) |
| + } |
| + return decideConnect(l, connect) |
| +} |
| + |
| +// Deadline is when id's tunnels must close, on the monotonic clock: the |
| +// earlier of its certificate's NotAfter and the current feed's expiry. A |
| +// fresher feed moves the second on; with no feed it is mono itself. |
| +func (f *Feed) Deadline(id Identity, mono time.Duration) time.Duration { |
| + f.mu.RLock() |
| + defer f.mu.RUnlock() |
| + if !f.have { |
| + return mono |
| + } |
| + return min(f.received+f.ttl, f.certEnd(id)) |
| +} |
diff --git a/internal/hostedproxy/log.go b/internal/hostedproxy/log.go| new file mode 100644 |
| index 00000000..b65bffa8 |
| --- /dev/null |
| +++ b/internal/hostedproxy/log.go |
| @@ -0,0 +1,79 @@ |
| +package hostedproxy |
| + |
| +import ( |
| + "encoding/json" |
| + "io" |
| + "sync" |
| + "time" |
| +) |
| + |
| +// logLine is one decision in the log: who (VM, launch, attempt, epoch), |
| +// where (the CONNECT target), what (method and path class, never the |
| +// path), the decision and its reason, the origin's status when it |
| +// answered, and the plaintext bytes from the VM (in) and to it (out). |
| +// It never holds a header, body, query, path or token. |
| +type logLine struct { |
| + Time string `json:"time"` |
| + 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"` |
| + Decision string `json:"decision"` |
| + Reason string `json:"reason,omitempty"` |
| + Status int `json:"status,omitempty"` |
| + BytesIn int64 `json:"bytes_in"` |
| + BytesOut int64 `json:"bytes_out"` |
| +} |
| + |
| +// decisionLog writes one JSON line per decision to w. |
| +type decisionLog struct { |
| + mu sync.Mutex |
| + w io.Writer |
| + clock Clock |
| +} |
| + |
| +// maxDestination bounds a logged CONNECT target: a DNS name and a port. |
| +const maxDestination = 253 + 6 |
| + |
| +// knownMethods are the methods logged by name; any other is "other", so |
| +// a made-up method cannot carry text into the log. |
| +var knownMethods = map[string]bool{"GET": true, "HEAD": true, "POST": true, "PUT": true, "PATCH": true, |
| + "DELETE": true, "OPTIONS": true, "CONNECT": true, "TRACE": true} |
| + |
| +// entry is what a caller knows of one decision. |
| +type entry struct { |
| + id Identity |
| + destination string |
| + method string |
| + pathClass string |
| + decision Decision |
| + status int |
| + in, out int64 |
| +} |
| + |
| +func (l *decisionLog) write(e entry) { |
| + method := e.method |
| + if !knownMethods[method] { |
| + method = "other" |
| + } |
| + dest := e.destination |
| + if len(dest) > maxDestination { |
| + dest = dest[:maxDestination] |
| + } |
| + line := logLine{Time: l.clock.Wall().UTC().Format(time.RFC3339Nano), VM: string(e.id.VMRef), Launch: e.id.LaunchID, |
| + Attempt: e.id.AttemptID, Epoch: e.id.Epoch, Destination: dest, Method: method, PathClass: e.pathClass, |
| + Decision: "deny", Reason: e.decision.Reason, Status: e.status, BytesIn: e.in, BytesOut: e.out} |
| + if e.decision.Allow { |
| + line.Decision = "allow" |
| + } |
| + raw, err := json.Marshal(line) |
| + if err != nil { |
| + return |
| + } |
| + l.mu.Lock() |
| + defer l.mu.Unlock() |
| + _, _ = l.w.Write(append(raw, '\n')) |
| +} |
diff --git a/internal/hostedproxy/origin.go b/internal/hostedproxy/origin.go| new file mode 100644 |
| index 00000000..82afef8f |
| --- /dev/null |
| +++ b/internal/hostedproxy/origin.go |
| @@ -0,0 +1,134 @@ |
| +package hostedproxy |
| + |
| +import ( |
| + "context" |
| + "crypto" |
| + "crypto/ecdsa" |
| + "crypto/elliptic" |
| + "crypto/rand" |
| + "crypto/tls" |
| + "crypto/x509" |
| + "crypto/x509/pkix" |
| + "errors" |
| + "fmt" |
| + "math/big" |
| + "net" |
| + "net/netip" |
| + "strconv" |
| + "sync" |
| + "time" |
| +) |
| + |
| +// Leaves the intercept CA mints live leafLife from their issue and are |
| +// minted again leafRenew before they end. They are dated leafBackdate |
| +// back, for a VM whose wall clock is a little behind. |
| +const ( |
| + leafLife = 24 * time.Hour |
| + leafRenew = time.Hour |
| + leafBackdate = time.Hour |
| +) |
| + |
| +// interceptCA mints the proxy's server leaves: one for each CONNECT host |
| +// (the inner TLS), and one for each listener's IP address. VMs trust only |
| +// this CA (its SPKI is the bootstrap's ProxyCAPin). |
| +type interceptCA struct { |
| + cert *x509.Certificate |
| + key crypto.Signer |
| + leafKey *ecdsa.PrivateKey |
| + clock Clock |
| + |
| + mu sync.Mutex |
| + leaves map[string]*tls.Certificate |
| +} |
| + |
| +func newInterceptCA(pair tls.Certificate, clock Clock) (*interceptCA, error) { |
| + if len(pair.Certificate) == 0 { |
| + return nil, errors.New("hostedproxy: intercept CA has no certificate") |
| + } |
| + c, err := x509.ParseCertificate(pair.Certificate[0]) |
| + if err != nil { |
| + return nil, fmt.Errorf("hostedproxy: intercept CA: %w", err) |
| + } |
| + if !c.BasicConstraintsValid || !c.IsCA || c.KeyUsage&x509.KeyUsageCertSign == 0 { |
| + return nil, errors.New("hostedproxy: intercept CA certificate is not a CA that may sign certificates") |
| + } |
| + key, ok := pair.PrivateKey.(crypto.Signer) |
| + if !ok { |
| + return nil, errors.New("hostedproxy: intercept CA key cannot sign") |
| + } |
| + leafKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| + if err != nil { |
| + return nil, fmt.Errorf("hostedproxy: leaf key: %w", err) |
| + } |
| + return &interceptCA{cert: c, key: key, leafKey: leafKey, clock: clock, leaves: map[string]*tls.Certificate{}}, nil |
| +} |
| + |
| +// hostLeaf is a server certificate for exactly the DNS name host. |
| +func (ca *interceptCA) hostLeaf(host string) (*tls.Certificate, error) { |
| + return ca.leaf("dns:"+host, func(t *x509.Certificate) { t.DNSNames = []string{host} }) |
| +} |
| + |
| +// ipLeaf is a server certificate for exactly the address a. |
| +func (ca *interceptCA) ipLeaf(a netip.Addr) (*tls.Certificate, error) { |
| + return ca.leaf("ip:"+a.String(), func(t *x509.Certificate) { t.IPAddresses = []net.IP{a.AsSlice()} }) |
| +} |
| + |
| +func (ca *interceptCA) leaf(key string, name func(*x509.Certificate)) (*tls.Certificate, error) { |
| + now := ca.clock.Wall() |
| + ca.mu.Lock() |
| + defer ca.mu.Unlock() |
| + if l, ok := ca.leaves[key]; ok && now.Before(l.Leaf.NotAfter.Add(-leafRenew)) && !now.Before(l.Leaf.NotBefore) { |
| + return l, nil |
| + } |
| + serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 127)) |
| + if err != nil { |
| + return nil, err |
| + } |
| + tmpl := &x509.Certificate{SerialNumber: serial.Add(serial, big.NewInt(1)), Subject: pkix.Name{CommonName: "equipo hosted proxy"}, |
| + NotBefore: now.Add(-leafBackdate), NotAfter: now.Add(leafLife), KeyUsage: x509.KeyUsageDigitalSignature, |
| + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, BasicConstraintsValid: true} |
| + name(tmpl) |
| + der, err := x509.CreateCertificate(rand.Reader, tmpl, ca.cert, &ca.leafKey.PublicKey, ca.key) |
| + if err != nil { |
| + return nil, fmt.Errorf("hostedproxy: mint leaf: %w", err) |
| + } |
| + c, err := x509.ParseCertificate(der) |
| + if err != nil { |
| + return nil, err |
| + } |
| + l := &tls.Certificate{Certificate: [][]byte{der}, PrivateKey: ca.leafKey, Leaf: c} |
| + ca.leaves[key] = l |
| + return l, nil |
| +} |
| + |
| +// originTimeout bounds dialling an origin and its TLS handshake. |
| +const originTimeout = 15 * time.Second |
| + |
| +// dialOrigin opens the proxy's own TLS to exactly host on ServicePort: |
| +// SNI host, the certificate checked against OriginRoots (system roots |
| +// when nil) for host, HTTP/1.1 only. |
| +func (s *Server) dialOrigin(ctx context.Context, host string) (net.Conn, error) { |
| + ctx, cancel := context.WithTimeout(ctx, originTimeout) |
| + defer cancel() |
| + addr := net.JoinHostPort(host, strconv.Itoa(ServicePort)) |
| + dial := s.cfg.DialOrigin |
| + if dial == nil { |
| + d := &net.Dialer{} |
| + dial = d.DialContext |
| + } |
| + raw, err := dial(ctx, "tcp", addr) |
| + if err != nil { |
| + return nil, err |
| + } |
| + c := tls.Client(raw, &tls.Config{ServerName: host, RootCAs: s.cfg.OriginRoots, NextProtos: []string{ALPNHTTP11}, |
| + MinVersion: tls.VersionTLS12, Time: s.clock.Wall}) |
| + if err := c.HandshakeContext(ctx); err != nil { |
| + raw.Close() |
| + return nil, err |
| + } |
| + if p := c.ConnectionState().NegotiatedProtocol; p != "" && p != ALPNHTTP11 { |
| + c.Close() |
| + return nil, fmt.Errorf("hostedproxy: origin %s chose %q", host, p) |
| + } |
| + return c, nil |
| +} |
diff --git a/internal/hostedproxy/policy.go b/internal/hostedproxy/policy.go| new file mode 100644 |
| index 00000000..fbb7ee59 |
| --- /dev/null |
| +++ b/internal/hostedproxy/policy.go |
| @@ -0,0 +1,283 @@ |
| +// Package hostedproxy is the authenticated egress proxy for hosted VMs |
| +// (spec §6, Fable H3). It is the only path from a VM to the outside. |
| +// |
| +// A VM holds a short-lived client certificate from the controller's CA, |
| +// bound to its launch, attempt, VM and epoch. Over that mutual TLS it opens |
| +// HTTP/1.1 CONNECT tunnels to exact service hosts on port 443. The proxy |
| +// terminates the inner TLS with a leaf for exactly the CONNECT host, reads |
| +// each request, and judges it with Feed.Decide against the controller's |
| +// signed feed: the CONNECT target, TLS SNI and Host must agree with each |
| +// other and with a service in the launch's manifest, and the method and |
| +// path must be in that service's path class. Allowed requests go out over |
| +// the proxy's own TLS to that exact host. Nothing else leaves. |
| +// |
| +// The bootstrap listener forwards a VM's certificate redemption, renewal |
| +// and certification report to the controller under the proxy's signature; |
| +// the proxy never vouches for a VM's identity there. |
| +package hostedproxy |
| + |
| +import ( |
| + "crypto/x509" |
| + "errors" |
| + "fmt" |
| + "net" |
| + "net/netip" |
| + "net/url" |
| + "strings" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/hostedctl/ctlproxy" |
| + "amadan.net/oficina/equipo/internal/hostedwire" |
| + "amadan.net/oficina/equipo/internal/isolatedjob" |
| +) |
| + |
| +// Reasons a request is refused. Each is a fixed word the decision log |
| +// carries; none ever holds request text. |
| +const ( |
| + ReasonStaleFeed = "stale_feed" |
| + ReasonCertExpired = "cert_expired" |
| + ReasonUnknownLaunch = "unknown_launch" |
| + ReasonRevoked = "revoked" |
| + ReasonWrongEpoch = "wrong_epoch" |
| + ReasonNotInManifest = "not_in_manifest" |
| + ReasonIPLiteral = "ip_literal" |
| + ReasonNoSNI = "no_sni" |
| + ReasonECH = "ech" |
| + ReasonSNIMismatch = "sni_mismatch" |
| + ReasonHostMismatch = "host_mismatch" |
| + ReasonBadPort = "bad_port" |
| + ReasonBadMethod = "bad_method" |
| + ReasonBadPath = "bad_path" |
| + ReasonALPN = "alpn" |
| + ReasonRedirectRefused = "redirect_refused" |
| + ReasonNestedTunnel = "nested_tunnel" |
| +) |
| + |
| +// ServicePort is the one port a VM may reach. |
| +const ServicePort = 443 |
| + |
| +// ALPNHTTP11 is the one application protocol the proxy speaks, on both |
| +// sides (plan decision S2-7): no HTTP/2, so no :authority to disagree with |
| +// Host. |
| +const ALPNHTTP11 = "http/1.1" |
| + |
| +// Identity is what a VM's client certificate binds it to. |
| +type Identity struct { |
| + LaunchID, AttemptID string |
| + VMRef isolatedjob.Ref |
| + Epoch int64 |
| + Serial string // lower-case hex, as the controller writes it |
| + NotAfter time.Time |
| +} |
| + |
| +// ErrIdentity is a client certificate that does not carry exactly one |
| +// launch URI and nothing else to name it. |
| +var ErrIdentity = errors.New("hostedproxy: certificate does not name one launch") |
| + |
| +// IdentityFromCert reads the identity of a verified client certificate: |
| +// exactly one URI SAN, equipo-launch://<launch>/<attempt>/<vm>/<epoch> |
| +// (ctlproxy.ParseLaunchURI), no other name of any kind, and a positive |
| +// serial. |
| +func IdentityFromCert(c *x509.Certificate) (Identity, error) { |
| + if c == nil { |
| + return Identity{}, ErrIdentity |
| + } |
| + if len(c.URIs) != 1 || len(c.DNSNames) != 0 || len(c.IPAddresses) != 0 || len(c.EmailAddresses) != 0 { |
| + return Identity{}, fmt.Errorf("%w: want one URI SAN and no other name", ErrIdentity) |
| + } |
| + l, err := ctlproxy.ParseLaunchURI(c.URIs[0]) |
| + if err != nil { |
| + return Identity{}, fmt.Errorf("%w: %w", ErrIdentity, err) |
| + } |
| + if c.SerialNumber == nil || c.SerialNumber.Sign() <= 0 { |
| + return Identity{}, fmt.Errorf("%w: serial", ErrIdentity) |
| + } |
| + return Identity{LaunchID: l.LaunchID, AttemptID: l.AttemptID, VMRef: l.VMRef, Epoch: l.Epoch, |
| + Serial: c.SerialNumber.Text(16), NotAfter: c.NotAfter}, nil |
| +} |
| + |
| +// Request is what the proxy knows about one request inside a tunnel. |
| +// Connect is the CONNECT target as sent ("host:port"); SNI and ALPN come |
| +// from the inner ClientHello (ALPN is the list the client offered); ECH |
| +// is true when that hello carried an encrypted_client_hello extension. |
| +// Host is the Host header, Path the request target exactly as sent, and |
| +// Upgrade is true when the request asks for a protocol upgrade. |
| +type Request struct { |
| + Connect, SNI, Host, Method, Path string |
| + ALPN []string |
| + ECH, Upgrade bool |
| +} |
| + |
| +// Decision is Decide's answer: allowed, or refused for Reason. Service is |
| +// the manifest entry the request goes to when allowed. |
| +type Decision struct { |
| + Allow bool |
| + Reason string |
| + Service hostedwire.Service |
| +} |
| + |
| +func deny(reason string) Decision { return Decision{Reason: reason} } |
| + |
| +// route is one method and exact request target a path class allows. |
| +// upgrade routes are WebSocket upgrades and nothing else. |
| +type route struct { |
| + method, path string |
| + upgrade bool |
| +} |
| + |
| +// pathClasses lists, per service class, every request a VM may make. |
| +// Paths are exact request targets: no prefix, no query, no other form. |
| +var pathClasses = map[string][]route{ |
| + hostedwire.ServiceInstance: { |
| + {method: "GET", path: "/api/runner/stream", upgrade: true}, |
| + {method: "GET", path: "/api/runner/protocol"}, |
| + {method: "POST", path: "/api/hosted/enrol"}, |
| + {method: "POST", path: "/api/runner/v2/hosted/challenge"}, |
| + {method: "POST", path: "/api/runner/v2/hosted/renew"}, |
| + }, |
| +} |
| + |
| +// classRoute judges method, path and upgrade against class's routes: "" |
| +// when one matches. |
| +func classRoute(class, method, path string, upgrade bool) string { |
| + known := false |
| + for _, r := range pathClasses[class] { |
| + if r.path != path { |
| + continue |
| + } |
| + known = true |
| + if r.method != method { |
| + continue |
| + } |
| + switch { |
| + case upgrade && !r.upgrade: |
| + return ReasonNestedTunnel |
| + case !upgrade && r.upgrade: |
| + return ReasonBadMethod |
| + } |
| + return "" |
| + } |
| + if !known { |
| + return ReasonBadPath |
| + } |
| + return ReasonBadMethod |
| +} |
| + |
| +// inClass reports whether path is one of class's request targets, by any |
| +// method. |
| +func inClass(class, path string) bool { |
| + for _, r := range pathClasses[class] { |
| + if r.path == path { |
| + return true |
| + } |
| + } |
| + return false |
| +} |
| + |
| +// pathClassOf names the class whose routes hold path, for the log: the |
| +// class, or "none". |
| +func pathClassOf(class, path string) string { |
| + if inClass(class, path) { |
| + return class |
| + } |
| + return "none" |
| +} |
| + |
| +// sameHost compares two DNS names exactly, ignoring only ASCII case. |
| +func sameHost(a, b string) bool { return a != "" && strings.EqualFold(a, b) } |
| + |
| +func isIPLiteral(host string) bool { |
| + _, err := netip.ParseAddr(strings.TrimSuffix(strings.TrimPrefix(host, "["), "]")) |
| + return err == nil |
| +} |
| + |
| +// decideConnect judges a CONNECT target against launch l's services: no |
| +// IP literal, port 443, and a host the manifest names exactly. |
| +func decideConnect(l hostedwire.FeedLaunch, connect string) Decision { |
| + host, port, err := net.SplitHostPort(connect) |
| + switch { |
| + case err != nil: |
| + if isIPLiteral(connect) { |
| + return deny(ReasonIPLiteral) |
| + } |
| + return deny(ReasonBadPort) |
| + case isIPLiteral(host): |
| + return deny(ReasonIPLiteral) |
| + case port != "443": |
| + return deny(ReasonBadPort) |
| + } |
| + for _, s := range l.Services { |
| + if s.Port == ServicePort && sameHost(s.Host, host) { |
| + return Decision{Allow: true, Service: s} |
| + } |
| + } |
| + return deny(ReasonNotInManifest) |
| +} |
| + |
| +// decideTLS judges the inner ClientHello against the CONNECT host: no |
| +// encrypted hello, an SNI naming exactly that host, and only HTTP/1.1 |
| +// offered (or no ALPN at all). |
| +func decideTLS(host, sni string, alpn []string, ech bool) string { |
| + switch { |
| + case ech: |
| + return ReasonECH |
| + case sni == "": |
| + return ReasonNoSNI |
| + case isIPLiteral(sni): |
| + return ReasonIPLiteral |
| + case !sameHost(sni, host): |
| + return ReasonSNIMismatch |
| + } |
| + for _, p := range alpn { |
| + if p != ALPNHTTP11 { |
| + return ReasonALPN |
| + } |
| + } |
| + return "" |
| +} |
| + |
| +// decideHost judges a Host header: the CONNECT host, with port 443 or no |
| +// port. |
| +func decideHost(host, header string) string { |
| + h, port := header, "" |
| + if i := strings.LastIndexByte(header, ':'); i >= 0 && !strings.HasSuffix(header, "]") { |
| + h, port = header[:i], header[i+1:] |
| + if port != "443" { |
| + return ReasonHostMismatch |
| + } |
| + } |
| + if !sameHost(h, host) || isIPLiteral(h) { |
| + return ReasonHostMismatch |
| + } |
| + return "" |
| +} |
| + |
| +// decideResponse judges an origin's answer: a 3xx whose Location names |
| +// another authority (another host, a port but 443, a scheme but https), |
| +// or that cannot be read, is refused. |
| +func decideResponse(svc hostedwire.Service, status int, location []string) Decision { |
| + if status < 300 || status > 399 || len(location) == 0 { |
| + return Decision{Allow: true, Service: svc} |
| + } |
| + if len(location) != 1 || !sameAuthority(svc.Host, location[0]) { |
| + return Decision{Reason: ReasonRedirectRefused, Service: svc} |
| + } |
| + return Decision{Allow: true, Service: svc} |
| +} |
| + |
| +func sameAuthority(host, location string) bool { |
| + if strings.ContainsAny(location, "\\\r\n\t ") { |
| + return false |
| + } |
| + u, err := url.Parse(location) |
| + if err != nil { |
| + return false |
| + } |
| + if u.Scheme == "" && u.Host == "" && u.User == nil { |
| + return u.Opaque == "" // a path on the same origin |
| + } |
| + if u.Scheme != "" && u.Scheme != "https" || u.User != nil || u.Opaque != "" { |
| + return false |
| + } |
| + return sameHost(u.Hostname(), host) && (u.Port() == "" || u.Port() == "443") |
| +} |
diff --git a/internal/hostedproxy/policy_test.go b/internal/hostedproxy/policy_test.go| new file mode 100644 |
| index 00000000..a19266d3 |
| --- /dev/null |
| +++ b/internal/hostedproxy/policy_test.go |
| @@ -0,0 +1,429 @@ |
| +package hostedproxy |
| + |
| +import ( |
| + "go/ast" |
| + "go/parser" |
| + "go/token" |
| + "io/fs" |
| + "maps" |
| + "os" |
| + "path/filepath" |
| + "slices" |
| + "strconv" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/hostedctl/ctlproxy" |
| + "amadan.net/oficina/equipo/internal/hostedwire" |
| + "amadan.net/oficina/equipo/internal/testci" |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "amadan.net/rastrillo/rastrillo/budget" |
| +) |
| + |
| +func TestMain(m *testing.M) { os.Exit(budget.Main(m)) } |
| + |
| +// fakeClock is a Clock tests move by hand. Advance moves both clocks and |
| +// fires timers; JumpWall moves the wall clock alone. |
| +type fakeClock struct { |
| + mu sync.Mutex |
| + mono time.Duration |
| + wall time.Time |
| + waiters []fakeWaiter |
| +} |
| + |
| +type fakeWaiter struct { |
| + at time.Duration |
| + ch chan time.Time |
| +} |
| + |
| +func newFakeClock() *fakeClock { |
| + return &fakeClock{mono: time.Hour, wall: time.Date(2026, 11, 30, 12, 0, 0, 0, time.UTC)} |
| +} |
| + |
| +func (c *fakeClock) Mono() time.Duration { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + return c.mono |
| +} |
| + |
| +func (c *fakeClock) Wall() time.Time { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + return c.wall |
| +} |
| + |
| +func (c *fakeClock) 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, fakeWaiter{at: c.mono + d, ch: ch}) |
| + return ch |
| +} |
| + |
| +func (c *fakeClock) 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 |
| +} |
| + |
| +func (c *fakeClock) JumpWall(d time.Duration) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + c.wall = c.wall.Add(d) |
| +} |
| + |
| +const ( |
| + testHost = "instance.example.test" |
| + testLocal = "instance.example.test:443" |
| +) |
| + |
| +// testFeed is a signed-feed body with one live launch, l-1 (attempt a-1 on |
| +// vm-1 at epoch 2, allowed testHost), another launch, and one revoked |
| +// serial. |
| +func testFeed() hostedwire.ProxyFeed { |
| + svc := []hostedwire.Service{{Host: testHost, Port: 443, Class: hostedwire.ServiceInstance}} |
| + return hostedwire.ProxyFeed{Version: ctlproxy.FeedVersion, Serial: 7, IssuedNS: int64(time.Minute), |
| + TTLMS: ctlproxy.FeedLifetime.Milliseconds(), |
| + Launches: []hostedwire.FeedLaunch{ |
| + {LaunchID: "l-1", AttemptID: "a-1", VMRef: "vm-1", Epoch: 2, Services: svc, DeadlineNS: int64(time.Hour)}, |
| + {LaunchID: "l-2", AttemptID: "a-2", VMRef: "vm-2", Epoch: 0, Services: []hostedwire.Service{ |
| + {Host: "other.example.test", Port: 443, Class: hostedwire.ServiceInstance}}, DeadlineNS: int64(time.Hour)}, |
| + }, |
| + Revoked: []string{"dead"}, |
| + } |
| +} |
| + |
| +// testIdentity is l-1's current certificate, valid 15 minutes from wall. |
| +func testIdentity(wall time.Time) Identity { |
| + return Identity{LaunchID: "l-1", AttemptID: "a-1", VMRef: "vm-1", Epoch: 2, Serial: "abc123", |
| + NotAfter: wall.Add(ctlproxy.CertLifetime)} |
| +} |
| + |
| +// okRequest is an allowed request for the protocol path. |
| +func okRequest() Request { |
| + return Request{Connect: testLocal, SNI: testHost, Host: testHost, Method: "GET", |
| + Path: "/api/runner/protocol", ALPN: []string{"http/1.1"}} |
| +} |
| + |
| +func installed(t *testing.T, c *fakeClock) *Feed { |
| + t.Helper() |
| + f := NewFeed(c) |
| + if err := f.Install(testFeed()); err != nil { |
| + t.Fatalf("Install: %v", err) |
| + } |
| + return f |
| +} |
| + |
| +// allReasons is every reason the proxy gives; TestDecideTable needs a row |
| +// for each. |
| +var allReasons = []string{ReasonStaleFeed, ReasonCertExpired, ReasonUnknownLaunch, ReasonRevoked, ReasonWrongEpoch, |
| + ReasonNotInManifest, ReasonIPLiteral, ReasonNoSNI, ReasonECH, ReasonSNIMismatch, ReasonHostMismatch, ReasonBadPort, |
| + ReasonBadMethod, ReasonBadPath, ReasonALPN, ReasonRedirectRefused, ReasonNestedTunnel} |
| + |
| +func TestDecideTable(t *testing.T) { |
| + c := newFakeClock() |
| + f := installed(t, c) |
| + wall, mono := c.Wall(), c.Mono() |
| + type row struct { |
| + name string |
| + id func(*Identity) |
| + req func(*Request) |
| + at time.Duration // added to the install's monotonic time |
| + reason string // "" for allowed |
| + } |
| + with := func(fn func(*Request)) func(*Request) { return fn } |
| + rows := []row{ |
| + // Allowed: each route of the instance class. |
| + {name: "stream upgrade", req: with(func(r *Request) { r.Path, r.Upgrade = "/api/runner/stream", true })}, |
| + {name: "protocol"}, |
| + {name: "enrol", req: with(func(r *Request) { r.Method, r.Path = "POST", "/api/hosted/enrol" })}, |
| + {name: "challenge", req: with(func(r *Request) { r.Method, r.Path = "POST", "/api/runner/v2/hosted/challenge" })}, |
| + {name: "renew", req: with(func(r *Request) { r.Method, r.Path = "POST", "/api/runner/v2/hosted/renew" })}, |
| + {name: "no ALPN offered", req: with(func(r *Request) { r.ALPN = nil })}, |
| + {name: "host with port 443", req: with(func(r *Request) { r.Host = testHost + ":443" })}, |
| + {name: "host names in other case", req: with(func(r *Request) { |
| + r.Connect, r.SNI, r.Host = "Instance.Example.Test:443", "INSTANCE.example.test", "instance.EXAMPLE.test" |
| + })}, |
| + {name: "just inside the feed's lifetime", at: ctlproxy.FeedLifetime - time.Millisecond}, |
| + |
| + {name: "stale feed", at: ctlproxy.FeedLifetime + time.Millisecond, reason: ReasonStaleFeed}, |
| + {name: "certificate expired", id: func(id *Identity) { id.NotAfter = wall.Add(time.Minute) }, at: time.Minute, reason: ReasonCertExpired}, |
| + {name: "unknown launch", id: func(id *Identity) { id.LaunchID = "l-9" }, reason: ReasonUnknownLaunch}, |
| + {name: "another launch's attempt", id: func(id *Identity) { id.AttemptID = "a-2" }, reason: ReasonUnknownLaunch}, |
| + {name: "another VM", id: func(id *Identity) { id.VMRef = "vm-2" }, reason: ReasonUnknownLaunch}, |
| + {name: "revoked serial", id: func(id *Identity) { id.Serial = "dead" }, reason: ReasonRevoked}, |
| + {name: "old epoch", id: func(id *Identity) { id.Epoch = 1 }, reason: ReasonWrongEpoch}, |
| + {name: "another launch's host", req: with(func(r *Request) { |
| + r.Connect, r.SNI, r.Host = "other.example.test:443", "other.example.test", "other.example.test" |
| + }), reason: ReasonNotInManifest}, |
| + {name: "a name ending in the allowed host", req: with(func(r *Request) { |
| + r.Connect, r.SNI, r.Host = "evil-instance.example.test:443", "evil-instance.example.test", "evil-instance.example.test" |
| + }), reason: ReasonNotInManifest}, |
| + {name: "a name under the allowed host", req: with(func(r *Request) { |
| + r.Connect, r.SNI, r.Host = "x.instance.example.test:443", "x.instance.example.test", "x.instance.example.test" |
| + }), reason: ReasonNotInManifest}, |
| + {name: "the allowed host's parent", req: with(func(r *Request) { |
| + r.Connect, r.SNI, r.Host = "example.test:443", "example.test", "example.test" |
| + }), reason: ReasonNotInManifest}, |
| + {name: "a trailing dot", req: with(func(r *Request) { r.Connect = testHost + ".:443" }), reason: ReasonNotInManifest}, |
| + {name: "user info in the target", req: with(func(r *Request) { r.Connect = "x@" + testLocal }), reason: ReasonNotInManifest}, |
| + {name: "IPv4 literal", req: with(func(r *Request) { r.Connect = "127.0.0.1:443" }), reason: ReasonIPLiteral}, |
| + {name: "IPv6 literal", req: with(func(r *Request) { r.Connect = "[::1]:443" }), reason: ReasonIPLiteral}, |
| + {name: "IP literal SNI", req: with(func(r *Request) { r.SNI = "127.0.0.1" }), reason: ReasonIPLiteral}, |
| + {name: "no SNI", req: with(func(r *Request) { r.SNI = "" }), reason: ReasonNoSNI}, |
| + {name: "encrypted hello", req: with(func(r *Request) { r.ECH = true }), reason: ReasonECH}, |
| + {name: "SNI of another host", req: with(func(r *Request) { r.SNI = "other.example.test" }), reason: ReasonSNIMismatch}, |
| + {name: "SNI ending in the host", req: with(func(r *Request) { r.SNI = "evil-instance.example.test" }), reason: ReasonSNIMismatch}, |
| + {name: "Host of another host", req: with(func(r *Request) { r.Host = "other.example.test" }), reason: ReasonHostMismatch}, |
| + {name: "Host ending in the host", req: with(func(r *Request) { r.Host = "evil-instance.example.test" }), reason: ReasonHostMismatch}, |
| + {name: "Host on another port", req: with(func(r *Request) { r.Host = testHost + ":8443" }), reason: ReasonHostMismatch}, |
| + {name: "Host as an IP", req: with(func(r *Request) { r.Host = "127.0.0.1" }), reason: ReasonHostMismatch}, |
| + {name: "no Host", req: with(func(r *Request) { r.Host = "" }), reason: ReasonHostMismatch}, |
| + {name: "Host with user info", req: with(func(r *Request) { r.Host = "x@" + testHost }), reason: ReasonHostMismatch}, |
| + {name: "port 8443", req: with(func(r *Request) { r.Connect = testHost + ":8443" }), reason: ReasonBadPort}, |
| + {name: "no port", req: with(func(r *Request) { r.Connect = testHost }), reason: ReasonBadPort}, |
| + {name: "DELETE on a known path", req: with(func(r *Request) { r.Method = "DELETE" }), reason: ReasonBadMethod}, |
| + {name: "HEAD on a GET path", req: with(func(r *Request) { r.Method = "HEAD" }), reason: ReasonBadMethod}, |
| + {name: "GET enrol", req: with(func(r *Request) { r.Path = "/api/hosted/enrol" }), reason: ReasonBadMethod}, |
| + {name: "stream without the upgrade", req: with(func(r *Request) { r.Path = "/api/runner/stream" }), reason: ReasonBadMethod}, |
| + {name: "another runner path", req: with(func(r *Request) { r.Path = "/api/runner/v2/leases" }), reason: ReasonBadPath}, |
| + {name: "a query", req: with(func(r *Request) { r.Path = "/api/runner/protocol?x=1" }), reason: ReasonBadPath}, |
| + {name: "a trailing slash", req: with(func(r *Request) { r.Path = "/api/runner/protocol/" }), reason: ReasonBadPath}, |
| + {name: "an encoded path", req: with(func(r *Request) { r.Path = "/api/runner/%70rotocol" }), reason: ReasonBadPath}, |
| + {name: "absolute form naming another host", req: with(func(r *Request) { |
| + r.Path = "https://other.example.test/api/runner/protocol" |
| + }), reason: ReasonBadPath}, |
| + {name: "ALPN h2 only", req: with(func(r *Request) { r.ALPN = []string{"h2"} }), reason: ReasonALPN}, |
| + {name: "ALPN h2 beside HTTP/1.1", req: with(func(r *Request) { r.ALPN = []string{"http/1.1", "h2"} }), reason: ReasonALPN}, |
| + {name: "a CONNECT inside the tunnel", req: with(func(r *Request) { r.Method, r.Path = "CONNECT", testLocal }), reason: ReasonNestedTunnel}, |
| + {name: "an upgrade on a plain path", req: with(func(r *Request) { r.Upgrade = true }), reason: ReasonNestedTunnel}, |
| + } |
| + seen := map[string]bool{} |
| + for _, tc := range rows { |
| + id, r := testIdentity(wall), okRequest() |
| + if tc.id != nil { |
| + tc.id(&id) |
| + } |
| + if tc.req != nil { |
| + tc.req(&r) |
| + } |
| + d := f.Decide(id, r, mono+tc.at) |
| + seen[tc.reason] = true |
| + switch { |
| + case tc.reason == "" && (!d.Allow || d.Reason != "" || d.Service.Host != testHost): |
| + t.Errorf("%s: Decide = %+v, want allowed to %s", tc.name, d, testHost) |
| + case tc.reason != "" && (d.Allow || d.Reason != tc.reason): |
| + t.Errorf("%s: Decide = %+v, want refused %s", tc.name, d, tc.reason) |
| + } |
| + } |
| + |
| + // A 3xx is judged on the origin's answer. |
| + svc := hostedwire.Service{Host: testHost, Port: 443, Class: hostedwire.ServiceInstance} |
| + for _, tc := range []struct { |
| + status int |
| + location []string |
| + allow bool |
| + }{ |
| + {302, []string{"/api/runner/protocol"}, true}, |
| + {301, []string{"https://instance.example.test/x"}, true}, |
| + {307, []string{"https://INSTANCE.example.test:443/x"}, true}, |
| + {304, nil, true}, |
| + {200, []string{"https://other.example.test/"}, true}, |
| + {302, []string{"https://other.example.test/x"}, false}, |
| + {302, []string{"//other.example.test/x"}, false}, |
| + {302, []string{"http://instance.example.test/x"}, false}, |
| + {302, []string{"https://instance.example.test:8443/x"}, false}, |
| + {302, []string{"https://x@instance.example.test/x"}, false}, |
| + {302, []string{"https://127.0.0.1/x"}, false}, |
| + {302, []string{"https://evil-instance.example.test/x"}, false}, |
| + {303, []string{"/a", "/b"}, false}, |
| + {308, []string{"https:/\\other.example.test/x"}, false}, |
| + {302, []string{"javascript:alert(1)"}, false}, |
| + } { |
| + d := decideResponse(svc, tc.status, tc.location) |
| + if tc.allow != d.Allow || !tc.allow && d.Reason != ReasonRedirectRefused { |
| + t.Errorf("decideResponse(%d, %q) = %+v, want allowed %v", tc.status, tc.location, d, tc.allow) |
| + } |
| + if !tc.allow { |
| + seen[ReasonRedirectRefused] = true |
| + } |
| + } |
| + for _, r := range allReasons { |
| + if !seen[r] { |
| + t.Errorf("no row refuses for %s", r) |
| + } |
| + } |
| +} |
| + |
| +func TestDecideDeadline(t *testing.T) { |
| + c := newFakeClock() |
| + f := installed(t, c) |
| + mono, wall := c.Mono(), c.Wall() |
| + id := testIdentity(wall) |
| + if got, want := f.Deadline(id, mono), mono+ctlproxy.FeedLifetime; got != want { |
| + t.Errorf("Deadline with a 15 minute certificate = %v, want the feed's expiry %v", got, want) |
| + } |
| + id.NotAfter = wall.Add(2 * time.Minute) |
| + if got, want := f.Deadline(id, mono), mono+2*time.Minute; got != want { |
| + t.Errorf("Deadline with a 2 minute certificate = %v, want its NotAfter %v", got, want) |
| + } |
| + // A fresher feed moves the feed's part on. |
| + c.Advance(time.Minute) |
| + if err := f.Install(testFeed()); err != nil { |
| + t.Fatal(err) |
| + } |
| + id = testIdentity(wall) |
| + if got, want := f.Deadline(id, mono), mono+time.Minute+ctlproxy.FeedLifetime; got != want { |
| + t.Errorf("Deadline after a fresher feed = %v, want %v", got, want) |
| + } |
| + if got := NewFeed(c).Deadline(id, c.Mono()); got > c.Mono() { |
| + t.Errorf("Deadline with no feed = %v, after now %v", got, c.Mono()) |
| + } |
| +} |
| + |
| +func TestStaleFeedDeniesAll(t *testing.T) { |
| + c := newFakeClock() |
| + if d := NewFeed(c).Decide(testIdentity(c.Wall()), okRequest(), c.Mono()); d.Allow || d.Reason != ReasonStaleFeed { |
| + t.Errorf("Decide with no feed = %+v, want %s", d, ReasonStaleFeed) |
| + } |
| + f := installed(t, c) |
| + id := testIdentity(c.Wall()) |
| + routes := []Request{okRequest()} |
| + for _, r := range pathClasses[hostedwire.ServiceInstance] { |
| + q := okRequest() |
| + q.Method, q.Path, q.Upgrade = r.method, r.path, r.upgrade |
| + routes = append(routes, q) |
| + } |
| + decideAll := func(when string, wantAllow bool) { |
| + t.Helper() |
| + for _, r := range routes { |
| + d := f.Decide(id, r, c.Mono()) |
| + if wantAllow && !d.Allow || !wantAllow && (d.Allow || d.Reason != ReasonStaleFeed) { |
| + t.Errorf("%s: %s %s = %+v, want allowed %v (else %s)", when, r.Method, r.Path, d, wantAllow, ReasonStaleFeed) |
| + } |
| + } |
| + } |
| + // The wall clock jumps an hour forward: nothing changes. |
| + c.Advance(time.Minute) |
| + c.JumpWall(time.Hour) |
| + decideAll("1 min on, wall clock an hour ahead", true) |
| + // Then two hours back, and the monotonic clock reaches the lifetime. |
| + c.JumpWall(-2 * time.Hour) |
| + c.Advance(ctlproxy.FeedLifetime - time.Minute - time.Millisecond) |
| + decideAll("lifetime less 1 ms, wall clock an hour behind", true) |
| + c.Advance(2 * time.Millisecond) |
| + decideAll("lifetime and 1 ms, wall clock an hour behind", false) |
| + |
| + // A feed claiming a longer life is held to the lifetime. |
| + long := testFeed() |
| + long.TTLMS = time.Hour.Milliseconds() |
| + if err := f.Install(long); err != nil { |
| + t.Fatal(err) |
| + } |
| + c.Advance(ctlproxy.FeedLifetime + time.Millisecond) |
| + decideAll("a feed claiming an hour, at the lifetime and 1 ms", false) |
| +} |
| + |
| +// TestPathClassCoversRunner reads the runner and wire sources for the |
| +// instance paths a hosted runner uses, and fails on one the instance class |
| +// does not hold. A path counts when it is a wire path constant the runner |
| +// refers to (the link's), a whole /api/ literal in internal/runner/hosted, |
| +// or any /api/ literal or wire constant with a /hosted/ segment. A hosted |
| +// path written as a fragment ("/hosted/...") fails too: the check can only |
| +// read whole paths. |
| +func TestPathClassCoversRunner(t *testing.T) { |
| + const runnerDir, wireDir = "../runner", "../wire" |
| + testci.Files(t, runnerDir, wireDir) |
| + wirePaths := map[string]string{} // constant name -> value |
| + required := map[string]string{} // path -> where it was found |
| + fset := token.NewFileSet() |
| + parse := func(path string) *ast.File { |
| + f, err := parser.ParseFile(fset, path, nil, parser.SkipObjectResolution) |
| + if err != nil { |
| + t.Fatalf("parse %s: %v", path, err) |
| + } |
| + return f |
| + } |
| + literal := func(n ast.Node) (string, bool) { |
| + b, ok := n.(*ast.BasicLit) |
| + if !ok || b.Kind != token.STRING { |
| + return "", false |
| + } |
| + s, err := strconv.Unquote(b.Value) |
| + return s, err == nil |
| + } |
| + sources := func(dir string, fn func(string, *ast.File)) { |
| + err := filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error { |
| + if err != nil || d.IsDir() || !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") { |
| + return err |
| + } |
| + fn(path, parse(path)) |
| + return nil |
| + }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + sources(wireDir, func(path string, f *ast.File) { |
| + ast.Inspect(f, func(n ast.Node) bool { |
| + if vs, ok := n.(*ast.ValueSpec); ok { |
| + for i, name := range vs.Names { |
| + if i < len(vs.Values) { |
| + if v, ok := literal(vs.Values[i]); ok && strings.HasPrefix(v, "/api/") { |
| + wirePaths[name.Name] = v |
| + if strings.Contains(v, "/hosted/") { |
| + required[v] = path |
| + } |
| + } |
| + } |
| + } |
| + } |
| + return true |
| + }) |
| + }) |
| + sources(runnerDir, func(path string, f *ast.File) { |
| + hosted := strings.Contains(filepath.ToSlash(path), "runner/hosted/") |
| + ast.Inspect(f, func(n ast.Node) bool { |
| + if sel, ok := n.(*ast.SelectorExpr); ok { |
| + if x, ok := sel.X.(*ast.Ident); ok && x.Name == "wire" && wirePaths[sel.Sel.Name] != "" { |
| + required[wirePaths[sel.Sel.Name]] = path + ": wire." + sel.Sel.Name |
| + } |
| + } |
| + v, ok := literal(n) |
| + switch { |
| + case !ok: |
| + case strings.HasPrefix(v, "/api/") && (hosted || strings.Contains(v, "/hosted/")): |
| + required[v] = path |
| + case strings.HasPrefix(v, "/hosted/") || strings.HasPrefix(v, "/runner/v2/hosted/"): |
| + t.Errorf("%s: %q is part of a hosted instance path; write the whole /api/ path so the proxy's class can be checked", path, v) |
| + } |
| + return true |
| + }) |
| + }) |
| + for _, p := range []string{wire.StreamPath, wire.RunnerProtocolPath} { |
| + if required[p] == "" { |
| + t.Errorf("the scan did not find the link's %s; it is not reading the runner", p) |
| + } |
| + } |
| + for _, p := range slices.Sorted(maps.Keys(required)) { |
| + if !inClass(hostedwire.ServiceInstance, p) { |
| + t.Errorf("%s (%s) is outside the proxy's instance path class", p, required[p]) |
| + } |
| + } |
| +} |