High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
refactor: two isolated worlds exist for the same rule… (PIN-170)
Luigi Agosti2ef35a26f93d
diff --git a/internal/bridge/action_resolve.go b/internal/bridge/action_resolve.goindex 0ada4e14..b11c9f69 100644--- a/internal/bridge/action_resolve.go+++ b/internal/bridge/action_resolve.go@@ -40,10 +40,6 @@ type FrameElementMeta struct {// Passes frameID == "" through as a no-op (returns 0, nil) so callers can// fall back to the default top-level context without branching.func FrameExecutionContextID(ctx context.Context, frameID string) (int64, error) {- return frameExecutionContextID(ctx, frameID)-}--func frameExecutionContextID(ctx context.Context, frameID string) (int64, error) {return bridgecdpops.FrameExecutionContextID(ctx, frameID)}@@ -52,25 +48,12 @@ func frameExecutionContextID(ctx context.Context, frameID string) (int64, error)// discovery run there so page script cannot hide or redirect targets by// replacing DOM methods in the main world. It never returns a usable zero: a// caller that cannot get an isolated context gets an error, not the main world.+//+// The frame fallback and the world creation both live with the owner in+// internal/cdptk. This package kept its own copy of that sequence, which is how+// two world names came to exist for one rule.func isolatedExecutionContextID(ctx context.Context, frameID string) (int64, error) {- if frameID == "" {- frameTree, err := FetchFrameTree(ctx)- if err != nil {- return 0, fmt.Errorf("resolve top frame: %w", err)- }- frameID = frameTree.Frame.ID- if frameID == "" {- return 0, fmt.Errorf("resolve top frame: frame id is empty")- }- }- execID, err := frameExecutionContextID(ctx, frameID)- if err != nil {- return 0, err- }- if execID == 0 {- return 0, fmt.Errorf("frame %q has no isolated execution context", frameID)- }- return execID, nil+ return cdptk.IsolatedContextID(ctx, frameID)}// IsolatedNodeObjectID converts a backend node id to a JS object handle in thediff --git a/internal/bridge/action_resolve_frame_scope_test.go b/internal/bridge/action_resolve_frame_scope_test.gonew file mode 100644index 00000000..346cb3fd--- /dev/null+++ b/internal/bridge/action_resolve_frame_scope_test.go@@ -0,0 +1,108 @@+package bridge++import (+ "context"+ "encoding/base64"+ "testing"+ "time"++ "github.com/chromedp/chromedp"++ "github.com/pinchtab/pinchtab/internal/selector"+ "github.com/pinchtab/pinchtab/internal/testbrowser"+)++// The frame question the world unification could silently get wrong: a scoped+// resolution must run in the document of the frame it was ASKED about, not the top+// frame's. Every other frame test in this package passes an empty frame id, which is+// the top frame — so ignoring the parameter entirely left them all green, and this+// property had no behavioural cover at all.+//+// The fixture makes the two documents distinguishable: #in-frame-only exists solely+// inside the child frame, so resolving it against the top document is+// ErrSelectorNoMatch rather than a wrong-but-plausible answer.+func TestAFrameScopedResolutionRunsInThatFramesDocument(t *testing.T) {+ ctx := newChildFrameFixture(t)++ childFrameID := childFrameIDForTest(t, ctx)++ nodeID, err := ResolveUnifiedSelectorInFrame(ctx, selector.Parse("css:#in-frame-only"), nil, childFrameID)+ if err != nil {+ t.Fatalf("resolving #in-frame-only in frame %q failed: %v — the element exists only in that frame, so this is what a resolution running in the TOP frame's document reports", childFrameID, err)+ }++ var text string+ if err := callFunctionOnNodeForTest(ctx, nodeID, `function() { return this.textContent; }`, &text); err != nil {+ t.Fatal(err)+ }+ if text != "child" {+ t.Errorf("resolved node text = %q, want %q — the handle came from the wrong document", text, "child")+ }+}++// The counter-direction on the same fixture: an element that exists ONLY in the top+// document must not be reachable from the child frame's scope. Without this, honouring+// the frame could be faked by resolving against both documents.+func TestAFrameScopedResolutionDoesNotSeeTheTopDocument(t *testing.T) {+ ctx := newChildFrameFixture(t)++ childFrameID := childFrameIDForTest(t, ctx)++ if _, err := ResolveUnifiedSelectorInFrame(ctx, selector.Parse("css:#top-only"), nil, childFrameID); err == nil {+ t.Errorf("#top-only resolved inside the child frame's scope, but it exists only in the top document — the scoped resolution is reading a document it was not asked about")+ }+}++func newChildFrameFixture(t *testing.T) context.Context {+ t.Helper()+ chromePath := testbrowser.Path(t)+ alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(+ chromedp.DefaultExecAllocatorOptions[:],+ chromedp.ExecPath(chromePath),+ chromedp.UserDataDir(testbrowser.ProfileDir(t)),+ chromedp.Flag("headless", true),+ chromedp.Flag("no-sandbox", true),+ )...)+ ctx, cancelBrowser := chromedp.NewContext(alloc)+ ctx, cancelTimeout := context.WithTimeout(ctx, 20*time.Second)+ t.Cleanup(func() {+ cancelTimeout()+ cancelBrowser()+ cancelAlloc()+ })++ html := `<body>+ <button id="top-only">top</button>+ <iframe id="child" width="300" height="200" srcdoc="<body><button id='in-frame-only'>child</button></body>"></iframe>+ </body>`+ dataURL := "data:text/html;base64," + base64.StdEncoding.EncodeToString([]byte(html))+ if err := chromedp.Run(ctx,+ chromedp.Navigate(dataURL),+ chromedp.WaitVisible("#child", chromedp.ByID),+ ); err != nil {+ t.Fatal(err)+ }+ return ctx+}++// childFrameIDForTest returns the id of the fixture's only child frame, failing+// rather than falling back to the top frame — a fallback would make both tests above+// exercise the very substitution they exist to detect.+func childFrameIDForTest(t *testing.T, ctx context.Context) string {+ t.Helper()++ deadline := time.Now().Add(10 * time.Second)+ for {+ tree, err := FetchFrameTree(ctx)+ if err != nil {+ t.Fatalf("fetch frame tree: %v", err)+ }+ if len(tree.ChildFrames) > 0 && tree.ChildFrames[0].Frame.ID != "" {+ return tree.ChildFrames[0].Frame.ID+ }+ if time.Now().After(deadline) {+ t.Fatalf("the fixture's child frame never appeared in the frame tree, so this guard would test the top frame instead: %+v", tree)+ }+ time.Sleep(50 * time.Millisecond)+ }+}diff --git a/internal/bridge/cdpops/frame_dom.go b/internal/bridge/cdpops/frame_dom.goindex 19d668ea..8d00adb7 100644--- a/internal/bridge/cdpops/frame_dom.go+++ b/internal/bridge/cdpops/frame_dom.go@@ -4,118 +4,41 @@ import ("context""encoding/json""fmt"- "strings""github.com/chromedp/chromedp"+ "github.com/pinchtab/pinchtab/internal/cdptk""github.com/pinchtab/pinchtab/internal/runtimetypes")// IsolatedNodeObjectID converts a backend node id to a JS object handle in the-// top frame's isolated world. DOM.resolveNode without an executionContextId-// hands back a main-world object, so every Runtime.callFunctionOn against it-// runs where page script can redefine the DOM methods it calls.-//-// A handle from any frame's isolated world reaches a node in another-// same-process frame, and a bare backend node id does not carry its own frame,-// so the top frame's world is used. Never falls back to the main world: a-// caller that cannot obtain an isolated context gets an error.+// top frame's isolated world. The rule and the world both have one owner in+// internal/cdptk, the lowest CDP layer: DOM.resolveNode without an+// executionContextId hands back a main-world object, so every+// Runtime.callFunctionOn against it runs where page script can redefine the DOM+// methods it calls.//// JS invoked on the returned handle must not read ambient globals. The handle// lives in the world it was resolved into, not necessarily the node's frame, so// `window` and `document` there are the top frame's. Derive them from the node// via ownerDocument/defaultView instead.func IsolatedNodeObjectID(ctx context.Context, backendNodeID int64) (string, error) {- execID, err := topFrameIsolatedContextID(ctx)- if err != nil {- return "", err- }-- var raw json.RawMessage- if err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {- return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.resolveNode", map[string]any{- "backendNodeId": backendNodeID,- "executionContextId": execID,- }, &raw)- })); err != nil {- return "", fmt.Errorf("resolve node: %w", err)- }-- var parsed struct {- Object struct {- ObjectID string `json:"objectId"`- } `json:"object"`- }- if err := json.Unmarshal(raw, &parsed); err != nil {- return "", err- }- if strings.TrimSpace(parsed.Object.ObjectID) == "" {- return "", fmt.Errorf("resolve node: backend node %d not found", backendNodeID)- }- return parsed.Object.ObjectID, nil-}--func topFrameIsolatedContextID(ctx context.Context) (int64, error) {- var raw json.RawMessage- if err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {- return chromedp.FromContext(ctx).Target.Execute(ctx, "Page.getFrameTree", nil, &raw)- })); err != nil {- return 0, fmt.Errorf("resolve top frame: %w", err)- }-- var tree struct {- FrameTree struct {- Frame struct {- ID string `json:"id"`- } `json:"frame"`- } `json:"frameTree"`- }- if err := json.Unmarshal(raw, &tree); err != nil {- return 0, err- }- if tree.FrameTree.Frame.ID == "" {- return 0, fmt.Errorf("resolve top frame: frame id is empty")- }-- execID, err := FrameExecutionContextID(ctx, tree.FrameTree.Frame.ID)- if err != nil {- return 0, err- }- if execID == 0 {- return 0, fmt.Errorf("frame %q has no isolated execution context", tree.FrameTree.Frame.ID)- }- return execID, nil+ return cdptk.IsolatedNodeObjectID(ctx, backendNodeID)}// FrameExecutionContextID returns a Runtime.executionContextId that evaluates-// in the given frame's document. Returns (0, nil) when frameID is empty so-// callers can fall back to the default top-level context without branching.+// in the given frame's document, minted by the one owner in internal/cdptk.+//+// Returns (0, nil) when frameID is empty, and that check stays HERE rather than+// being handed to the owner: callers branch on the zero to fall back to the+// context they already have, whereas an empty frame means the top frame's+// isolated world one layer down. Collapsing the two spellings of "empty" would+// silently move every unscoped caller into a freshly minted world.func FrameExecutionContextID(ctx context.Context, frameID string) (int64, error) {if frameID == "" {return 0, nil}-- var worldResult json.RawMessage- err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {- return chromedp.FromContext(ctx).Target.Execute(ctx, "Page.createIsolatedWorld", map[string]any{- "frameId": frameID,- "worldName": "pinchtab-frame-scope",- }, &worldResult)- }))- if err != nil {- return 0, fmt.Errorf("create isolated world for frame %q: %w", frameID, err)- }-- var resp struct {- ExecutionContextID int64 `json:"executionContextId"`- }- if err := json.Unmarshal(worldResult, &resp); err != nil {- return 0, err- }- if resp.ExecutionContextID == 0 {- return 0, fmt.Errorf("frame %q has no execution context", frameID)- }- return resp.ExecutionContextID, nil+ return cdptk.IsolatedContextID(ctx, frameID)}// CallFunctionOnNode resolves a backend node to a JS object and invokes thediff --git a/internal/bridge/cdpops/frame_dom_test.go b/internal/bridge/cdpops/frame_dom_test.gonew file mode 100644index 00000000..0ce9921a--- /dev/null+++ b/internal/bridge/cdpops/frame_dom_test.go@@ -0,0 +1,135 @@+package cdpops++import (+ "context"+ "go/ast"+ "go/parser"+ "go/token"+ "path/filepath"+ "strings"+ "testing"+)++// The two spellings of "empty" that the world unification could have collapsed.+// Here, an unnamed frame means "the caller already has a context, do nothing" and+// the zero is what callers branch on; one layer down, in cdptk.IsolatedContextID,+// an unnamed frame means the TOP frame's isolated world. Handing this check to the+// owner would move every unscoped caller into a freshly minted world instead.+//+// No CDP is needed: the contract is that this answers before issuing a call, which+// is also why an unscoped caller costs nothing.+func TestAnUnnamedFrameIsANoOpRatherThanTheTopFrame(t *testing.T) {+ execID, err := FrameExecutionContextID(context.Background(), "")++ if err != nil {+ t.Fatalf("FrameExecutionContextID(ctx, \"\") = (%d, %v), want (0, nil): an unnamed frame must be a no-op the caller can branch on, not an error", execID, err)+ }+ if execID != 0 {+ t.Errorf("FrameExecutionContextID(ctx, \"\") = %d, want 0 — callers read the zero as \"use the context you already have\"; a real id here silently moves them into a minted world", execID)+ }+}++// The frame a caller names must be the frame handed to the world owner. This is a+// source guard because the behavioural half needs a browser: the reachable failure+// is passing "" (or another frame) to the owner, which returns the TOP frame's+// world, and every frame-scoped evaluation then reads the wrong document while+// still succeeding.+//+// Pinned through the AST by argument POSITION rather than by matching call text, so+// renaming the parameter keeps this green while dropping it reds.+func TestTheNamedFrameIsHandedToTheWorldOwner(t *testing.T) {+ fset := token.NewFileSet()+ parsed, err := parser.ParseFile(fset, "frame_dom.go", nil, 0)+ if err != nil {+ t.Fatal(err)+ }++ var fn *ast.FuncDecl+ for _, decl := range parsed.Decls {+ if candidate, ok := decl.(*ast.FuncDecl); ok && candidate.Name.Name == "FrameExecutionContextID" {+ fn = candidate+ }+ }+ if fn == nil {+ t.Fatal("FrameExecutionContextID is gone from frame_dom.go; re-point this guard at whatever scopes an evaluation to a frame rather than deleting it")+ }+ params := fn.Type.Params.List+ frameParam := params[len(params)-1].Names[0].Name++ handedOver := false+ ast.Inspect(fn, func(node ast.Node) bool {+ call, ok := node.(*ast.CallExpr)+ if !ok {+ return true+ }+ sel, ok := call.Fun.(*ast.SelectorExpr)+ if !ok || sel.Sel.Name != "IsolatedContextID" {+ return true+ }+ if len(call.Args) == 0 {+ return true+ }+ last := call.Args[len(call.Args)-1]+ ident, isIdent := last.(*ast.Ident)+ if !isIdent || ident.Name != frameParam {+ t.Errorf("the world owner is called with %s in the frame position, not this function's %s parameter — a frame-scoped evaluation would then run in the top frame's document and still succeed", describeExpr(last), frameParam)+ return true+ }+ handedOver = true+ return true+ })++ if !handedOver {+ t.Errorf("FrameExecutionContextID never hands its %s parameter to IsolatedContextID; the frame the caller asked for has to reach the world creation, or scoping is silently ignored", frameParam)+ }+}++// The world must have exactly one owner: this package kept its own+// resolve-the-frame-then-create-a-world sequence, which is how a second world name+// came to exist for one rule.+func TestThisPackageMintsNoIsolatedWorldOfItsOwn(t *testing.T) {+ paths, err := filepath.Glob("*.go")+ if err != nil {+ t.Fatal(err)+ }++ files := 0+ for _, path := range paths {+ if strings.HasSuffix(path, "_test.go") {+ continue+ }+ files+++ fset := token.NewFileSet()+ parsed, err := parser.ParseFile(fset, path, nil, 0)+ if err != nil {+ t.Fatalf("cannot parse %s, so this guard would skip it silently: %v", path, err)+ }+ ast.Inspect(parsed, func(node ast.Node) bool {+ lit, ok := node.(*ast.BasicLit)+ if !ok || lit.Kind != token.STRING {+ return true+ }+ if strings.Trim(lit.Value, `"`) == "Page.createIsolatedWorld" {+ t.Errorf("%s:%d mints an isolated world in this package; the world has one owner in internal/cdptk so a frame cannot end up with two, and a handle from one world is unusable alongside a handle from the other", path, fset.Position(lit.Pos()).Line)+ }+ return true+ })+ }+ if files < 2 {+ t.Fatalf("scanned %d non-test file(s) in this package, fewer than this guard was written over; it would pass vacuously", files)+ }+}++func describeExpr(expr ast.Expr) string {+ switch e := expr.(type) {+ case *ast.Ident:+ return e.Name+ case *ast.BasicLit:+ return e.Value+ case *ast.CallExpr:+ return describeExpr(e.Fun) + "(...)"+ case *ast.SelectorExpr:+ return describeExpr(e.X) + "." + e.Sel.Name+ }+ return "a computed expression"+}diff --git a/internal/cdptk/isolated_world.go b/internal/cdptk/isolated_world.goindex a5c79bda..6569a06b 100644--- a/internal/cdptk/isolated_world.go+++ b/internal/cdptk/isolated_world.go@@ -8,10 +8,32 @@ import ("github.com/chromedp/chromedp")-// isolatedWorldName labels the world reused for node resolution.-// Page.createIsolatedWorld keys on the name, so repeat calls return the same-// context rather than minting one per resolution.-const isolatedWorldName = "pinchtab-node-scope"+// isolatedWorldName is the ONE name every PinchTab isolated world is created+// under. Page.createIsolatedWorld keys on frame and name, so repeat calls for a+// frame return the same context rather than minting one per resolution — and one+// name means a frame has ONE PinchTab world instead of two, which makes handles+// resolved there interchangeable in a single Runtime.callFunctionOn by+// construction rather than by a rule nobody can check.+//+// There were two names for this one rule: a node scope here and a frame scope in+// the bridge. Neither frame policy was wrong. A bare backend node id does not+// carry its frame, so node resolution must use the top frame; evaluating+// `document` for a named frame must use that frame. Those are two needs of one+// mechanism, which is why the frame is a parameter and the mechanism is shared.+//+// No isolation is weakened by sharing it. The world exists so page script cannot+// hide or redirect targets by replacing DOM methods in the main world, and page+// script can reach neither name. Fewer worlds is not a looser boundary.+//+// CROSS-FRAME RESIDUAL, recorded rather than built: handles from two DIFFERENT+// frames' worlds are still not interchangeable, and nothing in the types says+// which frame a handle came from. That hazard has no call site — the only place+// passing an object handle as a callFunctionOn ARGUMENT resolves both handles in+// one IsolatedNodeObjectIDs call, so they share a world — and a handle type+// carrying its context id is real machinery against a shape nothing writes. The+// same-frame case, the only one reachable today, is closed above. Reopen it when+// a caller genuinely needs handles from two frames in one call.+const isolatedWorldName = "pinchtab-scope"// IsolatedNodeObjectID converts a backend node id to a JS object handle in the// top frame's isolated world.@@ -47,7 +69,7 @@ func IsolatedNodeObjectIDs(ctx context.Context, backendNodeIDs ...int64) ([]strireturn nil, fmt.Errorf("no backend node ids to resolve")}- execID, err := topFrameIsolatedContextID(ctx)+ execID, err := IsolatedContextID(ctx, "")if err != nil {return nil, err}@@ -88,24 +110,24 @@ func resolveNodeInContext(ctx context.Context, backendNodeID, execID int64) (strreturn parsed.Object.ObjectID, nil}-func topFrameIsolatedContextID(ctx context.Context) (int64, error) {- // GetFrameTree issues a CDP call, so it needs an executor context; calling it- // with the caller's bare ctx fails with "invalid context".- var frameID string- if err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {- tree, err := GetFrameTree(ctx)+// IsolatedContextID returns the execution context of the isolated world for+// frameID, or for the top frame when frameID is empty. It is the only place a+// PinchTab isolated world is created — see isolatedWorldName for why one name and+// a frame parameter replaced two worlds, and TestOnlyOneIsolatedWorldNameExists+// for the census that keeps it that way.+//+// It never returns a usable zero: a caller that cannot obtain an isolated context+// gets an error rather than a main-world context, so the boundary fails closed.+// Callers that want a NO-OP for an unnamed frame — "use whatever context the+// caller already has" — must keep that check themselves, because empty here means+// the top frame's isolated world, not the default context.+func IsolatedContextID(ctx context.Context, frameID string) (int64, error) {+ if frameID == "" {+ resolved, err := topFrameID(ctx)if err != nil {- return err- }- if tree != nil && tree.Frame != nil {- frameID = tree.Frame.ID.String()+ return 0, err}- return nil- })); err != nil {- return 0, fmt.Errorf("resolve top frame: %w", err)- }- if frameID == "" {- return 0, fmt.Errorf("resolve top frame: frame id is empty")+ frameID = resolved}var raw json.RawMessage@@ -115,7 +137,7 @@ func topFrameIsolatedContextID(ctx context.Context) (int64, error) {"worldName": isolatedWorldName,}, &raw)})); err != nil {- return 0, fmt.Errorf("create isolated world: %w", err)+ return 0, fmt.Errorf("create isolated world for frame %q: %w", frameID, err)}var resp struct {@@ -125,7 +147,31 @@ func topFrameIsolatedContextID(ctx context.Context) (int64, error) {return 0, err}if resp.ExecutionContextID == 0 {- return 0, fmt.Errorf("top frame has no isolated execution context")+ return 0, fmt.Errorf("frame %q has no isolated execution context", frameID)}return resp.ExecutionContextID, nil}++// topFrameID reads the top frame's id, the frame IsolatedContextID falls back to+// when the caller names none.+func topFrameID(ctx context.Context) (string, error) {+ // GetFrameTree issues a CDP call, so it needs an executor context; calling it+ // with the caller's bare ctx fails with "invalid context".+ var frameID string+ if err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {+ tree, err := GetFrameTree(ctx)+ if err != nil {+ return err+ }+ if tree != nil && tree.Frame != nil {+ frameID = tree.Frame.ID.String()+ }+ return nil+ })); err != nil {+ return "", fmt.Errorf("resolve top frame: %w", err)+ }+ if frameID == "" {+ return "", fmt.Errorf("resolve top frame: frame id is empty")+ }+ return frameID, nil+}diff --git a/internal/cdptk/isolated_world_test.go b/internal/cdptk/isolated_world_test.gonew file mode 100644index 00000000..9f77ed83--- /dev/null+++ b/internal/cdptk/isolated_world_test.go@@ -0,0 +1,166 @@+package cdptk++import (+ "go/ast"+ "go/parser"+ "go/token"+ "path/filepath"+ "strings"+ "testing"++ "github.com/pinchtab/pinchtab/internal/srccensus"+)++// moduleGoFileFloor is the vacuity floor for the module-wide walk below: a walk+// that stops seeing the tree would otherwise report a clean single world.+const moduleGoFileFloor = 400++type worldSite struct {+ file string+ line int+ value string+}++// Two isolated world names existed for one rule — a node scope here and a frame+// scope in the bridge — and nobody noticed the second arrive, which is the whole+// reason this census exists rather than a comment asking for one world.+//+// The rule is one world name in the whole module, named by a constant rather than+// spelled inline at the call, so a third cannot be added quietly: an inline+// literal at a second call site is exactly how the second one appeared.+func TestOnlyOneIsolatedWorldNameExists(t *testing.T) {+ var creates, names []worldSite++ for _, file := range srccensus.Tree(t, filepath.Join("..", ".."), moduleGoFileFloor) {+ fset := token.NewFileSet()+ parsed, err := parser.ParseFile(fset, file.Name, file.Text, 0)+ if err != nil {+ t.Errorf("%s: cannot parse, so this census can neither clear nor flag it: %v", file.Name, err)+ continue+ }+ ast.Inspect(parsed, func(node ast.Node) bool {+ switch n := node.(type) {+ case *ast.BasicLit:+ if n.Kind == token.STRING && strings.Trim(n.Value, `"`) == "Page.createIsolatedWorld" {+ creates = append(creates, worldSite{file: file.Name, line: fset.Position(n.Pos()).Line})+ }+ case *ast.KeyValueExpr:+ key, ok := n.Key.(*ast.BasicLit)+ if !ok || key.Kind != token.STRING || strings.Trim(key.Value, `"`) != "worldName" {+ return true+ }+ site := worldSite{file: file.Name, line: fset.Position(n.Pos()).Line}+ if lit, inline := n.Value.(*ast.BasicLit); inline {+ site.value = "inline literal " + lit.Value+ } else if ident, named := n.Value.(*ast.Ident); named {+ site.value = ident.Name+ } else {+ site.value = "a computed expression"+ }+ names = append(names, site)+ }+ return true+ })+ }++ if len(creates) == 0 || len(names) == 0 {+ t.Fatalf("found %d Page.createIsolatedWorld call(s) and %d worldName argument(s) in the whole module; the census has nothing to guard and would pass vacuously — re-point it at whatever mints the isolated world now rather than deleting it", len(creates), len(names))+ }++ const why = "One world per frame is the rule: Page.createIsolatedWorld keys on frame and name, so a second name means two worlds in the same frame, and a handle from one is not usable in a Runtime.callFunctionOn with a handle from the other. Nothing in the code says which world a handle came from, and the failure is silent. Mint every isolated context through cdptk.IsolatedContextID, which takes the frame as a parameter."++ if len(creates) != 1 {+ t.Errorf("Page.createIsolatedWorld is called at %d sites (%v), want exactly one. %s", len(creates), describeWorldSites(creates), why)+ }+ if len(names) != 1 {+ t.Errorf("worldName is passed at %d sites (%v), want exactly one. %s", len(names), describeWorldSites(names), why)+ }+ for _, site := range names {+ if site.value != "isolatedWorldName" {+ t.Errorf("%s:%d passes worldName as %s rather than the isolatedWorldName constant; a name spelled at the call site is how the second world arrived. %s", site.file, site.line, site.value, why)+ }+ }+}++func describeWorldSites(sites []worldSite) []string {+ out := make([]string, 0, len(sites))+ for _, site := range sites {+ out = append(out, filepath.ToSlash(site.file)+":"+itoa(site.line))+ }+ return out+}++func itoa(n int) string {+ if n == 0 {+ return "0"+ }+ var digits []byte+ for n > 0 {+ digits = append([]byte{byte('0' + n%10)}, digits...)+ n /= 10+ }+ return string(digits)+}++// The frame a caller names must be the frame the world is created for. Merging the+// two worlds is easiest to get wrong here: hand the owner an empty frame and every+// frame-scoped evaluation silently moves to the top frame's document, which reads+// as a selector that stopped matching rather than as a scope bug.+func TestTheNamedFrameReachesTheWorldCreation(t *testing.T) {+ fset := token.NewFileSet()+ parsed, err := parser.ParseFile(fset, "isolated_world.go", nil, 0)+ if err != nil {+ t.Fatal(err)+ }++ owner := findFuncDecl(parsed, "IsolatedContextID")+ if owner == nil {+ t.Fatal("IsolatedContextID is gone from isolated_world.go; re-point this guard at whatever mints the isolated world rather than deleting it")+ }+ param := owner.Type.Params.List[len(owner.Type.Params.List)-1].Names[0].Name++ found := false+ ast.Inspect(owner, func(node ast.Node) bool {+ kv, ok := node.(*ast.KeyValueExpr)+ if !ok {+ return true+ }+ key, isLit := kv.Key.(*ast.BasicLit)+ if !isLit || strings.Trim(key.Value, `"`) != "frameId" {+ return true+ }+ ident, isIdent := kv.Value.(*ast.Ident)+ if !isIdent || ident.Name != param {+ t.Errorf("frameId is passed as %s, not the %s parameter — the frame the caller asked for must be the frame the world is created for", exprText(kv.Value), param)+ return true+ }+ found = true+ return true+ })+ if !found {+ t.Errorf("no frameId argument in IsolatedContextID carries its %s parameter, so a caller naming a frame cannot be sure the world belongs to it", param)+ }+}++func findFuncDecl(file *ast.File, name string) *ast.FuncDecl {+ for _, decl := range file.Decls {+ if fn, ok := decl.(*ast.FuncDecl); ok && fn.Name.Name == name {+ return fn+ }+ }+ return nil+}++func exprText(expr ast.Expr) string {+ switch e := expr.(type) {+ case *ast.Ident:+ return e.Name+ case *ast.BasicLit:+ return e.Value+ case *ast.CallExpr:+ return exprText(e.Fun) + "(...)"+ case *ast.SelectorExpr:+ return exprText(e.X) + "." + e.Sel.Name+ }+ return "a computed expression"+}