oficina / docs Public

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

Plain git — no account needed to clone.

Download

Download this file

1package docs
2
3// The smart door (Home spec 2026-11-19-smart-door.md, step 6; home/connect
4// MIGRATING.md): every route and state the door answers, remembering
5// Oficina ID in MintHomeSession, and the signed-out page's Forget, chained
6// to Oficina ID's own.
7
8import (
9 "fmt"
10 "html"
11 "net/http"
12 "net/http/httptest"
13 "net/url"
14 "regexp"
15 "strings"
16 "testing"
17 "time"
18
19 "amadan.net/oficina/estilo.git/chrome"
20 "amadan.net/rastrillo/rastrillo/lastsignin"
21)
22
23// remember gives the browser a remembered way in, sealed by Docs' own jar,
24// as rastrillo would have after a sign-in.
25func (b *routerBrowser) remember(t *testing.T, rec lastsignin.Record) {
26 t.Helper()
27 w := httptest.NewRecorder()
28 b.f.app.handlers.auth.RememberJar().Remember(w, rec)
29 cookies := w.Result().Cookies()
30 if len(cookies) != 1 {
31 t.Fatalf("the jar refused %+v", rec)
32 }
33 b.cookies[cookies[0].Name] = cookies[0]
34}
35
36// remembered is the browser's remembered way in, read by Docs' own jar.
37func (b *routerBrowser) remembered(t *testing.T) (lastsignin.Record, lastsignin.ReadResult) {
38 t.Helper()
39 return b.f.app.handlers.auth.RememberJar().Read(b.request("GET", "/", ""))
40}
41
42// door is the sign-in card's own content: rastrillo's section inside
43// estilo-signin-screen, unescaped.
44func door(t *testing.T, body string) string {
45 t.Helper()
46 start := strings.Index(body, "<div estilo-signin-screen>")
47 if start < 0 {
48 t.Fatalf("no estilo-signin-screen:\n%s", body)
49 }
50 end := strings.Index(body[start:], "</section>")
51 return html.UnescapeString(body[start : start+end])
52}
53
54var (
55 oficinaButton = "Continue with Oficina ID"
56 otherWays = "Other ways to sign in"
57 emailField = `name="address" required`
58)
59
60func TestSmartDoorStatesWithHome(t *testing.T) {
61 f := newRouterHomeFixture(t)
62 glyph := string(chrome.OficinaGlyph)
63 cases := []struct {
64 name, path string
65 record *lastsignin.Record
66 want, not []string
67 title string
68 }{
69 {name: "first visit", path: "/signin",
70 want: []string{oficinaButton, `href="/signin/oficina"`, glyph, otherWays, `href="/signin?way=oficina&ways=1"`},
71 not: []string{emailField, "Continue as", "Use a different email"},
72 title: "Sign in to Docs"},
73 {name: "first visit from a page", path: "/signin?return_to=%2Fd%2Fabc",
74 want: []string{`href="/signin/oficina?return_to=%2Fd%2Fabc"`, `href="/signin?return_to=%2Fd%2Fabc&way=oficina&ways=1"`}},
75 {name: "local: email is the one way", path: "/signin/local",
76 want: []string{emailField, ">Continue</button>"},
77 not: []string{"Oficina ID", "/signin/oficina", otherWays}},
78 {name: "step-up: local ways only", path: "/signin?reauth=1",
79 want: []string{emailField, "Sign in again to continue."},
80 not: []string{"Oficina ID", "/signin/oficina"}},
81 {name: "step-up remembered Oficina ID", path: "/signin?reauth=1",
82 record: &lastsignin.Record{Method: lastsignin.MethodFederated, Provider: lastsignin.ProviderOficina, Address: "alice@example.com"},
83 want: []string{"Continue as <bdi>alice@example.com</bdi>", "Sign in again to continue."},
84 not: []string{"Oficina ID", "/signin/oficina"}},
85 {name: "chooser", path: "/signin?ways=1",
86 want: []string{"<h1 id=\"rst-signin-heading\">Other ways to sign in</h1>", `href="/signin?way=email"`, ">Email</span>", ">Back</span>"},
87 not: []string{oficinaButton, emailField},
88 title: "Other ways to sign in to Docs"},
89 {name: "email chosen", path: "/signin?way=email",
90 want: []string{emailField, otherWays},
91 not: []string{oficinaButton}},
92 {name: "Oficina ID remembered", path: "/signin",
93 record: &lastsignin.Record{Method: lastsignin.MethodFederated, Provider: lastsignin.ProviderOficina, Address: "alice@example.com"},
94 want: []string{oficinaButton, otherWays},
95 // Never captioned with an address.
96 not: []string{"alice@example.com", emailField}},
97 {name: "Oficina ID remembered: the chooser", path: "/signin?ways=1&way=oficina",
98 record: &lastsignin.Record{Method: lastsignin.MethodFederated, Provider: lastsignin.ProviderOficina, Address: "alice@example.com"},
99 want: []string{">Email <bdi>alice@example.com</bdi></span>", "Use a different email", ">Back</span>"},
100 not: []string{oficinaButton}},
101 {name: "Oficina ID remembered for a Home-only person", path: "/signin?ways=1&way=oficina",
102 record: &lastsignin.Record{Method: lastsignin.MethodFederated, Provider: lastsignin.ProviderOficina},
103 want: []string{">Email</span>"},
104 not: []string{"<bdi>"}},
105 {name: "email link remembered", path: "/signin",
106 record: &lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "bob@example.com"},
107 want: []string{"Continue as <bdi>bob@example.com</bdi>", `name="address" value="bob@example.com"`, otherWays},
108 not: []string{oficinaButton}},
109 {name: "email link remembered: the chooser", path: "/signin?ways=1&way=email",
110 record: &lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "bob@example.com"},
111 want: []string{glyph + "<span>Oficina ID</span>", `href="/signin?way=oficina"`, "Use a different email"},
112 not: []string{">Email</span>"}},
113 {name: "Keymail remembered", path: "/signin",
114 record: &lastsignin.Record{Method: lastsignin.MethodKeymail, Address: "bob@example.com"},
115 // rastrillo v0.45.0: the door never names Keymail.
116 want: []string{"Continue as <bdi>bob@example.com</bdi>", `name="expect" value="keymail"`, otherWays}},
117 {name: "problem", path: "/signin?err=rate",
118 record: &lastsignin.Record{Method: lastsignin.MethodFederated, Provider: lastsignin.ProviderOficina},
119 want: []string{"Too many tries. Try again in a few minutes.", emailField},
120 not: []string{oficinaButton},
121 title: "Problem signing in to Docs"},
122 {name: "a failed Keymail keeps force", path: "/signin?err=keymail&force=1",
123 want: []string{"We couldn't confirm it's you.", `name="force" value="1"`, "Send me a link instead"}},
124 {name: "sent", path: "/signin?sent=1",
125 want: []string{"Check your email", "We sent a link to your inbox.", "Use a different email"},
126 not: []string{oficinaButton, emailField},
127 title: "Check your email to sign in to Docs"},
128 {name: "an unknown way is the remembered one", path: "/signin?way=nonsense",
129 want: []string{oficinaButton}},
130 }
131 for _, c := range cases {
132 t.Run(c.name, func(t *testing.T) {
133 b := f.browser()
134 if c.record != nil {
135 b.remember(t, *c.record)
136 }
137 rec := b.do("GET", c.path, "")
138 if rec.Code != http.StatusOK {
139 t.Fatalf("GET %s: %d %q", c.path, rec.Code, rec.Header().Get("Location"))
140 }
141 if rec.Header().Get("Cache-Control") != "no-store" {
142 t.Error("the door is cacheable")
143 }
144 card := door(t, rec.Body.String())
145 for _, want := range c.want {
146 if !strings.Contains(card, want) {
147 t.Errorf("lacks %q:\n%s", want, card)
148 }
149 }
150 for _, not := range c.not {
151 if strings.Contains(card, not) {
152 t.Errorf("has %q:\n%s", not, card)
153 }
154 }
155 if c.title != "" {
156 if got := html.UnescapeString(titleOfPage(rec.Body.String())); got != c.title {
157 t.Errorf("<title> = %q, want %q", got, c.title)
158 }
159 }
160 })
161 }
162}
163
164func titleOfPage(body string) string {
165 m := regexp.MustCompile(`<title>([^<]*)</title>`).FindStringSubmatch(body)
166 if m == nil {
167 return ""
168 }
169 return m[1]
170}
171
172// Standalone Docs has only email: no Oficina ID anywhere, and no chooser
173// with nothing on it.
174func TestSmartDoorStandaloneHasOnlyEmail(t *testing.T) {
175 app, err := NewForTest(t)
176 if err != nil {
177 t.Fatal(err)
178 }
179 for _, path := range []string{"/signin", "/signin?way=oficina"} {
180 rec := serve(app, httptest.NewRequest(http.MethodGet, path, nil))
181 card := door(t, rec.Body.String())
182 if rec.Code != http.StatusOK || !strings.Contains(card, emailField) || strings.Contains(card, "Oficina") || strings.Contains(card, otherWays) {
183 t.Errorf("GET %s: %d\n%s", path, rec.Code, card)
184 }
185 }
186 // Nothing links the chooser here; typed in, it has no Oficina ID row.
187 if card := door(t, serve(app, httptest.NewRequest(http.MethodGet, "/signin?ways=1", nil)).Body.String()); strings.Contains(card, "Oficina") || !strings.Contains(card, ">Back</span>") {
188 t.Errorf("standalone chooser:\n%s", card)
189 }
190 if rec := serve(app, httptest.NewRequest(http.MethodGet, "/signin/oficina", nil)); rec.Code != http.StatusNotFound {
191 t.Errorf("standalone /signin/oficina: %d, want 404", rec.Code)
192 }
193}
194
195// Continue with Oficina ID starts the Home exchange, keeping the page; a
196// step-up never reaches Home; a browser already signed in and admitted
197// skips both doors, unless the query names a state of the door.
198func TestSmartDoorRoutesWithHome(t *testing.T) {
199 f := newRouterHomeFixture(t)
200 b := f.browser()
201 routerRedirect(t, b.do("GET", "/signin/oficina?return_to=%2Fd%2Fabc", ""), "/auth/start?return_to=%2Fd%2Fabc")
202 if b.cookies[connectReturnCookie] == nil {
203 t.Fatal("/signin/oficina did not remember the page for the Home landing")
204 }
205 routerRedirect(t, b.do("GET", "/signin/oficina?reauth=1&return_to=%2Fd%2Fabc", ""), "/signin/local?reauth=1&return_to=%2Fd%2Fabc")
206
207 alice := f.browser()
208 alice.localSignin(t, "alice@example.com")
209 routerRedirect(t, alice.do("GET", "/signin?return_to=%2Fd%2Fabc", ""), "/d/abc")
210 routerRedirect(t, alice.do("GET", "/signin/oficina", ""), "/")
211 for _, path := range []string{"/signin?reauth=1", "/signin?sent=1", "/signin?err=rate", "/signin/local"} {
212 if rec := alice.do("GET", path, ""); rec.Code != http.StatusOK {
213 t.Errorf("signed in, GET %s: %d %q, want the door", path, rec.Code, rec.Header().Get("Location"))
214 }
215 }
216}
217
218// The refusal (Config.Refused) is drawn in the screen's app-problem slot,
219// with the email field, never the remembered one-tap that would only offer
220// the refused address again.
221func TestSmartDoorRefusalIsTheAppProblem(t *testing.T) {
222 f := newRouterHomeFixture(t)
223 b := f.browser()
224 b.remember(t, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "carol@example.com"})
225 rec := httptest.NewRecorder()
226 req := b.request("POST", "/auth/verify", "")
227 f.app.handlers.signinRefused(rec, req)
228 card := door(t, rec.Body.String())
229 if rec.Code != http.StatusForbidden || !strings.Contains(card, `id="rst-signin-app-problem"`) || !strings.Contains(card, "docs.signin.error.refused") || !strings.Contains(card, `id="rst-signin-email" name="address"`) || strings.Contains(card, "Continue as") {
230 t.Fatalf("refusal: %d\n%s", rec.Code, card)
231 }
232}
233
234// A Home sign-in is remembered as Oficina ID, with the address of the
235// person connect resolved, written in MintHomeSession and only there.
236func TestMintHomeSessionRemembersOficinaID(t *testing.T) {
237 f := newRouterHomeFixture(t)
238 alice := f.browser()
239 alice.localSignin(t, "alice@example.com")
240 alice.linkProof(t, "opaque-alice", "alice@example.com")
241 alice.confirmLink(t, "/")
242
243 // This browser last signed in as bob, by email. Oficina ID signs alice
244 // in: the record is hers, and nothing of bob's is carried over.
245 b := f.browser()
246 b.remember(t, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "bob@example.com"})
247 nonce := b.start(t, "/auth/start?return_to=%2F", "")
248 routerRedirect(t, b.exchange(t, nonce, "opaque-alice", time.Now().Add(-time.Hour)), "/")
249 got, res := b.remembered(t)
250 want := lastsignin.Record{Method: lastsignin.MethodFederated, Provider: lastsignin.ProviderOficina, Address: "alice@example.com"}
251 if res != lastsignin.Valid || got != want {
252 t.Fatalf("remembered %+v (%v), want %+v", got, res, want)
253 }
254 // And the door offers it next time, with her address only in the chooser.
255 signoutChained(t, b.do("POST", "/signout", ""))
256 card := door(t, b.do("GET", "/signin", "").Body.String())
257 if !strings.Contains(card, oficinaButton) || strings.Contains(card, "alice@example.com") {
258 t.Fatalf("the door after an Oficina ID sign-in:\n%s", card)
259 }
260
261 // A local sign-in is remembered by rastrillo itself, as the email link.
262 alice.localSignin(t, "alice@example.com")
263 if got, res := alice.remembered(t); res != lastsignin.Valid || got.Method != lastsignin.MethodMagicLink || got.Address != "alice@example.com" {
264 t.Fatalf("local sign-in remembered %+v (%v)", got, res)
265 }
266
267 // An unknown subject mints nothing, so remembers nothing.
268 stranger := f.browser()
269 stranger.remember(t, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "bob@example.com"})
270 if rec := stranger.exchange(t, stranger.start(t, "/auth/start?return_to=%2F", ""), "opaque-nobody", time.Now().Add(-time.Hour)); rec.Code != http.StatusForbidden {
271 t.Fatalf("unknown subject: %d", rec.Code)
272 }
273 if got, res := stranger.remembered(t); res != lastsignin.Valid || got.Method != lastsignin.MethodMagicLink || got.Address != "bob@example.com" {
274 t.Fatalf("an unknown Home subject changed the record: %+v (%v)", got, res)
275 }
276}
277
278// A Home-only person (team mode, "I'm new here") has no address here: the
279// record is Oficina ID with none.
280func TestMintHomeSessionRemembersAHomeOnlyPersonWithoutAnAddress(t *testing.T) {
281 f := newTeamRouterFixture(t)
282 b := f.browser()
283 b.remember(t, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "bob@example.com"})
284 nonce := b.start(t, "/auth/start?return_to=%2F", "")
285 b.chooseNew(t, b.exchange(t, nonce, teamSubject('b'), time.Now().Add(-time.Hour)))
286 got, res := b.remembered(t)
287 if want := (lastsignin.Record{Method: lastsignin.MethodFederated, Provider: lastsignin.ProviderOficina}); res != lastsignin.Valid || got != want {
288 t.Fatalf("remembered %+v (%v), want %+v", got, res, want)
289 }
290}
291
292// Signed out: "Forget me on this device", a POST to rastrillo's Forget.
293// With Home it then chains to Oficina ID's own Forget, which returns only
294// to this consumer's exact /signed-out. The door's "Use a different email"
295// posts to the same Forget and stays on the door.
296func TestSignedOutForgetChainsToOficinaID(t *testing.T) {
297 f := newRouterHomeFixture(t)
298 b := f.browser()
299 page := b.do("GET", "/signed-out", "")
300 form := regexp.MustCompile(`(?s)<form estilo-signin-forget method="post" action="([^"]+)">(.*?)</form>`).FindStringSubmatch(page.Body.String())
301 if page.Code != http.StatusOK || form == nil || form[1] != signinForgetPath || !strings.Contains(form[2], `name="chain" value="oficina"`) || !strings.Contains(form[2], "Forget me on this device") {
302 t.Fatalf("signed-out page has no chained Forget: %d\n%s", page.Code, page.Body.String())
303 }
304 if !strings.Contains(page.Body.String(), `href="/signin">Sign in</a>`) {
305 t.Fatal("signed-out page lost Sign in")
306 }
307
308 b.remember(t, lastsignin.Record{Method: lastsignin.MethodFederated, Provider: lastsignin.ProviderOficina, Address: "alice@example.com"})
309 jar := f.app.handlers.auth.RememberJar().CookieName()
310 rec := b.do("POST", signinForgetPath, url.Values{"chain": {"oficina"}}.Encode())
311 want := bridgeIssuer + "/forget?return=" + url.QueryEscape(bridgeOrigin+"/signed-out")
312 routerRedirect(t, rec, want)
313 if _, ok := b.cookies[jar]; ok {
314 t.Fatal("Forget kept the remembered way in")
315 }
316 if !strings.Contains(rec.Header().Get("Content-Security-Policy"), "form-action 'self' "+bridgeIssuer) {
317 t.Fatalf("form-action does not allow the chain to %s: %q", bridgeIssuer, rec.Header().Get("Content-Security-Policy"))
318 }
319
320 // The door's "Use a different email": forgets, and opens the email way.
321 b.remember(t, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "bob@example.com"})
322 routerRedirect(t, b.do("POST", signinForgetPath, url.Values{"way": {"email"}, "return_to": {"/d/abc"}}.Encode()), "/signin?return_to=%2Fd%2Fabc&way=email")
323 if _, ok := b.cookies[jar]; ok {
324 t.Fatal("Use a different email kept the remembered way in")
325 }
326
327 // A cross-site post is refused, and chains nowhere.
328 r := b.request("POST", signinForgetPath, url.Values{"chain": {"oficina"}}.Encode())
329 r.Header.Set("Origin", "https://evil.example")
330 r.Header.Set("Sec-Fetch-Site", "cross-site")
331 if refused := b.serve(r); refused.Code != http.StatusForbidden || refused.Header().Get("Location") != "" {
332 t.Fatalf("cross-site Forget: %d %q", refused.Code, refused.Header().Get("Location"))
333 }
334}
335
336// Standalone, the signed-out page's Forget is Docs' own, with no chain.
337func TestSignedOutForgetStandalone(t *testing.T) {
338 app, err := NewForTest(t)
339 if err != nil {
340 t.Fatal(err)
341 }
342 page := serve(app, httptest.NewRequest(http.MethodGet, "/signed-out", nil)).Body.String()
343 if !strings.Contains(page, `<form estilo-signin-forget method="post" action="/signin/forget">`) || strings.Contains(page, `name="chain"`) {
344 t.Fatalf("standalone signed-out page:\n%s", page)
345 }
346 req := httptest.NewRequest(http.MethodPost, DefaultOrigin+signinForgetPath, strings.NewReader("chain=oficina"))
347 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
348 req.Header.Set("Sec-Fetch-Site", "same-origin")
349 rec := serve(app, req)
350 if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/signin" {
351 t.Fatalf("standalone Forget: %d %q, want 303 /signin", rec.Code, rec.Header().Get("Location"))
352 }
353}
354
355// The contract estilo's review asked for: estilo-signin-screen over
356// rastrillo's real sign-in states. HideBrand drops the partial's brand
357// column (estilo's door draws Docs' mark and name around the card), so
358// [estilo-signin-screen] > section has the door as its only element child,
359// in every state.
360func TestSmartDoorScreenHoldsOnlyTheDoor(t *testing.T) {
361 f := newRouterHomeFixture(t)
362 oficina := &lastsignin.Record{Method: lastsignin.MethodFederated, Provider: lastsignin.ProviderOficina, Address: "alice@example.com"}
363 email := &lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "bob@example.com"}
364 for _, c := range []struct {
365 name, path string
366 record *lastsignin.Record
367 }{
368 {"first visit", "/signin", nil},
369 {"Oficina ID remembered", "/signin", oficina},
370 {"email remembered", "/signin", email},
371 {"the chooser", "/signin?ways=1", email},
372 {"problem", "/signin?err=expired", email},
373 {"sent", "/signin?sent=1", email},
374 {"step-up", "/signin?reauth=1", oficina},
375 {"email only", "/signin/local", nil},
376 } {
377 t.Run(c.name, func(t *testing.T) {
378 b := f.browser()
379 if c.record != nil {
380 b.remember(t, *c.record)
381 }
382 rec := b.do("GET", c.path, "")
383 if rec.Code != http.StatusOK {
384 t.Fatalf("GET %s: %d", c.path, rec.Code)
385 }
386 screenOnlyHoldsTheDoor(t, rec.Body.String())
387 })
388 }
389 // And the confirm step an emailed link opens (Config.RenderConfirm).
390 b := f.browser()
391 confirm := b.do("GET", b.localLink(t, "alice@example.com"), "")
392 if confirm.Code != http.StatusOK {
393 t.Fatalf("confirm: %d", confirm.Code)
394 }
395 screenOnlyHoldsTheDoor(t, confirm.Body.String())
396}
397
398var startTag = regexp.MustCompile(`<(/?)([a-zA-Z][a-zA-Z0-9-]*)([^>]*)>`)
399
400// voidElements have no end tag.
401var voidElements = map[string]bool{"area": true, "base": true, "br": true, "col": true, "embed": true, "hr": true, "img": true, "input": true, "link": true, "meta": true, "source": true, "track": true, "wbr": true}
402
403// screenOnlyHoldsTheDoor checks that the first section inside
404// [estilo-signin-screen] is rastrillo's [rst-signin] and that its only
405// element child is the door, [rst-signin-door].
406func screenOnlyHoldsTheDoor(t *testing.T, body string) {
407 t.Helper()
408 children, err := screenChildren(body)
409 if err != nil {
410 t.Fatal(err)
411 }
412 if len(children) != 1 || !strings.HasPrefix(children[0], "<div rst-signin-door") {
413 t.Fatalf("[estilo-signin-screen] > section has %d element children %q, want only the door", len(children), children)
414 }
415}
416
417// screenChildren is the start tags of the element children of
418// [estilo-signin-screen] > section, which must be rastrillo's.
419func screenChildren(body string) ([]string, error) {
420 at := strings.Index(body, "<div estilo-signin-screen>")
421 if at < 0 {
422 return nil, fmt.Errorf("no [estilo-signin-screen]")
423 }
424 rest := body[at+len("<div estilo-signin-screen>"):]
425 tags := startTag.FindAllStringSubmatchIndex(rest, -1)
426 if len(tags) == 0 {
427 return nil, fmt.Errorf("[estilo-signin-screen] is empty")
428 }
429 first := rest[tags[0][0]:tags[0][1]]
430 if strings.TrimSpace(rest[:tags[0][0]]) != "" || !strings.HasPrefix(first, "<section rst-signin") {
431 return nil, fmt.Errorf("[estilo-signin-screen]'s first child is not rastrillo's section: %q", first)
432 }
433 depth := 0
434 var children []string
435 for _, m := range tags[1:] {
436 closing, name, tag := rest[m[2]:m[3]] == "/", strings.ToLower(rest[m[4]:m[5]]), rest[m[0]:m[1]]
437 if closing {
438 if depth == 0 {
439 if name != "section" {
440 return nil, fmt.Errorf("unbalanced markup: %q closes the section", tag)
441 }
442 return children, nil
443 }
444 depth--
445 continue
446 }
447 if depth == 0 {
448 children = append(children, tag)
449 }
450 if !voidElements[name] && !strings.HasSuffix(tag, "/>") {
451 depth++
452 }
453 }
454 return nil, fmt.Errorf("the section never closes")
455}
456
457// The check sees what HideBrand removes: a brand column beside the door,
458// as the partial draws without it, is a second child.
459func TestScreenChildrenSeesABrandColumn(t *testing.T) {
460 branded := `<div estilo-signin-screen>
461<section rst-signin aria-labelledby="rst-signin-heading">
462<div rst-signin-brand><div rst-signin-mark><img src="x" alt=""></div><p rst-signin-name>Docs</p></div>
463<div rst-signin-door="one-way"><h1>Sign in to Docs</h1><input name="address"><br></div>
464</section>
465</div>`
466 children, err := screenChildren(branded)
467 if err != nil || len(children) != 2 || !strings.HasPrefix(children[0], "<div rst-signin-brand") {
468 t.Fatalf("children %q, %v: want the brand column and the door", children, err)
469 }
470}
471
472// Fable on #139, A2: a linked person the signed-in routes no longer admit
473// signs in through Oficina ID (connect mints for any linked person). The
474// sign-in is not remembered as Oficina ID, and the door they bounce to says
475// why, with the email field, and forgets a remembered Oficina ID, so it is
476// not offered round the same loop again.
477func TestARefusedOficinaIDSignInIsNotRememberedAndTheDoorSaysWhy(t *testing.T) {
478 f := newRouterHomeFixture(t)
479 alice := f.browser()
480 alice.localSignin(t, "alice@example.com")
481 sqid := strings.TrimPrefix(routerRedirect(t, alice.do("POST", "/documents", "title=Minutes"), ""), "/d/")
482 if rec := alice.do("POST", "/d/"+sqid+"/share", "address=carol@example.com&role=reader"); rec.Code != http.StatusSeeOther {
483 t.Fatalf("share: %d", rec.Code)
484 }
485 carol := f.browser()
486 carol.localSignin(t, "carol@example.com")
487 carol.linkProof(t, "opaque-carol", "carol@example.com")
488 carol.confirmLink(t, "/")
489 if rec := alice.do("POST", "/d/"+sqid+"/share/revoke", "address=carol@example.com"); rec.Code != http.StatusSeeOther {
490 t.Fatalf("revoke: %d", rec.Code)
491 }
492
493 b := f.browser()
494 b.remember(t, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "bob@example.com"})
495 b.exchange(t, b.start(t, "/auth/start?return_to=%2F", ""), "opaque-carol", time.Now().Add(-time.Hour))
496 if got, res := b.remembered(t); res != lastsignin.Valid || got.Method != lastsignin.MethodMagicLink || got.Address != "bob@example.com" {
497 t.Fatalf("a refused Oficina ID sign-in changed the record: %+v (%v)", got, res)
498 }
499 list := b.do("GET", "/", "")
500 if list.Code != http.StatusSeeOther || !strings.HasPrefix(list.Header().Get("Location"), "/signin") {
501 t.Fatalf("the refused session reached the list: %d %q", list.Code, list.Header().Get("Location"))
502 }
503 // An Oficina ID remembered from before the refusal.
504 b.remember(t, lastsignin.Record{Method: lastsignin.MethodFederated, Provider: lastsignin.ProviderOficina, Address: "carol@example.com"})
505 jar := f.app.handlers.auth.RememberJar().CookieName()
506 for _, path := range []string{list.Header().Get("Location"), "/signin/local"} {
507 rec := b.do("GET", path, "")
508 card := door(t, rec.Body.String())
509 if rec.Code != http.StatusOK || !strings.Contains(card, `id="rst-signin-app-problem"`) || !strings.Contains(card, "docs.signin.error.refused") || !strings.Contains(card, `id="rst-signin-email" name="address"`) || strings.Contains(card, oficinaButton) {
510 t.Fatalf("GET %s for a refused session: %d\n%s", path, rec.Code, card)
511 }
512 if _, kept := b.cookies[jar]; kept {
513 t.Fatalf("GET %s kept the remembered Oficina ID for a refused session", path)
514 }
515 b.remember(t, lastsignin.Record{Method: lastsignin.MethodFederated, Provider: lastsignin.ProviderOficina})
516 }
517 // A remembered email way is kept: it is no loop.
518 b.remember(t, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "carol@example.com"})
519 b.do("GET", "/signin", "")
520 if _, kept := b.cookies[jar]; !kept {
521 t.Fatal("the door forgot a remembered email way for a refused session")
522 }
523}
524
525// A step-up's reauth=1 survives Begin's answer and Docs' return_to: the
526// next door is still local ways only, for the same page.
527func TestAStepUpPostKeepsReauthAndTheReturn(t *testing.T) {
528 f := newRouterHomeFixture(t)
529 b := f.browser()
530 for _, address := range []string{"not an address", "bob@example.com"} {
531 rec := b.do("POST", "/signin", url.Values{"address": {address}, "reauth": {"1"}, "return_to": {"/d/abc"}}.Encode())
532 loc := routerRedirect(t, rec, "")
533 u, err := url.Parse(loc)
534 if err != nil || u.Path != "/signin" || u.Query().Get("reauth") != "1" || u.Query().Get("return_to") != "/d/abc" {
535 t.Fatalf("%q: redirected to %q, want the door with reauth=1 and return_to=/d/abc", address, loc)
536 }
537 card := door(t, b.do("GET", loc, "").Body.String())
538 if strings.Contains(card, "Oficina ID") || !strings.Contains(card, `name="return_to" value="/d/abc"`) {
539 t.Fatalf("%q: the step-up's next door:\n%s", address, card)
540 }
541 }
542}
543
544// Opening an emailed link (the confirm step) leaves the remembered way in
545// alone: it neither clears nor rewrites it.
546func TestConfirmingALinkLeavesTheRecordAlone(t *testing.T) {
547 f := newRouterHomeFixture(t)
548 b := f.browser()
549 want := lastsignin.Record{Method: lastsignin.MethodFederated, Provider: lastsignin.ProviderOficina, Address: "alice@example.com"}
550 b.remember(t, want)
551 jar := f.app.handlers.auth.RememberJar().CookieName()
552 rec := b.do("GET", b.localLink(t, "bob@example.com"), "")
553 if rec.Code != http.StatusOK {
554 t.Fatalf("confirm: %d", rec.Code)
555 }
556 for _, c := range rec.Result().Cookies() {
557 if c.Name == jar {
558 t.Fatalf("the confirm step set the remembered cookie: %+v", c)
559 }
560 }
561 if got, res := b.remembered(t); res != lastsignin.Valid || got != want {
562 t.Fatalf("remembered %+v (%v), want %+v", got, res, want)
563 }
564}
565
566// A plain /signin/local (connect's failed, unknown and connect pages send
567// people there) keeps the page the sign-in began from: it remembers
568// nothing new, and its form posts the remembered page.
569func TestSigninLocalKeepsTheRememberedPage(t *testing.T) {
570 f := newRouterHomeFixture(t)
571 b := f.browser()
572 b.do("GET", "/signin?return_to=%2Fd%2Fabc", "")
573 kept := b.cookies[homeReturnCookie]
574 if kept == nil {
575 t.Fatal("the door did not remember the page")
576 }
577 rec := b.do("GET", "/signin/local", "")
578 for _, c := range rec.Result().Cookies() {
579 if c.Name == homeReturnCookie {
580 t.Fatal("a plain /signin/local overwrote the remembered page")
581 }
582 }
583 if card := door(t, rec.Body.String()); !strings.Contains(card, `name="return_to" value="/d/abc"`) {
584 t.Fatalf("/signin/local does not carry the remembered page:\n%s", card)
585 }
586 // With its own return_to it remembers that.
587 b.do("GET", "/signin/local?return_to=%2Fd%2Fxyz", "")
588 if b.cookies[homeReturnCookie] == nil || b.cookies[homeReturnCookie].Value == kept.Value {
589 t.Fatal("/signin/local?return_to= did not remember its page")
590 }
591}
592
593// Fable on #139, N1: for a refused session, "Other ways to sign in" opens
594// the chooser, and each way its own page, with no refusal over them, so a
595// refused person can reach another way in (another Oficina ID account).
596func TestARefusedSessionCanReachOtherWays(t *testing.T) {
597 check := func(t *testing.T, get func(string) string, ways bool) {
598 t.Helper()
599 plain := get("/signin")
600 if !strings.Contains(plain, `id="rst-signin-app-problem"`) {
601 t.Fatalf("the plain door does not say why:\n%s", plain)
602 }
603 if way := get("/signin?way=email"); strings.Contains(way, `id="rst-signin-app-problem"`) {
604 t.Fatalf("a way's own page redraws the refusal:\n%s", way)
605 }
606 if !ways {
607 // Email is standalone Docs' only way: there is no chooser to reach.
608 if strings.Contains(plain, "ways=1") {
609 t.Fatalf("standalone refusal links a chooser:\n%s", plain)
610 }
611 return
612 }
613 m := regexp.MustCompile(`href="(/signin\?[^"]*ways=1[^"]*)"`).FindStringSubmatch(plain)
614 if m == nil {
615 t.Fatalf("no Other ways to sign in on the refusal:\n%s", plain)
616 }
617 chooser := get(m[1])
618 if strings.Contains(chooser, `id="rst-signin-app-problem"`) || !strings.Contains(chooser, `<h1 id="rst-signin-heading">Other ways to sign in</h1>`) {
619 t.Fatalf("GET %s for a refused session is not the chooser:\n%s", m[1], chooser)
620 }
621 if !strings.Contains(chooser, `href="/signin?way=oficina"`) {
622 t.Fatalf("the chooser does not offer Oficina ID:\n%s", chooser)
623 }
624 }
625 t.Run("Home", func(t *testing.T) {
626 f := newRouterHomeFixture(t)
627 alice := f.browser()
628 alice.localSignin(t, "alice@example.com")
629 sqid := strings.TrimPrefix(routerRedirect(t, alice.do("POST", "/documents", "title=Minutes"), ""), "/d/")
630 alice.do("POST", "/d/"+sqid+"/share", "address=carol@example.com&role=reader")
631 carol := f.browser()
632 carol.localSignin(t, "carol@example.com")
633 alice.do("POST", "/d/"+sqid+"/share/revoke", "address=carol@example.com")
634 check(t, func(path string) string { return door(t, carol.do("GET", path, "").Body.String()) }, true)
635 })
636 t.Run("standalone", func(t *testing.T) {
637 app, err := NewForTestWith(t, Config{AllowedAddresses: "alice@example.com"})
638 if err != nil {
639 t.Fatal(err)
640 }
641 alice := newBrowser(t, app)
642 alice.signIn("alice@example.com")
643 sqid := strings.TrimPrefix(alice.do("POST", "/documents", "title=Minutes").Header().Get("Location"), "/d/")
644 alice.do("POST", "/d/"+sqid+"/share", "address=guest@example.com&role=reader")
645 guest := newBrowser(t, app)
646 guest.signIn("guest@example.com")
647 alice.do("POST", "/d/"+sqid+"/share/revoke", "address=guest@example.com")
648 check(t, func(path string) string { return door(t, guest.do("GET", path, "").Body.String()) }, false)
649 })
650}
651