package connect import ( "context" "database/sql" "errors" "net/http" "net/http/httptest" "net/url" "slices" "strings" "sync" "testing" "time" ) // homeOnlyHooks is a team-mode app in miniature: a Home-only person table, // a roster decision and an allocation decision a test sets (admit, refuse, // or cannot decide). It counts how often each hook is asked, so a test can // prove when connect does not ask at all. type homeOnlyHooks struct { db *sql.DB admission error // Admit: nil is a Member; ErrNoPerson a non-member; anything else unavailable decision error // Unlinked: nil allocates; anything else is returned as is label string lookupErr error admitted int unlinked int homeOnly int remember int // mu guards the counters when a test races requests. mu sync.Mutex } func (h *homeOnlyHooks) tally(n *int) { h.mu.Lock() *n++ h.mu.Unlock() } func (h *homeOnlyHooks) install(f *bridgeFixture, c *Config) { h.db = f.db if _, err := f.db.Exec("CREATE TABLE home_only(id INTEGER PRIMARY KEY AUTOINCREMENT, issuer TEXT NOT NULL, subject TEXT NOT NULL, UNIQUE(issuer,subject)); INSERT INTO sqlite_sequence(name,seq) VALUES('home_only',1000)"); err != nil { panic(err) } c.HomeOnly = func(ctx context.Context, issuer, subject string) (Person, error) { h.tally(&h.homeOnly) if h.lookupErr != nil { return Person{}, h.lookupErr } var p Person err := h.db.QueryRowContext(ctx, "SELECT id FROM home_only WHERE issuer=? AND subject=?", issuer, subject).Scan(&p.ID) if errors.Is(err, sql.ErrNoRows) { return Person{}, ErrNoPerson } p.Label = h.label return p, err } c.Admit = func(ctx context.Context, issuer, subject string) error { h.tally(&h.admitted) return h.admission } c.Unlinked = func(ctx context.Context, issuer, subject string) (Person, error) { h.tally(&h.unlinked) if h.decision != nil { return Person{}, h.decision } res, err := h.db.ExecContext(ctx, "INSERT INTO home_only(issuer,subject) VALUES(?,?)", issuer, subject) if err != nil { return Person{}, err } id, err := res.LastInsertId() return Person{ID: id, Label: h.label}, err } } func newHomeOnlyFixture(t *testing.T) (*bridgeFixture, *homeOnlyHooks) { t.Helper() h := &homeOnlyHooks{} f := newBridgeFixtureWith(t, h.install) f.b.rememberUnknown = func(http.ResponseWriter) { h.remember++ } return f, h } func (h *homeOnlyHooks) count(t *testing.T) int { t.Helper() var n int if err := h.db.QueryRow("SELECT COUNT(*) FROM home_only").Scan(&n); err != nil { t.Fatal(err) } return n } // finishAs runs one ordinary exchange for subject with cookies present. func (f *bridgeFixture) finishAs(t *testing.T, subject string, cookies []*http.Cookie) *httptest.ResponseRecorder { t.Helper() pending, nonce := f.start(t, cookies, "/next") inbox := f.callback(t, subject, nonce, time.Now().Add(-time.Minute)) w := httptest.NewRecorder() f.b.Finish(w, bridgeRequest(http.MethodGet, "/auth/finish", append(append([]*http.Cookie{}, cookies...), pending, inbox))) return w } // choose follows a finish that answered "choose": the page, then the POST. // It returns the page's response and the POST's. func (f *bridgeFixture) choose(t *testing.T, finish *httptest.ResponseRecorder, choice string, cookies []*http.Cookie) (*httptest.ResponseRecorder, *httptest.ResponseRecorder) { t.Helper() if finish.Code != 303 || finish.Header().Get("Location") != ChoosePath { t.Fatalf("finish=%d %q, want the choose page", finish.Code, finish.Header().Get("Location")) } proof := bridgeCookie(t, finish, homeChoiceCookie) cookies = append(append([]*http.Cookie{}, cookies...), proof) page := httptest.NewRecorder() f.b.ChoosePage(page, bridgeRequest(http.MethodGet, ChoosePath, cookies)) if page.Code != 200 || page.Body.String() != "choose" { t.Fatalf("choose page=%d %q", page.Code, page.Body.String()) } return page, f.choosePost(t, choice, f.b.choiceToken(proof.Value), cookies) } func (f *bridgeFixture) choosePost(t *testing.T, choice, token string, cookies []*http.Cookie) *httptest.ResponseRecorder { t.Helper() form := url.Values{"choice": {choice}, "token": {token}} r := httptest.NewRequest(http.MethodPost, bridgeOrigin+ChoosePath, strings.NewReader(form.Encode())) r.Header.Set("Origin", bridgeOrigin) r.Header.Set("Content-Type", "application/x-www-form-urlencoded") for _, c := range cookies { r.AddCookie(c) } w := httptest.NewRecorder() f.b.ChoosePost(w, r) return w } // signInNew is a Member's first sign-in: finish, then "I'm new here". It // returns the session cookie. func (f *bridgeFixture) signInNew(t *testing.T, subject string) *http.Cookie { t.Helper() _, w := f.choose(t, f.finishAs(t, subject, nil), "new", nil) if w.Code != 303 || w.Header().Get("Location") != "/" { t.Fatalf("choose new=%d %q body=%s", w.Code, w.Header().Get("Location"), w.Body.String()) } return bridgeCookie(t, w, f.b.sessionCookie) } func TestTeamHooksAreATrio(t *testing.T) { hook := func(context.Context, string, string) (Person, error) { return Person{}, ErrNoPerson } admit := func(context.Context, string, string) error { return ErrNoPerson } newBridgeFixtureWith(t, func(_ *bridgeFixture, c *Config) { for name, adjust := range map[string]func(*Config){ "unlinked only": func(c *Config) { c.Unlinked = hook }, "home-only only": func(c *Config) { c.HomeOnly = hook }, "admit only": func(c *Config) { c.Admit = admit }, "no admit": func(c *Config) { c.Unlinked, c.HomeOnly = hook, hook }, "no unlinked": func(c *Config) { c.Admit, c.HomeOnly = admit, hook }, "no home-only only": func(c *Config) { c.Admit, c.Unlinked = admit, hook }, } { one := *c adjust(&one) if _, err := New(one); err == nil { t.Errorf("%s: New accepted an incomplete set of team hooks", name) } } all := *c all.Admit, all.Unlinked, all.HomeOnly = admit, hook, hook if _, err := New(all); err != nil { t.Errorf("New refused all three hooks: %v", err) } }) } // A Member with no link is asked, not allocated: the finish leaves a proof // and the choose page, and "I'm new here" makes the Home-only person. func TestMemberChoosesNewAndSignsInAsAHomeOnlyPerson(t *testing.T) { f, h := newHomeOnlyFixture(t) finish := f.finishAs(t, "pr_member", nil) bridgeNoSession(t, f.b, finish) if h.admitted != 1 || h.unlinked != 0 || h.count(t) != 0 || h.remember != 0 { t.Fatalf("finish admitted=%d unlinked=%d people=%d remember=%d", h.admitted, h.unlinked, h.count(t), h.remember) } _, w := f.choose(t, finish, "new", nil) if w.Code != 303 || w.Header().Get("Location") != "/" { t.Fatalf("choose new=%d %q", w.Code, w.Header().Get("Location")) } if h.unlinked != 1 || h.count(t) != 1 || h.admitted != 2 { t.Fatalf("unlinked=%d people=%d admitted=%d", h.unlinked, h.count(t), h.admitted) } cookie := bridgeCookie(t, w, f.b.sessionCookie) r := bridgeRequest(http.MethodGet, "/", []*http.Cookie{cookie}) s, _ := f.sessions.From(r) if s.Method != HomeMethod || s.Subject != "pr_member" { t.Fatalf("session %+v", s) } p, err := f.b.ResolveSession(r) if err != nil || p.ID <= 1000 || p.Label != "" { t.Fatalf("ResolveSession %+v %v", p, err) } // A second sign-in is the same person, straight through: no roster // decision, no choice, no allocation. again := f.finishAs(t, "pr_member", nil) if again.Code != 303 || again.Header().Get("Location") != "/next" || h.unlinked != 1 || h.admitted != 2 || h.count(t) != 1 { t.Fatalf("second sign-in=%d %q unlinked=%d admitted=%d", again.Code, again.Header().Get("Location"), h.unlinked, h.admitted) } if p2, err := f.b.Resolve(context.Background(), "pr_member"); err != nil || p2.ID != p.ID { t.Fatal("Resolve does not find the Home-only person", err) } own := f.finishAs(t, "pr_member", []*http.Cookie{cookie}) if own.Code != 303 || h.unlinked != 1 { t.Fatalf("same person over own session=%d", own.Code) } } // "Connect my existing account" spends the proof and goes to local sign-in // with the link-resuming marker; the spent proof cannot then say "new". func TestChooseConnectConsumesTheProof(t *testing.T) { f, h := newHomeOnlyFixture(t) finish := f.finishAs(t, "pr_member", nil) proof := bridgeCookie(t, finish, homeChoiceCookie) _, w := f.choose(t, finish, "connect", nil) if w.Code != 303 || w.Header().Get("Location") != "/signin/local" || h.remember != 1 { t.Fatalf("connect=%d %q remember=%d", w.Code, w.Header().Get("Location"), h.remember) } bridgeNoSession(t, f.b, w) if again := f.choosePost(t, "new", f.b.choiceToken(proof.Value), []*http.Cookie{proof}); again.Code != 403 { t.Fatalf("spent proof chose new: %d", again.Code) } if h.unlinked != 0 || h.count(t) != 0 { t.Fatal("connect allocated a person") } } // The POST that allocates refuses while any app session is present, and // leaves the proof for a choice made without one. func TestChooseNewRefusedWithAnAppSession(t *testing.T) { f, h := newHomeOnlyFixture(t) finish := f.finishAs(t, "pr_member", nil) proof := bridgeCookie(t, finish, homeChoiceCookie) local := f.local(t, "guest@example.com", "magiclink", time.Now().Add(-time.Minute)) w := f.choosePost(t, "new", f.b.choiceToken(proof.Value), []*http.Cookie{proof, local}) if w.Code != 403 || h.unlinked != 0 || h.count(t) != 0 { t.Fatalf("new over a session=%d unlinked=%d", w.Code, h.unlinked) } bridgeNoSession(t, f.b, w) if ok := f.choosePost(t, "new", f.b.choiceToken(proof.Value), []*http.Cookie{proof}); ok.Code != 303 { t.Fatalf("proof did not survive the refusal: %d", ok.Code) } } // The form token is bound to its proof cookie, and the POST to this origin. func TestChooseFormIsBoundToItsProof(t *testing.T) { f, h := newHomeOnlyFixture(t) mine := bridgeCookie(t, f.finishAs(t, "pr_member", nil), homeChoiceCookie) other := bridgeCookie(t, f.finishAs(t, "pr_other", nil), homeChoiceCookie) for name, w := range map[string]*httptest.ResponseRecorder{ "another proof's token": f.choosePost(t, "new", f.b.choiceToken(other.Value), []*http.Cookie{mine}), "no token": f.choosePost(t, "new", "", []*http.Cookie{mine}), "no proof": f.choosePost(t, "new", f.b.choiceToken(mine.Value), nil), "unknown choice": f.choosePost(t, "both", f.b.choiceToken(mine.Value), []*http.Cookie{mine}), } { if w.Code == 303 { t.Errorf("%s: accepted", name) } bridgeNoSession(t, f.b, w) } for _, origin := range []string{"", "null", "https://evil.example", bridgeIssuer} { form := url.Values{"choice": {"new"}, "token": {f.b.choiceToken(mine.Value)}} r := httptest.NewRequest(http.MethodPost, bridgeOrigin+ChoosePath, strings.NewReader(form.Encode())) if origin != "" { r.Header.Set("Origin", origin) } r.Header.Set("Content-Type", "application/x-www-form-urlencoded") r.AddCookie(mine) w := httptest.NewRecorder() f.b.ChoosePost(w, r) if w.Code != 403 { t.Errorf("Origin %q: %d", origin, w.Code) } } if h.unlinked != 0 || h.count(t) != 0 { t.Fatal("a forged choice allocated") } // The proof survived every refusal. if w := f.choosePost(t, "new", f.b.choiceToken(mine.Value), []*http.Cookie{mine}); w.Code != 303 { t.Fatalf("genuine choice=%d", w.Code) } } func TestChoosePageNeedsALiveProof(t *testing.T) { f, _ := newHomeOnlyFixture(t) for name, cookies := range map[string][]*http.Cookie{ "none": nil, "malformed": {{Name: homeChoiceCookie, Value: "bad"}}, "unknown": {{Name: homeChoiceCookie, Value: strings.Repeat("A", 43)}}, } { w := httptest.NewRecorder() f.b.ChoosePage(w, bridgeRequest(http.MethodGet, ChoosePath, cookies)) if w.Code != 403 || w.Body.String() != "failed" { t.Errorf("%s: %d %q", name, w.Code, w.Body.String()) } } proof := bridgeCookie(t, f.finishAs(t, "pr_member", nil), homeChoiceCookie) f.b.now = func() time.Time { return time.Now().Add(11 * time.Minute) } w := httptest.NewRecorder() f.b.ChoosePage(w, bridgeRequest(http.MethodGet, ChoosePath, []*http.Cookie{proof})) if w.Code != 403 { t.Fatalf("expired proof page=%d", w.Code) } } // Without the hooks there is no choice to make. func TestChooseWithoutHooksIsNotFound(t *testing.T) { f := newBridgeFixture(t) w := httptest.NewRecorder() f.b.ChoosePage(w, bridgeRequest(http.MethodGet, ChoosePath, nil)) if w.Code != 404 { t.Fatalf("page=%d", w.Code) } } // Two "I'm new here" POSTs racing on one proof make one person. func TestChooseRaceMakesOnePerson(t *testing.T) { f, h := newHomeOnlyFixture(t) proof := bridgeCookie(t, f.finishAs(t, "pr_member", nil), homeChoiceCookie) token := f.b.choiceToken(proof.Value) codes := make(chan int, 4) var wg sync.WaitGroup for range 4 { wg.Go(func() { codes <- f.choosePost(t, "new", token, []*http.Cookie{proof}).Code }) } wg.Wait() close(codes) minted := 0 for c := range codes { if c == 303 { minted++ } } if minted != 1 || h.count(t) != 1 { t.Fatalf("minted=%d people=%d", minted, h.count(t)) } } // Unlinked refusing after the roster said Member: resolve again. Nobody // found is unknown, an error is a 503, and a person made meanwhile (a // racing choice) is signed in. func TestChooseNewReResolvesAfterUnlinkedRefuses(t *testing.T) { for _, c := range []struct { name string decision error existing bool code int body string }{ {"refused, nobody", ErrNoPerson, false, 403, "unknown"}, {"error, nobody", errors.New("disk"), false, 503, "failed"}, {"refused, made meanwhile", ErrNoPerson, true, 303, ""}, {"error, made meanwhile", errors.New("disk"), true, 303, ""}, } { t.Run(c.name, func(t *testing.T) { f, h := newHomeOnlyFixture(t) finish := f.finishAs(t, "pr_member", nil) proof := bridgeCookie(t, finish, homeChoiceCookie) h.decision = c.decision if c.existing { // The person appears between the re-check and Unlinked. inner := f.b.unlinked f.b.unlinked = func(ctx context.Context, issuer, subject string) (Person, error) { if _, err := h.db.Exec("INSERT INTO home_only(issuer,subject) VALUES(?,?)", issuer, subject); err != nil { t.Fatal(err) } return inner(ctx, issuer, subject) } } w := f.choosePost(t, "new", f.b.choiceToken(proof.Value), []*http.Cookie{proof}) if w.Code != c.code || (c.body != "" && w.Body.String() != c.body) { t.Fatalf("%d %q", w.Code, w.Body.String()) } if c.code != 303 { bridgeNoSession(t, f.b, w) } }) } } func TestNonMemberIsConnectsUnknown(t *testing.T) { f, h := newHomeOnlyFixture(t) h.admission = ErrNoPerson w := f.finishAs(t, "pr_stranger", nil) if w.Code != 403 || w.Body.String() != "unknown" || h.remember != 1 { t.Fatalf("refused=%d %q remember=%d", w.Code, w.Body.String(), h.remember) } bridgeNoSession(t, f.b, w) for _, c := range w.Result().Cookies() { if c.Name == homeChoiceCookie { t.Fatal("a non-member got a choice proof") } } if h.count(t) != 0 || h.unlinked != 0 { t.Fatal("refusal allocated a person") } } // The answer to a non-member is the answer an instance without the hooks // gives, status, body and headers alike; only the freshly sealed marker // cookie's value differs. func TestNonMemberAnswerIsByteIdenticalToNoHooks(t *testing.T) { plain := newBridgeFixture(t) plain.routes(t) team, h := newHomeOnlyFixture(t) team.routes(t) h.admission = ErrNoPerson a := plain.finishAs(t, "pr_stranger", nil) b := team.finishAs(t, "pr_stranger", nil) if a.Code != b.Code || a.Body.String() != b.Body.String() { t.Fatalf("status/body differ: %d %q vs %d %q", a.Code, a.Body.String(), b.Code, b.Body.String()) } if shape(a.Header()) != shape(b.Header()) { t.Fatalf("headers differ:\n%s\n%s", shape(a.Header()), shape(b.Header())) } } // shape is a header set with cookie values elided. func shape(h http.Header) string { var lines []string for k, vs := range h { for _, v := range vs { if k == "Set-Cookie" { name, rest, _ := strings.Cut(v, "=") _, attrs, _ := strings.Cut(rest, ";") v = name + "=…;" + attrs } lines = append(lines, k+": "+v) } } slices.Sort(lines) return strings.Join(lines, "\n") } func TestRosterUnavailableIsRetryable(t *testing.T) { f, h := newHomeOnlyFixture(t) h.admission = errors.New("roster unknown") w := f.finishAs(t, "pr_member", nil) if w.Code != 503 || w.Body.String() != "failed" || h.remember != 0 { t.Fatalf("undecided=%d %q remember=%d", w.Code, w.Body.String(), h.remember) } bridgeNoSession(t, f.b, w) if h.count(t) != 0 || h.unlinked != 0 { t.Fatal("undecided allocated a person") } h.admission = nil h.lookupErr = errors.New("disk") w = f.finishAs(t, "pr_member", nil) if w.Code != 503 || h.admitted != 1 { t.Fatalf("unreadable Home-only store=%d admitted=%d", w.Code, h.admitted) } bridgeNoSession(t, f.b, w) } // An addressless person is the contract: a hook handing back a label (an // address) is refused, never minted. func TestHomeOnlyPersonWithAnAddressIsRefused(t *testing.T) { f, h := newHomeOnlyFixture(t) h.label = "someone@example.com" _, w := f.choose(t, f.finishAs(t, "pr_member", nil), "new", nil) if w.Code != 403 || w.Body.String() != "unknown" { t.Fatalf("labelled Home-only person=%d %q", w.Code, w.Body.String()) } bridgeNoSession(t, f.b, w) if _, err := f.b.Resolve(context.Background(), "pr_member"); err == nil { t.Fatal("Resolve accepted a Home-only person with an address") } } // Somebody already signed in: an unknown arrival is refused before the // roster is asked and before any proof is issued. func TestAdmitNeverAskedOverALiveSession(t *testing.T) { f, h := newHomeOnlyFixture(t) local := f.local(t, "x@example.com", "magiclink", time.Now().Add(-time.Minute)) w := f.finishAs(t, "pr_member", []*http.Cookie{local}) if w.Code != 403 || w.Body.String() != "unknown" || h.remember != 1 || h.admitted != 0 || h.unlinked != 0 || h.count(t) != 0 { t.Fatalf("arrival over a live session=%d %q admitted=%d unlinked=%d", w.Code, w.Body.String(), h.admitted, h.unlinked) } for _, c := range w.Result().Cookies() { if c.Name == homeChoiceCookie { t.Fatal("a proof was issued over a live session") } } bridgeNoSession(t, f.b, w) } // A guest's local account never blocks a new member's first sign-in: // the roster decides, not whether local accounts exist. func TestGuestLocalAccountNeverBlocksANewMember(t *testing.T) { f, h := newHomeOnlyFixture(t) f.local(t, "guest@example.com", "magiclink", time.Now().Add(-time.Minute)) f.signInNew(t, "pr_member") if h.count(t) != 1 { t.Fatal("member was not admitted beside a guest's local account") } } // Connect's same-person rule holds for Home-only people: a known Home-only // member arriving over somebody else's live session is 403, and that // session survives. func TestKnownHomeOnlyArrivalOverAnotherSessionIsRefused(t *testing.T) { f, h := newHomeOnlyFixture(t) f.signInNew(t, "pr_member") local := f.local(t, "x@example.com", "magiclink", time.Now().Add(-time.Minute)) w := f.finishAs(t, "pr_member", []*http.Cookie{local}) if w.Code != 403 || w.Body.String() != "failed" { t.Fatalf("known arrival over another session=%d %q", w.Code, w.Body.String()) } bridgeNoSession(t, f.b, w) if s, ok := f.sessions.From(bridgeRequest(http.MethodGet, "/", []*http.Cookie{local})); !ok || s.Subject != "x@example.com" { t.Fatal("the live local session changed") } if h.unlinked != 1 { t.Fatal("Unlinked asked again") } } // A linked subject is the linked account: no hook decides anything, and // the link flow never reaches them. func TestLinkedSubjectNeverReachesTheHooks(t *testing.T) { f, h := newHomeOnlyFixture(t) local := f.local(t, "one@example.com", "magiclink", time.Now().Add(-time.Minute)) f.link(t, local, "pr_linked") if h.unlinked != 0 || h.admitted != 0 { t.Fatal("the link flow asked a team hook") } before := h.homeOnly w := f.finishAs(t, "pr_linked", nil) if w.Code != 303 || h.unlinked != 0 || h.admitted != 0 || h.homeOnly != before || h.count(t) != 0 { t.Fatalf("linked sign-in=%d unlinked=%d admitted=%d homeOnly=%d", w.Code, h.unlinked, h.admitted, h.homeOnly-before) } p, err := f.b.ResolveSession(bridgeRequest(http.MethodGet, "/", []*http.Cookie{bridgeCookie(t, w, f.b.sessionCookie)})) if err != nil || p.Label != "one@example.com" { t.Fatal("linked identity changed", err) } } // Malformed cookies are still connect's refusals with the hooks set: the // shape checks are shared, and none reaches a team hook. func TestTeamHooksKeepConnectsCookieChecks(t *testing.T) { f, h := newHomeOnlyFixture(t) pending, nonce := f.start(t, nil, "/") inbox := f.callback(t, "pr_member", nonce, time.Now().Add(-time.Minute)) bad := strings.Repeat("A", 43) for name, cookies := range map[string][]*http.Cookie{ "unreadable session": {{Name: f.b.sessionCookie, Value: bad}}, "duplicate session": {{Name: f.b.sessionCookie, Value: bad}, {Name: f.b.sessionCookie, Value: bad}}, "malformed init": {{Name: homeInitCookie, Value: "bad"}}, "malformed proof": {{Name: homeProofCookie, Value: "bad"}}, } { w := httptest.NewRecorder() f.b.Finish(w, bridgeRequest(http.MethodGet, "/auth/finish", append(cookies, pending, inbox))) if w.Code == 303 { t.Fatalf("%s: answered %q", name, w.Header().Get("Location")) } bridgeNoSession(t, f.b, w) } if h.unlinked != 0 || h.admitted != 0 || h.count(t) != 0 { t.Fatal("a malformed cookie reached a team hook") } } // Signing out ends a pending choice: the proof row goes, not just the cookie. func TestSignoutDropsAPendingChoice(t *testing.T) { f, h := newHomeOnlyFixture(t) routes := f.routes(t) proof := bridgeCookie(t, f.finishAs(t, "pr_member", nil), homeChoiceCookie) r := httptest.NewRequest(http.MethodPost, bridgeOrigin+"/signout", nil) r.AddCookie(proof) routes.Signout(httptest.NewRecorder(), r) // The browser kept a copy of the cookie: it chooses nothing. if w := f.choosePost(t, "new", f.b.choiceToken(proof.Value), []*http.Cookie{proof}); w.Code != 403 { t.Fatalf("choice after sign-out=%d", w.Code) } if h.unlinked != 0 || h.count(t) != 0 { t.Fatal("a signed-out choice allocated") } }