High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix(state): keep one file per state name and honour the configured encryption key
Luigi Agosti7156657a2b24
diff --git a/internal/handlers/state.go b/internal/handlers/state.goindex d22a0ee5..b8696a04 100644--- a/internal/handlers/state.go+++ b/internal/handlers/state.go@@ -7,6 +7,7 @@ import ("net/http""os""path/filepath"+ "strings""time""github.com/pinchtab/pinchtab/internal/httpx"@@ -46,7 +47,7 @@ func (h *Handlers) HandleStateShow(w http.ResponseWriter, r *http.Request) {return}- encryptionKey := os.Getenv("PINCHTAB_STATE_KEY")+ encryptionKey := h.stateEncryptionKey()path := state.ResolvePath(h.Config.StateDir, name)sf, err := state.Load(path, encryptionKey)if err != nil {@@ -56,6 +57,22 @@ func (h *Handlers) HandleStateShow(w http.ResponseWriter, r *http.Request) {httpx.JSON(w, 200, sf)}+// stateEncryptionKey resolves the key the state files are encrypted with. The+// environment variable wins so an operator can override per process, and+// security.stateEncryptionKey answers otherwise — it is the documented knob,+// it is redacted by the dashboard config API, and it was reachable by+// `config set` while nothing read it, so setting it stored a secret that did+// nothing and the request still refused for want of a key.+func (h *Handlers) stateEncryptionKey() string {+ if key := strings.TrimSpace(os.Getenv("PINCHTAB_STATE_KEY")); key != "" {+ return key+ }+ if h == nil || h.Config == nil {+ return ""+ }+ return strings.TrimSpace(h.Config.StateEncryptionKey)+}+type stateSaveRequest struct {Name string `json:"name"`Encrypt bool `json:"encrypt"`@@ -77,9 +94,9 @@ func (h *Handlers) HandleStateSave(w http.ResponseWriter, r *http.Request) {encryptionKey := ""if req.Encrypt {- encryptionKey = os.Getenv("PINCHTAB_STATE_KEY")+ encryptionKey = h.stateEncryptionKey()if err := state.ValidateEncryptionKey(encryptionKey); err != nil {- httpx.Error(w, 400, fmt.Errorf("encryption key required: set PINCHTAB_STATE_KEY environment variable"))+ httpx.Error(w, 400, fmt.Errorf("encryption key required: set security.stateEncryptionKey or the PINCHTAB_STATE_KEY environment variable"))return}}diff --git a/internal/handlers/state_capture.go b/internal/handlers/state_capture.goindex 734125dd..99c9b197 100644--- a/internal/handlers/state_capture.go+++ b/internal/handlers/state_capture.go@@ -79,7 +79,7 @@ func (h *Handlers) HandleStateLoad(w http.ResponseWriter, r *http.Request) {return}- encryptionKey := os.Getenv("PINCHTAB_STATE_KEY")+ encryptionKey := h.stateEncryptionKey()path := state.ResolvePath(h.Config.StateDir, req.Name)if _, err := os.Stat(path); os.IsNotExist(err) {matches, matchErr := state.FindByPrefix(h.Config.StateDir, req.Name)diff --git a/internal/handlers/state_test.go b/internal/handlers/state_test.goindex e62381e8..d8ce55e6 100644--- a/internal/handlers/state_test.go+++ b/internal/handlers/state_test.go@@ -98,3 +98,39 @@ func TestHandleStateLoadBatchesStorage(t *testing.T) {t.Fatalf("expected %d origins, got %v", len(sf.Origins), got["origins"])}}++// security.stateEncryptionKey is the documented knob: it loads from the config+// file, `config set` writes it, and the dashboard config API redacts it as a+// secret. Nothing read it — every state path took the key from the environment+// only — so setting it stored a secret that did nothing while an encrypted save+// still refused for want of a key.+func TestStateEncryptionKeyFallsBackToTheConfiguredKey(t *testing.T) {+ t.Setenv("PINCHTAB_STATE_KEY", "")++ h := &Handlers{Config: &config.RuntimeConfig{StateEncryptionKey: " from-config "}}+ if got := h.stateEncryptionKey(); got != "from-config" {+ t.Errorf("stateEncryptionKey() = %q, want the configured key; setting it must have an effect", got)+ }+}++// The environment variable stays the override, so a deployment that exports it+// today keeps behaving exactly as before.+func TestStateEncryptionKeyPrefersTheEnvironment(t *testing.T) {+ t.Setenv("PINCHTAB_STATE_KEY", "from-env")++ h := &Handlers{Config: &config.RuntimeConfig{StateEncryptionKey: "from-config"}}+ if got := h.stateEncryptionKey(); got != "from-env" {+ t.Errorf("stateEncryptionKey() = %q, want the environment override", got)+ }+}++// Neither source set is still "no key", which is what makes an encrypted save+// refuse rather than write something unreadable.+func TestStateEncryptionKeyIsEmptyWhenNeitherSourceIsSet(t *testing.T) {+ t.Setenv("PINCHTAB_STATE_KEY", "")++ h := &Handlers{Config: &config.RuntimeConfig{}}+ if got := h.stateEncryptionKey(); got != "" {+ t.Errorf("stateEncryptionKey() = %q, want empty", got)+ }+}diff --git a/internal/state/pairing_test.go b/internal/state/pairing_test.gonew file mode 100644index 00000000..c14cc0f4--- /dev/null+++ b/internal/state/pairing_test.go@@ -0,0 +1,106 @@+package state++import (+ "os"+ "path/filepath"+ "testing"+)++func statePath(stateDir, name string) string {+ return filepath.Join(SessionsDir(stateDir), name)+}++func exists(t *testing.T, path string) bool {+ t.Helper()+ _, err := os.Stat(path)+ if err != nil && !os.IsNotExist(err) {+ t.Fatalf("stat %s: %v", path, err)+ }+ return err == nil+}++func saveNamed(t *testing.T, dir, name, key string) {+ t.Helper()+ sf := &StateFile{+ Name: name,+ Origins: []string{"https://example.com"},+ Cookies: []Cookie{{Name: "session", Value: "secret-cookie", Domain: "example.com"}},+ }+ if _, err := Save(dir, sf, key); err != nil {+ t.Fatalf("Save(%q, key=%t): %v", name, key != "", err)+ }+}++// A state name has two possible spellings on disk and Save picks one from+// whether a key was supplied. Saving the same name again with encryption turned+// on left the earlier file in place — and that file is a plaintext copy of the+// same cookies, sitting beside the encrypted one the caller was told about.+func TestSavingEncryptedRemovesThePlaintextCopyOfTheSameName(t *testing.T) {+ dir := t.TempDir()+ saveNamed(t, dir, "github", "")+ if !exists(t, statePath(dir, "github.json")) {+ t.Fatal("the plaintext save did not land")+ }++ saveNamed(t, dir, "github", "passphrase")++ if exists(t, statePath(dir, "github.json")) {+ t.Error("the plaintext copy survived an encrypted save of the same name; its cookies are still readable on disk")+ }+ if !exists(t, statePath(dir, "github.json.enc")) {+ t.Error("the encrypted save did not land")+ }+}++// The other direction matters too: a name saved without a key must not keep+// answering from a stale encrypted file, which is the one ResolvePath prefers.+func TestSavingPlaintextRemovesTheEncryptedCopyOfTheSameName(t *testing.T) {+ dir := t.TempDir()+ saveNamed(t, dir, "github", "passphrase")+ saveNamed(t, dir, "github", "")++ if exists(t, statePath(dir, "github.json.enc")) {+ t.Error("the encrypted copy survived a plaintext save; ResolvePath prefers it, so loads would answer from the stale file")+ }+ resolved := ResolvePath(dir, "github")+ if filepath.Base(resolved) != "github.json" {+ t.Errorf("ResolvePath returned %q, want the file just written", resolved)+ }+}++// One name, one delete. Stopping at the first successful removal reported the+// state deleted while leaving the other spelling on disk.+func TestDeleteRemovesBothSpellingsOfAName(t *testing.T) {+ dir := t.TempDir()+ sessions, err := EnsureSessionsDir(dir)+ if err != nil {+ t.Fatalf("EnsureSessionsDir: %v", err)+ }+ // Both on disk at once is what an older build left behind, so deletion has to+ // cope with it rather than only with what today's Save produces.+ for _, name := range []string{"github.json", "github.json.enc"} {+ if err := os.WriteFile(filepath.Join(sessions, name), []byte("{}"), 0600); err != nil {+ t.Fatalf("seed %s: %v", name, err)+ }+ }++ if err := Delete(dir, "github"); err != nil {+ t.Fatalf("Delete: %v", err)+ }+ for _, name := range []string{"github.json", "github.json.enc"} {+ if exists(t, statePath(dir, name)) {+ t.Errorf("%s survived the delete; the state was reported deleted while a copy remained", name)+ }+ }+}++// Deleting a name that was never saved must still say so.+func TestDeleteReportsAMissingName(t *testing.T) {+ dir := t.TempDir()+ if _, err := EnsureSessionsDir(dir); err != nil {+ t.Fatalf("EnsureSessionsDir: %v", err)+ }+ if err := Delete(dir, "never-saved"); err == nil {+ t.Fatal("Delete reported success for a name that does not exist")+ }+}diff --git a/internal/state/state.go b/internal/state/state.goindex e5545cc8..70f252a7 100644--- a/internal/state/state.go+++ b/internal/state/state.go@@ -138,9 +138,49 @@ func Save(stateDir string, sf *StateFile, encryptionKey string) (string, error)return "", fmt.Errorf("write state file: %w", err)}+ // One name is one file. Save picks its extension from whether a key was+ // supplied, so saving a name again with the encryption flag flipped used to+ // leave the earlier file beside the new one — and the earlier one is the+ // plaintext copy of the same cookies whenever the flip was towards+ // encryption. Removing the sibling is the difference between "this state is+ // encrypted now" and "there is also an unencrypted copy of it on disk".+ if err := removeSibling(dir, sanitizeFilename(sf.Name), ext); err != nil {+ return path, err+ }+return path, nil}+// removeSibling deletes the same state name under the extension Save did not+// write. A failure is returned rather than logged: the caller has just been told+// the state is encrypted, and the whole point is that the other copy is gone.+func removeSibling(dir, base, writtenExt string) error {+ for _, ext := range stateExtensions {+ if ext == writtenExt {+ continue+ }+ path, ok := statePathWithin(dir, base, ext)+ if !ok {+ continue+ }+ if err := os.Remove(path); err != nil && !os.IsNotExist(err) {+ return fmt.Errorf("remove previous %s copy of state %q: %w", ext, base, err)+ }+ }+ return nil+}++// stateExtensions are the two spellings one state name can have on disk,+// encrypted first because that is the one ResolvePath prefers.+var stateExtensions = []string{".json.enc", ".json"}++// statePathWithin joins a state file path and reports whether it stayed inside+// dir, so every caller applies the same containment rule.+func statePathWithin(dir, base, ext string) (string, bool) {+ path := filepath.Clean(filepath.Join(dir, base+ext))+ return path, strings.HasPrefix(path, filepath.Clean(dir)+string(os.PathSeparator))+}+// Load reads a StateFile from disk. If encryptionKey is non-empty, the file// is decrypted before parsing.func Load(path, encryptionKey string) (*StateFile, error) {@@ -262,23 +302,31 @@ func FindByPrefix(stateDir, prefix string) ([]StateEntry, error) {return matched, nil}-// Delete removes a named state file. Tries .json.enc first, falls back to .json.+// Delete removes a named state file under BOTH spellings. Stopping at the first+// success reported the state deleted while leaving the other copy on disk, and+// the copy left behind was the plaintext one whenever both existed.func Delete(stateDir, name string) error {dir := SessionsDir(stateDir)base := sanitizeFilename(name)- cleanDir := filepath.Clean(dir) + string(os.PathSeparator)- for _, ext := range []string{".json.enc", ".json"} {- path := filepath.Clean(filepath.Join(dir, base+ext))- if !strings.HasPrefix(path, cleanDir) {+ removed := false+ for _, ext := range stateExtensions {+ path, ok := statePathWithin(dir, base, ext)+ if !ok {return fmt.Errorf("resolved path escapes sessions dir")}- if err := os.Remove(path); err == nil {- return nil- } else if !os.IsNotExist(err) {+ err := os.Remove(path)+ switch {+ case err == nil:+ removed = true+ case os.IsNotExist(err):+ default:return fmt.Errorf("delete state file: %w", err)}}- return fmt.Errorf("state file %q not found", name)+ if !removed {+ return fmt.Errorf("state file %q not found", name)+ }+ return nil}// Clean removes state files older than the given duration.@@ -449,10 +497,9 @@ func sanitizeFilename(name string) string {func ResolvePath(stateDir, name string) string {dir := SessionsDir(stateDir)base := sanitizeFilename(name)- for _, ext := range []string{".json.enc", ".json"} {- resolved := filepath.Clean(filepath.Join(dir, base+ext))- cleanDir := filepath.Clean(dir) + string(os.PathSeparator)- if !strings.HasPrefix(resolved, cleanDir) {+ for _, ext := range stateExtensions {+ resolved, ok := statePathWithin(dir, base, ext)+ if !ok {return ""}if _, err := os.Stat(resolved); err == nil {@@ -460,9 +507,8 @@ func ResolvePath(stateDir, name string) string {}}// File doesn't exist yet — return the .json path (for new saves).- resolved := filepath.Clean(filepath.Join(dir, base+".json"))- cleanDir := filepath.Clean(dir) + string(os.PathSeparator)- if !strings.HasPrefix(resolved, cleanDir) {+ resolved, ok := statePathWithin(dir, base, ".json")+ if !ok {return ""}return resolved