High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: a failed network export abandons its reserved name, so the obvious file is empty and the next export hides behind a -1 suffix (PIN-050)
Luigi Agosti5e12b1764be3
diff --git a/internal/fileout/fileout.go b/internal/fileout/fileout.goindex 0cff19c4..04207497 100644--- a/internal/fileout/fileout.go+++ b/internal/fileout/fileout.go@@ -57,16 +57,30 @@ func CreateUnique(dir, base, ext string) (*os.File, string, error) {// WriteUnique creates a fresh file under dir and writes buf to it, returning the path// actually used.+// A failed write removes the file it created. CreateUnique reserves the name by+// creating it, so returning an error while leaving it behind hands the caller a+// 0-byte file under a name that reads like a real output — the same defect as an+// abandoned reservation, one layer down.func WriteUnique(dir, base, ext string, buf []byte) (string, error) {- f, path, err := CreateUnique(dir, base, ext)+ return writeUnique(dir, base, ext, buf, CreateUnique)+}++// writeUnique takes its creator as a parameter so a test can hand it a handle whose+// write fails and assert the file it created is gone. A real write failure needs a+// full disk or a revoked handle, neither of which a test can arrange portably, and an+// unpinned removal is an unproven one.+func writeUnique(dir, base, ext string, buf []byte, create func(string, string, string) (*os.File, string, error)) (string, error) {+ f, path, err := create(dir, base, ext)if err != nil {return "", err}if _, err := f.Write(buf); err != nil {_ = f.Close()+ _ = os.Remove(path)return "", err}if err := f.Close(); err != nil {+ _ = os.Remove(path)return "", err}return path, nildiff --git a/internal/fileout/fileout_test.go b/internal/fileout/fileout_test.goindex 7d57a1c1..b556a6a0 100644--- a/internal/fileout/fileout_test.go+++ b/internal/fileout/fileout_test.go@@ -130,3 +130,45 @@ func assertContents(t *testing.T, path string, want []byte) {t.Errorf("%s holds %q, want %q", path, got, want)}}++// TestWriteUniqueRemovesTheFileItCreatedWhenTheWriteFails pins the removal through+// the creator seam: the stub creates a REAL file and hands back a closed handle, so+// the write fails for a reason the caller cannot control and the file it left is the+// thing under test. Without the removal the caller gets an error plus a 0-byte file+// wearing the output's name.+func TestWriteUniqueRemovesTheFileItCreatedWhenTheWriteFails(t *testing.T) {+ dir := t.TempDir()+ created := ""+ closedHandle := func(dir, base, ext string) (*os.File, string, error) {+ f, path, err := CreateUnique(dir, base, ext)+ if err != nil {+ return nil, "", err+ }+ if err := f.Close(); err != nil {+ return nil, "", err+ }+ created = path+ return f, path, nil+ }++ path, err := writeUnique(dir, "capture-20260101_000000", ".png", []byte("bytes"), closedHandle)+ if err == nil {+ t.Fatal("precondition: writing through a closed handle must fail")+ }+ if path != "" {+ t.Errorf("WriteUnique returned %q alongside its error; a failed write has no path to report", path)+ }+ if created == "" {+ t.Fatal("the stub creator never ran, so this guard checked nothing")+ }+ if _, err := os.Stat(created); !os.IsNotExist(err) {+ t.Errorf("%s survived a failed write (stat err = %v); the created file must be removed", created, err)+ }+ entries, err := os.ReadDir(dir)+ if err != nil {+ t.Fatal(err)+ }+ for _, entry := range entries {+ t.Errorf("a failed write left %s in the output directory", entry.Name())+ }+}diff --git a/internal/handlers/network_export.go b/internal/handlers/network_export.goindex b922e23a..ea4a6f1f 100644--- a/internal/handlers/network_export.go+++ b/internal/handlers/network_export.go@@ -311,6 +311,17 @@ func (h *Handlers) writeExportFile() error {userPath := r.URL.Query().Get("path")autoNamed := userPath == ""+ // A reservation is a real 0-byte file, so every exit that is not the completed+ // rename has to remove it. Left behind it poisons the name twice over: the obvious+ // name holds an empty export, and the next export in the same second is pushed onto+ // a -1 suffix. Releasing it from a deferred check rather than at each return is what+ // makes that exhaustive — a branch added later inherits it instead of forgetting it.+ reservedPath, committed := "", false+ defer func() {+ if !committed && reservedPath != "" {+ _ = os.Remove(reservedPath)+ }+ }()if autoNamed {// Reserve the generated name before resolveExportFile derives the tmp path from// it. Two auto-named exports in the same second used to rename onto one file —@@ -321,11 +332,12 @@ func (h *Handlers) writeExportFile(if err := os.MkdirAll(exportDir, 0750); err != nil {return fmt.Errorf("create dir: %w", err)}- reserved, reservedPath, err := createUniqueFile(exportDir, "network-"+exportTimestamp(), enc.FileExtension())+ reserved, path, err := createUniqueFile(exportDir, "network-"+exportTimestamp(), enc.FileExtension())if err != nil {return fmt.Errorf("reserve export name: %w", err)}_ = reserved.Close()+ reservedPath = pathuserPath = filepath.Base(reservedPath)}@@ -367,6 +379,7 @@ func (h *Handlers) writeExportFile(_ = os.Remove(tmpPath)return err}+ committed = truehttpx.JSON(w, 200, map[string]any{"path": absPath,diff --git a/internal/handlers/network_export_test.go b/internal/handlers/network_export_test.goindex 37ceb5b8..9d8a127b 100644--- a/internal/handlers/network_export_test.go+++ b/internal/handlers/network_export_test.go@@ -3,6 +3,7 @@ package handlersimport ("encoding/json""fmt"+ "io""net/http/httptest""os""path/filepath"@@ -11,6 +12,8 @@ import ("time""github.com/pinchtab/pinchtab/internal/bridge"+ "github.com/pinchtab/pinchtab/internal/bridge/observe"+ "github.com/pinchtab/pinchtab/internal/config")// TestHandleNetworkExportPrefersRetainedBodyInOrder verifies the non-streaming@@ -116,3 +119,114 @@ func TestCleanupStaleTmpExports_NoDir(t *testing.T) {// Should not panic when exports/ doesn't exist.CleanupStaleTmpExports(t.TempDir())}++// failingExportEncoder fails at one named stage so every non-success exit of+// writeExportFile can be driven. The reservation the auto-named path creates is a+// real file, so each of these stages is a chance to abandon it.+type failingExportEncoder struct {+ failAt string+}++func (e failingExportEncoder) ContentType() string { return "application/json" }+func (e failingExportEncoder) FileExtension() string { return ".har" }++func (e failingExportEncoder) Start(w io.Writer) error {+ if e.failAt == "start" {+ return fmt.Errorf("start refused")+ }+ _, err := w.Write([]byte("{"))+ return err+}++func (e failingExportEncoder) Encode(entry observe.ExportEntry) error {+ if e.failAt == "encode" {+ return fmt.Errorf("encode refused")+ }+ return nil+}++func (e failingExportEncoder) Finish() error {+ if e.failAt == "finish" {+ return fmt.Errorf("finish refused")+ }+ return nil+}++func exportDirEntries(t *testing.T, stateDir string) []string {+ t.Helper()++ entries, err := os.ReadDir(filepath.Join(stateDir, "exports"))+ if err != nil {+ if os.IsNotExist(err) {+ return nil+ }+ t.Fatal(err)+ }+ names := make([]string, 0, len(entries))+ for _, entry := range entries {+ names = append(names, entry.Name())+ }+ return names+}++func TestAFailedAutoNamedExportLeavesNothingBehind(t *testing.T) {+ for _, failAt := range []string{"start", "encode", "finish"} {+ t.Run(failAt, func(t *testing.T) {+ stateDir := t.TempDir()+ h := New(&networkMockBridge{nm: bridge.NewNetworkMonitor(10)}, &config.RuntimeConfig{StateDir: stateDir}, nil, nil, nil)++ req := httptest.NewRequest("GET", "/network/export", nil)+ err := h.writeExportFile(httptest.NewRecorder(), req, failingExportEncoder{failAt: failAt}, "har",+ func(emit func(observe.ExportEntry) error) error {+ return emit(observe.ExportEntry{})+ })+ if err == nil {+ t.Fatalf("precondition: an encoder failing at %s must fail the export", failAt)+ }++ for _, name := range exportDirEntries(t, stateDir) {+ t.Errorf("an export that failed at %s left %s behind; the reserved name now holds an empty export", failAt, name)+ }+ })+ }+}++// TestAFailedExportDoesNotPoisonTheNextName is the assertion that catches the+// consequence rather than the litter: an abandoned reservation pushes the NEXT+// export in the same second onto a -1 suffix, so the obvious name holds 0 bytes+// while the real export hides behind a suffix nobody asked for. Counting the files+// is what distinguishes that from a leak that merely litters.+func TestAFailedExportDoesNotPoisonTheNextName(t *testing.T) {+ stateDir := t.TempDir()+ h := New(&networkMockBridge{nm: bridge.NewNetworkMonitor(10)}, &config.RuntimeConfig{StateDir: stateDir}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/network/export", nil)++ if err := h.writeExportFile(httptest.NewRecorder(), req, failingExportEncoder{failAt: "encode"}, "har",+ func(emit func(observe.ExportEntry) error) error {+ return emit(observe.ExportEntry{})+ }); err == nil {+ t.Fatal("precondition: the first export must fail")+ }++ if err := h.writeExportFile(httptest.NewRecorder(), req, failingExportEncoder{}, "har",+ func(emit func(observe.ExportEntry) error) error {+ return emit(observe.ExportEntry{})+ }); err != nil {+ t.Fatalf("second export: %v", err)+ }++ names := exportDirEntries(t, stateDir)+ if len(names) != 1 {+ t.Fatalf("exports dir holds %v, want exactly one file: a failed export must not leave a name behind for the next one to trip over", names)+ }+ if strings.Contains(names[0], "-1.") {+ t.Errorf("the successful export landed on %s; the suffix means a stale reservation still holds the unsuffixed name", names[0])+ }+ info, err := os.Stat(filepath.Join(stateDir, "exports", names[0]))+ if err != nil {+ t.Fatal(err)+ }+ if info.Size() == 0 {+ t.Errorf("%s is empty; the file under the export's own name is a reservation, not an export", names[0])+ }+}