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 slides
4
5// The smart door in a real Chromium, served through rastrillo's production
6// stack with Home configured, so the door offers Continue with Oficina ID.
7// Every state, the widest included (a long remembered address, Keymail, the
8// confirm step, the Keymail continuation, a refusal, the removal), reflows
9// at 320px (WCAG 1.4.10), every control on the card is a 24px target on its
10// smaller axis (2.5.8), and the Oficina ID button draws its glyph. The page
11// is put in the light scheme through the DevTools protocol, whatever the
12// machine's.
13//
14// CGO_ENABLED=0 go test -tags browser -run SmartDoorInABrowser ./internal/slides/
15//
16// SLIDES_SIGNIN_SHOTS=<dir> also writes a screenshot of each state there.
17
18import (
19 "context"
20 "io"
21 "log/slog"
22 "net/http"
23 "net/http/httptest"
24 "net/url"
25 "os"
26 "path/filepath"
27 "regexp"
28 "strings"
29 "sync"
30 "testing"
31 "time"
32
33 "amadan.net/oficina/estilo.git/brand"
34 "amadan.net/oficina/estilo.git/chrome"
35 "amadan.net/oficina/estilo.git/sky"
36 "amadan.net/rastrillo/rastrillo"
37 rauth "amadan.net/rastrillo/rastrillo/auth"
38 "amadan.net/rastrillo/rastrillo/harness"
39 "amadan.net/rastrillo/rastrillo/lastsignin"
40 "github.com/chromedp/cdproto/cdp"
41 "github.com/chromedp/cdproto/emulation"
42 "github.com/chromedp/chromedp"
43)
44
45// continuePreviewPath draws the Keymail continuation in preview (no meta
46// refresh, the link goes nowhere), so its layout can be measured without a
47// Keymail server.
48const continuePreviewPath = "/__test/continue"
49
50func TestSmartDoorInABrowser(t *testing.T) {
51 host := strings.TrimPrefix(homeTestOrigin, "https://")
52 mux, a, u, _ := homeFixtureKey(t)
53 served, closeServed, err := rastrillo.Handler(a.ServeOptions(rastrillo.Options{Logger: slog.New(slog.NewTextHandler(io.Discard, nil))}, mux))
54 if err != nil {
55 t.Fatal(err)
56 }
57 t.Cleanup(func() { _ = closeServed() })
58 var (
59 mu sync.Mutex
60 inject []*http.Cookie
61 )
62 rig := harness.New(t, func(string) http.Handler {
63 // connect answers only its own origin's host; the browser is on
64 // the rig's. The case's cookies are added here, since the
65 // remembered and session cookies are __Host- and Secure.
66 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
67 r.Host = host
68 mu.Lock()
69 for _, c := range inject {
70 r.AddCookie(c)
71 }
72 mu.Unlock()
73 if r.URL.Path == continuePreviewPath {
74 st := rauth.SigninState{Step: rauth.StepContinue, ContinueURL: "https://keymail.example.com/oauth/authorize"}
75 screen := chrome.SignInScreen{Icon: brand.Path("slides"), App: appName, Sky: sky.For(r.Host), State: st, Preview: true}
76 title, _ := signinTitle(screen)
77 a.renderPage(w, "signin", http.StatusOK, signinView{shell: a.publicShell(r, frame{title: title, signinPage: true}), Screen: screen})
78 return
79 }
80 served.ServeHTTP(w, r)
81 })
82 })
83 remembered := func(rec lastsignin.Record) func() []*http.Cookie {
84 return func() []*http.Cookie {
85 w := httptest.NewRecorder()
86 a.auth.RememberJar().Remember(w, rec)
87 return w.Result().Cookies()
88 }
89 }
90 long := "someone.with.a.rather.long.name@a-team-with-a-long-domain.example.com"
91 // A session the signed-in routes refuse, minted afresh for each load:
92 // the door ends it, as the next page would.
93 refused := func() []*http.Cookie {
94 return append(remembered(lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: long})(),
95 homeSession(t, a, "nobody-here@example.com", "magiclink"))
96 }
97
98 // An emailed link's confirm step.
99 mail := a.cfg.Mailer.(*homeTestMail)
100 begin := httptest.NewRequest(http.MethodPost, homeTestOrigin+"/signin", strings.NewReader(url.Values{"address": {u.Email}}.Encode()))
101 begin.Header.Set("Content-Type", "application/x-www-form-urlencoded")
102 begin.Header.Set("Origin", homeTestOrigin)
103 mux.ServeHTTP(httptest.NewRecorder(), begin)
104 a.FlushMail()
105 link, err := url.Parse(regexp.MustCompile(`https://[^\s<>]+/auth/verify\?token=[A-Za-z0-9_-]+`).FindString(mail.body))
106 if err != nil || link.Path == "" {
107 t.Fatalf("no link mailed: %v", err)
108 }
109 confirm := link.RequestURI()
110
111 type measure struct {
112 Light, Door bool
113 Overflow int
114 Small []string
115 GlyphW, GlyphH float64
116 Heading, Text string
117 }
118 const script = `(() => {
119 const card = document.querySelector('[estilo-signin]');
120 const small = [];
121 for (const el of card ? card.querySelectorAll('a, button, input:not([type=hidden])') : []) {
122 const r = el.getBoundingClientRect();
123 if (Math.min(r.width, r.height) < 24) small.push(el.outerHTML.slice(0, 80) + ' ' + r.width + 'x' + r.height);
124 }
125 const glyph = card && card.querySelector('a[href^="/signin/oficina"] svg');
126 const g = glyph ? glyph.getBoundingClientRect() : {width: 0, height: 0};
127 const h = card && card.querySelector('h1');
128 return {
129 Light: matchMedia('(prefers-color-scheme: light)').matches,
130 Door: !!card,
131 Overflow: document.documentElement.scrollWidth - innerWidth,
132 Small: small,
133 GlyphW: g.width, GlyphH: g.height,
134 Heading: h ? h.textContent : '',
135 Text: card ? card.textContent : '',
136 };
137 })()`
138 light := chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
139 _, err := cdp.Call(ctx, target, emulation.SetEmulatedMedia, emulation.SetEmulatedMediaParams{
140 Features: []*emulation.MediaFeature{{Name: "prefers-color-scheme", Value: "light"}},
141 })
142 return err
143 })
144 shots := os.Getenv("SLIDES_SIGNIN_SHOTS")
145 for _, c := range []struct {
146 name, path, heading string
147 cookies func() []*http.Cookie
148 glyph bool
149 says string
150 }{
151 {name: "first visit", path: "/signin", heading: "Sign in to Slides", glyph: true},
152 {name: "from a page", path: "/signin?return_to=" + url.QueryEscape("/d/7"), heading: "Sign in to Slides", glyph: true},
153 {name: "other ways", path: "/signin?ways=1", heading: "Other ways to sign in"},
154 {name: "other ways remembered", path: "/signin?ways=1&way=oficina", heading: "Other ways to sign in",
155 cookies: remembered(lastsignin.Record{Method: lastsignin.MethodFederated, Provider: lastsignin.ProviderOficina, Address: long})},
156 {name: "email", path: "/signin?way=email", heading: "Sign in to Slides"},
157 {name: "continue as", path: "/signin", heading: "Sign in to Slides",
158 cookies: remembered(lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: long})},
159 {name: "keymail", path: "/signin", heading: "Sign in to Slides",
160 cookies: remembered(lastsignin.Record{Method: lastsignin.MethodKeymail, Address: long})},
161 {name: "email only", path: "/signin/local", heading: "Sign in to Slides"},
162 {name: "problem", path: "/signin?err=rate", heading: "Sign in to Slides"},
163 {name: "refusal", path: "/signin", heading: "Sign in to Slides", cookies: refused, says: refusalText},
164 {name: "removed", path: "/signin?err=removed", heading: "Sign in to Slides",
165 cookies: remembered(lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: long}), says: removedText},
166 {name: "step-up", path: "/signin?reauth=1", heading: "Sign in to Slides"},
167 {name: "sent", path: "/signin?sent=1", heading: "Check your email"},
168 {name: "confirm", path: confirm, heading: "Sign in to Slides"},
169 {name: "continuation", path: continuePreviewPath, heading: "Taking you to Keymail"},
170 {name: "signed out", path: "/signed-out", heading: "You’re signed out"},
171 } {
172 for _, width := range []int64{320, 1280} {
173 mu.Lock()
174 inject = nil
175 if c.cookies != nil {
176 inject = c.cookies()
177 }
178 mu.Unlock()
179 ctx, cancel := context.WithTimeout(rig.Context(), 30*time.Second)
180 var m measure
181 err := chromedp.Do(ctx,
182 light,
183 chromedp.EmulateViewport(width, 900),
184 chromedp.Navigate(rig.Origin+c.path),
185 chromedp.WaitVisible(chromedp.CSS("[estilo-signin] h1")),
186 harness.Into(&m, chromedp.Evaluate[measure](script)),
187 )
188 if err == nil && shots != "" {
189 var shot []byte
190 shot, err = chromedp.Run(ctx, chromedp.CaptureScreenshot())
191 if err == nil {
192 name := strings.ReplaceAll(c.name, " ", "-") + "-" + map[int64]string{320: "phone", 1280: "desk"}[width] + ".png"
193 err = os.WriteFile(filepath.Join(shots, name), shot, 0o644)
194 }
195 }
196 cancel()
197 if err != nil {
198 t.Fatalf("%s at %dpx: %v", c.name, width, err)
199 }
200 if !m.Light {
201 t.Fatal("the page is not in the light scheme")
202 }
203 if !m.Door || m.Heading != c.heading {
204 t.Errorf("%s at %dpx: door=%v heading %q, want %q", c.name, width, m.Door, m.Heading, c.heading)
205 }
206 if c.says != "" && !strings.Contains(m.Text, c.says) {
207 t.Errorf("%s at %dpx does not say %q:\n%s", c.name, width, c.says, m.Text)
208 }
209 if m.Overflow > 0 {
210 t.Errorf("%s at %dpx scrolls sideways by %dpx", c.name, width, m.Overflow)
211 }
212 if len(m.Small) > 0 {
213 t.Errorf("%s at %dpx: targets under 24px: %q", c.name, width, m.Small)
214 }
215 if c.glyph && (m.GlyphW < 12 || m.GlyphH < 12) {
216 t.Errorf("%s at %dpx: the Oficina glyph is %vx%v", c.name, width, m.GlyphW, m.GlyphH)
217 }
218 }
219 }
220}
221