//go:build browser package slidestest // The sealed frame in a real Chromium (scenes and clips spec ยง3, Review // Focus 2): a scene runs inside a page of this app and reaches nothing // but the page's messages, and the example in docs/scenes.md keeps the // contract. import ( "context" "fmt" "net/http" "net/http/httptest" "os" "sort" "strings" "sync" "testing" "time" "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/network" "github.com/chromedp/chromedp" ) // hostileScene tries every way out it can think of, then posts what // happened to each try back to the page. Every URL it aims at this app // carries scene-probe, so the server's request log can say whether any // of them arrived. A try reports "refused: ..." when it visibly failed // and "reached: ..." when it visibly worked; "tried" is a try whose // failure only shows outside the frame (the page's URL, the server's // log), which the test checks there. // // Framed with ?navigate=URL it tries nothing else: it navigates its own // frame to URL, which ends the scene, so each target gets a frame of // its own. const hostileScene = ` hostile ` // requestLog is every request a server saw, as method, URI and whether // it carried a Cookie header: "GET /x?y cookie=false". type requestLog struct { mu sync.Mutex seen []string } func (l *requestLog) wrap(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { l.mu.Lock() l.seen = append(l.seen, fmt.Sprintf("%s %s cookie=%t", r.Method, r.URL.RequestURI(), r.Header.Get("Cookie") != "")) l.mu.Unlock() h.ServeHTTP(w, r) }) } func (l *requestLog) matching(s string) []string { l.mu.Lock() defer l.mu.Unlock() var out []string for _, r := range l.seen { if strings.Contains(r, s) { out = append(out, r) } } return out } // browserCookies is every cookie the browser holds for origin, as // name=value, sorted. func browserCookies(origin string, out *[]string) chromedp.Action[chromedp.Void] { return chromedp.Func(func(ctx context.Context, t *chromedp.Target) error { res, err := cdp.Call(ctx, t, network.GetCookies, network.GetCookiesParams{URLs: []string{origin + "/"}}) if err != nil { return err } *out = nil for _, c := range res.Cookies { *out = append(*out, c.Name+"="+c.Value) } sort.Strings(*out) return nil }) } // pageState is what a scene must leave as it found it: the page's // address, its document and its own storage. type pageState struct { URL, DOM, Storage string } const pageStateJS = `({ URL: location.href, DOM: document.documentElement.outerHTML, Storage: JSON.stringify([Object.entries(localStorage), Object.entries(sessionStorage)]), })` func TestASceneCannotReachAnything(t *testing.T) { log := &requestLog{} rig, app := newRigAppWrapped(t, dirStore(t), log.wrap) cookies := signedIn(t, app, allowedAddress) token := mintAgent(t, app, cookies, "scenes") sqid := apiDeck(t, app, token, "Hostile") ref := uploadScene(t, app, "/d/"+sqid, cookies, []byte(hostileScene)) id := addScene(t, app, token, sqid, ref) // The browser signed in too, so there is a session cookie to steal. browserSignIn(t, rig, app.mailer) rig.Run(chromedp.Navigate(rig.Origin + "/d/" + sqid + "?slide=1")) rig.Screen("[slides-slide]", "the viewer, before the scene") var before, after []string rig.Run( browserCookies(rig.Origin, &before), // The page puts something of its own in storage, so "unchanged" // is about something. evalValue(nil, `localStorage.setItem('page', 'mine'); sessionStorage.setItem('page', 'mine')`), ) if len(before) == 0 { t.Fatal("the signed-in browser holds no cookie") } // The frame goes in, and the page is read straight after: the frame // is the one change the test itself makes. var ran struct { Out map[string]string Before pageState } rig.Run(evalInto(&ran, fmt.Sprintf(`new Promise((resolve) => { const f = document.createElement('iframe'); f.title = 'scene'; f.src = %q; document.body.append(f); const before = %s; addEventListener('message', (e) => { if (e.source === f.contentWindow && e.data && e.data.type === 'probes') resolve({Out: e.data.out, Before: before}); }); setTimeout(() => resolve({Out: null, Before: before}), 20000); })`, "/d/"+sqid+"/scenes/"+id+"/"+ref, pageStateJS), awaitPromise)) out := ran.Out if out == nil { t.Fatal("the scene never reported: a try took its document away") } // A moment for anything a try set off to land. var page pageState rig.Run( chromedp.Sleep(500*time.Millisecond), evalInto(&page, pageStateJS), browserCookies(rig.Origin, &after), ) tries := []string{ "fetch this app", "fetch elsewhere", "XMLHttpRequest", "read document.cookie", "write document.cookie", "localStorage", "sessionStorage", "indexedDB.open", "parent.document", "parent.location", "window.open", "navigator.sendBeacon", "WebSocket", "img src", "top.location", "form post", } outside := map[string]bool{"navigator.sendBeacon": true, "top.location": true, "form post": true} for _, name := range tries { got, ok := out[name] switch { case !ok: t.Errorf("%s: no outcome reported", name) case strings.HasPrefix(got, "refused"): case outside[name] && got == "tried": default: t.Errorf("%s: %s, want refused", name, got) } } if t.Failed() { t.Logf("outcomes: %v", out) } // The log saw the scene's own document arrive, so it was listening. if hits := log.matching("/scenes/" + id + "/" + ref + " "); len(hits) != 1 { t.Errorf("the request log saw the scene's document %d times, want once", len(hits)) } if hits := log.matching("scene-probe"); len(hits) > 0 { t.Errorf("the server saw requests from the scene: %v", hits) } if strings.Join(before, "; ") != strings.Join(after, "; ") { t.Errorf("the cookies changed: %v, then %v", before, after) } if want := rig.Origin + "/d/" + sqid + "?slide=1"; page.URL != want || ran.Before.URL != want { t.Errorf("the page is at %q, want %q", page.URL, want) } if page.Storage != ran.Before.Storage || !strings.Contains(page.Storage, `"page","mine"`) { t.Errorf("the page's storage changed: %s, then %s", ran.Before.Storage, page.Storage) } if page.DOM != ran.Before.DOM { t.Errorf("the page's document changed:\nbefore %s\nafter %s", ran.Before.DOM, page.DOM) } // Navigating its own frame ends the scene and reaches no other // origin: the page's own policy (default-src 'self', so frame-src // 'self') refuses the frame a document from elsewhere. Elsewhere is // a server of our own on another origin, so "no request left" is // something the test can see; example.com is tried too. elsewhere := &requestLog{} other := httptest.NewServer(elsewhere.wrap(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("

elsewhere

")) }))) defer other.Close() if strings.HasPrefix(other.URL, rig.Origin) { t.Fatalf("elsewhere %s is the app's own origin", other.URL) } // Same-origin, it reaches Slides and nothing else, and without the // reader's cookies: the scene's origin matches nothing. targets := []string{other.URL + "/?scene-navigate=elsewhere", "https://example.com/?scene-navigate=example", "/?scene-navigate=self"} for _, target := range targets { rig.Run(evalValue(nil, fmt.Sprintf(`new Promise((resolve) => { const f = document.createElement('iframe'); f.title = 'scene'; f.src = %q + '?navigate=' + encodeURIComponent(%q); document.body.append(f); setTimeout(resolve, 1500); })`, "/d/"+sqid+"/scenes/"+id+"/"+ref, target), awaitPromise)) } var url string rig.Run(evalInto(&url, `location.href`), browserCookies(rig.Origin, &after)) if hits := elsewhere.matching(""); len(hits) > 0 { t.Errorf("a scene navigating its frame reached another origin: %v", hits) } if hits := log.matching("scene-navigate=example"); len(hits) > 0 { t.Errorf("navigating to example.com came back to the app: %v", hits) } if hits := log.matching("scene-navigate=self"); len(hits) != 1 || !strings.HasSuffix(hits[0], " cookie=false") { t.Errorf("a same-origin self-navigation: the app saw %v, want one request with no Cookie header", hits) } if want := rig.Origin + "/d/" + sqid + "?slide=1"; url != want { t.Errorf("after the navigations the page is at %q, want %q", url, want) } if strings.Join(before, "; ") != strings.Join(after, "; ") { t.Errorf("after the navigations the cookies changed: %v, then %v", before, after) } } // TestTheExampleSceneAnswersReady: docs/scenes/example.html, posted to // the preview as the code panel posts it (a form into a named frame), // says nothing until it is told init, then answers ready once, within // the 3 seconds, and takes a state change without saying it again or // putting anything wrong on the page. func TestTheExampleSceneAnswersReady(t *testing.T) { example, err := os.ReadFile("../../docs/scenes/example.html") if err != nil { t.Fatalf("read the example: %v", err) } if n := strings.Count(string(example), "\n"); n > 40 { t.Errorf("the example is %d lines, want 40 at most", n) } rig, mailer := newRig(t) browserSignIn(t, rig, mailer) var deck string rig.Run(evalInto(&deck, `(document.querySelector('a[href^="/d/"]')?.getAttribute('href') ?? '').replace(/\/edit$/, '')`)) if deck == "" { t.Fatal("the deck list links no deck") } rig.Run(chromedp.Navigate(rig.Origin + deck + "?slide=1")) rig.Screen("[slides-slide]", "the viewer") var got struct { Early, Ready, AfterState int Millis float64 } rig.Run(evalInto(&got, fmt.Sprintf(`(async (html, preview) => { const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); const f = document.createElement('iframe'); f.name = 'scene-preview'; f.title = 'scene'; f.style.cssText = 'width: 640px; height: 360px'; document.body.append(f); await sleep(100); const messages = []; addEventListener('message', (e) => { if (e.source === f.contentWindow) messages.push(e.data); }); const loaded = new Promise((r) => f.addEventListener('load', r, {once: true})); const form = document.createElement('form'); form.method = 'post'; form.action = preview; form.target = 'scene-preview'; form.hidden = true; const field = document.createElement('textarea'); field.name = 'html'; field.value = html; form.append(field); document.body.append(form); form.submit(); await loaded; await sleep(300); const early = messages.length; const readies = () => messages.filter((m) => m && m.type === 'ready').length; const start = performance.now(); f.contentWindow.postMessage({ type: 'init', state: 'one', size: {w: 640, h: 360}, words: {one: 'First', two: 'Second', three: 'Third'}, data: {states: [{id: 'one', colour: '#c0392b'}, {id: 'two', colour: '#2471a3'}, {id: 'three', colour: '#1e8449'}]}, reducedMotion: false, fonts: [], }, '*'); while (readies() === 0 && performance.now() - start < 3000) await sleep(20); const millis = performance.now() - start; const ready = readies(); f.contentWindow.postMessage({type: 'state', state: 'two', animate: true}, '*'); f.contentWindow.postMessage({type: 'state', state: 'three', animate: false}, '*'); await sleep(500); return {Early: early, Ready: ready, AfterState: readies(), Millis: millis}; })(%q, %q)`, example, deck+"/scenes/preview"), awaitPromise)) if got.Early != 0 { t.Errorf("the example said %d things before init, want nothing", got.Early) } if got.Ready != 1 || got.Millis >= 3000 { t.Errorf("the example answered ready %d times in %.0f ms, want once inside 3 s", got.Ready, got.Millis) } if got.AfterState != 1 { t.Errorf("after two states the example has said ready %d times, want once", got.AfterState) } rig.Screen("[slides-slide]", "the example scene ran") }