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
3import (
4 "bytes"
5 "crypto/sha256"
6 "encoding/base64"
7 "encoding/hex"
8 "encoding/json"
9 "net/http"
10 "net/http/httptest"
11 "net/url"
12 "reflect"
13 "strings"
14 "testing"
15 "time"
16
17 "amadan.net/rastrillo/rastrillo/assertion"
18 assertioncrypto "amadan.net/rastrillo/rastrillo/crypto"
19 "amadan.net/rastrillo/rastrillo/sessions"
20)
21
22type routerHomeFixture struct {
23 app *App
24 key *assertioncrypto.Keypair
25 keyID string
26 sessions *sessions.Sessions
27}
28type routerBrowser struct {
29 f *routerHomeFixture
30 cookies map[string]*http.Cookie
31 // returnTo is posted with the local sign-in form, as the door's form
32 // posts the page it was opened for.
33 returnTo string
34}
35
36func newRouterHomeFixture(t *testing.T) *routerHomeFixture {
37 return newRouterHomeFixtureDirectory(t, "")
38}
39func newRouterHomeFixtureDirectory(t *testing.T, directory string) *routerHomeFixture {
40 t.Helper()
41 key, err := assertioncrypto.Generate()
42 if err != nil {
43 t.Fatal(err)
44 }
45 digest := sha256.Sum256(key.SignPub())
46 kid := hex.EncodeToString(digest[:])
47 manifest, err := json.Marshal(map[string]string{kid: base64.StdEncoding.EncodeToString(key.SignPub())})
48 if err != nil {
49 t.Fatal(err)
50 }
51 cfg := HomeConfig{Issuer: bridgeIssuer, ConsumerID: "router-docs", KeysBase64: base64.StdEncoding.EncodeToString(manifest), DEKBase64: base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{83}, 32))}
52 app, err := NewForTestWith(t, Config{Origin: bridgeOrigin, Directory: directory, Home: &cfg, AllowedAddresses: "alice@example.com,bob@example.com", SampleDocuments: "0", Mailer: navigationMail{}})
53 if err != nil {
54 t.Fatal(err)
55 }
56 sess, err := sessions.New(sessions.Config{DB: app.db.Writer(), Origin: bridgeOrigin})
57 if err != nil {
58 t.Fatal(err)
59 }
60 return &routerHomeFixture{app: app, key: key, keyID: kid, sessions: sess}
61}
62func (f *routerHomeFixture) browser() *routerBrowser {
63 return &routerBrowser{f: f, cookies: map[string]*http.Cookie{}}
64}
65func (b *routerBrowser) request(method, path, body string) *http.Request {
66 r := httptest.NewRequest(method, bridgeOrigin+path, strings.NewReader(body))
67 for _, c := range b.cookies {
68 r.AddCookie(c)
69 }
70 if method == "POST" {
71 r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
72 r.Header.Set("Origin", bridgeOrigin)
73 r.Header.Set("Sec-Fetch-Site", "same-origin")
74 }
75 return r
76}
77func (b *routerBrowser) serve(r *http.Request) *httptest.ResponseRecorder {
78 rec := httptest.NewRecorder()
79 var w http.ResponseWriter = rec
80 if b.f.app.store.team != nil {
81 w = &teamDeadlineRecorder{ResponseRecorder: rec}
82 }
83 b.f.app.Handler().ServeHTTP(w, r)
84 for _, c := range rec.Result().Cookies() {
85 if c.MaxAge < 0 {
86 delete(b.cookies, c.Name)
87 } else {
88 b.cookies[c.Name] = c
89 }
90 }
91 return rec
92}
93func (b *routerBrowser) do(method, path, body string) *httptest.ResponseRecorder {
94 return b.serve(b.request(method, path, body))
95}
96func routerRedirect(t *testing.T, rec *httptest.ResponseRecorder, want string) string {
97 t.Helper()
98 location := rec.Header().Get("Location")
99 if rec.Code != 303 || (want != "" && location != want) {
100 t.Fatalf("router redirect status=%d target=%q want=%q", rec.Code, location, want)
101 }
102 return location
103}
104func (b *routerBrowser) localLink(t *testing.T, address string) string {
105 t.Helper()
106 b.f.app.signinMail.wait()
107 b.f.app.mailRecorder.mu.Lock()
108 before := b.f.app.mailRecorder.sends
109 b.f.app.mailRecorder.mu.Unlock()
110 form := url.Values{"address": {address}, "force": {"1"}}
111 if b.returnTo != "" {
112 form.Set("return_to", b.returnTo)
113 }
114 rec := b.do("POST", "/signin", form.Encode())
115 if rec.Code != 303 || !strings.Contains(rec.Header().Get("Location"), "sent=1") {
116 t.Fatal("local mail begin failed", rec.Code)
117 }
118 b.f.app.signinMail.wait() // the link is sent after the response
119 b.f.app.mailRecorder.mu.Lock()
120 to, body, after := b.f.app.mailRecorder.lastTo, b.f.app.mailRecorder.lastBody, b.f.app.mailRecorder.sends
121 b.f.app.mailRecorder.mu.Unlock()
122 if after != before+1 || to != address {
123 t.Fatal("actual local mail not captured")
124 }
125 link := magicLinkPattern.FindString(body)
126 path, err := linkPath(link)
127 if err != nil || path == "" {
128 t.Fatal("captured verification link missing")
129 }
130 return path
131}
132
133// localSignin completes a local email sign-in. It lands on the list, or
134// on landing when the browser was sent to sign in from a page (spec
135// §9.4: the remembered return path, not "/").
136func (b *routerBrowser) localSignin(t *testing.T, address string, landing ...string) {
137 t.Helper()
138 want := "/"
139 if len(landing) == 1 {
140 want = landing[0]
141 }
142 path := b.localLink(t, address)
143 verifyPath, verifyForm := confirmForm(path)
144 rec := b.do("POST", verifyPath, verifyForm)
145 routerRedirect(t, rec, localLinkCompletePath)
146 routerRedirect(t, b.do("GET", localLinkCompletePath, ""), want)
147 if _, ok := b.cookies[b.f.sessions.CookieName()]; !ok {
148 t.Fatal("local verification did not set real session")
149 }
150}
151func (b *routerBrowser) start(t *testing.T, path, maxAge string) string {
152 t.Helper()
153 rec := b.do("GET", path, "")
154 target, err := url.Parse(routerRedirect(t, rec, ""))
155 if err != nil {
156 t.Fatal(err)
157 }
158 if target.Scheme+"://"+target.Host != bridgeIssuer || target.Path != "/authorize" || target.Query().Get("consumer") != "router-docs" || target.Query().Get("max_age") != maxAge || target.Query().Get("nonce") == "" {
159 t.Fatal("router selected wrong issuer/freshness")
160 }
161 return target.Query().Get("nonce")
162}
163func (f *routerHomeFixture) token(t *testing.T, nonce, subject string, auth time.Time, change func(*assertion.Claims)) string {
164 t.Helper()
165 id, err := assertion.RandomID()
166 if err != nil {
167 t.Fatal(err)
168 }
169 now := time.Now().Unix()
170 c := assertion.Claims{Version: 1, Issuer: bridgeIssuer, Audience: bridgeOrigin, Subject: subject, KeyID: f.keyID, ID: id, Nonce: nonce, IssuedAt: now, ExpiresAt: now + 120, AuthTime: auth.Unix()}
171 if change != nil {
172 change(&c)
173 }
174 token, err := assertion.Sign(f.key, c)
175 if err != nil {
176 t.Fatal(err)
177 }
178 return token
179}
180func (b *routerBrowser) callback(token, origin string) *httptest.ResponseRecorder {
181 // The issuer POST deliberately carries no browser cookies, as with Lax cookies.
182 r := httptest.NewRequest("POST", bridgeOrigin+"/auth/assertion", strings.NewReader(url.Values{"assertion": {token}}.Encode()))
183 r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
184 r.Header.Set("Origin", origin)
185 r.Header.Set("Sec-Fetch-Site", "cross-site")
186 return b.serve(r)
187}
188func (b *routerBrowser) exchange(t *testing.T, nonce, subject string, auth time.Time) *httptest.ResponseRecorder {
189 t.Helper()
190 routerRedirect(t, b.callback(b.f.token(t, nonce, subject, auth, nil), bridgeIssuer), "/auth/finish")
191 return b.do("GET", "/auth/finish", "")
192}
193func (b *routerBrowser) linkProof(t *testing.T, subject, address string) {
194 t.Helper()
195 page := b.do("GET", "/account/home", "")
196 if page.Code != 200 || !strings.Contains(page.Body.String(), address) {
197 t.Fatal("explicit initiation page did not identify local account", page.Code)
198 }
199 next := routerRedirect(t, b.do("POST", "/account/home", ""), "")
200 nonce := b.start(t, next, "300")
201 routerRedirect(t, b.exchange(t, nonce, subject, time.Now().Add(-time.Minute)), "/account/home/confirm")
202 confirm := b.do("GET", "/account/home/confirm", "")
203 if confirm.Code != 200 || !strings.Contains(confirm.Body.String(), address) {
204 t.Fatal("confirmation did not identify local account", confirm.Code)
205 }
206}
207func routerRows(t *testing.T, f *routerHomeFixture, table string) int {
208 t.Helper()
209 var n int
210 if err := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM " + table).Scan(&n); err != nil {
211 t.Fatal(err)
212 }
213 return n
214}
215
216func TestHomeRouterExistingAccountRoundTripPreservesOwnedAndSharedContent(t *testing.T) {
217 f := newRouterHomeFixture(t)
218 s := f.app.store
219 ctx := t.Context()
220 alice, err := s.EnsurePerson(ctx, "alice@example.com")
221 if err != nil {
222 t.Fatal(err)
223 }
224 bob, err := s.EnsurePerson(ctx, "bob@example.com")
225 if err != nil {
226 t.Fatal(err)
227 }
228 own, err := s.createDocument(ctx, alice, "Alice original", "", VisibilityPrivate)
229 if err != nil {
230 t.Fatal(err)
231 }
232 shared, err := s.createDocument(ctx, bob, "Bob shared", "", VisibilityPrivate)
233 if err != nil {
234 t.Fatal(err)
235 }
236 hidden, err := s.createDocument(ctx, bob, "Bob private", "", VisibilityPrivate)
237 if err != nil {
238 t.Fatal(err)
239 }
240 if err = s.Grant(ctx, bob, shared.Sqid, "alice@example.com", RoleWriter); err != nil {
241 t.Fatal(err)
242 }
243 for _, doc := range []*Document{own, shared} {
244 owner := alice
245 address := "alice@example.com"
246 if doc.ID == shared.ID {
247 owner = bob
248 address = "bob@example.com"
249 }
250 if _, err = s.ApplyUpdate(ctx, doc, localActor(owner, address), ReadFixture(t, "hello")); err != nil {
251 t.Fatal(err)
252 }
253 }
254 var originalDocs []Document
255 var originalUpdates []DocUpdate
256 var originalGrants []Grant
257 if err = s.db.Order("id").Find(&originalDocs).Error; err != nil {
258 t.Fatal(err)
259 }
260 if err = s.db.Order("id").Find(&originalUpdates).Error; err != nil {
261 t.Fatal(err)
262 }
263 if err = s.db.Order("id").Find(&originalGrants).Error; err != nil {
264 t.Fatal(err)
265 }
266 b := f.browser()
267 resource := "/d/" + own.Sqid
268 signin := routerRedirect(t, b.do("GET", resource, ""), "")
269 parsed, err := url.Parse(signin)
270 if err != nil || parsed.Path != "/signin" || parsed.Query().Get("return_to") != resource {
271 t.Fatal("unsigned document lost original destination")
272 }
273 // The door, then Continue with Oficina ID, which keeps the resource.
274 if door := b.do("GET", signin, ""); door.Code != 200 {
275 t.Fatal("the door did not render", door.Code)
276 }
277 start := routerRedirect(t, b.do("GET", "/signin/oficina?return_to="+url.QueryEscape(resource), ""), "")
278 nonce := b.start(t, start, "")
279 unknown := b.exchange(t, nonce, "opaque-alice", time.Now().Add(-time.Hour))
280 if unknown.Code != 403 || !strings.Contains(unknown.Body.String(), "/signin/local") {
281 t.Fatal("unknown Home subject did not show local guidance", unknown.Code)
282 }
283 if routerRows(t, f, "people") != 2 || routerRows(t, f, "documents") != 3 || routerRows(t, f, "home_identity_links") != 0 || b.cookies[f.sessions.CookieName()] != nil {
284 t.Fatal("unknown Home subject created an account or session")
285 }
286 // The unknown arrival is remembered, so signing in locally resumes the
287 // link straight away: Home's freshness check, then the confirm step.
288 // The document this browser was sent to sign in from (spec §9.4) is
289 // where "Accounts connected" leads back to.
290 b.localSignin(t, "alice@example.com", "/auth/start?return_to=%2Faccount%2Fhome%2Fconfirm")
291 localCookie := b.cookies[f.sessions.CookieName()].Value
292 nonce = b.start(t, "/auth/start?return_to=%2Faccount%2Fhome%2Fconfirm", "300")
293 routerRedirect(t, b.exchange(t, nonce, "opaque-alice", time.Now().Add(-time.Minute)), "/account/home/confirm")
294 if confirm := b.do("GET", "/account/home/confirm", ""); confirm.Code != 200 || !strings.Contains(confirm.Body.String(), "alice@example.com") {
295 t.Fatal("confirmation did not identify local account", confirm.Code)
296 }
297 if b.cookies[f.sessions.CookieName()].Value != localCookie || routerRows(t, f, "home_identity_links") != 0 {
298 t.Fatal("proof replaced local session or linked before confirmation")
299 }
300 routerRedirect(t, b.do("POST", "/account/home/confirm", ""), connectedURL(resource))
301 if b.cookies[f.sessions.CookieName()].Value != localCookie || routerRows(t, f, "home_identity_links") != 1 {
302 t.Fatal("confirmation failed local session retention")
303 }
304 if rec := b.do("GET", resource, ""); rec.Code != 200 {
305 t.Fatal("linked local account cannot read original document", rec.Code)
306 }
307 signoutChained(t, b.do("POST", "/signout", ""))
308 signedOut := b.do("GET", "/signed-out", "")
309 if signedOut.Code != http.StatusOK || signedOut.Header().Get("Location") != "" || !strings.Contains(signedOut.Body.String(), `href="/signin"`) {
310 t.Fatal("signout automatically resumed Home authentication")
311 }
312 if b.cookies[f.sessions.CookieName()] != nil {
313 t.Fatal("actual signout retained session cookie")
314 }
315 oldRequest := httptest.NewRequest("GET", bridgeOrigin+resource, nil)
316 oldRequest.AddCookie(&http.Cookie{Name: f.sessions.CookieName(), Value: localCookie})
317 oldRec := httptest.NewRecorder()
318 f.app.Handler().ServeHTTP(oldRec, oldRequest)
319 if oldRec.Code != 303 {
320 t.Fatal("actual signout did not revoke old session")
321 }
322 routerRedirect(t, b.do("GET", resource, ""), "")
323 start = routerRedirect(t, b.do("GET", "/signin/oficina?return_to="+url.QueryEscape(resource), ""), "")
324 nonce = b.start(t, start, "")
325 originalAuth := time.Now().Add(-2 * time.Hour).Truncate(time.Second)
326 routerRedirect(t, b.exchange(t, nonce, "opaque-alice", originalAuth), resource)
327 session, ok := f.sessions.From(b.request("GET", resource, ""))
328 if !ok || session.Method != homeAssertionMethod || session.Subject != "opaque-alice" || !session.AuthTime.Equal(originalAuth) {
329 t.Fatal("ordinary Home session lost actual authentication time")
330 }
331 for _, doc := range []*Document{own, shared} {
332 rec := b.do("GET", "/d/"+doc.Sqid, "")
333 if rec.Code != 200 {
334 t.Fatal("Home session lost owned/shared access", rec.Code)
335 }
336 }
337 if rec := b.do("GET", "/d/"+hidden.Sqid, ""); rec.Code != 404 {
338 t.Fatal("Home link widened another owner's private access", rec.Code)
339 }
340 var afterDocs []Document
341 var afterUpdates []DocUpdate
342 var afterGrants []Grant
343 if err = s.db.Order("id").Find(&afterDocs).Error; err != nil {
344 t.Fatal(err)
345 }
346 if err = s.db.Order("id").Find(&afterUpdates).Error; err != nil {
347 t.Fatal(err)
348 }
349 if err = s.db.Order("id").Find(&afterGrants).Error; err != nil {
350 t.Fatal(err)
351 }
352 if !reflect.DeepEqual(originalDocs, afterDocs) || !reflect.DeepEqual(originalUpdates, afterUpdates) || !reflect.DeepEqual(originalGrants, afterGrants) || routerRows(t, f, "people") != 2 {
353 t.Fatal("account link changed owners/grants/content encoding or bytes")
354 }
355 // A different current local account cannot be silently replaced by Alice's SSO.
356 other := f.browser()
357 other.localSignin(t, "bob@example.com")
358 before := other.cookies[f.sessions.CookieName()].Value
359 nonce = other.start(t, "/auth/start?return_to=%2F", "")
360 if rec := other.exchange(t, nonce, "opaque-alice", time.Now()); rec.Code != 403 {
361 t.Fatal("different local account was replaced", rec.Code)
362 }
363 if other.cookies[f.sessions.CookieName()].Value != before {
364 t.Fatal("conflict rotated local account")
365 }
366}
367
368func TestHomeRouterCSRFGuardsBothLinkMutations(t *testing.T) {
369 f := newRouterHomeFixture(t)
370 b := f.browser()
371 b.localSignin(t, "alice@example.com")
372 if rec := b.do("GET", "/account/home", ""); rec.Code != 200 {
373 t.Fatal("missing local initiation page")
374 }
375 for _, fetch := range []string{"cross-site", ""} {
376 r := b.request("POST", "/account/home", "")
377 r.Header.Set("Origin", "https://evil.example")
378 r.Header.Set("Sec-Fetch-Site", fetch)
379 rec := b.serve(r)
380 if rec.Code != 403 || routerRows(t, f, "home_link_flows") != 0 {
381 t.Fatal("actual router permitted foreign link initiation", rec.Code)
382 }
383 }
384 b.linkProof(t, "opaque-alice", "alice@example.com")
385 for _, fetch := range []string{"cross-site", ""} {
386 r := b.request("POST", "/account/home/confirm", "")
387 r.Header.Set("Origin", "https://evil.example")
388 r.Header.Set("Sec-Fetch-Site", fetch)
389 rec := b.serve(r)
390 if rec.Code != 403 || routerRows(t, f, "home_identity_links") != 0 || routerRows(t, f, "home_link_flows") != 1 {
391 t.Fatal("actual router permitted foreign confirmation or consumed valid proof", rec.Code)
392 }
393 }
394 routerRedirect(t, b.do("POST", "/account/home/confirm", ""), connectedURL("/"))
395 if routerRows(t, f, "home_identity_links") != 1 {
396 t.Fatal("valid same-origin confirmation failed after refusal")
397 }
398}
399
400func TestHomeRouterRejectsDuplicateCookiesBeforeActualEmailVerification(t *testing.T) {
401 f := newRouterHomeFixture(t)
402 b := f.browser()
403 b.localSignin(t, "alice@example.com")
404 old := b.cookies[f.sessions.CookieName()]
405 path := b.localLink(t, "alice@example.com")
406 for _, name := range []string{f.sessions.CookieName(), "__Host-rastrillo_pending"} {
407 verifyPath, verifyForm := confirmForm(path)
408 r := b.request("POST", verifyPath, verifyForm)
409 if name == f.sessions.CookieName() {
410 r.AddCookie(old)
411 } else {
412 r.AddCookie(&http.Cookie{Name: name, Value: "one"})
413 r.AddCookie(&http.Cookie{Name: name, Value: "two"})
414 }
415 rec := b.serve(r)
416 if rec.Code != 400 {
417 t.Fatal("duplicate cookie reached actual Verify", name, rec.Code)
418 }
419 if b.cookies[f.sessions.CookieName()].Value != old.Value {
420 t.Fatal("refused duplicate rotated browser session")
421 }
422 if _, ok := f.sessions.From(b.request("GET", "/", "")); !ok {
423 t.Fatal("refused duplicate revoked actual session")
424 }
425 }
426 // Both refusals happened before CompleteMagicLink consumed the token.
427 verifyPath, verifyForm := confirmForm(path)
428 routerRedirect(t, b.do("POST", verifyPath, verifyForm), localLinkCompletePath)
429 if b.cookies[f.sessions.CookieName()].Value == old.Value {
430 t.Fatal("clean real Verify did not rotate cookie")
431 }
432 r := httptest.NewRequest("GET", bridgeOrigin+"/", nil)
433 r.AddCookie(old)
434 if _, ok := f.sessions.From(r); ok {
435 t.Fatal("successful real Verify did not revoke old session")
436 }
437 routerRedirect(t, b.do("GET", localLinkCompletePath, ""), "/")
438}
439
440func TestHomeRouterStaleLocalGestureRestartsWithoutResumingProof(t *testing.T) {
441 f := newRouterHomeFixture(t)
442 b := f.browser()
443 b.localSignin(t, "alice@example.com")
444 b.linkProof(t, "opaque-alice", "alice@example.com")
445 oldProof := b.cookies[homeProofCookie]
446 oldSession := b.cookies[f.sessions.CookieName()]
447 if oldProof == nil || routerRows(t, f, "home_link_flows") != 1 {
448 t.Fatal("pending proof fixture missing")
449 }
450 // Move only the actual stored local verification time into the past:
451 // auth_time, which a magic link records from rastrillo v0.45.0. The
452 // row's created_at stays fresh, so this holds that auth_time is what
453 // decides. The old pending proof remains present so its post-rotation
454 // refusal is exercised.
455 stale := time.Now().Add(-6 * time.Minute).UTC().Format(time.RFC3339)
456 if _, err := f.app.db.Writer().Exec(`UPDATE sessions SET auth_time=? WHERE token_hash=?`, stale, sessions.HashToken(oldSession.Value)); err != nil {
457 t.Fatal(err)
458 }
459 routerRedirect(t, b.do("GET", "/account/home", ""), "/signin/local?reauth=1")
460 if b.cookies[localLinkNavigationCookie] == nil || b.cookies[homeInitCookie] != nil || b.cookies[homeProofCookie] != nil {
461 t.Fatal("stale local restart retained link browser proof")
462 }
463 if rec := b.do("GET", "/signin/local?reauth=1", ""); rec.Code != 200 {
464 t.Fatal("signed-in stale visitor could not see local signin")
465 }
466 path := b.localLink(t, "alice@example.com")
467 verifyPath, verifyForm := confirmForm(path)
468 routerRedirect(t, b.do("POST", verifyPath, verifyForm), localLinkCompletePath)
469 routerRedirect(t, b.do("GET", localLinkCompletePath, ""), "/account/home")
470 if b.cookies[f.sessions.CookieName()].Value == oldSession.Value || b.cookies[homeProofCookie] != nil || b.cookies[homeInitCookie] != nil || routerRows(t, f, "home_identity_links") != 0 {
471 t.Fatal("navigation minted or resumed link authority")
472 }
473 if rec := b.do("GET", "/account/home", ""); rec.Code != 200 {
474 t.Fatal("fresh local gesture did not reach initiation page")
475 }
476 // A copied old proof cannot attach to the freshly rotated local session.
477 b.cookies[homeProofCookie] = oldProof
478 if rec := b.do("POST", "/account/home/confirm", ""); rec.Code != 403 {
479 t.Fatal("old proof resumed after actual session rotation", rec.Code)
480 }
481 if routerRows(t, f, "home_identity_links") != 0 || routerRows(t, f, "home_link_flows") != 0 {
482 t.Fatal("old proof failure created link or retained reusable proof")
483 }
484 oldRequest := httptest.NewRequest("GET", bridgeOrigin+"/", nil)
485 oldRequest.AddCookie(oldSession)
486 if _, ok := f.sessions.From(oldRequest); ok {
487 t.Fatal("old local browser token survived reverification")
488 }
489 // Only this new explicit POST creates a new initiation, not the email or GET.
490 routerRedirect(t, b.do("POST", "/account/home", ""), "/auth/start?return_to=%2Faccount%2Fhome%2Fconfirm")
491 if routerRows(t, f, "home_link_flows") != 1 || routerRows(t, f, "home_identity_links") != 0 || b.cookies[homeProofCookie] != nil {
492 t.Fatal("new explicit initiation state wrong")
493 }
494}
495
496func TestHomeRouterCallbackChecksExactOriginIssuerAndAudience(t *testing.T) {
497 f := newRouterHomeFixture(t)
498 b := f.browser()
499 nonce := b.start(t, "/auth/start?return_to=%2F", "")
500 for _, tc := range []struct {
501 name, origin string
502 change func(*assertion.Claims)
503 }{
504 {"wrong origin", "https://evil.example", nil},
505 {"missing origin", "", nil},
506 {"wrong signed issuer", bridgeIssuer, func(c *assertion.Claims) { c.Issuer = "https://other-id.example" }},
507 {"wrong signed audience", bridgeIssuer, func(c *assertion.Claims) { c.Audience = "https://other.docs.oficina.works" }},
508 } {
509 t.Run(tc.name, func(t *testing.T) {
510 rec := b.callback(f.token(t, nonce, "opaque", time.Now(), tc.change), tc.origin)
511 if rec.Code != 400 || routerRows(t, f, "oficina_handoff_inbox") != 0 || b.cookies[f.sessions.CookieName()] != nil {
512 t.Fatal("invalid callback created inbox/session", rec.Code)
513 }
514 })
515 }
516 r := b.request("GET", "/auth/start?return_to=%2F", "")
517 r.Host = "other.docs.oficina.works"
518 if rec := b.serve(r); rec.Code != 404 {
519 t.Fatal("router accepted another team host", rec.Code)
520 }
521 // A valid issuer callback still crosses the outer CSRF boundary and reaches
522 // the shared consumer. Duplicate local cookies cannot poison that callback.
523 token := f.token(t, nonce, "opaque", time.Now(), nil)
524 r = httptest.NewRequest("POST", bridgeOrigin+"/auth/assertion", strings.NewReader(url.Values{"assertion": {token}}.Encode()))
525 r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
526 r.Header.Set("Origin", bridgeIssuer)
527 r.Header.Set("Sec-Fetch-Site", "cross-site")
528 r.AddCookie(&http.Cookie{Name: f.sessions.CookieName(), Value: "bad"})
529 r.AddCookie(&http.Cookie{Name: f.sessions.CookieName(), Value: "bad"})
530 routerRedirect(t, b.serve(r), "/auth/finish")
531 if rec := b.do("GET", "/auth/finish", ""); rec.Code != 403 || !strings.Contains(rec.Body.String(), "/signin/local") {
532 t.Fatal("unknown verified identity not guided after valid callback")
533 }
534 if routerRows(t, f, "people") != 0 || routerRows(t, f, "home_identity_links") != 0 {
535 t.Fatal("unknown callback created person/link")
536 }
537}
538