oficina / slides Public

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

Plain git — no account needed to clone.

Download

Download this file

1package slides
2
3import (
4 "bytes"
5 "context"
6 "encoding/base64"
7 "encoding/json"
8 "errors"
9 "html"
10 "net/http"
11 "net/http/httptest"
12 "net/url"
13 "regexp"
14 "strings"
15 "testing"
16 "time"
17
18 "amadan.net/oficina/home/connect"
19 "amadan.net/oficina/home/connect/linkstore"
20 "amadan.net/oficina/home/handoff"
21 "amadan.net/rastrillo/rastrillo"
22 "amadan.net/rastrillo/rastrillo/assertion"
23 assertioncrypto "amadan.net/rastrillo/rastrillo/crypto"
24 "amadan.net/rastrillo/rastrillo/sessions"
25 "gorm.io/gorm"
26)
27
28const homeTestOrigin = "https://slides.example.com"
29
30// confirmForm is the confirm door's one form, as a browser would read it
31// (signin.html's Confirm branch, renderConfirm).
32var confirmForm = regexp.MustCompile(`<form[^>]*method="post" action="([^"]+)">\s*<input type="hidden" name="token" value="([^"]+)">`)
33
34func homeFixture(t *testing.T) (*http.ServeMux, *app, User) {
35 mux, a, u, _ := homeFixtureKey(t)
36 return mux, a, u
37}
38func homeFixtureKey(t *testing.T) (*http.ServeMux, *app, User, *assertioncrypto.Keypair) {
39 t.Helper()
40 return homeFixtureDirectory(t, "")
41}
42
43// homeFixtureDirectory is homeFixtureKey with a hub directory origin
44// (HOME_DIRECTORY_ORIGIN) configured, which is what turns the switcher on.
45func homeFixtureDirectory(t *testing.T, directory string) (*http.ServeMux, *app, User, *assertioncrypto.Keypair) {
46 t.Helper()
47 d := testDB(t)
48 key, err := assertioncrypto.Generate()
49 if err != nil {
50 t.Fatal(err)
51 }
52 raw, _ := json.Marshal(map[string]string{"test": base64.StdEncoding.EncodeToString(key.SignPub())})
53 cfg := Config{KeymailServers: testKeymailServers, Mailer: &homeTestMail{}, Env: EnvDevelopment, Origin: homeTestOrigin, Logger: quietLogger(), AllowedAddresses: []string{"owner@example.com"}, Home: &connect.Credentials{Issuer: "https://home.example.com", ConsumerID: "slides-test", KeysBase64: base64.StdEncoding.EncodeToString(raw), DEKBase64: base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{8}, 32)), Directory: directory}}
54 mux, a, err := New(d, cfg)
55 if err != nil {
56 t.Fatal(err)
57 }
58 t.Cleanup(func() { a.Close() })
59 u := User{ID: 72, Email: "owner@example.com", Name: "Existing owner", Colour: "#112233"}
60 if err := d.G.Create(&u).Error; err != nil {
61 t.Fatal(err)
62 }
63 return mux, a, u, key
64}
65func homeSession(t *testing.T, a *app, subject, method string) *http.Cookie {
66 t.Helper()
67 w := httptest.NewRecorder()
68 r := httptest.NewRequest("GET", homeTestOrigin+"/", nil)
69 if err := a.homeSessions.SignIn(w, r, sessions.Session{Subject: subject, Method: method, AuthTime: time.Now()}); err != nil {
70 t.Fatal(err)
71 }
72 for _, c := range w.Result().Cookies() {
73 if c.Name == a.homeSessions.CookieName() {
74 return c
75 }
76 }
77 t.Fatal("missing session cookie")
78 return nil
79}
80func homeLinked(t *testing.T, a *app, u User) { homeLinkedSubject(t, a, u, "home-person") }
81func homeLinkedSubject(t *testing.T, a *app, u User, subject string) {
82 t.Helper()
83 ctx := context.Background()
84 now := time.Now()
85 c, err := connect.DecodeCredentials(a.cfg.Home, a.cfg.Origin)
86 if err != nil {
87 t.Fatal(err)
88 }
89 store, err := linkstore.New(a.db.Writer(), c.DEK, a.cfg.Origin, c.Issuer, "oficina/slides", func(ctx context.Context, q linkstore.Queryer, id int64) (string, error) {
90 var address string
91 err := q.QueryRowContext(ctx, "SELECT email FROM users WHERE id=?", id).Scan(&address)
92 return address, err
93 })
94 if err != nil {
95 t.Fatal(err)
96 }
97 local := linkstore.Local{PersonID: u.ID, SessionToken: base64.RawURLEncoding.EncodeToString(bytes.Repeat([]byte{17}, 32)), AuthTime: now}
98 nonce := base64.RawURLEncoding.EncodeToString(bytes.Repeat([]byte{19}, 16))
99 init, err := store.Start(ctx, local, "/", now)
100 if err != nil {
101 t.Fatal(err)
102 }
103 if err := store.BindNonce(ctx, init, local, nonce, now); err != nil {
104 t.Fatal(err)
105 }
106 proof, err := store.Complete(ctx, init, local, linkstore.Home{Issuer: c.Issuer, Subject: subject, Nonce: nonce, AuthTime: now}, now)
107 if err != nil {
108 t.Fatal(err)
109 }
110 if _, err := store.Confirm(ctx, proof, local, now); err != nil {
111 t.Fatal(err)
112 }
113}
114
115func TestHomeExistingIdentityNoCreationAndStableActors(t *testing.T) {
116 mux, a, u := homeFixture(t)
117 homeLinked(t, a, u)
118 cookie := homeSession(t, a, "home-person", connect.HomeMethod)
119 r := httptest.NewRequest("GET", homeTestOrigin+"/", nil)
120 r.AddCookie(cookie)
121 w := httptest.NewRecorder()
122 mux.ServeHTTP(w, r)
123 if w.Code != 200 {
124 t.Fatalf("home root: %d %s", w.Code, w.Body.String())
125 }
126 var users, decks int64
127 a.db.G.Model(&User{}).Count(&users)
128 a.db.G.Model(&Deck{}).Count(&decks)
129 if users != 1 || decks != 0 {
130 t.Fatalf("Home created rows users=%d decks=%d", users, decks)
131 }
132 if got, _ := a.admittedPresenter(httptest.NewRecorder(), r); got != actorFor(u) {
133 t.Fatalf("actor %q", got)
134 }
135 s, _ := a.homeSessions.From(r)
136 r = sessions.WithSession(r, s)
137 principal, ok := a.sessionSubject(httptest.NewRecorder(), r)
138 if !ok || principal != u.Email {
139 t.Fatal("export owner changed")
140 }
141 jobsRequest := a.exportPrincipal(r)
142 jobsSession, _ := sessions.Current(jobsRequest)
143 if jobsSession.Subject != u.Email {
144 t.Fatal("job lookup owner changed")
145 }
146 restored, _ := sessions.Current(restoreExportPrincipal(jobsRequest))
147 if restored.Subject != "home-person" || restored.Method != connect.HomeMethod {
148 t.Fatal("job renderer changed verified identity")
149 }
150}
151func TestHomeUnknownSubjectNeverMatchesEmailOrSeeds(t *testing.T) {
152 mux, a, u := homeFixture(t)
153 r := httptest.NewRequest("GET", homeTestOrigin+"/", nil)
154 r.AddCookie(homeSession(t, a, u.Email, connect.HomeMethod))
155 w := httptest.NewRecorder()
156 mux.ServeHTTP(w, r)
157 if w.Code == 200 {
158 t.Fatal("Home subject matched existing email without explicit link")
159 }
160 var n int64
161 a.db.G.Model(&User{}).Count(&n)
162 if n != 1 {
163 t.Fatal("Home created user")
164 }
165 a.db.G.Model(&Deck{}).Count(&n)
166 if n != 0 {
167 t.Fatal("Home seeded content")
168 }
169}
170func TestHomeOffboardingRevokesBothMethodsAndEndsPresentation(t *testing.T) {
171 mux, a, u := homeFixture(t)
172 homeLinked(t, a, u)
173 home := homeSession(t, a, "home-person", connect.HomeMethod)
174 _ = homeSession(t, a, u.Email, "magiclink")
175 p := Presentation{Sqid: "testtalk", Actor: actorFor(u), StartedAt: time.Now()}
176 if err := a.db.G.Create(&p).Error; err != nil {
177 t.Fatal(err)
178 }
179 a.allowed = allowlist{addrs: map[string]struct{}{}}
180 r := httptest.NewRequest("POST", homeTestOrigin+"/decks", strings.NewReader("Title=unexpected"))
181 r.Header.Set("Origin", homeTestOrigin)
182 r.AddCookie(home)
183 w := httptest.NewRecorder()
184 mux.ServeHTTP(w, r)
185 if w.Code != 403 {
186 t.Fatalf("removed POST: %d", w.Code)
187 }
188 var n int64
189 a.db.G.Table("sessions").Count(&n)
190 if n != 0 {
191 t.Fatal("offboarding retained sessions", n)
192 }
193 a.db.G.First(&p, p.ID)
194 if p.EndedAt == nil {
195 t.Fatal("removed presenter stayed live")
196 }
197 a.db.G.Model(&User{}).Count(&n)
198 if n != 1 {
199 t.Fatal("offboarding deleted account")
200 }
201}
202func TestHomeFrontDoorLocalRecoveryAndCallbackGuard(t *testing.T) {
203 mux, a, _ := homeFixture(t)
204 for _, tc := range []struct {
205 method, path string
206 status int
207 }{{"GET", "/signin?return_to=%2Fd%2Fexisting", 200}, {"GET", "/signin/oficina?return_to=%2Fd%2Fexisting", 303}, {"GET", "/signin/local", 200}, {"GET", "/account/home", 303}, {"POST", "/account/home", 403}, {"POST", handoff.CallbackPath, 400}, {"GET", "/signed-out", 200}} {
208 r := httptest.NewRequest(tc.method, homeTestOrigin+tc.path, nil)
209 w := httptest.NewRecorder()
210 mux.ServeHTTP(w, r)
211 if w.Code != tc.status {
212 t.Errorf("%s %s status %d body %s", tc.method, tc.path, w.Code, w.Body.String())
213 }
214 if tc.path == "/signin/local" && (!strings.Contains(w.Body.String(), `name="address"`) || strings.Contains(w.Body.String(), "/signin/oficina")) {
215 t.Error("the local door is not email alone")
216 }
217 if strings.HasPrefix(tc.path, "/signin?") && !strings.Contains(w.Body.String(), `href="/signin/oficina?return_to=%2Fd%2Fexisting"`) {
218 t.Errorf("the door does not offer Continue with Oficina ID with its page:\n%s", w.Body.String())
219 }
220 if strings.HasPrefix(tc.path, "/signin/oficina") && w.Header().Get("Location") != handoff.StartPath+"?return_to=%2Fd%2Fexisting" {
221 t.Errorf("Continue with Oficina ID went to %q", w.Header().Get("Location"))
222 }
223 // connect's "signedout" state draws the door's signed-out page,
224 // never connect's own "Sign in with Home".
225 if tc.path == "/signed-out" && (!strings.Contains(w.Body.String(), "You’re signed out") || strings.Contains(w.Body.String(), "with Home")) {
226 t.Errorf("Home-mode signed-out page is not the door's:\n%s", w.Body.String())
227 }
228 }
229 r := httptest.NewRequest("GET", homeTestOrigin+"/signin/local", nil)
230 c := homeSession(t, a, "home-person", connect.HomeMethod)
231 r.AddCookie(c)
232 r.AddCookie(c)
233 w := httptest.NewRecorder()
234 mux.ServeHTTP(w, r)
235 if w.Code != 400 {
236 t.Fatal("duplicate session bypassed guard")
237 }
238 if !strings.Contains(w.Header().Get("Content-Security-Policy"), "form-action 'self' https://home.example.com") {
239 t.Fatal("Home POST continuation omitted from CSP")
240 }
241}
242
243// TestHomeDifferentEmailKeepsThePage: a local sign-in begun from a page
244// keeps that page through Sent, "Use a different email" (auth's Forget,
245// which opens the email way) and a second post, and lands on it once the
246// link is followed (homeLocalComplete).
247func TestHomeDifferentEmailKeepsThePage(t *testing.T) {
248 b, u := newHomeBrowser(t)
249 const deep = "/d/keep-going?from=signin"
250 first := b.get("/signin/local?return_to=" + url.QueryEscape(deep))
251 if first.Code != http.StatusOK || !strings.Contains(first.Body.String(), `name="return_to" value="`+deep+`"`) {
252 t.Fatalf("local door lost return_to: %d\n%s", first.Code, first.Body.String())
253 }
254 sent := b.do(http.MethodPost, signinPath, url.Values{"address": {u.Email}, "return_to": {deep}}, "")
255 loc, _ := url.Parse(sent.Header().Get("Location"))
256 if sent.Code != http.StatusSeeOther || loc == nil || loc.Path != signinPath || loc.Query().Get("sent") != "1" || loc.Query().Get("return_to") != deep {
257 t.Fatalf("first submission: %d %q", sent.Code, sent.Header().Get("Location"))
258 }
259 sentPage := b.get(sent.Header().Get("Location"))
260 if sentPage.Code != http.StatusOK || !strings.Contains(sentPage.Body.String(), `action="/signin/forget"><input type="hidden" name="return_to" value="`+deep+`">`) {
261 t.Fatalf("sent page's Use a different email lost the page: %d\n%s", sentPage.Code, sentPage.Body.String())
262 }
263 forget := b.do(http.MethodPost, signinForgetPath, url.Values{"return_to": {deep}, "way": {"email"}}, "")
264 if forget.Code != http.StatusSeeOther || forget.Header().Get("Location") != "/signin?return_to="+url.QueryEscape(deep)+"&way=email" {
265 t.Fatalf("forget: %d %q", forget.Code, forget.Header().Get("Location"))
266 }
267 retry := b.get(forget.Header().Get("Location"))
268 if retry.Code != http.StatusOK || !strings.Contains(retry.Body.String(), `name="return_to" value="`+deep+`"`) || !strings.Contains(retry.Body.String(), `name="address"`) {
269 t.Fatalf("retry form lost return_to: %d\n%s", retry.Code, retry.Body.String())
270 }
271 b.a.cfg.Mailer.(*homeTestMail).body = ""
272 verify := b.localSignInReturning(u.Email, deep)
273 if verify.Code != http.StatusSeeOther || verify.Header().Get("Location") != connect.LocalCompletePath {
274 t.Fatalf("verify: %d %q", verify.Code, verify.Header().Get("Location"))
275 }
276 if done := b.get(connect.LocalCompletePath); done.Code != http.StatusSeeOther || done.Header().Get("Location") != deep {
277 t.Fatalf("landed on %q, want %q", done.Header().Get("Location"), deep)
278 }
279}
280func TestHomeInvalidConfigurationDoesNotMigrate(t *testing.T) {
281 d := testDB(t)
282 _, _, err := New(d, Config{KeymailServers: testKeymailServers, Env: EnvDevelopment, Origin: homeTestOrigin, Home: &connect.Credentials{Issuer: "https://home.example.com"}})
283 if err == nil {
284 t.Fatal("partial config accepted")
285 }
286 var n int
287 if err := d.Writer().QueryRowContext(context.Background(), "SELECT count(*) FROM sqlite_master WHERE type='table'").Scan(&n); err != nil || n != 0 {
288 t.Fatal("invalid configuration changed database", n, err)
289 }
290}
291
292func TestHomeRealSignedExchangeExplicitLinkAndReplay(t *testing.T) {
293 mux, a, u, key := homeFixtureKey(t)
294 jar := map[string]*http.Cookie{}
295 local := homeSession(t, a, u.Email, "magiclink")
296 jar[local.Name] = local
297 call := func(method, path, origin, form string) *httptest.ResponseRecorder {
298 r := httptest.NewRequest(method, homeTestOrigin+path, strings.NewReader(form))
299 if origin != "" {
300 r.Header.Set("Origin", origin)
301 }
302 if form != "" {
303 r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
304 }
305 for _, c := range jar {
306 r.AddCookie(c)
307 }
308 w := httptest.NewRecorder()
309 mux.ServeHTTP(w, r)
310 for _, c := range w.Result().Cookies() {
311 if c.MaxAge < 0 {
312 delete(jar, c.Name)
313 } else {
314 jar[c.Name] = c
315 }
316 }
317 return w
318 }
319 start := call("POST", "/account/home", homeTestOrigin, "")
320 if start.Code != 303 {
321 t.Fatal("start", start.Code, start.Body.String())
322 }
323 auth := call("GET", start.Header().Get("Location"), "", "")
324 target, err := url.Parse(auth.Header().Get("Location"))
325 if err != nil || target.Query().Get("max_age") != "300" {
326 t.Fatal("fresh Home request absent", auth.Code, auth.Header())
327 }
328 id, _ := assertion.RandomID()
329 now := time.Now().Unix()
330 token, err := assertion.Sign(key, assertion.Claims{Version: 1, Issuer: a.cfg.Home.Issuer, Audience: homeTestOrigin, Subject: "linked-home-person", KeyID: "test", ID: id, Nonce: target.Query().Get("nonce"), IssuedAt: now, ExpiresAt: now + 90, AuthTime: now})
331 if err != nil {
332 t.Fatal(err)
333 }
334 callback := call("POST", handoff.CallbackPath, a.cfg.Home.Issuer, url.Values{"assertion": {token}}.Encode())
335 if callback.Code != 303 {
336 t.Fatal("signed callback", callback.Code, callback.Body.String())
337 }
338 finish := call("GET", handoff.FinishPath, "", "")
339 if finish.Code != 303 || finish.Header().Get("Location") != "/account/home/confirm" {
340 t.Fatal("finish", finish.Code, finish.Header(), finish.Body.String())
341 }
342 var links int64
343 a.db.G.Table("home_identity_links").Count(&links)
344 if links != 0 {
345 t.Fatal("link before explicit confirmation")
346 }
347 confirm := call("POST", "/account/home/confirm", homeTestOrigin, "")
348 if confirm.Code != 303 {
349 t.Fatal("confirm", confirm.Code, confirm.Body.String())
350 }
351 person, err := a.home.Resolve(context.Background(), "linked-home-person")
352 if err != nil || person.ID != u.ID {
353 t.Fatal("existing identity lost", person, err)
354 }
355 if jar[a.homeSessions.CookieName()].Value != local.Value {
356 t.Fatal("link silently replaced local session")
357 }
358 replay := call("POST", handoff.CallbackPath, a.cfg.Home.Issuer, url.Values{"assertion": {token}}.Encode())
359 if replay.Code < 400 {
360 t.Fatal("assertion replay accepted", replay.Code)
361 }
362 var users, decks int64
363 a.db.G.Model(&User{}).Count(&users)
364 a.db.G.Model(&Deck{}).Count(&decks)
365 if users != 1 || decks != 0 {
366 t.Fatal("link created data", users, decks)
367 }
368}
369
370func TestHomeDeletedLocalIDCannotBeReused(t *testing.T) {
371 _, a, u := homeFixture(t)
372 homeLinked(t, a, u)
373 if err := a.db.G.Delete(&u).Error; err != nil {
374 t.Fatal(err)
375 }
376 replacement := User{Email: u.Email}
377 if err := a.db.G.Create(&replacement).Error; err != nil {
378 t.Fatal(err)
379 }
380 if replacement.ID <= u.ID {
381 t.Fatal("user IDs may be reused", replacement.ID, u.ID)
382 }
383 if _, err := a.home.Resolve(context.Background(), "home-person"); err == nil {
384 t.Fatal("deleted user's link reassigned to replacement")
385 }
386}
387
388// TestHomePolicyTracksActualFrameworkAndStandalone: with Home, every
389// page's policy is connect.FormPolicy — Slides' own policy with the
390// issuer added to form-action, and nothing else changed — and standalone
391// it is Slides' own policy, through the same ServeOptions main uses.
392// Slides' policy is rastrillo's default bar style-src
393// (TestProductionCSPIsTheDefaultBarStyles in serving_test.go).
394func TestHomePolicyTracksActualFrameworkAndStandalone(t *testing.T) {
395 policy := ContentSecurityPolicy
396 mux, a, _ := homeFixture(t)
397 want := strings.Replace(policy, "form-action 'self'", "form-action 'self' "+a.cfg.Home.Issuer, 1)
398 if want == policy {
399 t.Fatal("framework form policy changed")
400 }
401 wrapped, closeHome, err := rastrillo.Handler(a.ServeOptions(rastrillo.Options{}, mux))
402 if err != nil {
403 t.Fatal(err)
404 }
405 defer closeHome()
406 for _, path := range []string{"/signin/local", "/account/home", "/auth/start", "/signed-out"} {
407 rec := httptest.NewRecorder()
408 wrapped.ServeHTTP(rec, httptest.NewRequest("GET", homeTestOrigin+path, nil))
409 if got := rec.Header().Get("Content-Security-Policy"); got != want {
410 t.Fatal("Home CSP drift", path, got, want)
411 }
412 }
413 plain, app, err := New(testDB(t), Config{KeymailServers: testKeymailServers, Env: EnvDevelopment, Origin: homeTestOrigin})
414 if err != nil {
415 t.Fatal(err)
416 }
417 defer app.Close()
418 standalone, closePlain, err := rastrillo.Handler(app.ServeOptions(rastrillo.Options{}, plain))
419 if err != nil {
420 t.Fatal(err)
421 }
422 defer closePlain()
423 rec := httptest.NewRecorder()
424 standalone.ServeHTTP(rec, httptest.NewRequest("GET", homeTestOrigin+"/signin", nil))
425 if got := rec.Header().Values("Content-Security-Policy"); len(got) != 1 || got[0] != policy {
426 t.Fatal("standalone CSP changed", got)
427 }
428}
429
430type homeTestMail struct{ body string }
431
432func (m *homeTestMail) Send(_ context.Context, _, _ string, body string) error {
433 m.body = body
434 return nil
435}
436func TestHomeLocalPluginRecoveryRotatesThenReturnsToLink(t *testing.T) {
437 mux, a, u := homeFixture(t)
438 old := homeSession(t, a, "unlinked-home", connect.HomeMethod)
439 jar := []*http.Cookie{old}
440 run := func(method, path, form string) *httptest.ResponseRecorder {
441 r := httptest.NewRequest(method, homeTestOrigin+path, strings.NewReader(form))
442 for _, c := range jar {
443 r.AddCookie(c)
444 }
445 if method == "POST" {
446 r.Header.Set("Origin", homeTestOrigin)
447 r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
448 }
449 w := httptest.NewRecorder()
450 mux.ServeHTTP(w, r)
451 return w
452 }
453 begin := run("GET", "/account/home", "")
454 if begin.Code != 303 || begin.Header().Get("Location") != "/signin/local?reauth=1" {
455 t.Fatal("recovery did not begin", begin.Code)
456 }
457 for _, c := range begin.Result().Cookies() {
458 if c.MaxAge > 0 {
459 jar = append(jar, c)
460 }
461 }
462 sent := run("POST", "/signin", url.Values{"address": {u.Email}}.Encode())
463 if sent.Code != 303 {
464 t.Fatal(sent.Code)
465 }
466 a.FlushMail()
467 body := a.cfg.Mailer.(*homeTestMail).body
468 link := regexp.MustCompile(`https://[^\s<>]+/auth/verify\?token=[A-Za-z0-9_-]+`).FindString(body)
469 if link == "" {
470 t.Fatal("local fixture link missing")
471 }
472 parsed, _ := url.Parse(link)
473 // Opening the link draws the confirm door under LocalGuard and
474 // spends nothing; its Sign in button POSTs the token back, and that
475 // POST is the local verification.
476 open := run("GET", parsed.RequestURI(), "")
477 m := confirmForm.FindStringSubmatch(open.Body.String())
478 if open.Code != 200 || m == nil || !strings.Contains(open.Body.String(), "estilo-door") || len(open.Result().Cookies()) != 0 {
479 t.Fatal("Home-local link did not open the confirm door", open.Code, open.Body.String())
480 }
481 verify := run("POST", html.UnescapeString(m[1]), url.Values{"token": {html.UnescapeString(m[2])}}.Encode())
482 if verify.Code != 303 || verify.Header().Get("Location") != connect.LocalCompletePath {
483 t.Fatal("local verify did not reach continuation", verify.Code, verify.Header())
484 }
485 for _, c := range verify.Result().Cookies() {
486 if c.Name == old.Name && c.MaxAge >= 0 {
487 jar[0] = c
488 }
489 }
490 if jar[0].Value == old.Value {
491 t.Fatal("local verification retained old session")
492 }
493 stale := httptest.NewRequest("GET", homeTestOrigin+"/", nil)
494 stale.AddCookie(old)
495 if _, ok := a.homeSessions.From(stale); ok {
496 t.Fatal("old session not revoked")
497 }
498 done := run("GET", connect.LocalCompletePath, "")
499 if done.Code != 303 || done.Header().Get("Location") != "/account/home" {
500 t.Fatal("recovery lost link navigation", done.Code, done.Header())
501 }
502 var n int64
503 a.db.G.Model(&User{}).Count(&n)
504 if n != 1 {
505 t.Fatal("recovery created user")
506 }
507 a.db.G.Model(&Deck{}).Count(&n)
508 if n != 0 {
509 t.Fatal("recovery seeded deck")
510 }
511}
512
513func TestHomeTransientReadFailureKeepsAllSessions(t *testing.T) {
514 mux, a, u := homeFixture(t)
515 homeLinked(t, a, u)
516 cookie := homeSession(t, a, "home-person", connect.HomeMethod)
517 _ = homeSession(t, a, "home-person", connect.HomeMethod)
518 if err := a.db.G.Callback().Query().Before("gorm:query").Register("home_test:transient", func(tx *gorm.DB) {
519 if tx.Statement.Table == "users" {
520 tx.AddError(errors.New("synthetic transient read failure"))
521 }
522 }); err != nil {
523 t.Fatal(err)
524 }
525 r := httptest.NewRequest("GET", homeTestOrigin+"/", nil)
526 r.AddCookie(cookie)
527 w := httptest.NewRecorder()
528 mux.ServeHTTP(w, r)
529 if w.Code != 500 {
530 t.Fatal("storage read did not fail", w.Code)
531 }
532 var n int64
533 a.db.G.Table("sessions").Count(&n)
534 if n != 2 {
535 t.Fatal("transient read revoked sessions", n)
536 }
537 for _, c := range w.Result().Cookies() {
538 if c.Name == cookie.Name {
539 t.Fatal("transient read mutated session cookie")
540 }
541 }
542}
543func TestHomeFinishRemovedPersonIsAdmissionRefusal(t *testing.T) {
544 for _, remove := range []string{"deleted", "denied"} {
545 t.Run(remove, func(t *testing.T) {
546 mux, a, u, key := homeFixtureKey(t)
547 homeLinked(t, a, u)
548 start := httptest.NewRecorder()
549 mux.ServeHTTP(start, httptest.NewRequest("GET", homeTestOrigin+handoff.StartPath, nil))
550 target, _ := url.Parse(start.Header().Get("Location"))
551 if start.Code != 303 {
552 t.Fatal("start", start.Code)
553 }
554 now := time.Now().Unix()
555 id, _ := assertion.RandomID()
556 token, err := assertion.Sign(key, assertion.Claims{Version: 1, Issuer: a.cfg.Home.Issuer, Audience: homeTestOrigin, Subject: "home-person", KeyID: "test", ID: id, Nonce: target.Query().Get("nonce"), IssuedAt: now, ExpiresAt: now + 90, AuthTime: now})
557 if err != nil {
558 t.Fatal(err)
559 }
560 callbackReq := httptest.NewRequest("POST", homeTestOrigin+handoff.CallbackPath, strings.NewReader(url.Values{"assertion": {token}}.Encode()))
561 callbackReq.Header.Set("Origin", a.cfg.Home.Issuer)
562 callbackReq.Header.Set("Content-Type", "application/x-www-form-urlencoded")
563 callback := httptest.NewRecorder()
564 mux.ServeHTTP(callback, callbackReq)
565 if callback.Code != 303 {
566 t.Fatal("callback", callback.Code)
567 }
568 if remove == "deleted" {
569 if err := a.db.G.Delete(&u).Error; err != nil {
570 t.Fatal(err)
571 }
572 } else {
573 a.allowed = allowlist{addrs: map[string]struct{}{}}
574 }
575 finishReq := httptest.NewRequest("GET", homeTestOrigin+handoff.FinishPath, nil)
576 for _, response := range []*httptest.ResponseRecorder{start, callback} {
577 for _, c := range response.Result().Cookies() {
578 if c.MaxAge >= 0 {
579 finishReq.AddCookie(c)
580 }
581 }
582 }
583 finish := httptest.NewRecorder()
584 mux.ServeHTTP(finish, finishReq)
585 if finish.Code != 403 {
586 t.Fatal("admission became storage failure", finish.Code, finish.Body.String())
587 }
588 for _, c := range finish.Result().Cookies() {
589 if c.Name == a.homeSessions.CookieName() {
590 t.Fatal("removed person received session")
591 }
592 }
593 })
594 }
595}
596
597func TestHomeEditorPresentationAndExportUseExistingOwner(t *testing.T) {
598 mux, a, u := homeFixture(t)
599 homeLinked(t, a, u)
600 a.seedSampleDeckFor(context.Background(), u)
601 var deck Deck
602 if err := a.db.G.Where("owner_id=?", u.ID).Take(&deck).Error; err != nil {
603 t.Fatal(err)
604 }
605 home := homeSession(t, a, "home-person", connect.HomeMethod)
606 local := homeSession(t, a, u.Email, "magiclink")
607 request := func(method, path string, cookie *http.Cookie) *httptest.ResponseRecorder {
608 r := httptest.NewRequest(method, homeTestOrigin+path, nil)
609 r.AddCookie(cookie)
610 if method == "POST" {
611 r.Header.Set("Origin", homeTestOrigin)
612 }
613 w := httptest.NewRecorder()
614 mux.ServeHTTP(w, r)
615 return w
616 }
617 base := "/d/" + deck.Sqid
618 for _, path := range []string{base + "/edit", base + "/updates?since=0", "/agents"} {
619 if w := request("GET", path, home); w.Code != 200 {
620 t.Fatal("Home route", path, w.Code)
621 }
622 }
623 present := request("POST", base+"/present", home)
624 if present.Code != 303 {
625 t.Fatal("present", present.Code)
626 }
627 if notes := request("GET", present.Header().Get("Location"), home); notes.Code != 200 {
628 t.Fatal("Home presenter lost access", notes.Code)
629 }
630 export := request("POST", base+"/export", home)
631 if export.Code != 303 {
632 t.Fatal("export", export.Code)
633 }
634 status := export.Header().Get("Location")
635 if page := request("GET", status, home); page.Code != 200 {
636 t.Fatal("Home job status", page.Code, page.Body.String())
637 }
638 if page := request("GET", status, local); page.Code != 200 {
639 t.Fatal("local method lost same owner's job", page.Code)
640 }
641 deadline := time.Now().Add(30 * time.Second)
642 for time.Now().Before(deadline) {
643 pdf := request("GET", status+".pdf", home)
644 if pdf.Code == 200 {
645 if !bytes.HasPrefix(pdf.Body.Bytes(), []byte("%PDF-")) {
646 t.Fatal("export not PDF")
647 }
648 return
649 }
650 time.Sleep(25 * time.Millisecond)
651 }
652 t.Fatal("Home export did not become readable PDF")
653}
654
655// Astra's door-copy review: the account-connection start page's action
656// is the verb the page is about, "Connect", not a bare "Continue".
657func TestHomeStartPageActionSaysConnect(t *testing.T) {
658 mux, a, u := homeFixture(t)
659 loc, err := rastrillo.NewLocales(Locales, DefaultLocale, rastrillo.BaseCatalog(), LocaleFS)
660 if err != nil {
661 t.Fatal(err)
662 }
663 r := httptest.NewRequest("GET", homeTestOrigin+"/account/home", nil)
664 r.AddCookie(homeSession(t, a, u.Email, "magiclink"))
665 w := httptest.NewRecorder()
666 loc.Middleware(mux).ServeHTTP(w, r)
667 if w.Code != 200 {
668 t.Fatal(w.Code)
669 }
670 b := w.Body.String()
671 if !strings.Contains(b, "Connect your Oficina account") {
672 t.Fatal("not the connection start page")
673 }
674 if !strings.Contains(b, ">Connect</button>") {
675 t.Error("the start action does not say Connect")
676 }
677 if strings.Contains(b, ">Continue</button>") {
678 t.Error("the start action still says Continue")
679 }
680}
681
682// The switcher appears only with a hub directory configured. It shows the
683// suite's six apps as tiles at their hosts under the directory's, with
684// Slides marked current, and "All apps" below a divider.
685func TestTheSwitcherShowsTheSuite(t *testing.T) {
686 loc, err := rastrillo.NewLocales(Locales, DefaultLocale, rastrillo.BaseCatalog(), LocaleFS)
687 if err != nil {
688 t.Fatal(err)
689 }
690 page := func(mux *http.ServeMux, a *app, u User) string {
691 t.Helper()
692 r := httptest.NewRequest("GET", homeTestOrigin+"/", nil)
693 r.AddCookie(homeSession(t, a, u.Email, "magiclink"))
694 w := httptest.NewRecorder()
695 loc.Middleware(mux).ServeHTTP(w, r)
696 if w.Code != 200 {
697 t.Fatal(w.Code)
698 }
699 return w.Body.String()
700 }
701
702 if body := page(homeFixture(t)); strings.Contains(body, "estilo-switcher") {
703 t.Error("a switcher with no hub directory")
704 }
705
706 mux, a, u, _ := homeFixtureDirectory(t, "https://oficina.works")
707 body := page(mux, a, u)
708 start := strings.Index(body, `<details estilo-switcher name="estilo-menus">`)
709 if start < 0 {
710 t.Fatal("no switcher", body)
711 }
712 panel := body[start:]
713 panel = panel[:strings.Index(panel, "</details>")]
714 grid, allApps, ok := strings.Cut(panel, "<hr>")
715 if !ok || !strings.Contains(allApps, `<a estilo-menu-item href="https://oficina.works/"><span estilo-menu-label>All apps</span></a>`) {
716 t.Error("the switcher does not offer All apps below the tiles", panel)
717 }
718 var tiles []string
719 for _, tile := range strings.Split(grid, "<a estilo-switcher-app ")[1:] {
720 tiles = append(tiles, tile[:strings.Index(tile, "</a>")])
721 }
722 want := []string{"docs", "sheets", "slides", "calendar", "memoria", "calls"}
723 names := []string{"Docs", "Sheets", "Slides", "Calendar", "Memoria", "Calls"}
724 if len(tiles) != len(want) {
725 t.Fatalf("%d tiles, want %d: %s", len(tiles), len(want), grid)
726 }
727 for i, slug := range want {
728 head := `href="https://` + slug + `.oficina.works/"`
729 if slug == "slides" {
730 head += ` aria-current="true"`
731 }
732 head += `><img src="/static/estilo/brand/` + slug + `.svg" alt="" width="32" height="32"><span>` + names[i]
733 if !strings.HasPrefix(tiles[i], head) {
734 t.Errorf("tile %d = %s, want it to start %s", i, tiles[i], head)
735 }
736 }
737 if strings.Count(grid, "aria-current") != 1 || !strings.Contains(tiles[2], "<span estilo-visually-hidden> (this app)</span>") {
738 t.Error("Slides is not the one current tile", grid)
739 }
740
741 // The tiles' icons are public: no cookie, no session.
742 w := httptest.NewRecorder()
743 mux.ServeHTTP(w, httptest.NewRequest("GET", homeTestOrigin+"/static/estilo/brand/calls.svg", nil))
744 if w.Code != http.StatusOK {
745 t.Errorf("a tile's icon is %d", w.Code)
746 }
747}
748