package slidestest import ( "bufio" "context" "crypto/rand" "encoding/base64" "encoding/json" "net/http" "net/http/httptest" "net/url" "regexp" "strconv" "strings" "sync" "testing" "time" ) // pressAnswer is the server's answer to a press asked for as JSON: the // talk's absolute position after it, the session's own sequence and the // deck's (presenting_position.go's positionAnswer). type pressAnswer struct { Slide string `json:"slide"` Step int `json:"step"` Mode string `json:"mode"` Black bool `json:"black"` Seq int64 `json:"seq"` DeckSeq int64 `json:"deckSeq"` } // newPressID is what a window sends with each press: 16 random bytes, // base64url, so a press sent twice can be told from two presses. func newPressID(t *testing.T) string { t.Helper() raw := make([]byte, 16) if _, err := rand.Read(raw); err != nil { t.Fatalf("press id: %v", err) } return base64.RawURLEncoding.EncodeToString(raw) } // pressRequest is one press as a window posts it: a form, asking for // JSON, with a browser's same-origin evidence. token is sent when it is // not empty and cookies when there are some, because who may drive is // half of what these tests are about. func pressRequest(t *testing.T, a *testApp, session, token string, form url.Values, cookies []*http.Cookie) *httptest.ResponseRecorder { t.Helper() body := url.Values{} for k, vs := range form { body[k] = vs } if token != "" { body.Set("t", token) } req := httptest.NewRequest(http.MethodPost, "/p/"+session+"/command", strings.NewReader(body.Encode())) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Accept", "application/json") req.Header.Set("Origin", testOrigin) req.Header.Set("Sec-Fetch-Site", "same-origin") for _, c := range cookies { req.AddCookie(c) } rec := httptest.NewRecorder() a.ServeHTTP(rec, req) return rec } // press sends one press and insists on a JSON position back. func press(t *testing.T, a *testApp, session, token string, form url.Values, cookies []*http.Cookie) pressAnswer { t.Helper() rec := pressRequest(t, a, session, token, form, cookies) if rec.Code != http.StatusOK { t.Fatalf("press %v: status %d, want 200\n%s", form, rec.Code, rec.Body) } if ct := rec.Header().Get("Content-Type"); !strings.HasPrefix(ct, "application/json") { t.Fatalf("press %v: Content-Type %q, want JSON", form, ct) } var out pressAnswer if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil { t.Fatalf("press %v: %v\n%s", form, err, rec.Body) } return out } // op is a press's form: the op and a fresh press id. func op(t *testing.T, name string) url.Values { return url.Values{"op": {name}, "press": {newPressID(t)}} } // stepsDeck is a talk to press through, made over the API: "steps" // with four presses, "plain" with none, "extra" for the full talk only, // "parked" in no talk, and "last". It returns the deck's path. func stepsDeck(t *testing.T, a *testApp, cookies []*http.Cookie) string { t.Helper() token := mintAgent(t, a, cookies, "steps-deck") sqid := apiDeck(t, a, token, "Steps") view := apiJSON(t, a, http.MethodGet, "/api/v1/decks/"+sqid, token, "", http.StatusOK) slides, _ := view["slides"].([]any) var ops []string for _, s := range slides { id, _ := s.(map[string]any)["id"].(string) ops = append(ops, `{"op":"remove_slide","id":`+quote(id)+`}`) } ops = append(ops, `{"op":"add_slide","id":"steps","layout":"flow","template":"title-body"}`) for i, word := range []string{"one", "two", "three", "four"} { id := quote("b" + string(rune('1'+i))) ops = append(ops, `{"op":"add_block","slide":"steps","id":`+id+`,"type":"text","region":"body","markdown":`+quote(word)+`}`, `{"op":"set_block","slide":"steps","id":`+id+`,"step":`+string(rune('1'+i))+`}`) } for _, id := range []string{"plain", "extra", "parked", "last"} { ops = append(ops, `{"op":"add_slide","id":`+quote(id)+`,"layout":"flow","template":"title-body"}`) } ops = append(ops, `{"op":"set_slide","id":"extra","talk":"full"}`, `{"op":"set_slide","id":"parked","talk":"parked"}`) apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", token, `{"ops":[`+strings.Join(ops, ",")+`]}`, http.StatusOK) return "/d/" + sqid } // rowPosition reads the session's position straight off its row. func rowPosition(t *testing.T, a *testApp, session string) (slideID string, step int, seq int64) { t.Helper() row := a.db.G.Raw("SELECT slide_id, step, seq FROM presentations WHERE sqid = ?", session).Row() if err := row.Scan(&slideID, &step, &seq); err != nil { t.Fatalf("read the session's position: %v", err) } return slideID, step, seq } // openStream opens the session's SSE stream on a real server. func openStream(t *testing.T, a *testApp, path string) *bufio.Reader { t.Helper() srv := httptest.NewServer(a) t.Cleanup(srv.Close) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) t.Cleanup(cancel) req, err := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL+path, nil) if err != nil { t.Fatalf("build the stream request: %v", err) } resp, err := http.DefaultClient.Do(req) if err != nil { t.Fatalf("open the stream: %v", err) } t.Cleanup(func() { resp.Body.Close() }) return bufio.NewReader(resp.Body) } // streamEvent is the stream's event, with the position fields. type streamEvent struct { Slide int `json:"slide"` Blackout bool `json:"blackout"` Ended bool `json:"ended"` SlideID string `json:"slideId"` Step int `json:"step"` Mode string `json:"mode"` Seq int64 `json:"seq"` } func nextPositionEvent(t *testing.T, r *bufio.Reader) streamEvent { t.Helper() var e streamEvent data := nextSlideEvent(t, r) if err := json.Unmarshal([]byte(data), &e); err != nil { t.Fatalf("the stream's event %q: %v", data, err) } return e } // TestLaptopAndPhoneCrossingPressesBothCount: the laptop and the phone // both press next from step 2 of a four-step slide at the same moment. // The server orders them, so the talk reaches step 4 rather than one // of the presses being lost (S18). func TestLaptopAndPhoneCrossingPressesBothCount(t *testing.T) { a := newApp(t) cookies := signedIn(t, a, allowedAddress) session, token := startPresenting(t, a, stepsDeck(t, a, cookies), cookies) press(t, a, session, token, op(t, "next"), nil) at := press(t, a, session, token, op(t, "next"), nil) if at.Slide != "steps" || at.Step != 2 { t.Fatalf("two nexts reached %+v, want steps at step 2", at) } var wg sync.WaitGroup answers := make([]pressAnswer, 2) codes := make([]int, 2) start := make(chan struct{}) for i := range 2 { wg.Add(1) go func() { defer wg.Done() <-start var rec *httptest.ResponseRecorder if i == 0 { rec = pressRequest(t, a, session, "", op(t, "next"), cookies) // the laptop } else { rec = pressRequest(t, a, session, token, op(t, "next"), nil) // the phone } codes[i] = rec.Code _ = json.Unmarshal(rec.Body.Bytes(), &answers[i]) }() } close(start) wg.Wait() for i, code := range codes { if code != http.StatusOK { t.Fatalf("press %d: status %d, want 200", i, code) } } if answers[0].Seq == answers[1].Seq { t.Errorf("both presses answered seq %d; each press must move the sequence", answers[0].Seq) } slide, step, seq := rowPosition(t, a, session) if slide != "steps" || step != 4 { t.Errorf("after two crossing presses the talk is at %s step %d, want steps step 4", slide, step) } if seq != at.Seq+2 { t.Errorf("after two crossing presses seq is %d, want %d", seq, at.Seq+2) } } // TestAPressSentTwiceCountsOnce: a window that did not hear its answer // sends the same press again. The second answers where the talk is, // moves nothing, publishes nothing and leaves the sequence alone. Only // the newest 64 ids are kept per session. func TestAPressSentTwiceCountsOnce(t *testing.T) { a := newApp(t) cookies := signedIn(t, a, allowedAddress) session, token := startPresenting(t, a, stepsDeck(t, a, cookies), cookies) events := openStream(t, a, "/p/"+session+"/stream") nextPositionEvent(t, events) // the connect event form := op(t, "next") first := press(t, a, session, token, form, nil) again := press(t, a, session, token, form, nil) if again != first { t.Errorf("the press sent again answered %+v, want the same position %+v", again, first) } if first.Slide != "steps" || first.Step != 1 { t.Errorf("one next answered %+v, want steps at step 1", first) } if _, step, seq := rowPosition(t, a, session); step != 1 || seq != first.Seq { t.Errorf("after a repeated press the row is at step %d seq %d, want step 1 seq %d", step, seq, first.Seq) } // The stream heard the first and nothing for the second: the event // after the first press's is the next press's own. if e := nextPositionEvent(t, events); e.Seq != first.Seq || e.Step != 1 || e.SlideID != "steps" { t.Errorf("the first press's event is %+v, want steps step 1 seq %d", e, first.Seq) } second := press(t, a, session, token, op(t, "next"), nil) if e := nextPositionEvent(t, events); e.Seq != second.Seq { t.Errorf("the event after the repeat is seq %d, want the next press's seq %d", e.Seq, second.Seq) } // A malformed press id is refused, and so is a press with none: // without an id a press sent twice would count twice. _, _, before := rowPosition(t, a, session) bad := url.Values{"op": {"next"}, "press": {"short"}} if rec := pressRequest(t, a, session, token, bad, nil); rec.Code != http.StatusUnprocessableEntity { t.Errorf("a press id of %q: status %d, want 422", "short", rec.Code) } if rec := pressRequest(t, a, session, token, url.Values{"op": {"next"}}, nil); rec.Code != http.StatusUnprocessableEntity { t.Errorf("a press with no id: status %d, want 422", rec.Code) } if _, _, seq := rowPosition(t, a, session); seq != before { t.Errorf("refused presses moved the sequence from %d to %d", before, seq) } // Sixty-four more presses push the first id out, and the table // keeps sixty-four for the session. for range 64 { press(t, a, session, token, op(t, "blackout"), nil) } var kept int64 if err := a.db.G.Raw(`SELECT COUNT(*) FROM presentation_presses WHERE presentation_id = (SELECT id FROM presentations WHERE sqid = ?)`, session).Scan(&kept).Error; err != nil { t.Fatalf("count press ids: %v", err) } if kept != 64 { t.Errorf("the session keeps %d press ids, want 64", kept) } _, _, before = rowPosition(t, a, session) if late := press(t, a, session, token, form, nil); late.Seq != before+1 { t.Errorf("a press id older than the newest 64 answered seq %d, want it counted as new (%d)", late.Seq, before+1) } } // TestResumeTakesTheWindowsPosition: a window that pressed while the // network was down sends resume with where it got to, and the server // takes it, settled into the deck. func TestResumeTakesTheWindowsPosition(t *testing.T) { a := newApp(t) cookies := signedIn(t, a, allowedAddress) session, token := startPresenting(t, a, stepsDeck(t, a, cookies), cookies) press(t, a, session, token, op(t, "next"), nil) // the phone, meanwhile form := op(t, "resume") form.Set("at_slide", "extra") form.Set("at_step", "0") form.Set("at_mode", "full") got := press(t, a, session, "", form, cookies) if got.Slide != "extra" || got.Step != 0 || got.Mode != "full" { t.Errorf("resume answered %+v, want extra step 0 in full", got) } // The stored number is the slide's place in the full talk. surface := mustGet(t, a, "/p/"+session, http.StatusOK, nil).Body.String() if !strings.Contains(surface, `data-slide="3"`) { t.Errorf("after resuming on the third slide of the full talk the surface does not say slide 3:\n%s", surface) } // A step past the slide's presses settles onto its last. form = op(t, "resume") form.Set("at_slide", "steps") form.Set("at_step", "9") form.Set("at_mode", "core") if got := press(t, a, session, "", form, cookies); got.Slide != "steps" || got.Step != 4 || got.Mode != "core" { t.Errorf("resume past the last press answered %+v, want steps step 4 in core", got) } // A mode that is not one is refused. form = op(t, "resume") form.Set("at_slide", "steps") form.Set("at_mode", "sideways") if rec := pressRequest(t, a, session, "", form, cookies); rec.Code != http.StatusUnprocessableEntity { t.Errorf("resume in mode sideways: status %d, want 422", rec.Code) } } // TestPresentAgainLeavesThePhonePaired: pressing Present again rejoins // the talk and leaves the phone's token working (S19). func TestPresentAgainLeavesThePhonePaired(t *testing.T) { a := newApp(t) cookies := signedIn(t, a, allowedAddress) path := sampleDeck(t, a, cookies) session, token := startPresenting(t, a, path, cookies) rec := post(t, a, path+"/present", nil, cookies...) if rec.Code != http.StatusSeeOther { t.Fatalf("pressing Present again: status %d, want 303\n%s", rec.Code, rec.Body) } if loc := rec.Header().Get("Location"); loc != "/p/"+session { t.Errorf("pressing Present again went to %q, want the same talk /p/%s", loc, session) } if rec := command(t, a, session, "next", token, "", nil); rec.Code != http.StatusNoContent { t.Errorf("the phone's token after Present again: status %d, want 204", rec.Code) } } // TestARevokedTokenDrivesNothing: once the phone's token is replaced, the // old one moves nothing and reads nothing. func TestARevokedTokenDrivesNothing(t *testing.T) { a := newApp(t) cookies := signedIn(t, a, allowedAddress) session, old := startPresenting(t, a, stepsDeck(t, a, cookies), cookies) press(t, a, session, old, op(t, "next"), nil) pairPhone(t, a, session, cookies) _, _, before := rowPosition(t, a, session) if rec := pressRequest(t, a, session, old, op(t, "next"), nil); rec.Code != http.StatusNotFound { t.Errorf("a press with a replaced token: status %d, want 404", rec.Code) } if rec := command(t, a, session, "next", old, "", nil); rec.Code != http.StatusNotFound { t.Errorf("a form command with a replaced token: status %d, want 404", rec.Code) } mustGet(t, a, "/p/"+session+"/remote?t="+old, http.StatusNotFound, nil) if slide, step, seq := rowPosition(t, a, session); slide != "steps" || step != 1 || seq != before { t.Errorf("a replaced token moved the talk to %s step %d seq %d", slide, step, seq) } } // TestTheSignedInPresenterMayDriveWithoutAToken: the presenter's own // session is enough to drive their own talk (S19). func TestTheSignedInPresenterMayDriveWithoutAToken(t *testing.T) { a := newApp(t) cookies := signedIn(t, a, allowedAddress) session, _ := startPresenting(t, a, stepsDeck(t, a, cookies), cookies) got := press(t, a, session, "", op(t, "next"), cookies) if got.Slide != "steps" || got.Step != 1 { t.Errorf("the presenter's press answered %+v, want steps step 1", got) } // And a form with no JSON asked for keeps the old answers. rec := post(t, a, "/p/"+session+"/command", op(t, "next"), cookies...) if rec.Code != http.StatusSeeOther && rec.Code != http.StatusNoContent { t.Errorf("the presenter's form press: status %d, want 303 or 204\n%s", rec.Code, rec.Body) } if _, step, _ := rowPosition(t, a, session); step != 2 { t.Errorf("after the presenter's two presses the talk is at step %d, want 2", step) } } // TestSomeoneElseSignedInMayNotDrive: being signed in is not being the // presenter. func TestSomeoneElseSignedInMayNotDrive(t *testing.T) { a := newSharedApp(t) mine := signedIn(t, a, allowedAddress) theirs := signedIn(t, a, otherAddress) session, _ := startPresenting(t, a, stepsDeck(t, a, mine), mine) if rec := pressRequest(t, a, session, "", op(t, "next"), theirs); rec.Code != http.StatusNotFound { t.Errorf("somebody else's press: status %d, want 404", rec.Code) } if rec := pressRequest(t, a, session, "", op(t, "next"), nil); rec.Code != http.StatusNotFound { t.Errorf("a press from nobody: status %d, want 404", rec.Code) } if _, step, _ := rowPosition(t, a, session); step != 0 { t.Errorf("a refused press moved the talk to step %d", step) } } // TestACrossSitePressIsRefused: the presenter's cookie makes a press // from their browser enough, so another site must not be able to make // that browser press. The app-wide origin check refuses it. func TestACrossSitePressIsRefused(t *testing.T) { a := newApp(t) cookies := signedIn(t, a, allowedAddress) session, _ := startPresenting(t, a, stepsDeck(t, a, cookies), cookies) form := op(t, "next") req := httptest.NewRequest(http.MethodPost, "/p/"+session+"/command", strings.NewReader(form.Encode())) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Accept", "application/json") req.Header.Set("Origin", "https://elsewhere.example") req.Header.Set("Sec-Fetch-Site", "cross-site") for _, c := range cookies { req.AddCookie(c) } rec := httptest.NewRecorder() a.ServeHTTP(rec, req) if rec.Code != http.StatusForbidden { t.Errorf("a cross-site press with the presenter's cookie: status %d, want 403", rec.Code) } if _, step, _ := rowPosition(t, a, session); step != 0 { t.Errorf("a cross-site press moved the talk to step %d", step) } } // TestCommandsOnAnEmptyTalk: a deck with no slides, or with every slide // parked, has nowhere to go, and every press still answers without an // error. func TestCommandsOnAnEmptyTalk(t *testing.T) { a := newApp(t) cookies := signedIn(t, a, allowedAddress) parked := stepsDeck(t, a, cookies) token := mintAgent(t, a, cookies, "park-everything") sqid := strings.TrimPrefix(parked, "/d/") var ops []string for _, id := range []string{"steps", "plain", "extra", "last"} { ops = append(ops, `{"op":"set_slide","id":`+quote(id)+`,"talk":"parked"}`) } apiJSON(t, a, http.MethodPost, "/api/v1/decks/"+sqid+"/ops", token, `{"ops":[`+strings.Join(ops, ",")+`]}`, http.StatusOK) for name, path := range map[string]string{ "empty": strings.TrimSuffix(emptyDeck(t, a, cookies), "/edit"), "parked": parked, } { t.Run(name, func(t *testing.T) { session, token := startPresenting(t, a, path, cookies) for _, name := range []string{"next", "prev", "first", "last", "mode", "blackout", "timer-reset", "resume", "goto"} { form := op(t, name) if name == "goto" { form.Set("slide", "parked") } if name == "resume" { form.Set("at_slide", "steps") } got := press(t, a, session, token, form, nil) if got.Slide != "" || got.Step != 0 { t.Errorf("%s on an empty talk answered %+v, want nowhere", name, got) } } mustGet(t, a, "/p/"+session, http.StatusOK, nil) }) } } // TestASessionFromBeforeTheDeployKeepsItsIndex: a talk begun before // positions existed carries on by its index for its remaining hours, // and the new presses are not ones it knows. func TestASessionFromBeforeTheDeployKeepsItsIndex(t *testing.T) { a := newApp(t) cookies := signedIn(t, a, allowedAddress) path := sampleDeck(t, a, cookies) session, token := startPresenting(t, a, path, cookies) // What migration 0009 leaves on a row that was already there: the // new columns, all NULL. if err := a.db.G.Exec(`UPDATE presentations SET positional = NULL, slide_id = NULL, step = NULL, mode = NULL, seq = NULL, timer_at = NULL, slide = 2 WHERE sqid = ?`, session).Error; err != nil { t.Fatalf("make the session a pre-deploy one: %v", err) } if rec := command(t, a, session, "next", token, "", nil); rec.Code != http.StatusNoContent { t.Fatalf("next on a pre-deploy session: status %d, want 204\n%s", rec.Code, rec.Body) } surface := mustGet(t, a, "/p/"+session, http.StatusOK, nil).Body.String() if !strings.Contains(surface, "4 / 8") { t.Errorf("next from index 2 does not show slide 4:\n%s", surface) } var untouched int64 if err := a.db.G.Raw(`SELECT COUNT(*) FROM presentations WHERE sqid = ? AND positional IS NULL AND slide_id IS NULL AND seq IS NULL AND timer_at IS NULL`, session).Scan(&untouched).Error; err != nil { t.Fatalf("read the session: %v", err) } if untouched != 1 { t.Error("a pre-deploy session gained a position, a sequence or a timer") } for _, name := range []string{"first", "last", "mode", "timer-reset", "resume"} { if rec := command(t, a, session, name, token, "", nil); rec.Code != http.StatusUnprocessableEntity { t.Errorf("%s on a pre-deploy session: status %d, want 422", name, rec.Code) } } // The presenter's cookie drives it too, by its index: Present // again rejoins it without a token (S19), and a talk the presenter // can no longer drive would be no talk at all. if rec := pressRequest(t, a, session, "", op(t, "prev"), cookies); rec.Code != http.StatusNoContent { t.Errorf("the presenter's tokenless press on a pre-deploy session: status %d, want 204", rec.Code) } if surface := mustGet(t, a, "/p/"+session, http.StatusOK, nil).Body.String(); !strings.Contains(surface, "3 / 8") { t.Errorf("the presenter's prev from index 3 does not show slide 3:\n%s", surface) } } // TestTheFirstPressStartsTheTimer: the timer starts at the first move, // not when the session opens, and timer-reset clears it until the next. func TestTheFirstPressStartsTheTimer(t *testing.T) { a := newApp(t) cookies := signedIn(t, a, allowedAddress) session, token := startPresenting(t, a, stepsDeck(t, a, cookies), cookies) timerSet := func() bool { t.Helper() var n int64 if err := a.db.G.Raw("SELECT COUNT(*) FROM presentations WHERE sqid = ? AND timer_at IS NOT NULL", session).Scan(&n).Error; err != nil { t.Fatalf("read the timer: %v", err) } return n == 1 } timerAt := func() string { t.Helper() var at string if err := a.db.G.Raw("SELECT timer_at FROM presentations WHERE sqid = ?", session).Row().Scan(&at); err != nil { t.Fatalf("read the timer: %v", err) } return at } if timerSet() { t.Fatal("the timer runs before anybody pressed anything") } press(t, a, session, token, op(t, "next"), nil) if !timerSet() { t.Fatal("the first press did not start the timer") } started := timerAt() time.Sleep(5 * time.Millisecond) press(t, a, session, token, op(t, "next"), nil) if again := timerAt(); again != started { t.Errorf("a later press restarted the timer: %s then %s", started, again) } press(t, a, session, token, op(t, "timer-reset"), nil) if timerSet() { t.Error("timer-reset left the timer running") } press(t, a, session, token, op(t, "prev"), nil) if !timerSet() { t.Error("the first press after a reset did not start the timer") } } // pressField finds the press ids on a page's control forms. var pressField = regexp.MustCompile(`name="press" value="([^"]*)"`) // TestEveryControlFormCarriesAFreshPressID: each control form carries a // press id, fresh on every render, so a form resubmitted by a reload // counts once and a page loaded again makes new presses. func TestEveryControlFormCarriesAFreshPressID(t *testing.T) { a := newApp(t) cookies := signedIn(t, a, allowedAddress) session, token := startPresenting(t, a, stepsDeck(t, a, cookies), cookies) seen := map[string]bool{} for _, page := range []string{ "/p/" + session + "/remote?t=" + token, "/p/" + session + "/remote?t=" + token, "/p/" + session + "/notes?t=" + token, "/p/" + session + "?t=" + token, } { body := mustGet(t, a, page, http.StatusOK, nil).Body.String() forms := strings.Count(body, `
\s*\s*