oficina / slides Public

Clone
git clone https://amadan.net/oficina/slides

Plain git — no account needed to clone.

Download

Download this file

1//go:build browser
2
3package slidestest
4
5// The sealed frame in a real Chromium (scenes and clips spec §3, Review
6// Focus 2): a scene runs inside a page of this app and reaches nothing
7// but the page's messages, and the example in docs/scenes.md keeps the
8// contract.
9
10import (
11 "context"
12 "fmt"
13 "net/http"
14 "net/http/httptest"
15 "os"
16 "sort"
17 "strings"
18 "sync"
19 "testing"
20 "time"
21
22 "github.com/chromedp/cdproto/cdp"
23 "github.com/chromedp/cdproto/network"
24 "github.com/chromedp/chromedp"
25)
26
27// hostileScene tries every way out it can think of, then posts what
28// happened to each try back to the page. Every URL it aims at this app
29// carries scene-probe, so the server's request log can say whether any
30// of them arrived. A try reports "refused: ..." when it visibly failed
31// and "reached: ..." when it visibly worked; "tried" is a try whose
32// failure only shows outside the frame (the page's URL, the server's
33// log), which the test checks there.
34//
35// Framed with ?navigate=URL it tries nothing else: it navigates its own
36// frame to URL, which ends the scene, so each target gets a frame of
37// its own.
38const hostileScene = `<!doctype html>
39<html><head><meta charset="utf-8"><title>hostile</title></head>
40<body><script>
41const out = {};
42const wait = (p, ms) => Promise.race([p, new Promise((r) => setTimeout(() => r('refused: no answer'), ms))]);
43const attempt = async (name, fn) => {
44 try { out[name] = String(await fn()); } catch (e) { out[name] = 'refused: ' + ((e && e.name) || e); }
45};
46const away = new URLSearchParams(location.search).get('navigate');
47if (away) location = away;
48else (async () => {
49 await attempt('fetch this app', async () => 'reached: ' + (await fetch('/?scene-probe=fetch')).status);
50 await attempt('fetch elsewhere', async () => 'reached: ' + (await fetch('https://example.com/?scene-probe=fetch')).status);
51 await attempt('XMLHttpRequest', () => wait(new Promise((res) => {
52 const x = new XMLHttpRequest();
53 x.open('GET', '/?scene-probe=xhr');
54 x.onload = () => res('reached: ' + x.status);
55 x.onerror = () => res('refused: error');
56 x.send();
57 }), 2000));
58 await attempt('read document.cookie', () => { const c = document.cookie; return c ? 'reached: ' + c : 'refused: empty'; });
59 await attempt('write document.cookie', () => {
60 document.cookie = 'scene=1; path=/';
61 return document.cookie.includes('scene=1') ? 'reached' : 'refused: not kept';
62 });
63 await attempt('localStorage', () => { localStorage.setItem('scene', '1'); return 'reached'; });
64 await attempt('sessionStorage', () => { sessionStorage.setItem('scene', '1'); return 'reached'; });
65 await attempt('indexedDB.open', () => wait(new Promise((res) => {
66 const q = indexedDB.open('scene');
67 q.onsuccess = () => res('reached');
68 q.onerror = () => res('refused: error');
69 }), 2000));
70 await attempt('parent.document', () => 'reached: ' + parent.document.title);
71 await attempt('parent.location', () => 'reached: ' + parent.location.href);
72 await attempt('window.open', () => (window.open('/?scene-probe=open') ? 'reached' : 'refused: no window'));
73 await attempt('navigator.sendBeacon', () => (navigator.sendBeacon('/?scene-probe=beacon', 'x') ? 'tried' : 'refused: not queued'));
74 await attempt('WebSocket', () => wait(new Promise((res) => {
75 const s = new WebSocket('ws://' + location.host + '/?scene-probe=ws');
76 s.onopen = () => res('reached');
77 s.onerror = () => res('refused: error');
78 }), 2000));
79 await attempt('img src', () => wait(new Promise((res) => {
80 const i = new Image();
81 i.onload = () => res('reached');
82 i.onerror = () => res('refused: error');
83 i.src = '/?scene-probe=img';
84 document.body.append(i);
85 }), 2000));
86 await attempt('top.location', () => { top.location = '/?scene-probe=top'; return 'tried'; });
87 await attempt('form post', () => {
88 const f = document.createElement('form');
89 f.method = 'post';
90 f.action = '/?scene-probe=form';
91 const i = document.createElement('input');
92 i.name = 'x';
93 i.value = '1';
94 f.append(i);
95 document.body.append(f);
96 f.submit();
97 return 'tried';
98 });
99 // Long enough for a navigation the tries above started to have taken
100 // this document away, so no answer at all is its own failure.
101 setTimeout(() => parent.postMessage({type: 'probes', out}, '*'), 500);
102})();
103</script></body></html>
104`
105
106// requestLog is every request a server saw, as method, URI and whether
107// it carried a Cookie header: "GET /x?y cookie=false".
108type requestLog struct {
109 mu sync.Mutex
110 seen []string
111}
112
113func (l *requestLog) wrap(h http.Handler) http.Handler {
114 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
115 l.mu.Lock()
116 l.seen = append(l.seen, fmt.Sprintf("%s %s cookie=%t", r.Method, r.URL.RequestURI(), r.Header.Get("Cookie") != ""))
117 l.mu.Unlock()
118 h.ServeHTTP(w, r)
119 })
120}
121
122func (l *requestLog) matching(s string) []string {
123 l.mu.Lock()
124 defer l.mu.Unlock()
125 var out []string
126 for _, r := range l.seen {
127 if strings.Contains(r, s) {
128 out = append(out, r)
129 }
130 }
131 return out
132}
133
134// browserCookies is every cookie the browser holds for origin, as
135// name=value, sorted.
136func browserCookies(origin string, out *[]string) chromedp.Action[chromedp.Void] {
137 return chromedp.Func(func(ctx context.Context, t *chromedp.Target) error {
138 res, err := cdp.Call(ctx, t, network.GetCookies, network.GetCookiesParams{URLs: []string{origin + "/"}})
139 if err != nil {
140 return err
141 }
142 *out = nil
143 for _, c := range res.Cookies {
144 *out = append(*out, c.Name+"="+c.Value)
145 }
146 sort.Strings(*out)
147 return nil
148 })
149}
150
151// pageState is what a scene must leave as it found it: the page's
152// address, its document and its own storage.
153type pageState struct {
154 URL, DOM, Storage string
155}
156
157const pageStateJS = `({
158 URL: location.href,
159 DOM: document.documentElement.outerHTML,
160 Storage: JSON.stringify([Object.entries(localStorage), Object.entries(sessionStorage)]),
161})`
162
163func TestASceneCannotReachAnything(t *testing.T) {
164 log := &requestLog{}
165 rig, app := newRigAppWrapped(t, dirStore(t), log.wrap)
166 cookies := signedIn(t, app, allowedAddress)
167 token := mintAgent(t, app, cookies, "scenes")
168 sqid := apiDeck(t, app, token, "Hostile")
169 ref := uploadScene(t, app, "/d/"+sqid, cookies, []byte(hostileScene))
170 id := addScene(t, app, token, sqid, ref)
171
172 // The browser signed in too, so there is a session cookie to steal.
173 browserSignIn(t, rig, app.mailer)
174 rig.Run(chromedp.Navigate(rig.Origin + "/d/" + sqid + "?slide=1"))
175 rig.Screen("[slides-slide]", "the viewer, before the scene")
176
177 var before, after []string
178 rig.Run(
179 browserCookies(rig.Origin, &before),
180 // The page puts something of its own in storage, so "unchanged"
181 // is about something.
182 evalValue(nil, `localStorage.setItem('page', 'mine'); sessionStorage.setItem('page', 'mine')`),
183 )
184 if len(before) == 0 {
185 t.Fatal("the signed-in browser holds no cookie")
186 }
187
188 // The frame goes in, and the page is read straight after: the frame
189 // is the one change the test itself makes.
190 var ran struct {
191 Out map[string]string
192 Before pageState
193 }
194 rig.Run(evalInto(&ran, fmt.Sprintf(`new Promise((resolve) => {
195 const f = document.createElement('iframe');
196 f.title = 'scene';
197 f.src = %q;
198 document.body.append(f);
199 const before = %s;
200 addEventListener('message', (e) => {
201 if (e.source === f.contentWindow && e.data && e.data.type === 'probes') resolve({Out: e.data.out, Before: before});
202 });
203 setTimeout(() => resolve({Out: null, Before: before}), 20000);
204 })`, "/d/"+sqid+"/scenes/"+id+"/"+ref, pageStateJS), awaitPromise))
205 out := ran.Out
206 if out == nil {
207 t.Fatal("the scene never reported: a try took its document away")
208 }
209 // A moment for anything a try set off to land.
210 var page pageState
211 rig.Run(
212 chromedp.Sleep(500*time.Millisecond),
213 evalInto(&page, pageStateJS),
214 browserCookies(rig.Origin, &after),
215 )
216
217 tries := []string{
218 "fetch this app", "fetch elsewhere", "XMLHttpRequest", "read document.cookie",
219 "write document.cookie", "localStorage", "sessionStorage", "indexedDB.open",
220 "parent.document", "parent.location", "window.open", "navigator.sendBeacon",
221 "WebSocket", "img src", "top.location", "form post",
222 }
223 outside := map[string]bool{"navigator.sendBeacon": true, "top.location": true, "form post": true}
224 for _, name := range tries {
225 got, ok := out[name]
226 switch {
227 case !ok:
228 t.Errorf("%s: no outcome reported", name)
229 case strings.HasPrefix(got, "refused"):
230 case outside[name] && got == "tried":
231 default:
232 t.Errorf("%s: %s, want refused", name, got)
233 }
234 }
235 if t.Failed() {
236 t.Logf("outcomes: %v", out)
237 }
238
239 // The log saw the scene's own document arrive, so it was listening.
240 if hits := log.matching("/scenes/" + id + "/" + ref + " "); len(hits) != 1 {
241 t.Errorf("the request log saw the scene's document %d times, want once", len(hits))
242 }
243 if hits := log.matching("scene-probe"); len(hits) > 0 {
244 t.Errorf("the server saw requests from the scene: %v", hits)
245 }
246 if strings.Join(before, "; ") != strings.Join(after, "; ") {
247 t.Errorf("the cookies changed: %v, then %v", before, after)
248 }
249 if want := rig.Origin + "/d/" + sqid + "?slide=1"; page.URL != want || ran.Before.URL != want {
250 t.Errorf("the page is at %q, want %q", page.URL, want)
251 }
252 if page.Storage != ran.Before.Storage || !strings.Contains(page.Storage, `"page","mine"`) {
253 t.Errorf("the page's storage changed: %s, then %s", ran.Before.Storage, page.Storage)
254 }
255 if page.DOM != ran.Before.DOM {
256 t.Errorf("the page's document changed:\nbefore %s\nafter %s", ran.Before.DOM, page.DOM)
257 }
258
259 // Navigating its own frame ends the scene and reaches no other
260 // origin: the page's own policy (default-src 'self', so frame-src
261 // 'self') refuses the frame a document from elsewhere. Elsewhere is
262 // a server of our own on another origin, so "no request left" is
263 // something the test can see; example.com is tried too.
264 elsewhere := &requestLog{}
265 other := httptest.NewServer(elsewhere.wrap(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
266 w.Write([]byte("<!doctype html><p>elsewhere</p>"))
267 })))
268 defer other.Close()
269 if strings.HasPrefix(other.URL, rig.Origin) {
270 t.Fatalf("elsewhere %s is the app's own origin", other.URL)
271 }
272 // Same-origin, it reaches Slides and nothing else, and without the
273 // reader's cookies: the scene's origin matches nothing.
274 targets := []string{other.URL + "/?scene-navigate=elsewhere", "https://example.com/?scene-navigate=example", "/?scene-navigate=self"}
275 for _, target := range targets {
276 rig.Run(evalValue(nil, fmt.Sprintf(`new Promise((resolve) => {
277 const f = document.createElement('iframe');
278 f.title = 'scene';
279 f.src = %q + '?navigate=' + encodeURIComponent(%q);
280 document.body.append(f);
281 setTimeout(resolve, 1500);
282 })`, "/d/"+sqid+"/scenes/"+id+"/"+ref, target), awaitPromise))
283 }
284 var url string
285 rig.Run(evalInto(&url, `location.href`), browserCookies(rig.Origin, &after))
286 if hits := elsewhere.matching(""); len(hits) > 0 {
287 t.Errorf("a scene navigating its frame reached another origin: %v", hits)
288 }
289 if hits := log.matching("scene-navigate=example"); len(hits) > 0 {
290 t.Errorf("navigating to example.com came back to the app: %v", hits)
291 }
292 if hits := log.matching("scene-navigate=self"); len(hits) != 1 || !strings.HasSuffix(hits[0], " cookie=false") {
293 t.Errorf("a same-origin self-navigation: the app saw %v, want one request with no Cookie header", hits)
294 }
295 if want := rig.Origin + "/d/" + sqid + "?slide=1"; url != want {
296 t.Errorf("after the navigations the page is at %q, want %q", url, want)
297 }
298 if strings.Join(before, "; ") != strings.Join(after, "; ") {
299 t.Errorf("after the navigations the cookies changed: %v, then %v", before, after)
300 }
301}
302
303// TestTheExampleSceneAnswersReady: docs/scenes/example.html, posted to
304// the preview as the code panel posts it (a form into a named frame),
305// says nothing until it is told init, then answers ready once, within
306// the 3 seconds, and takes a state change without saying it again or
307// putting anything wrong on the page.
308func TestTheExampleSceneAnswersReady(t *testing.T) {
309 example, err := os.ReadFile("../../docs/scenes/example.html")
310 if err != nil {
311 t.Fatalf("read the example: %v", err)
312 }
313 if n := strings.Count(string(example), "\n"); n > 40 {
314 t.Errorf("the example is %d lines, want 40 at most", n)
315 }
316 rig, mailer := newRig(t)
317 browserSignIn(t, rig, mailer)
318 var deck string
319 rig.Run(evalInto(&deck, `(document.querySelector('a[href^="/d/"]')?.getAttribute('href') ?? '').replace(/\/edit$/, '')`))
320 if deck == "" {
321 t.Fatal("the deck list links no deck")
322 }
323 rig.Run(chromedp.Navigate(rig.Origin + deck + "?slide=1"))
324 rig.Screen("[slides-slide]", "the viewer")
325
326 var got struct {
327 Early, Ready, AfterState int
328 Millis float64
329 }
330 rig.Run(evalInto(&got, fmt.Sprintf(`(async (html, preview) => {
331 const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
332 const f = document.createElement('iframe');
333 f.name = 'scene-preview';
334 f.title = 'scene';
335 f.style.cssText = 'width: 640px; height: 360px';
336 document.body.append(f);
337 await sleep(100);
338 const messages = [];
339 addEventListener('message', (e) => { if (e.source === f.contentWindow) messages.push(e.data); });
340 const loaded = new Promise((r) => f.addEventListener('load', r, {once: true}));
341 const form = document.createElement('form');
342 form.method = 'post';
343 form.action = preview;
344 form.target = 'scene-preview';
345 form.hidden = true;
346 const field = document.createElement('textarea');
347 field.name = 'html';
348 field.value = html;
349 form.append(field);
350 document.body.append(form);
351 form.submit();
352 await loaded;
353 await sleep(300);
354 const early = messages.length;
355 const readies = () => messages.filter((m) => m && m.type === 'ready').length;
356 const start = performance.now();
357 f.contentWindow.postMessage({
358 type: 'init', state: 'one', size: {w: 640, h: 360},
359 words: {one: 'First', two: 'Second', three: 'Third'},
360 data: {states: [{id: 'one', colour: '#c0392b'}, {id: 'two', colour: '#2471a3'}, {id: 'three', colour: '#1e8449'}]},
361 reducedMotion: false, fonts: [],
362 }, '*');
363 while (readies() === 0 && performance.now() - start < 3000) await sleep(20);
364 const millis = performance.now() - start;
365 const ready = readies();
366 f.contentWindow.postMessage({type: 'state', state: 'two', animate: true}, '*');
367 f.contentWindow.postMessage({type: 'state', state: 'three', animate: false}, '*');
368 await sleep(500);
369 return {Early: early, Ready: ready, AfterState: readies(), Millis: millis};
370 })(%q, %q)`, example, deck+"/scenes/preview"), awaitPromise))
371 if got.Early != 0 {
372 t.Errorf("the example said %d things before init, want nothing", got.Early)
373 }
374 if got.Ready != 1 || got.Millis >= 3000 {
375 t.Errorf("the example answered ready %d times in %.0f ms, want once inside 3 s", got.Ready, got.Millis)
376 }
377 if got.AfterState != 1 {
378 t.Errorf("after two states the example has said ready %d times, want once", got.AfterState)
379 }
380 rig.Screen("[slides-slide]", "the example scene ran")
381}
382