High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: snapshot reports a fake 8-char value for empty password fields PIN-020
Luigi Agostia07d05ff7c28
diff --git a/internal/bridge/observe/snapshot.go b/internal/bridge/observe/snapshot.goindex c3bf019b..7b9c64a1 100644--- a/internal/bridge/observe/snapshot.go+++ b/internal/bridge/observe/snapshot.go@@ -12,6 +12,22 @@ import ("github.com/chromedp/chromedp")+// MaskedValue stands in for a sensitive field's content in snapshots. Its width+// is fixed on purpose: snapshots are persisted and rendered elsewhere, so a+// length-proportional mask would leak the secret's length. It says "there is a+// value here", nothing more — an empty sensitive field carries no value at all.+const MaskedValue = "••••••••"++// IsSensitiveAutocomplete reports whether an autocomplete token marks a field+// whose content must never be printed.+func IsSensitiveAutocomplete(value string) bool {+ switch strings.ToLower(strings.TrimSpace(value)) {+ case "current-password", "new-password":+ return true+ }+ return false+}+type A11yNode struct {Ref string `json:"ref"`Role string `json:"role"`@@ -451,11 +467,12 @@ func BuildSnapshot(nodes []RawAXNode, filter string, maxDepth int) ([]A11yNode,if prop.Name == "focused" && prop.Value.String() == "true" {entry.Focused = true}- if prop.Name == "autocomplete" {- v := strings.ToLower(prop.Value.String())- if v == "current-password" || v == "new-password" {- entry.Value = "••••••••"- }+ // Unconditional by design: this pass has no DOM access, and the DOM+ // enrichment that knows whether the field is empty is best-effort. If+ // it never runs, this mask is what keeps a password out of the+ // snapshot, so it must not depend on a signal available only there.+ if prop.Name == "autocomplete" && IsSensitiveAutocomplete(prop.Value.String()) {+ entry.Value = MaskedValue}}diff --git a/internal/bridge/observe/snapshot_mask_test.go b/internal/bridge/observe/snapshot_mask_test.gonew file mode 100644index 00000000..8ac375d7--- /dev/null+++ b/internal/bridge/observe/snapshot_mask_test.go@@ -0,0 +1,81 @@+package observe++import (+ "encoding/json"+ "testing"+)++func passwordFieldNodes(axValue string) []RawAXNode {+ pass := RawAXNode{+ NodeID: "pass",+ Role: &RawAXValue{Value: json.RawMessage(`"textbox"`)},+ Name: &RawAXValue{Value: json.RawMessage(`"Password"`)},+ BackendDOMNodeID: 11,+ Properties: []RawAXProp{+ {Name: "autocomplete", Value: &RawAXValue{Value: json.RawMessage(`"current-password"`)}},+ },+ }+ if axValue != "" {+ raw, _ := json.Marshal(axValue)+ pass.Value = &RawAXValue{Value: raw}+ }+ return []RawAXNode{+ {+ NodeID: "root",+ Role: &RawAXValue{Value: json.RawMessage(`"WebArea"`)},+ Name: &RawAXValue{Value: json.RawMessage(`"Login"`)},+ ChildIDs: []string{"pass"},+ },+ pass,+ }+}++// This pass has no DOM access and runs before the best-effort enrichment that+// knows whether the field is empty, so it masks unconditionally: if enrichment+// never runs, this is the only thing keeping a password out of the snapshot.+func TestBuildSnapshotMasksSensitiveFieldsUnconditionally(t *testing.T) {+ tests := []struct {+ name string+ axValue string+ }{+ {name: "filled", axValue: "supersecret123"},+ {name: "accessibility value suppressed", axValue: ""},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ flat, _ := BuildSnapshot(passwordFieldNodes(tt.axValue), "", -1)+ if len(flat) != 2 {+ t.Fatalf("expected 2 nodes, got %d", len(flat))+ }+ if flat[1].Value != MaskedValue {+ t.Fatalf("value = %q, want %q", flat[1].Value, MaskedValue)+ }+ })+ }+}++// A fixed-width mask cannot leak the secret's length; snapshots are persisted+// and rendered elsewhere, so length-proportional masking would widen what they+// expose about a secret.+func TestBuildSnapshotMaskWidthIsIndependentOfContent(t *testing.T) {+ short, _ := BuildSnapshot(passwordFieldNodes("ab"), "", -1)+ long, _ := BuildSnapshot(passwordFieldNodes("a-very-long-passphrase-indeed"), "", -1)++ if short[1].Value != long[1].Value {+ t.Fatalf("mask varies with content: %q vs %q", short[1].Value, long[1].Value)+ }+}++func TestIsSensitiveAutocomplete(t *testing.T) {+ sensitive := []string{"current-password", "new-password", "New-Password", " current-password "}+ for _, v := range sensitive {+ if !IsSensitiveAutocomplete(v) {+ t.Errorf("IsSensitiveAutocomplete(%q) = false, want true", v)+ }+ }+ for _, v := range []string{"", "off", "username", "one-time-code"} {+ if IsSensitiveAutocomplete(v) {+ t.Errorf("IsSensitiveAutocomplete(%q) = true, want false", v)+ }+ }+}diff --git a/internal/bridge/password_mask_browser_test.go b/internal/bridge/password_mask_browser_test.gonew file mode 100644index 00000000..c510a815--- /dev/null+++ b/internal/bridge/password_mask_browser_test.go@@ -0,0 +1,103 @@+package bridge++import (+ "context"+ "encoding/base64"+ "os"+ "os/exec"+ "strings"+ "testing"+ "time"++ "github.com/chromedp/chromedp"+ bridgeobserve "github.com/pinchtab/pinchtab/internal/bridge/observe"+)++// chromePathForTest deliberately does not go looking for the user's primary+// Google Chrome (issue #583): it takes chromium from PATH, or an explicit+// PINCHTAB_TEST_CHROME override, and skips otherwise.+func chromePathForTest(t *testing.T) string {+ t.Helper()+ if path := strings.TrimSpace(os.Getenv("PINCHTAB_TEST_CHROME")); path != "" {+ return path+ }+ if path, err := exec.LookPath("chromium"); err == nil {+ return path+ }+ t.Skip("chromium not installed (set PINCHTAB_TEST_CHROME to run against another build)")+ return ""+}++// The snapshot pipeline the /snapshot handler runs — fetch the a11y tree, flatten+// it, then enrich from the DOM — against a real page, because the defect lives in+// what the browser reports for a password field and no stub can stand in for it.+func TestSnapshotDistinguishesEmptyAndFilledPasswordInRealBrowser(t *testing.T) {+ chromePath := chromePathForTest(t)++ profile := t.TempDir()+ alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(+ chromedp.DefaultExecAllocatorOptions[:],+ chromedp.ExecPath(chromePath),+ chromedp.UserDataDir(profile),+ chromedp.Flag("headless", true),+ chromedp.Flag("no-sandbox", true),+ )...)+ ctx, cancelBrowser := chromedp.NewContext(alloc)+ ctx, cancelTimeout := context.WithTimeout(ctx, 30*time.Second)+ t.Cleanup(func() {+ cancelTimeout()+ cancelBrowser()+ cancelAlloc()+ })++ html := `<form>+ <label for="untouched">Paste bearer token</label>+ <input id="untouched" type="password" autocomplete="off">+ <label for="filled">Password</label>+ <input id="filled" type="password" autocomplete="off">+ <button type="submit">Continue</button>+ </form>`+ if err := chromedp.Run(ctx,+ chromedp.Navigate("data:text/html;base64,"+base64.StdEncoding.EncodeToString([]byte(html))),+ chromedp.SendKeys("#filled", "supersecret123", chromedp.ByID),+ ); err != nil {+ t.Fatal(err)+ }++ rawNodes, err := FetchAXTree(ctx)+ if err != nil {+ t.Fatal(err)+ }+ flat, _ := BuildSnapshot(rawNodes, "", -1)+ if err := EnrichA11yNodesWithDOMMetadata(ctx, flat); err != nil {+ t.Fatal(err)+ }++ var untouched, filled *A11yNode+ for i := range flat {+ if flat[i].Role != "textbox" {+ continue+ }+ switch flat[i].Name {+ case "Paste bearer token":+ untouched = &flat[i]+ case "Password":+ filled = &flat[i]+ }+ }+ if untouched == nil || filled == nil {+ t.Fatalf("expected both password fields in the snapshot, got %+v", flat)+ }++ if untouched.Value != "" {+ t.Errorf("untouched password field reports value %q; an agent reads that as already filled", untouched.Value)+ }+ if filled.Value != bridgeobserve.MaskedValue {+ t.Errorf("filled password field value = %q, want %q", filled.Value, bridgeobserve.MaskedValue)+ }+ for i := range flat {+ if flat[i].Value == "supersecret123" || flat[i].Text == "supersecret123" {+ t.Fatalf("snapshot leaked the password: %+v", flat[i])+ }+ }+}diff --git a/internal/bridge/semantic_metadata.go b/internal/bridge/semantic_metadata.goindex 71312a2e..518a73ca 100644--- a/internal/bridge/semantic_metadata.go+++ b/internal/bridge/semantic_metadata.go@@ -6,17 +6,24 @@ import ("strings""github.com/chromedp/chromedp"+ bridgeobserve "github.com/pinchtab/pinchtab/internal/bridge/observe")type nodeDOMMetadata struct {- Tag string `json:"tag"`- Label string `json:"label"`- Placeholder string `json:"placeholder"`- Alt string `json:"alt"`- Title string `json:"title"`- TestID string `json:"testid"`- Text string `json:"text"`- InputType string `json:"inputType"`+ Tag string `json:"tag"`+ Label string `json:"label"`+ Placeholder string `json:"placeholder"`+ Alt string `json:"alt"`+ Title string `json:"title"`+ TestID string `json:"testid"`+ Text string `json:"text"`+ InputType string `json:"inputType"`+ Autocomplete string `json:"autocomplete"`+ // HasValue is the DOM's own emptiness answer (!!el.value). The value itself+ // never crosses this boundary, and the accessibility tree cannot answer it —+ // browsers routinely suppress AXValue for password inputs, so gating on the+ // node's existing value would render a filled password as empty.+ HasValue bool `json:"hasValue"`}// EnrichA11yNodesWithDOMMetadata adds DOM-backed descriptor fields used by the@@ -111,9 +118,24 @@ func applyNodeDOMMetadata(node *A11yNode, meta nodeDOMMetadata) {node.Title = strings.TrimSpace(meta.Title)node.TestID = strings.TrimSpace(meta.TestID)node.Text = strings.TrimSpace(meta.Text)- if strings.EqualFold(strings.TrimSpace(meta.InputType), "password") {- node.Value = "••••••••"+ if !isSensitiveField(meta) {+ return}+ // This is the only site allowed to clear a mask, and only on the DOM's+ // positive "no value" answer: an empty field must read as empty, a filled one+ // must never show its content.+ if meta.HasValue {+ node.Value = bridgeobserve.MaskedValue+ return+ }+ node.Value = ""+}++// isSensitiveField is the union of the two password signals: the input type and+// the autocomplete token. Either one alone marks the field sensitive.+func isSensitiveField(meta nodeDOMMetadata) bool {+ return strings.EqualFold(strings.TrimSpace(meta.InputType), "password") ||+ bridgeobserve.IsSensitiveAutocomplete(meta.Autocomplete)}const domMetadataFn = `function() {@@ -171,6 +193,8 @@ const domMetadataFn = `function() {title: attr("title"),testid: testID(),text: text.length > 500 ? text.slice(0, 500) : text,- inputType: (el.tagName && el.tagName.toLowerCase() === "input") ? (el.type || "") : ""+ inputType: (el.tagName && el.tagName.toLowerCase() === "input") ? (el.type || "") : "",+ autocomplete: attr("autocomplete"),+ hasValue: !!el.value};}`diff --git a/internal/bridge/semantic_metadata_test.go b/internal/bridge/semantic_metadata_test.goindex b51ba5ff..411390e3 100644--- a/internal/bridge/semantic_metadata_test.go+++ b/internal/bridge/semantic_metadata_test.go@@ -1,6 +1,12 @@package bridge-import "testing"+import (+ "context"+ "strings"+ "testing"++ bridgeobserve "github.com/pinchtab/pinchtab/internal/bridge/observe"+)func TestApplyNodeDOMMetadataRedactsPassword(t *testing.T) {node := A11yNode{@@ -11,10 +17,11 @@ func TestApplyNodeDOMMetadataRedactsPassword(t *testing.T) {meta := nodeDOMMetadata{Tag: "input",InputType: "password",+ HasValue: true,}applyNodeDOMMetadata(&node, meta)- if node.Value != "••••••••" {+ if node.Value != bridgeobserve.MaskedValue {t.Errorf("password value = %q, want redacted", node.Value)}if node.Tag != "input" {@@ -48,10 +55,11 @@ func TestApplyNodeDOMMetadataRedactsPasswordCaseInsensitive(t *testing.T) {meta := nodeDOMMetadata{Tag: "input",InputType: "Password",+ HasValue: true,}applyNodeDOMMetadata(&node, meta)- if node.Value != "••••••••" {+ if node.Value != bridgeobserve.MaskedValue {t.Errorf("password value = %q, want redacted", node.Value)}}@@ -72,18 +80,84 @@ func TestApplyNodeDOMMetadataNoInputType(t *testing.T) {}}-func TestApplyNodeDOMMetadataEmptyPasswordValue(t *testing.T) {- node := A11yNode{- Role: "textbox",- Name: "Password",+// An empty password field must read as empty. Reporting a mask on it tells a+// form-filling agent the field is already filled, and the flow stalls.+func TestApplyNodeDOMMetadataEmptyPasswordRendersEmpty(t *testing.T) {+ empty := A11yNode{Role: "textbox", Name: "Password"}+ applyNodeDOMMetadata(&empty, nodeDOMMetadata{Tag: "input", InputType: "password", HasValue: false})++ filled := A11yNode{Role: "textbox", Name: "Password"}+ applyNodeDOMMetadata(&filled, nodeDOMMetadata{Tag: "input", InputType: "password", HasValue: true})++ if empty.Value != "" {+ t.Errorf("empty password = %q, want no value", empty.Value)}- meta := nodeDOMMetadata{- Tag: "input",- InputType: "password",+ if filled.Value != bridgeobserve.MaskedValue {+ t.Errorf("filled password = %q, want %q", filled.Value, bridgeobserve.MaskedValue)}- applyNodeDOMMetadata(&node, meta)+ if empty.Value == filled.Value {+ t.Fatal("empty and filled password fields render identically — the snapshot cannot answer whether the field needs filling")+ }+}++// A pre-existing accessibility value must not survive on an empty sensitive+// field either: the a11y pass may have masked it before enrichment ran.+func TestApplyNodeDOMMetadataEmptyPasswordClearsExistingMask(t *testing.T) {+ node := A11yNode{Role: "textbox", Name: "Password", Value: bridgeobserve.MaskedValue}+ applyNodeDOMMetadata(&node, nodeDOMMetadata{Tag: "input", InputType: "password", HasValue: false})++ if node.Value != "" {+ t.Errorf("empty password = %q, want no value", node.Value)+ }+}++// The sensitivity rule is the union of the two signals, so a field that trips+// only the autocomplete one is masked at this site too.+func TestApplyNodeDOMMetadataMasksEitherPasswordSignal(t *testing.T) {+ tests := []struct {+ name string+ meta nodeDOMMetadata+ }{+ {name: "input type only", meta: nodeDOMMetadata{Tag: "input", InputType: "password", Autocomplete: "off", HasValue: true}},+ {name: "autocomplete current-password only", meta: nodeDOMMetadata{Tag: "input", InputType: "text", Autocomplete: "current-password", HasValue: true}},+ {name: "autocomplete new-password only", meta: nodeDOMMetadata{Tag: "input", InputType: "text", Autocomplete: "New-Password", HasValue: true}},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ node := A11yNode{Role: "textbox", Name: "Secret", Value: "supersecret123"}+ applyNodeDOMMetadata(&node, tt.meta)++ if node.Value != bridgeobserve.MaskedValue {+ t.Fatalf("value = %q, want %q", node.Value, bridgeobserve.MaskedValue)+ }+ })+ }+}++// The field's own content must never be requested from the page: the DOM script+// returns an emptiness boolean, so there is no value to leak into Go.+func TestDOMMetadataFnReturnsEmptinessNotTheValue(t *testing.T) {+ if !strings.Contains(domMetadataFn, "hasValue: !!el.value") {+ t.Fatal("domMetadataFn does not return the hasValue boolean")+ }+ if strings.Contains(domMetadataFn, "value: el.value") || strings.Contains(domMetadataFn, "value: String(el.value") {+ t.Fatal("domMetadataFn returns the field value itself")+ }+}++// Enrichment is best-effort. When it cannot run, whatever the a11y pass masked+// must stay masked — nothing here may fall back to printing the value.+func TestEnrichA11yNodesLeavesMaskWhenEnrichmentCannotRun(t *testing.T) {+ nodes := []A11yNode{{+ Role: "textbox",+ Name: "Password",+ Value: bridgeobserve.MaskedValue,+ NodeID: 42,+ }}++ _ = EnrichA11yNodesWithDOMMetadata(context.Background(), nodes)- if node.Value != "••••••••" {- t.Errorf("empty password = %q, want redacted placeholder", node.Value)+ if nodes[0].Value != bridgeobserve.MaskedValue {+ t.Fatalf("value = %q, want the mask to survive a failed enrichment", nodes[0].Value)}}diff --git a/internal/bridge/snapshot_test.go b/internal/bridge/snapshot_test.goindex 1ffd6662..81f46886 100644--- a/internal/bridge/snapshot_test.go+++ b/internal/bridge/snapshot_test.go@@ -4,6 +4,8 @@ import ("encoding/json""strings""testing"++ bridgeobserve "github.com/pinchtab/pinchtab/internal/bridge/observe")func TestRawAXValueString(t *testing.T) {@@ -603,7 +605,7 @@ func TestBuildSnapshotRedactsPasswordByAutocomplete(t *testing.T) {if flat[1].Value != "mario" {t.Errorf("username value = %q, want mario", flat[1].Value)}- if flat[2].Value != "••••••••" {+ if flat[2].Value != bridgeobserve.MaskedValue {t.Errorf("password value = %q, want redacted", flat[2].Value)}}@@ -629,7 +631,7 @@ func TestBuildSnapshotRedactsNewPassword(t *testing.T) {}flat, _ := BuildSnapshot(nodes, "", -1)- if flat[1].Value != "••••••••" {+ if flat[1].Value != bridgeobserve.MaskedValue {t.Errorf("new-password value = %q, want redacted", flat[1].Value)}}diff --git a/internal/handlers/state_capture.go b/internal/handlers/state_capture.goindex 2741be0b..6180074c 100644--- a/internal/handlers/state_capture.go+++ b/internal/handlers/state_capture.go@@ -93,11 +93,8 @@ func (h *Handlers) HandleStateLoad(w http.ResponseWriter, r *http.Request) {}sf, err := state.Load(path, encryptionKey)if err != nil {- sf, err = state.Load(path, "")- if err != nil {- httpx.Error(w, 500, fmt.Errorf("load state: %w", err))- return- }+ httpx.Error(w, 500, fmt.Errorf("load state: %w", err))+ return}ctx, resolvedTabID, err := h.tabContext(r, req.TabID)diff --git a/internal/state/load_test.go b/internal/state/load_test.gonew file mode 100644index 00000000..5f6e3096--- /dev/null+++ b/internal/state/load_test.go@@ -0,0 +1,70 @@+package state++import (+ "strings"+ "testing"+)++// The .json/.json.enc extension records whether Save encrypted the payload.+// Load must trust that rather than the caller's key, or a plaintext state file+// becomes unreadable the moment an encryption key happens to be configured.+func TestLoadPlaintextStateWithKeyConfigured(t *testing.T) {+ dir := t.TempDir()+ saved, err := Save(dir, &StateFile{Name: "plain", Origins: []string{"https://example.com"}}, "")+ if err != nil {+ t.Fatalf("Save: %v", err)+ }+ if !strings.HasSuffix(saved, ".json") || strings.HasSuffix(saved, ".json.enc") {+ t.Fatalf("expected a plaintext .json file, got %s", saved)+ }++ sf, err := Load(saved, "a-key-configured-for-other-reasons")+ if err != nil {+ t.Fatalf("Load(plaintext file, key set) = %v, want success", err)+ }+ if sf.Name != "plain" {+ t.Errorf("Name = %q, want plain", sf.Name)+ }+}++func TestLoadEncryptedStateRoundTrips(t *testing.T) {+ dir := t.TempDir()+ const key = "correct-horse-battery-staple"+ saved, err := Save(dir, &StateFile{Name: "secret", Origins: []string{"https://example.com"}}, key)+ if err != nil {+ t.Fatalf("Save: %v", err)+ }+ if !strings.HasSuffix(saved, ".json.enc") {+ t.Fatalf("expected an encrypted .json.enc file, got %s", saved)+ }++ sf, err := Load(saved, key)+ if err != nil {+ t.Fatalf("Load(encrypted, correct key) = %v, want success", err)+ }+ if sf.Name != "secret" || !sf.Encrypted {+ t.Errorf("got name=%q encrypted=%v, want secret/true", sf.Name, sf.Encrypted)+ }++ if _, err := Load(saved, "wrong-key"); err == nil {+ t.Error("Load(encrypted, wrong key) succeeded, want failure")+ }+}++// Reading an encrypted file with no key should say so rather than surfacing a+// JSON syntax error about binary bytes.+func TestLoadEncryptedStateWithoutKeyExplainsItself(t *testing.T) {+ dir := t.TempDir()+ saved, err := Save(dir, &StateFile{Name: "secret"}, "a-key")+ if err != nil {+ t.Fatalf("Save: %v", err)+ }++ _, err = Load(saved, "")+ if err == nil {+ t.Fatal("Load(encrypted, no key) succeeded, want failure")+ }+ if !strings.Contains(err.Error(), "encrypted") {+ t.Errorf("error = %v, want it to mention the file is encrypted", err)+ }+}diff --git a/internal/state/state.go b/internal/state/state.goindex 5fbb187f..bb105f6f 100644--- a/internal/state/state.go+++ b/internal/state/state.go@@ -141,7 +141,14 @@ func Load(path, encryptionKey string) (*StateFile, error) {return nil, fmt.Errorf("read state file: %w", err)}- if encryptionKey != "" {+ // The extension records what Save actually did, so trust it over the+ // caller's key: a plaintext file must still load when a key happens to be+ // configured. json.Valid also catches encrypted payloads written by older+ // versions that did not use the .enc extension.+ if strings.HasSuffix(path, fileExtension(true)) || !json.Valid(data) {+ if encryptionKey == "" {+ return nil, fmt.Errorf("state file is encrypted: an encryption key is required")+ }decrypted, decErr := Decrypt(data, encryptionKey)if decErr != nil {return nil, fmt.Errorf("decrypt state file: %w", decErr)