Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

fix: identify authenticated pinchtab servers in port-busy errors

Luigi Agosti53f1b5a02c53
diff --git a/cmd/pinchtab/cmd_server_background.go b/cmd/pinchtab/cmd_server_background.go
index 9aceed65..a9e1f060 100644
--- a/cmd/pinchtab/cmd_server_background.go
+++ b/cmd/pinchtab/cmd_server_background.go
@@ -138,11 +138,8 @@ func runServerBackground(cfg *config.RuntimeConfig, opts serverBackgroundOptions
}
baseURL := fmt.Sprintf("http://127.0.0.1:%s", cfg.Port)
- if isUnauthenticatedPinchTabServerReady(baseURL) {
- return fmt.Errorf("server already running at %s; stop it before starting a background server", baseURL)
- }
- if portIsListening(baseURL) {
- return fmt.Errorf("port already in use at %s, but it is not a healthy PinchTab server for this config", baseURL)
+ if err := portBusyError(baseURL, config.ConfigFilePath()); err != nil {
+ return err
}
binary, marker, err := prepareServerSpawn()
@@ -221,6 +218,48 @@ func isUnauthenticatedPinchTabServerReady(baseURL string) bool {
return isPinchTabHealthReady(baseURL+"/health", "")
}
+// portBusyError classifies whatever holds the port and returns an
+// actionable error, or nil when the port is free: a ready PinchTab server,
+// a PinchTab server running with a different config/token (its /health
+// answers with the PinchTab auth-error shape), or a foreign process.
+func portBusyError(baseURL, configPath string) error {
+ if isUnauthenticatedPinchTabServerReady(baseURL) {
+ return fmt.Errorf("server already running at %s; stop it with: pinchtab server stop", baseURL)
+ }
+ if isAuthenticatedPinchTabServer(baseURL) {
+ return fmt.Errorf("a PinchTab server (different config/token) is already running at %s; stop it with `pinchtab server stop` (or from its own checkout), or change \"port\" in %s", baseURL, configPath)
+ }
+ if portIsListening(baseURL) {
+ return fmt.Errorf("port already in use at %s by a process that is not a PinchTab server; stop that process or change \"port\" in %s", baseURL, configPath)
+ }
+ return nil
+}
+
+// isAuthenticatedPinchTabServer reports whether /health answered with a
+// PinchTab-shaped auth error, i.e. the occupant is a PinchTab server whose
+// token this config does not hold.
+func isAuthenticatedPinchTabServer(baseURL string) bool {
+ status, body, reachable := server.ProbeHealth(baseURL+"/health", 3*time.Second, nil)
+ if !reachable {
+ return false
+ }
+ return isPinchTabAuthError(status, body)
+}
+
+func isPinchTabAuthError(status int, body []byte) bool {
+ if status != http.StatusUnauthorized && status != http.StatusForbidden {
+ return false
+ }
+ var resp struct {
+ Error string `json:"error"`
+ Code string `json:"code"`
+ }
+ if err := json.Unmarshal(body, &resp); err != nil {
+ return false
+ }
+ return resp.Error != "" && resp.Code != ""
+}
+
func isPinchTabHealthReady(url, marker string) bool {
var headers map[string]string
if marker != "" {
diff --git a/cmd/pinchtab/cmd_server_background_test.go b/cmd/pinchtab/cmd_server_background_test.go
index 2332b202..52b099f9 100644
--- a/cmd/pinchtab/cmd_server_background_test.go
+++ b/cmd/pinchtab/cmd_server_background_test.go
@@ -198,3 +198,97 @@ func TestVerifyServerPIDInfoChecksProcessCommand(t *testing.T) {
t.Fatalf("verifyServerPIDInfo() error = %v", err)
}
}
+
+func TestIsPinchTabAuthError(t *testing.T) {
+ cases := []struct {
+ name string
+ status int
+ body string
+ want bool
+ }{
+ {"pinchtab 401", 401, `{"code":"missing_token","error":"unauthorized"}`, true},
+ {"pinchtab 403", 403, `{"code":"invalid_token","error":"unauthorized"}`, true},
+ {"foreign 401 html", 401, `<html>401 Authorization Required</html>`, false},
+ {"json missing code", 401, `{"error":"unauthorized"}`, false},
+ {"ok response", 200, `{"code":"x","error":"y"}`, false},
+ {"foreign 404", 404, `404 page not found`, false},
+ }
+ for _, tc := range cases {
+ if got := isPinchTabAuthError(tc.status, []byte(tc.body)); got != tc.want {
+ t.Errorf("%s: isPinchTabAuthError = %v, want %v", tc.name, got, tc.want)
+ }
+ }
+}
+
+func TestPortBusyErrorAuthenticatedPinchTab(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusUnauthorized)
+ _, _ = w.Write([]byte(`{"code":"missing_token","error":"unauthorized"}`))
+ }))
+ defer srv.Close()
+
+ err := portBusyError(srv.URL, "/home/user/.config/pinchtab/config.json")
+ if err == nil {
+ t.Fatal("expected an error for a busy port")
+ }
+ msg := err.Error()
+ for _, want := range []string{
+ "PinchTab server (different config/token)",
+ srv.URL,
+ "pinchtab server stop",
+ `"port"`,
+ "/home/user/.config/pinchtab/config.json",
+ } {
+ if !strings.Contains(msg, want) {
+ t.Errorf("message missing %q:\n%s", want, msg)
+ }
+ }
+ if strings.Contains(msg, "not a PinchTab server") {
+ t.Errorf("authenticated PinchTab server mislabeled as foreign:\n%s", msg)
+ }
+}
+
+func TestPortBusyErrorForeignListener(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _, _ = w.Write([]byte("<html>welcome to nginx</html>"))
+ }))
+ defer srv.Close()
+
+ err := portBusyError(srv.URL, "/tmp/config.json")
+ if err == nil {
+ t.Fatal("expected an error for a busy port")
+ }
+ msg := err.Error()
+ for _, want := range []string{"not a PinchTab server", srv.URL, `"port"`, "/tmp/config.json"} {
+ if !strings.Contains(msg, want) {
+ t.Errorf("message missing %q:\n%s", want, msg)
+ }
+ }
+}
+
+func TestPortBusyErrorReadyPinchTab(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"status":"ok","mode":"dashboard","version":"dev"}`))
+ }))
+ defer srv.Close()
+
+ err := portBusyError(srv.URL, "/tmp/config.json")
+ if err == nil {
+ t.Fatal("expected an error for a busy port")
+ }
+ if !strings.Contains(err.Error(), "server already running") || !strings.Contains(err.Error(), "pinchtab server stop") {
+ t.Errorf("ready-server message lacks the stop command:\n%s", err)
+ }
+}
+
+func TestPortBusyErrorFreePort(t *testing.T) {
+ srv := httptest.NewServer(http.NotFoundHandler())
+ url := srv.URL
+ srv.Close()
+
+ if err := portBusyError(url, "/tmp/config.json"); err != nil {
+ t.Errorf("free port should yield nil, got %v", err)
+ }
+}