Skip to content

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

fix(profiles): stop a partial metadata update from erasing what it could not read

Luigi Agosti50521becc826
diff --git a/internal/profiles/identity.go b/internal/profiles/identity.go
index fa2a9a0f..45ba0149 100644
--- a/internal/profiles/identity.go
+++ b/internal/profiles/identity.go
@@ -2,6 +2,9 @@ package profiles
import (
"encoding/json"
+ "errors"
+ "fmt"
+ "io/fs"
"os"
"path/filepath"
)
@@ -94,18 +97,60 @@ func readJSON(path string, out any) bool {
return true
}
+// readProfileMeta answers with the zero value when the metadata is absent or
+// unreadable. That is right for a listing, which must still describe a profile
+// whose sidecar is missing, and wrong for anything that writes the result back —
+// see readProfileMetaForUpdate.
func readProfileMeta(profileDir string) ProfileMeta {
var meta ProfileMeta
- readJSON(filepath.Join(profileDir, "profile.json"), &meta)
+ readJSON(profileMetaPath(profileDir), &meta)
return meta
}
+// readProfileMetaForUpdate is readProfileMeta for a read-modify-write. It tells
+// absent (nothing to preserve, start from zero) apart from present-but-unreadable,
+// which the zero value cannot represent: a partial update that starts from zero
+// writes back a record missing every field it failed to read, turning one bad read
+// into permanent loss of user-authored text.
+func readProfileMetaForUpdate(profileDir string) (ProfileMeta, error) {
+ path := profileMetaPath(profileDir)
+ data, err := os.ReadFile(path)
+ if errors.Is(err, fs.ErrNotExist) {
+ return ProfileMeta{}, nil
+ }
+ if err != nil {
+ return ProfileMeta{}, fmt.Errorf("read profile metadata: %w", err)
+ }
+ var meta ProfileMeta
+ if err := json.Unmarshal(data, &meta); err != nil {
+ return ProfileMeta{}, fmt.Errorf("profile metadata at %s is unreadable, so updating it would discard what it holds: %w", path, err)
+ }
+ return meta, nil
+}
+
+func profileMetaPath(profileDir string) string {
+ return filepath.Join(profileDir, "profile.json")
+}
+
+// writeProfileMeta replaces the sidecar atomically. A truncated profile.json
+// reads back as no metadata at all, which costs the profile its id and the
+// operator's own useWhen/description text — the same reason the session stores
+// in this repo write through a temp file and rename.
func writeProfileMeta(profileDir string, meta ProfileMeta) error {
data, err := profileMetaJSON(meta)
if err != nil {
return err
}
- return os.WriteFile(filepath.Join(profileDir, "profile.json"), data, 0644)
+ path := profileMetaPath(profileDir)
+ tmp := path + ".tmp"
+ if err := os.WriteFile(tmp, data, 0644); err != nil {
+ return err
+ }
+ if err := os.Rename(tmp, path); err != nil {
+ _ = os.Remove(tmp)
+ return err
+ }
+ return nil
}
func writeProfileMetaRoot(root *os.Root, meta ProfileMeta) error {
diff --git a/internal/profiles/meta_update_safety_test.go b/internal/profiles/meta_update_safety_test.go
new file mode 100644
index 00000000..69f06fb8
--- /dev/null
+++ b/internal/profiles/meta_update_safety_test.go
@@ -0,0 +1,124 @@
+package profiles
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+// UpdateMeta is a partial update: it is handed one or two fields and must leave
+// the rest of the record alone. It reads the sidecar to do that, and the reader
+// it used answered "unreadable" and "absent" with the same zero value — so a
+// profile.json truncated by a crash or half-written by an interrupted save turned
+// the next description edit into permanent loss of the id and the useWhen text
+// beside it, with no error to say so.
+func TestUpdateMetaRefusesToRewriteAnUnreadableSidecar(t *testing.T) {
+ base := t.TempDir()
+ pm := NewProfileManager(base)
+ if err := pm.Create("work"); err != nil {
+ t.Fatalf("Create: %v", err)
+ }
+ dir, err := pm.findProfileDirByName("work")
+ if err != nil {
+ t.Fatalf("findProfileDirByName: %v", err)
+ }
+ path := filepath.Join(dir, "profile.json")
+
+ // A truncated write: valid JSON up to the point the process died.
+ corrupt := []byte(`{"id":"work","name":"work","useWhen":"signed in as t`)
+ if err := os.WriteFile(path, corrupt, 0644); err != nil {
+ t.Fatalf("write corrupt sidecar: %v", err)
+ }
+
+ updateErr := pm.UpdateMeta("work", map[string]string{"description": "new"})
+ if updateErr == nil {
+ t.Fatal("UpdateMeta accepted an unreadable sidecar; it has just overwritten the fields it could not read")
+ }
+ if !strings.Contains(updateErr.Error(), "unreadable") {
+ t.Errorf("error %q does not say the metadata could not be read, so an operator cannot tell this from a validation failure", updateErr)
+ }
+
+ after, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("read sidecar: %v", err)
+ }
+ if string(after) != string(corrupt) {
+ t.Errorf("the sidecar was rewritten to %q; a refused update must leave the file for recovery", after)
+ }
+}
+
+// The absent case must stay a normal update rather than an error: a profile
+// directory with no sidecar at all has nothing to lose, and refusing there would
+// make the metadata uneditable for every profile created before it existed.
+func TestUpdateMetaStillWritesWhenThereIsNoSidecarYet(t *testing.T) {
+ base := t.TempDir()
+ pm := NewProfileManager(base)
+ if err := pm.Create("work"); err != nil {
+ t.Fatalf("Create: %v", err)
+ }
+ dir, err := pm.findProfileDirByName("work")
+ if err != nil {
+ t.Fatalf("findProfileDirByName: %v", err)
+ }
+ if err := os.Remove(filepath.Join(dir, "profile.json")); err != nil {
+ t.Fatalf("remove sidecar: %v", err)
+ }
+
+ if err := pm.UpdateMeta("work", map[string]string{"description": "new"}); err != nil {
+ t.Fatalf("UpdateMeta on a profile with no sidecar: %v", err)
+ }
+ if got := readProfileMeta(dir); got.Description != "new" || got.Name != "work" {
+ t.Errorf("meta after update = %+v, want the description written and the name filled in", got)
+ }
+}
+
+// A partial update must preserve the fields it was not asked to change.
+func TestUpdateMetaPreservesTheFieldsItWasNotGiven(t *testing.T) {
+ base := t.TempDir()
+ pm := NewProfileManager(base)
+ if err := pm.Create("work"); err != nil {
+ t.Fatalf("Create: %v", err)
+ }
+ if err := pm.UpdateMeta("work", map[string]string{"useWhen": "signed in as test"}); err != nil {
+ t.Fatalf("UpdateMeta useWhen: %v", err)
+ }
+ if err := pm.UpdateMeta("work", map[string]string{"description": "the work profile"}); err != nil {
+ t.Fatalf("UpdateMeta description: %v", err)
+ }
+
+ dir, err := pm.findProfileDirByName("work")
+ if err != nil {
+ t.Fatalf("findProfileDirByName: %v", err)
+ }
+ got := readProfileMeta(dir)
+ if got.UseWhen != "signed in as test" {
+ t.Errorf("useWhen = %q after a description-only update, want it preserved", got.UseWhen)
+ }
+ if got.Description != "the work profile" {
+ t.Errorf("description = %q, want the value just written", got.Description)
+ }
+ if got.ID == "" {
+ t.Error("the profile lost its id across a metadata update")
+ }
+}
+
+// The sidecar is replaced by rename, so a reader never sees a half-written file.
+func TestWriteProfileMetaLeavesNoPartialFile(t *testing.T) {
+ dir := t.TempDir()
+ if err := writeProfileMeta(dir, ProfileMeta{ID: "a", Name: "a", UseWhen: "x"}); err != nil {
+ t.Fatalf("writeProfileMeta: %v", err)
+ }
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ t.Fatalf("read dir: %v", err)
+ }
+ for _, e := range entries {
+ if strings.HasSuffix(e.Name(), ".tmp") {
+ t.Errorf("%s was left behind; the temp file must not survive a successful write", e.Name())
+ }
+ }
+ if got := readProfileMeta(dir); got.UseWhen != "x" {
+ t.Errorf("meta = %+v, want the written record", got)
+ }
+}
diff --git a/internal/profiles/profiles_crud.go b/internal/profiles/profiles_crud.go
index c8612d1e..385e9eac 100644
--- a/internal/profiles/profiles_crud.go
+++ b/internal/profiles/profiles_crud.go
@@ -250,7 +250,10 @@ func (pm *ProfileManager) UpdateMeta(name string, meta map[string]string) error
return err
}
- existing := readProfileMeta(dir)
+ existing, err := readProfileMetaForUpdate(dir)
+ if err != nil {
+ return err
+ }
if existing.Name == "" {
existing.Name = name
}
@@ -291,7 +294,8 @@ func (pm *ProfileManager) Rename(oldName, newName string) error {
return err
}
- meta := readProfileMeta(oldDir)
+ original := readProfileMeta(oldDir)
+ meta := original
meta.ID = newID
meta.Name = newName
if err := writeProfileMeta(oldDir, meta); err != nil {
@@ -299,9 +303,10 @@ func (pm *ProfileManager) Rename(oldName, newName string) error {
}
if err := os.Rename(oldDir, newDir); err != nil {
- meta.ID = profileID(oldName)
- meta.Name = oldName
- _ = writeProfileMeta(oldDir, meta)
+ // Restore what was read, not a recomputed equivalent: an imported profile
+ // can carry an id that is not profileID(oldName), and the listing asserts
+ // identity on that id.
+ _ = writeProfileMeta(oldDir, original)
return fmt.Errorf("failed to rename profile directory: %w", err)
}