| new file mode 100644 |
| index 000000000..b5ad5e0e2 |
| --- /dev/null |
| +++ b/internal/edge/devboxfront_test.go |
| @@ -0,0 +1,448 @@ |
| +package edge |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/netip" |
| + "os" |
| + "path/filepath" |
| + "runtime" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +var frontVisitor = Visitor{Login: "alice@github", Name: "Alice Example", Node: "laptop"} |
| +var frontSelf = netip.MustParseAddr("100.64.0.1") |
| + |
| +func frontIdentity(v Visitor) VisitorIdentity { |
| + return visitorIdentityFunc(func(context.Context, netip.AddrPort) (Visitor, bool, error) { return v, true, nil }) |
| +} |
| + |
| +func frontRequest() *http.Request { |
| + r := httptest.NewRequest(http.MethodGet, "https://shop.example.com/", nil) |
| + r.RemoteAddr = "100.64.0.2:12345" |
| + return r |
| +} |
| + |
| +func assertNoVisitorHeaders(t *testing.T, h http.Header) { |
| + t.Helper() |
| + for k := range h { |
| + for _, name := range []string{"Carlos-Visitor-Login", "Carlos-Visitor-Name", "Carlos-Visitor-Node"} { |
| + if strings.EqualFold(k, name) { |
| + t.Errorf("visitor header remains: %q = %q", k, h[k]) |
| + } |
| + } |
| + } |
| +} |
| + |
| +func TestFrontStripsVisitorHeaders(t *testing.T) { |
| + for _, upgrade := range []bool{false, true} { |
| + t.Run(map[bool]string{false: "ordinary", true: "upgrade"}[upgrade], func(t *testing.T) { |
| + r := frontRequest() |
| + r.Header = http.Header{ |
| + "Carlos-Visitor-Login": {"forged"}, "cArLoS-vIsItOr-LoGiN": {"forged too"}, |
| + "carlos-visitor-name": {"forged"}, "CARLOS-VISITOR-NODE": {"forged"}, |
| + } |
| + if upgrade { |
| + r.Header.Set("Connection", "Upgrade") |
| + r.Header.Set("Upgrade", "websocket") |
| + } |
| + calls := 0 |
| + cfg := DevboxConfig{Identity: visitorIdentityFunc(func(context.Context, netip.AddrPort) (Visitor, bool, error) { |
| + calls++ |
| + assertNoVisitorHeaders(t, r.Header) |
| + return Visitor{}, false, nil |
| + })} |
| + reached := false |
| + devboxFront(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + reached = true |
| + assertNoVisitorHeaders(t, r.Header) |
| + }), cfg, frontSelf).ServeHTTP(httptest.NewRecorder(), r) |
| + if !reached || calls != 1 { |
| + t.Fatalf("next=%v lookup calls=%d", reached, calls) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestFrontSetsIdentity(t *testing.T) { |
| + r := frontRequest() |
| + r.RemoteAddr = "[::ffff:100.64.0.2]:12345" |
| + cfg := DevboxConfig{Identity: visitorIdentityFunc(func(_ context.Context, remote netip.AddrPort) (Visitor, bool, error) { |
| + if remote != netip.MustParseAddrPort("100.64.0.2:12345") { |
| + t.Errorf("remote = %v", remote) |
| + } |
| + return frontVisitor, true, nil |
| + })} |
| + devboxFront(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + for k, want := range map[string]string{"Carlos-Visitor-Login": frontVisitor.Login, "Carlos-Visitor-Name": frontVisitor.Name, "Carlos-Visitor-Node": frontVisitor.Node} { |
| + if got := r.Header.Get(k); got != want { |
| + t.Errorf("%s = %q, want %q", k, got, want) |
| + } |
| + } |
| + }), cfg, frontSelf).ServeHTTP(httptest.NewRecorder(), r) |
| +} |
| + |
| +func assertFrontAnonymous(t *testing.T, cfg DevboxConfig, remote string) { |
| + t.Helper() |
| + for _, private := range []bool{false, true} { |
| + calls := 0 |
| + cfg.AllowFor = func(string) []string { |
| + if private { |
| + return []string{frontVisitor.Login} |
| + } |
| + return nil |
| + } |
| + h := devboxFront(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + calls++ |
| + assertNoVisitorHeaders(t, r.Header) |
| + }), cfg, frontSelf) |
| + r := frontRequest() |
| + r.RemoteAddr = remote |
| + r.Header.Set("Carlos-Visitor-Login", frontVisitor.Login) |
| + w := httptest.NewRecorder() |
| + h.ServeHTTP(w, r) |
| + if private { |
| + if w.Code != http.StatusForbidden || calls != 0 { |
| + t.Fatalf("private: code=%d next calls=%d", w.Code, calls) |
| + } |
| + } else if w.Code != http.StatusOK || calls != 1 { |
| + t.Fatalf("open: code=%d next calls=%d", w.Code, calls) |
| + } |
| + } |
| +} |
| + |
| +func TestFrontSelfIPIsAnonymous(t *testing.T) { |
| + assertFrontAnonymous(t, DevboxConfig{Identity: frontIdentity(frontVisitor)}, "[::ffff:100.64.0.1]:12345") |
| +} |
| +func TestFrontSharedNodeIsAnonymous(t *testing.T) { |
| + assertFrontAnonymous(t, DevboxConfig{Identity: frontIdentity(frontVisitor), SharedNodes: []string{"LAPTOP"}}, "100.64.0.2:12345") |
| +} |
| +func TestFrontNilIdentityIsAnonymous(t *testing.T) { |
| + assertFrontAnonymous(t, DevboxConfig{}, "100.64.0.2:12345") |
| +} |
| +func TestFrontMalformedRemoteIsAnonymous(t *testing.T) { |
| + cfg := DevboxConfig{Identity: visitorIdentityFunc(func(context.Context, netip.AddrPort) (Visitor, bool, error) { |
| + t.Error("lookup called for invalid remote") |
| + return frontVisitor, true, nil |
| + })} |
| + for _, remote := range []string{"", "100.64.0.2", "laptop:12345", "100.64.0.2:bad"} { |
| + assertFrontAnonymous(t, cfg, remote) |
| + } |
| +} |
| +func TestFrontAllowRefusesAnonymous(t *testing.T) { |
| + for _, err := range []error{nil, errors.New("lookup failed")} { |
| + cfg := DevboxConfig{Identity: visitorIdentityFunc(func(context.Context, netip.AddrPort) (Visitor, bool, error) { |
| + return frontVisitor, err != nil, err |
| + })} |
| + assertFrontAnonymous(t, cfg, "100.64.0.2:12345") |
| + } |
| +} |
| +func TestFrontOpenLinkServesAnonymous(t *testing.T) { |
| + calls := 0 |
| + cfg := DevboxConfig{} |
| + devboxFront(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++; assertNoVisitorHeaders(t, r.Header) }), cfg, frontSelf).ServeHTTP(httptest.NewRecorder(), frontRequest()) |
| + if calls != 1 { |
| + t.Fatalf("next calls=%d", calls) |
| + } |
| +} |
| + |
| +func TestFrontAllowRefusesOthers(t *testing.T) { |
| + for _, upgrade := range []bool{false, true} { |
| + r := frontRequest() |
| + if upgrade { |
| + r.Header.Set("Connection", "Upgrade") |
| + r.Header.Set("Upgrade", "websocket") |
| + } |
| + cfg := DevboxConfig{Identity: frontIdentity(frontVisitor), AllowFor: func(host string) []string { |
| + if host != r.Host { |
| + t.Errorf("host = %q, want %q", host, r.Host) |
| + } |
| + return []string{"bob@github", "*@github"} |
| + }} |
| + w := httptest.NewRecorder() |
| + devboxFront(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { t.Error("refused request reached next") }), cfg, frontSelf).ServeHTTP(w, r) |
| + if w.Code != http.StatusForbidden { |
| + t.Fatalf("code=%d", w.Code) |
| + } |
| + for k, want := range map[string]string{"Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff"} { |
| + if got := w.Header().Get(k); got != want { |
| + t.Errorf("%s = %q, want %q", k, got, want) |
| + } |
| + } |
| + body := w.Body.String() |
| + for _, want := range []string{"<title>" + devboxPrivateTitle + "</title>", "<h1>" + devboxPrivateTitle + "</h1>", "<p>" + devboxPrivateSentence + "</p>"} { |
| + if !strings.Contains(body, want) { |
| + t.Errorf("body %q lacks %q", body, want) |
| + } |
| + } |
| + for _, secret := range []string{"bob@github", "*@github", "owner", frontVisitor.Login} { |
| + if strings.Contains(strings.ToLower(body), strings.ToLower(secret)) { |
| + t.Errorf("body discloses %q", secret) |
| + } |
| + } |
| + } |
| +} |
| + |
| +func TestFrontAllowListChangeTakesEffect(t *testing.T) { |
| + allow := []string{"ALICE@GITHUB"} |
| + cfg := DevboxConfig{Identity: frontIdentity(frontVisitor), AllowFor: func(host string) []string { |
| + if host != "SHOP.Example.com.:443" { |
| + t.Errorf("host changed: %q", host) |
| + } |
| + return allow |
| + }} |
| + h := devboxFront(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNoContent) }), cfg, frontSelf) |
| + for _, step := range []struct { |
| + allow []string |
| + code int |
| + }{ |
| + {allow, http.StatusNoContent}, {[]string{"bob@github"}, http.StatusForbidden}, {nil, http.StatusNoContent}, |
| + } { |
| + allow = step.allow |
| + r := frontRequest() |
| + r.Host = "SHOP.Example.com.:443" |
| + w := httptest.NewRecorder() |
| + h.ServeHTTP(w, r) |
| + if w.Code != step.code { |
| + t.Errorf("allow=%v code=%d want=%d", allow, w.Code, step.code) |
| + } |
| + } |
| +} |
| + |
| +func TestFrontDropsNonPrintableHeaderValues(t *testing.T) { |
| + for _, bad := range []string{"\x00", "\t", "\r\n", "\x1f", "\x7f", "é", "\xff"} { |
| + for _, field := range []string{"login", "name", "node"} { |
| + t.Run(field+"/"+bad, func(t *testing.T) { |
| + v := frontVisitor |
| + key := "Carlos-Visitor-" + field |
| + switch field { |
| + case "login": |
| + v.Login += bad |
| + case "name": |
| + v.Name += bad |
| + case "node": |
| + v.Node += bad |
| + } |
| + devboxFront(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if _, exists := r.Header[http.CanonicalHeaderKey(key)]; exists { |
| + t.Errorf("invalid %s header was set", field) |
| + } |
| + if len(r.Header) != 2 { |
| + t.Errorf("headers = %v, want the other two values", r.Header) |
| + } |
| + }), DevboxConfig{Identity: frontIdentity(v)}, frontSelf).ServeHTTP(httptest.NewRecorder(), frontRequest()) |
| + }) |
| + } |
| + } |
| +} |
| + |
| +func frontSocketBackend(t *testing.T, handler http.Handler) string { |
| + t.Helper() |
| + path := filepath.Join(t.TempDir(), "up.sock") |
| + ln, err := net.Listen("unix", path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + srv := &httptest.Server{Listener: ln, Config: &http.Server{Handler: handler}} |
| + srv.Start() |
| + t.Cleanup(srv.Close) |
| + return path |
| +} |
| + |
| +func TestDevboxFrontUnixUpstreamIdentityAndOwner(t *testing.T) { |
| + if runtime.GOOS != "linux" { |
| + t.Skip("socket identities require Linux") |
| + } |
| + var calls atomic.Int32 |
| + path := frontSocketBackend(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + calls.Add(1) |
| + for k, want := range map[string]string{"Carlos-Visitor-Login": frontVisitor.Login, "Carlos-Visitor-Name": frontVisitor.Name, "Carlos-Visitor-Node": frontVisitor.Node} { |
| + if got := r.Header.Get(k); got != want { |
| + t.Errorf("upstream %s=%q want=%q", k, got, want) |
| + } |
| + } |
| + w.WriteHeader(http.StatusNoContent) |
| + })) |
| + reg := openReg(t) |
| + if err := reg.Upsert(registry.Route{Host: "shop.example.com", Kind: "service", Socket: path, Status: "ready"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + wantPath, wantUID := path, uint32(os.Getuid()) |
| + cfg := DevboxConfig{Registry: reg, SpoolRoot: t.TempDir(), Identity: frontIdentity(frontVisitor), SocketOwnerFor: func(host string) (string, uint32, bool) { |
| + if host != "shop.example.com:443" { |
| + t.Errorf("socket host changed: %q", host) |
| + } |
| + return wantPath, wantUID, true |
| + }} |
| + e, err := newDevboxEdge(cfg) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + h := devboxFront(e, cfg, frontSelf) |
| + for _, step := range []struct { |
| + name string |
| + path string |
| + uid uint32 |
| + code int |
| + }{ |
| + {"match", path, uint32(os.Getuid()), http.StatusNoContent}, |
| + {"uid mismatch after success", path, uint32(os.Getuid()) + 1, http.StatusBadGateway}, |
| + {"path mismatch", path + ".other", uint32(os.Getuid()), http.StatusBadGateway}, |
| + {"match again", path, uint32(os.Getuid()), http.StatusNoContent}, |
| + {"upgrade", path, uint32(os.Getuid()), http.StatusNoContent}, |
| + } { |
| + t.Run(step.name, func(t *testing.T) { |
| + wantPath, wantUID = step.path, step.uid |
| + r := frontRequest() |
| + r.Host = "shop.example.com:443" |
| + r.Header.Set("Carlos-Visitor-Login", "mallory@github") |
| + r.Header["cArLoS-vIsItOr-LoGiN"] = []string{"forged"} |
| + r.Header.Set("Connection", "Carlos-Visitor-Login, Carlos-Visitor-Name, Carlos-Visitor-Node") |
| + if step.name == "upgrade" { |
| + if err := e.Reload(); err != nil { |
| + t.Fatal(err) |
| + } |
| + r.Header.Add("Connection", "Upgrade") |
| + r.Header.Set("Upgrade", "websocket") |
| + } |
| + w := httptest.NewRecorder() |
| + h.ServeHTTP(w, r) |
| + if w.Code != step.code { |
| + t.Fatalf("code=%d want=%d body=%s", w.Code, step.code, w.Body) |
| + } |
| + }) |
| + } |
| + if calls.Load() != 3 { |
| + t.Fatalf("upstream calls=%d, want 3", calls.Load()) |
| + } |
| +} |
| + |
| +func TestDevboxFrontSocketExpectationRefusesTCP(t *testing.T) { |
| + upstream := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { t.Error("socket expectation reached TCP upstream") })) |
| + defer upstream.Close() |
| + reg := openReg(t) |
| + if err := reg.Upsert(registry.Route{Host: "shop.example.com", Kind: "service", Addr: upstream.Listener.Addr().String(), Status: "ready"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + cfg := DevboxConfig{Registry: reg, SpoolRoot: t.TempDir(), SocketOwnerFor: func(string) (string, uint32, bool) { |
| + return "/run/carlos-devbox/sockets/shop.sock", uint32(os.Getuid()), true |
| + }} |
| + e, err := newDevboxEdge(cfg) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + w := httptest.NewRecorder() |
| + devboxFront(e, cfg, frontSelf).ServeHTTP(w, frontRequest()) |
| + if w.Code != http.StatusBadGateway { |
| + t.Fatalf("code=%d want 502", w.Code) |
| + } |
| +} |
| + |
| +func TestFrontOrderAndHostLookups(t *testing.T) { |
| + r := frontRequest() |
| + r.Host = "SHOP.Example.com.:443" |
| + r.Header.Set("Carlos-Visitor-Login", "forged") |
| + var order []string |
| + cfg := DevboxConfig{ |
| + Identity: visitorIdentityFunc(func(context.Context, netip.AddrPort) (Visitor, bool, error) { |
| + assertNoVisitorHeaders(t, r.Header) |
| + order = append(order, "identity") |
| + return frontVisitor, true, nil |
| + }), |
| + AllowFor: func(host string) []string { |
| + assertNoVisitorHeaders(t, r.Header) |
| + if host != r.Host { |
| + t.Errorf("allow host=%q want=%q", host, r.Host) |
| + } |
| + order = append(order, "allow") |
| + return []string{"ALICE@GITHUB"} |
| + }, |
| + SocketOwnerFor: func(host string) (string, uint32, bool) { |
| + if host != r.Host { |
| + t.Errorf("socket host=%q want=%q", host, r.Host) |
| + } |
| + if r.Header.Get("Carlos-Visitor-Login") != frontVisitor.Login { |
| + t.Error("identity not set after allow") |
| + } |
| + order = append(order, "socket") |
| + return "/run/carlos-devbox/sockets/shop.sock", 1234, true |
| + }, |
| + } |
| + devboxFront(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + order = append(order, "next") |
| + front := r.Context().Value(devboxFrontKey{}).(devboxFrontRequest) |
| + if front.socketOwner == nil || front.socketOwner.path != "/run/carlos-devbox/sockets/shop.sock" || front.socketOwner.uid != 1234 { |
| + t.Errorf("socket owner=%+v", front.socketOwner) |
| + } |
| + }), cfg, frontSelf).ServeHTTP(httptest.NewRecorder(), r) |
| + if got := strings.Join(order, ","); got != "identity,allow,socket,next" { |
| + t.Errorf("order=%s", got) |
| + } |
| +} |
| + |
| +func TestFrontSelfStillLooksUpIdentity(t *testing.T) { |
| + calls := 0 |
| + cfg := DevboxConfig{Identity: visitorIdentityFunc(func(context.Context, netip.AddrPort) (Visitor, bool, error) { calls++; return frontVisitor, true, nil })} |
| + assertFrontAnonymous(t, cfg, "100.64.0.1:12345") |
| + if calls != 2 { |
| + t.Errorf("lookup calls=%d want=2", calls) |
| + } |
| +} |
| + |
| +func TestDevboxSocketExpectationAbsent(t *testing.T) { |
| + path := frontSocketBackend(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNoContent) })) |
| + reg := openReg(t) |
| + if err := reg.Upsert(registry.Route{Host: "shop.example.com", Kind: "service", Socket: path, Status: "ready"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + cfg := DevboxConfig{Registry: reg, SpoolRoot: t.TempDir(), SocketOwnerFor: func(string) (string, uint32, bool) { return "ignored", ^uint32(0), false }} |
| + e, err := newDevboxEdge(cfg) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + w := httptest.NewRecorder() |
| + devboxFront(e, cfg, frontSelf).ServeHTTP(w, frontRequest()) |
| + if w.Code != http.StatusNoContent { |
| + t.Fatalf("code=%d want=204", w.Code) |
| + } |
| +} |
| + |
| +func TestUnixProxyWithoutDevboxExpectation(t *testing.T) { |
| + path := frontSocketBackend(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.Header.Get("Carlos-Visitor-Login") != "unchanged" { |
| + t.Error("normal Unix proxy changed visitor header") |
| + } |
| + w.WriteHeader(http.StatusNoContent) |
| + })) |
| + p := unixProxy(path) |
| + tr, ok := p.Transport.(*http.Transport) |
| + if !ok { |
| + t.Fatal("normal Unix proxy transport changed") |
| + } |
| + defer tr.CloseIdleConnections() |
| + r := frontRequest() |
| + r.Header.Set("Carlos-Visitor-Login", "unchanged") |
| + w := httptest.NewRecorder() |
| + p.ServeHTTP(w, r) |
| + if w.Code != http.StatusNoContent { |
| + t.Fatalf("code=%d want=204", w.Code) |
| + } |
| +} |
| + |
| +func TestFrontPrintableASCIIBoundaries(t *testing.T) { |
| + v := Visitor{Login: " ~", Name: " ~", Node: " ~"} |
| + devboxFront(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + for _, key := range []string{"Carlos-Visitor-Login", "Carlos-Visitor-Name", "Carlos-Visitor-Node"} { |
| + if got := r.Header.Get(key); got != " ~" { |
| + t.Errorf("%s=%q", key, got) |
| + } |
| + } |
| + }), DevboxConfig{Identity: frontIdentity(v)}, frontSelf).ServeHTTP(httptest.NewRecorder(), frontRequest()) |
| +} |