Skip to content

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

fix: one unconfirmed dashboard click deletes the live browser's profile directory out from under it and answers 200, and the running flag that would guard it is never assigned (PIN-250)

Luigi Agosticb7475666fa5
diff --git a/internal/bridge/profile_lock.go b/internal/bridge/profile_lock.go
index b75cdf1a..4c49ca71 100644
--- a/internal/bridge/profile_lock.go
+++ b/internal/bridge/profile_lock.go
@@ -324,6 +324,14 @@ func quarantineCorruptedProfile(profileDir string, keep int) (string, error) {
return quarantinePath, nil
}
+// ProfileOwnedByRunningPinchtab reports whether a live pinchtab process holds
+// profileDir via its pinchtab.pid lock. It is the per-directory truth the
+// profiles destructive-route guard falls back to on surfaces that have no
+// orchestrator instance mapping.
+func ProfileOwnedByRunningPinchtab(profileDir string) (bool, int) {
+ return isProfileOwnedByRunningPinchtab(profileDir)
+}
+
func isProfileOwnedByRunningPinchtab(profileDir string) (bool, int) {
pidFile := filepath.Join(profileDir, "pinchtab.pid")
data, err := os.ReadFile(pidFile)
diff --git a/internal/profiles/handlers.go b/internal/profiles/handlers.go
index ef810182..c7321795 100644
--- a/internal/profiles/handlers.go
+++ b/internal/profiles/handlers.go
@@ -62,7 +62,7 @@ func profileMutationStatus(err error) int {
return http.StatusOK
case errors.Is(err, ErrInvalidProfileName):
return http.StatusBadRequest
- case errors.Is(err, ErrProfileExists), errors.Is(err, ErrProfileDirExists):
+ case errors.Is(err, ErrProfileExists), errors.Is(err, ErrProfileDirExists), errors.Is(err, ErrProfileInUse):
return http.StatusConflict
default:
return http.StatusInternalServerError
@@ -230,8 +230,23 @@ func (pm *ProfileManager) handleDeleteByID(w http.ResponseWriter, r *http.Reques
return
}
+ if r.URL.Query().Get("force") == "true" {
+ orphaned, err := pm.ForceDelete(name)
+ if err != nil {
+ httpx.Error(w, profileMutationStatus(err), err)
+ return
+ }
+ authn.AuditLog(r, "profile.deleted", "profileId", id, "profileName", name, "force", "true", "orphanedInstance", orphaned)
+ resp := map[string]any{"status": "deleted", "id": id, "name": name}
+ if orphaned != "" {
+ resp["orphanedInstance"] = orphaned
+ }
+ httpx.JSON(w, 200, resp)
+ return
+ }
+
if err := pm.Delete(name); err != nil {
- httpx.Error(w, 500, err)
+ httpx.Error(w, profileMutationStatus(err), err)
return
}
@@ -312,7 +327,7 @@ func (pm *ProfileManager) handleResetByIDOrName(w http.ResponseWriter, r *http.R
}
if err := pm.Reset(name); err != nil {
- httpx.Error(w, 500, err)
+ httpx.Error(w, profileMutationStatus(err), err)
return
}
authn.AuditLog(r, "profile.reset", "profileId", id, "profileName", name)
diff --git a/internal/profiles/profiles.go b/internal/profiles/profiles.go
index c09d7a86..151f3afe 100644
--- a/internal/profiles/profiles.go
+++ b/internal/profiles/profiles.go
@@ -1,6 +1,7 @@
package profiles
import (
+ "errors"
"fmt"
"io/fs"
"os"
@@ -15,9 +16,11 @@ import (
)
type ProfileManager struct {
- baseDir string
- activity activity.Recorder
- mu sync.RWMutex
+ baseDir string
+ activity activity.Recorder
+ instanceLookup func(profileID string) (instanceID string, running bool)
+ lockOwner func(dir string) (owned bool, pid int)
+ mu sync.RWMutex
}
type ProfileMeta struct {
@@ -45,7 +48,8 @@ type ProfileDetailedInfo struct {
func NewProfileManager(baseDir string) *ProfileManager {
_ = os.MkdirAll(baseDir, 0755)
return &ProfileManager{
- baseDir: baseDir,
+ baseDir: baseDir,
+ lockOwner: bridge.ProfileOwnedByRunningPinchtab,
}
}
@@ -55,6 +59,37 @@ func (pm *ProfileManager) SetActivityRecorder(rec activity.Recorder) {
pm.activity = rec
}
+// ErrProfileInUse indicates a destructive operation was refused because a
+// running instance holds the profile.
+var ErrProfileInUse = errors.New("profile in use")
+
+// SetInstanceLookup installs the orchestrator's profile→instance mapping at
+// composition time. Without it (a mux serving no orchestrator), profileHolder
+// falls back to the pinchtab.pid lock so the guard refuses on both surfaces.
+func (pm *ProfileManager) SetInstanceLookup(lookup func(profileID string) (instanceID string, running bool)) {
+ pm.mu.Lock()
+ defer pm.mu.Unlock()
+ pm.instanceLookup = lookup
+}
+
+// profileHolder is the single owner of the in-use rule: the Delete and Reset
+// guards and the published running flag must agree, so all of them consult
+// this and nothing else. Callers hold pm.mu.
+func (pm *ProfileManager) profileHolder(id, dir string) (holder string, held bool) {
+ if pm.instanceLookup != nil {
+ if instanceID, running := pm.instanceLookup(id); running {
+ return instanceID, true
+ }
+ return "", false
+ }
+ if pm.lockOwner != nil {
+ if owned, pid := pm.lockOwner(dir); owned {
+ return fmt.Sprintf("pinchtab process %d", pid), true
+ }
+ }
+ return "", false
+}
+
func (pm *ProfileManager) findProfileDirByName(name string) (string, error) {
direct := filepath.Join(pm.baseDir, name)
if info, err := os.Stat(direct); err == nil && info.IsDir() {
@@ -127,11 +162,14 @@ func (pm *ProfileManager) List() ([]bridge.ProfileInfo, error) {
pathExists = false
}
+ _, held := pm.profileHolder(info.ID, filepath.Join(pm.baseDir, entry.Name()))
+
profiles = append(profiles, bridge.ProfileInfo{
ID: info.ID,
Name: info.Name,
Path: info.Path,
PathExists: pathExists,
+ Running: held,
Created: info.CreatedAt,
Temporary: strings.HasPrefix(info.Name, "instance-"),
Quarantined: bridge.IsQuarantinedProfileDir(entry.Name()),
diff --git a/internal/profiles/profiles_crud.go b/internal/profiles/profiles_crud.go
index ddad6493..df004f0b 100644
--- a/internal/profiles/profiles_crud.go
+++ b/internal/profiles/profiles_crud.go
@@ -140,6 +140,9 @@ func (pm *ProfileManager) Reset(name string) error {
if err != nil {
return err
}
+ if holder, held := pm.profileHolder(profileID(name), dir); held {
+ return tagged(ErrProfileInUse, fmt.Sprintf("profile %q is in use by %s; stop it before resetting", name, holder))
+ }
resetProfileDir(dir)
slog.Info("profile reset", "name", name)
@@ -179,17 +182,40 @@ func resetProfileDir(dir string) {
}
func (pm *ProfileManager) Delete(name string) error {
+ _, err := pm.remove(name, false)
+ return err
+}
+
+// ForceDelete skips the in-use refusal. profiles is a leaf and cannot stop
+// instances, so a held profile is removed anyway and the holder is returned
+// for the response to report as orphaned — a browser left running on a
+// deleted directory must never be silent.
+func (pm *ProfileManager) ForceDelete(name string) (orphanedInstance string, err error) {
+ return pm.remove(name, true)
+}
+
+func (pm *ProfileManager) remove(name string, force bool) (string, error) {
if err := ValidateProfileName(name); err != nil {
- return err
+ return "", err
}
pm.mu.Lock()
defer pm.mu.Unlock()
dir, err := pm.findProfileDirByName(name)
if err != nil {
- return err
+ return "", err
+ }
+ holder, held := pm.profileHolder(profileID(name), dir)
+ if held && !force {
+ return "", tagged(ErrProfileInUse, fmt.Sprintf("profile %q is in use by %s; delete with force=true to remove it anyway", name, holder))
+ }
+ if err := os.RemoveAll(dir); err != nil {
+ return "", err
+ }
+ if held {
+ return holder, nil
}
- return os.RemoveAll(dir)
+ return "", nil
}
func (pm *ProfileManager) UpdateMeta(name string, meta map[string]string) error {
diff --git a/internal/profiles/profiles_test.go b/internal/profiles/profiles_test.go
index b028daa7..4e0d0227 100644
--- a/internal/profiles/profiles_test.go
+++ b/internal/profiles/profiles_test.go
@@ -1347,3 +1347,223 @@ func TestHandleListMarksQuarantinedEntries(t *testing.T) {
}
}
}
+
+func newHeldProfile(t *testing.T, pm *ProfileManager, name string) (id, cookies string) {
+ t.Helper()
+ if err := pm.Create(name); err != nil {
+ t.Fatal(err)
+ }
+ cookies = filepath.Join(pm.baseDir, profileID(name), "Default", "Cookies")
+ if err := os.WriteFile(cookies, []byte("session-data"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ return profileID(name), cookies
+}
+
+func requireCookiesIntact(t *testing.T, cookies string) {
+ t.Helper()
+ data, err := os.ReadFile(cookies)
+ if err != nil {
+ t.Fatalf("cookies file gone after a refused operation: %v", err)
+ }
+ if string(data) != "session-data" {
+ t.Fatalf("cookies content changed after a refused operation: %q", data)
+ }
+}
+
+// instanceLookupFrom derives the holder mapping the same way server.go composes
+// it from orch.List(), so running-ness in these tests and the guard share one
+// source instead of a per-test fixture.
+func instanceLookupFrom(instances []bridge.Instance) func(string) (string, bool) {
+ return func(profileID string) (string, bool) {
+ for _, inst := range instances {
+ if inst.ProfileID != profileID {
+ continue
+ }
+ switch inst.Status {
+ case "starting", "running", "stopping":
+ return inst.ID, true
+ }
+ }
+ return "", false
+ }
+}
+
+func TestDeleteRefusesAProfileAnInstanceHolds(t *testing.T) {
+ pm := NewProfileManager(t.TempDir())
+ id, cookies := newHeldProfile(t, pm, "held")
+ pm.SetInstanceLookup(instanceLookupFrom([]bridge.Instance{
+ {ID: "inst_holder01", ProfileID: id, Status: "running"},
+ }))
+ mux := http.NewServeMux()
+ pm.RegisterHandlers(mux)
+
+ req := httptest.NewRequest("DELETE", "/profiles/"+id, nil)
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+
+ if w.Code != 409 {
+ t.Fatalf("expected 409, got %d: %s", w.Code, w.Body.String())
+ }
+ if !strings.Contains(w.Body.String(), "inst_holder01") {
+ t.Fatalf("409 body does not name the holding instance: %s", w.Body.String())
+ }
+ requireCookiesIntact(t, cookies)
+}
+
+func TestResetRefusesAProfileAnInstanceHolds(t *testing.T) {
+ pm := NewProfileManager(t.TempDir())
+ id, cookies := newHeldProfile(t, pm, "held")
+ pm.SetInstanceLookup(instanceLookupFrom([]bridge.Instance{
+ {ID: "inst_holder02", ProfileID: id, Status: "running"},
+ }))
+ mux := http.NewServeMux()
+ pm.RegisterHandlers(mux)
+
+ req := httptest.NewRequest("POST", "/profiles/"+id+"/reset", nil)
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+
+ if w.Code != 409 {
+ t.Fatalf("expected 409, got %d: %s", w.Code, w.Body.String())
+ }
+ if !strings.Contains(w.Body.String(), "inst_holder02") {
+ t.Fatalf("409 body does not name the holding instance: %s", w.Body.String())
+ }
+ requireCookiesIntact(t, cookies)
+}
+
+// The force contract is delete-and-report-orphaned: profiles cannot stop
+// instances, so the holder is named in the response instead of being left
+// running on a removed directory silently.
+func TestForceDeleteRemovesAHeldProfileAndReportsTheOrphanedInstance(t *testing.T) {
+ pm := NewProfileManager(t.TempDir())
+ id, _ := newHeldProfile(t, pm, "held")
+ pm.SetInstanceLookup(instanceLookupFrom([]bridge.Instance{
+ {ID: "inst_holder03", ProfileID: id, Status: "running"},
+ }))
+ mux := http.NewServeMux()
+ pm.RegisterHandlers(mux)
+
+ req := httptest.NewRequest("DELETE", "/profiles/"+id+"?force=true", nil)
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+
+ if w.Code != 200 {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var resp map[string]any
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatal(err)
+ }
+ if resp["orphanedInstance"] != "inst_holder03" {
+ t.Fatalf("force delete did not report the orphaned instance: %v", resp)
+ }
+ if _, err := os.Stat(filepath.Join(pm.baseDir, id)); !os.IsNotExist(err) {
+ t.Fatalf("profile directory still present after force delete: %v", err)
+ }
+}
+
+func TestDeleteAndResetOfIdleProfilesAreUnchanged(t *testing.T) {
+ pm := NewProfileManager(t.TempDir())
+ idleID, idleCookies := newHeldProfile(t, pm, "idle")
+ heldID, _ := newHeldProfile(t, pm, "held")
+ pm.SetInstanceLookup(instanceLookupFrom([]bridge.Instance{
+ {ID: "inst_holder04", ProfileID: heldID, Status: "running"},
+ }))
+ mux := http.NewServeMux()
+ pm.RegisterHandlers(mux)
+
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, httptest.NewRequest("POST", "/profiles/"+idleID+"/reset", nil))
+ if w.Code != 200 {
+ t.Fatalf("idle reset: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ if _, err := os.Stat(idleCookies); !os.IsNotExist(err) {
+ t.Fatalf("idle reset left the cookies file in place: %v", err)
+ }
+
+ w = httptest.NewRecorder()
+ mux.ServeHTTP(w, httptest.NewRequest("DELETE", "/profiles/"+idleID, nil))
+ if w.Code != 200 {
+ t.Fatalf("idle delete: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ if _, err := os.Stat(filepath.Join(pm.baseDir, idleID)); !os.IsNotExist(err) {
+ t.Fatalf("idle delete left the directory in place: %v", err)
+ }
+}
+
+func TestListRunningComesFromTheSameSourceAsTheGuard(t *testing.T) {
+ pm := NewProfileManager(t.TempDir())
+ heldID, _ := newHeldProfile(t, pm, "held")
+ if err := pm.Create("idle"); err != nil {
+ t.Fatal(err)
+ }
+ instances := []bridge.Instance{{ID: "inst_holder05", ProfileID: heldID, Status: "running"}}
+ pm.SetInstanceLookup(instanceLookupFrom(instances))
+ mux := http.NewServeMux()
+ pm.RegisterHandlers(mux)
+
+ req := httptest.NewRequest("GET", "/profiles", nil)
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+
+ var listed []profileResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &listed); err != nil {
+ t.Fatal(err)
+ }
+ if len(listed) != 2 {
+ t.Fatalf("expected 2 profiles, got %d", len(listed))
+ }
+ for _, p := range listed {
+ want := false
+ for _, inst := range instances {
+ if inst.ProfileID == p.ID && inst.Status == "running" {
+ want = true
+ }
+ }
+ if p.Running != want {
+ t.Errorf("profile %q running = %v, want %v (from the instance mapping)", p.Name, p.Running, want)
+ }
+ }
+}
+
+// The bridge surface has no orchestrator, so the guard's fallback is the
+// pinchtab.pid lock in the profile directory; this mux is built with no
+// instance lookup at all and must still refuse.
+func TestDestructiveRoutesRefuseWithoutAnOrchestrator(t *testing.T) {
+ pm := NewProfileManager(t.TempDir())
+ id, cookies := newHeldProfile(t, pm, "held")
+ pm.lockOwner = func(string) (bool, int) { return true, 4242 }
+ mux := http.NewServeMux()
+ pm.RegisterHandlers(mux)
+
+ for _, req := range []*http.Request{
+ httptest.NewRequest("DELETE", "/profiles/"+id, nil),
+ httptest.NewRequest("POST", "/profiles/"+id+"/reset", nil),
+ } {
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+ if w.Code != 409 {
+ t.Fatalf("%s %s: expected 409, got %d: %s", req.Method, req.URL.Path, w.Code, w.Body.String())
+ }
+ if !strings.Contains(w.Body.String(), "4242") {
+ t.Fatalf("%s %s: 409 body does not name the holder: %s", req.Method, req.URL.Path, w.Body.String())
+ }
+ }
+ requireCookiesIntact(t, cookies)
+}
+
+func TestDefaultLockOwnerTreatsAPidFreeDirectoryAsIdle(t *testing.T) {
+ pm := NewProfileManager(t.TempDir())
+ id, _ := newHeldProfile(t, pm, "no-pid-file")
+ mux := http.NewServeMux()
+ pm.RegisterHandlers(mux)
+
+ req := httptest.NewRequest("DELETE", "/profiles/"+id, nil)
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+ if w.Code != 200 {
+ t.Fatalf("expected 200 for a directory with no pinchtab.pid, got %d: %s", w.Code, w.Body.String())
+ }
+}
diff --git a/internal/server/server.go b/internal/server/server.go
index a9f796f8..0bd404d7 100644
--- a/internal/server/server.go
+++ b/internal/server/server.go
@@ -73,6 +73,18 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {
orch := orchestrator.NewOrchestrator(profilesDir)
orch.ApplyRuntimeConfig(cfg)
orch.SetProfileManager(profMgr)
+ profMgr.SetInstanceLookup(func(profileID string) (string, bool) {
+ for _, inst := range orch.List() {
+ if inst.ProfileID != profileID {
+ continue
+ }
+ switch inst.Status {
+ case "starting", "running", "stopping":
+ return inst.ID, true
+ }
+ }
+ return "", false
+ })
dash.SetInstanceLister(orch)
dash.SetMonitoringSource(orch)
dash.SetServerMetricsProvider(func() dashboard.MonitoringServerMetrics {