package rexterm_test import ( "context" "net/http" "net/http/httptest" "net/http/httputil" "net/url" "strconv" "strings" "sync" "testing" "time" "go.mitchellh.com/libghostty" "100gex/internal/rex" "100gex/internal/rex/rextest" "100gex/internal/rexterm" ) // TestRemote reaches a server over the network the way a tailnet server is // reached: HTTPS, with WebSockets over TLS, here through a TLS proxy in // front of the server's plain listener. The control connection, a terminal's // stream, and typing all go through it. func TestRemote(t *testing.T) { port := rextest.FreePort(t) srv := rextest.StartArgs(t, "", "--extra-listen", "http://127.0.0.1:"+strconv.Itoa(port), "--allow-anonymous") plain, _ := url.Parse("http://127.0.0.1:" + strconv.Itoa(port)) var mu sync.Mutex through := map[string]int{} forward := httputil.NewSingleHostReverseProxy(plain) proxy := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { mu.Lock() through[r.URL.Path]++ mu.Unlock() forward.ServeHTTP(w, r) })) defer proxy.Close() proxied, _ := url.Parse(proxy.URL) proxyPort, _ := strconv.Atoi(proxied.Port()) ep := rex.Endpoint{Host: "127.0.0.1", Port: proxyPort, TLS: true, HTTPClient: proxy.Client()} ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c, err := rex.Dial(ctx, ep, rex.ClientInfo{Kind: "app", Name: "100gex-test"}) if err != nil { t.Fatal(err) } defer c.Close() sid, bid := rextest.NewSession(t, c, rextest.RawCat...) h := open(t, &rextest.Server{Endpoint: ep}, c, sid, bid) h.until("the snapshot, over TLS", func(term *libghostty.Terminal, _ rexterm.State) bool { return term != nil && strings.Contains(screen(t, term), "ready") }) h.pane.Key(rex.KeyEvent{Action: "press", Key: "key_x", Text: "x", UnshiftedCodepoint: 'x'}) h.until("typing, over TLS", func(term *libghostty.Terminal, _ rexterm.State) bool { return strings.Contains(screen(t, term), "ready\nx") }) mu.Lock() if through["/api/control"] != 1 || through["/api/data"] != 1 { t.Errorf("through the TLS proxy: %v, want one control and one data connection", through) } mu.Unlock() // host:port means HTTPS, then plain HTTP. The plain listener refuses // TLS, so the second answers. eps, err := rex.Candidates("127.0.0.1:" + strconv.Itoa(port)) if err != nil { t.Fatal(err) } c2, got, err := rex.DialAny(ctx, eps, rex.ClientInfo{Name: "100gex-test"}) if err != nil { t.Fatal(err) } c2.Close() if got.TLS || got.Port != port { t.Errorf("DialAny chose %v, want plain HTTP on %d", got, port) } _ = srv }