oficina / memoria Public

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

Plain git — no account needed to clone.

Download

Download this file

1//go:build browser
2
3package memoria
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, the 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. Slides' test (internal/slides/signin_browser_test.go), ported.
13//
14// CGO_ENABLED=0 go test -tags browser -run SmartDoorInABrowser ./internal/memoria/
15//
16// MEMORIA_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 "strings"
28 "sync"
29 "testing"
30 "time"
31
32 "amadan.net/oficina/estilo.git/chrome"
33 "amadan.net/oficina/estilo.git/sky"
34 "amadan.net/rastrillo/rastrillo"
35 rauth "amadan.net/rastrillo/rastrillo/auth"
36 "amadan.net/rastrillo/rastrillo/harness"
37 "amadan.net/rastrillo/rastrillo/lastsignin"
38 "github.com/chromedp/cdproto/cdp"
39 "github.com/chromedp/cdproto/emulation"
40 "github.com/chromedp/chromedp"
41)
42
43// Test-only paths the rig answers itself: the Keymail continuation in
44// preview (no meta refresh, the link goes nowhere), so its layout can be
45// measured without a Keymail server; and the refusal auth's Refused hook
46// draws after a verified address Admit refuses.
47const (
48 continuePreviewPath = "/__test/continue"
49 refusalPath = "/__test/refused"
50)
51
52func TestSmartDoorInABrowser(t *testing.T) {
53 host := strings.TrimPrefix(homeTestOrigin, "https://")
54 f := newHomeRouterFixture(t)
55 a := f.app
56 served, closeServed, err := rastrillo.Handler(a.ServeOptions(rastrillo.Options{Logger: slog.New(slog.NewTextHandler(io.Discard, nil))}, f.handler.(*http.ServeMux)))
57 if err != nil {
58 t.Fatal(err)
59 }
60 t.Cleanup(func() { _ = closeServed() })
61 var (
62 mu sync.Mutex
63 inject []*http.Cookie
64 )
65 rig := harness.New(t, func(string) http.Handler {
66 // connect answers only its own origin's host; the browser is on
67 // the rig's. The case's cookies are added here, since the
68 // remembered and session cookies are __Host- and Secure.
69 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
70 r.Host = host
71 mu.Lock()
72 for _, c := range inject {
73 r.AddCookie(c)
74 }
75 mu.Unlock()
76 switch r.URL.Path {
77 case continuePreviewPath:
78 st := rauth.SigninState{Step: rauth.StepContinue, ContinueURL: "https://keymail.example.com/oauth/authorize"}
79 screen := chrome.SignInScreen{Icon: doorIcon(), App: appName, Sky: sky.For(r.Host), State: st, Preview: true}
80 title, _ := signinTitle(screen)
81 renderStatus(w, "signin", signinPage{page: page{Frame: a.frameAs(r, viewer{}, frame{title: title, signinPage: true})}, Screen: &screen}, http.StatusOK)
82 return
83 case refusalPath:
84 r.URL.Path = "/auth/callback"
85 a.refused(w, r, rauthIdentity("someone@else.test"))
86 return
87 }
88 served.ServeHTTP(w, r)
89 })
90 })
91 remembered := func(rec lastsignin.Record) func() []*http.Cookie {
92 return func() []*http.Cookie {
93 w := httptest.NewRecorder()
94 a.auth.RememberJar().Remember(w, rec)
95 return w.Result().Cookies()
96 }
97 }
98 long := "someone.with.a.rather.long.name@a-team-with-a-long-domain.example.com"
99 // A session the signed-in routes end as removed (an address taken off
100 // the owners list), minted afresh for each load: the door ends it.
101 removedSession := func() []*http.Cookie {
102 br := f.fresh()
103 br.session(t, "nobody-here@example.com", "magiclink", time.Now())
104 return append(remembered(lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: long})(), br.sessionCookie())
105 }
106
107 // An emailed link's confirm step.
108 f.mail.body = ""
109 f.fresh().do(http.MethodPost, "/auth/begin", url.Values{"address": {"alice@example.test"}, "force": {"1"}}.Encode())
110 link, err := url.Parse(signinLink.FindString(f.mail.body))
111 if err != nil || link.Path == "" {
112 t.Fatalf("no link mailed: %v", err)
113 }
114 confirm := link.RequestURI()
115
116 type measure struct {
117 Light, Door bool
118 Overflow int
119 Small []string
120 GlyphW, GlyphH float64
121 Heading, Text string
122 }
123 const script = `(() => {
124 const card = document.querySelector('[estilo-signin]');
125 const small = [];
126 for (const el of card ? card.querySelectorAll('a, button, input:not([type=hidden])') : []) {
127 const r = el.getBoundingClientRect();
128 if (Math.min(r.width, r.height) < 24) small.push(el.outerHTML.slice(0, 80) + ' ' + r.width + 'x' + r.height);
129 }
130 const glyph = card && card.querySelector('a[href^="/signin/oficina"] svg');
131 const g = glyph ? glyph.getBoundingClientRect() : {width: 0, height: 0};
132 const h = card && card.querySelector('h1');
133 return {
134 Light: matchMedia('(prefers-color-scheme: light)').matches,
135 Door: !!card,
136 Overflow: document.documentElement.scrollWidth - innerWidth,
137 Small: small,
138 GlyphW: g.width, GlyphH: g.height,
139 Heading: h ? h.textContent : '',
140 Text: card ? card.textContent : '',
141 };
142 })()`
143 light := chromedp.Func(func(ctx context.Context, target *chromedp.Target) error {
144 _, err := cdp.Call(ctx, target, emulation.SetEmulatedMedia, emulation.SetEmulatedMediaParams{
145 Features: []*emulation.MediaFeature{{Name: "prefers-color-scheme", Value: "light"}},
146 })
147 return err
148 })
149 shots := os.Getenv("MEMORIA_SIGNIN_SHOTS")
150 for _, c := range []struct {
151 name, path, heading string
152 cookies func() []*http.Cookie
153 glyph bool
154 says string
155 }{
156 {name: "first visit", path: "/signin", heading: "Sign in to Memoria", glyph: true},
157 {name: "from a page", path: "/signin?return_to=" + url.QueryEscape("/documents/7"), heading: "Sign in to Memoria", glyph: true},
158 {name: "other ways", path: "/signin?ways=1", heading: "Other ways to sign in"},
159 {name: "other ways remembered", path: "/signin?ways=1&way=oficina", heading: "Other ways to sign in",
160 cookies: remembered(lastsignin.Record{Method: lastsignin.MethodFederated, Provider: lastsignin.ProviderOficina, Address: long})},
161 {name: "email", path: "/signin?way=email", heading: "Sign in to Memoria"},
162 {name: "continue as", path: "/signin", heading: "Sign in to Memoria",
163 cookies: remembered(lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: long})},
164 {name: "keymail", path: "/signin", heading: "Sign in to Memoria",
165 cookies: remembered(lastsignin.Record{Method: lastsignin.MethodKeymail, Address: long})},
166 {name: "email only", path: "/signin/local", heading: "Sign in to Memoria"},
167 {name: "problem", path: "/signin?err=rate", heading: "Sign in to Memoria"},
168 {name: "refusal", path: refusalPath, heading: "Sign in to Memoria", says: signinRefusal},
169 {name: "removed session", path: "/signin", heading: "Sign in to Memoria", cookies: removedSession, says: signinRemoved},
170 {name: "removed", path: "/signin?err=removed", heading: "Sign in to Memoria",
171 cookies: remembered(lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: long}), says: signinRemoved},
172 {name: "step-up", path: "/signin?reauth=1", heading: "Sign in to Memoria"},
173 {name: "sent", path: "/signin?sent=1", heading: "Check your email"},
174 {name: "confirm", path: confirm, heading: "Sign in to Memoria"},
175 {name: "continuation", path: continuePreviewPath, heading: "Signing you in"},
176 {name: "signed out", path: "/signed-out", heading: "You’re signed out"},
177 } {
178 for _, width := range []int64{320, 1280} {
179 mu.Lock()
180 inject = nil
181 if c.cookies != nil {
182 inject = c.cookies()
183 }
184 mu.Unlock()
185 ctx, cancel := context.WithTimeout(rig.Context(), 30*time.Second)
186 var m measure
187 err := chromedp.Do(ctx,
188 light,
189 chromedp.EmulateViewport(width, 900),
190 chromedp.Navigate(rig.Origin+c.path),
191 chromedp.WaitVisible(chromedp.CSS("[estilo-signin] h1")),
192 harness.Into(&m, chromedp.Evaluate[measure](script)),
193 )
194 if err == nil && shots != "" {
195 var shot []byte
196 shot, err = chromedp.Run(ctx, chromedp.CaptureScreenshot())
197 if err == nil {
198 name := strings.ReplaceAll(c.name, " ", "-") + "-" + map[int64]string{320: "phone", 1280: "desk"}[width] + ".png"
199 err = os.WriteFile(filepath.Join(shots, name), shot, 0o644)
200 }
201 }
202 cancel()
203 if err != nil {
204 t.Fatalf("%s at %dpx: %v", c.name, width, err)
205 }
206 if !m.Light {
207 t.Fatal("the page is not in the light scheme")
208 }
209 if !m.Door || m.Heading != c.heading {
210 t.Errorf("%s at %dpx: door=%v heading %q, want %q", c.name, width, m.Door, m.Heading, c.heading)
211 }
212 if c.says != "" && !strings.Contains(m.Text, c.says) {
213 t.Errorf("%s at %dpx does not say %q:\n%s", c.name, width, c.says, m.Text)
214 }
215 if m.Overflow > 0 {
216 t.Errorf("%s at %dpx scrolls sideways by %dpx", c.name, width, m.Overflow)
217 }
218 if len(m.Small) > 0 {
219 t.Errorf("%s at %dpx: targets under 24px: %q", c.name, width, m.Small)
220 }
221 if c.glyph && (m.GlyphW < 12 || m.GlyphH < 12) {
222 t.Errorf("%s at %dpx: the Oficina glyph is %vx%v", c.name, width, m.GlyphW, m.GlyphH)
223 }
224 }
225 }
226}
227