package connect import ( "bytes" "context" "crypto/rand" "encoding/base64" "errors" "net/http" "net/http/httptest" "strings" "sync" "testing" "time" "amadan.net/oficina/home/handoff" "amadan.net/rastrillo/rastrillo/assertion" json "github.com/go-json-experiment/json" ) // newNativeFixture is a bridge with NativeExchange on, with the team hooks // when team is set (h is nil otherwise). func newNativeFixture(t *testing.T, team bool) (*bridgeFixture, *homeOnlyHooks) { t.Helper() var h *homeOnlyHooks if team { h = &homeOnlyHooks{} } f := newBridgeFixtureWith(t, func(f *bridgeFixture, c *Config) { if h != nil { h.install(f, c) } c.MintNativeSession = func(_ context.Context, s Session) (string, error) { return f.sessions.Mint(s) } }) if h != nil { f.b.rememberUnknown = func(http.ResponseWriter) { h.remember++ } } return f, h } func newVerifier(t *testing.T) string { t.Helper() raw := make([]byte, 32) if _, err := rand.Read(raw); err != nil { t.Fatal(err) } return base64.RawURLEncoding.EncodeToString(raw) } // nativeAssertion is what Home's assert returns for verifier's challenge. func (f *bridgeFixture) nativeAssertion(t *testing.T, subject, verifier string) string { t.Helper() challenge, ok := handoff.NativeChallenge(verifier) if !ok { t.Fatal("verifier") } nonce, _ := handoff.NativeNonce(challenge) return f.signed(t, subject, nonce, bridgeOrigin) } func (f *bridgeFixture) signed(t *testing.T, subject, nonce, audience string) string { t.Helper() now := time.Now().Unix() id, err := assertion.RandomID() if err != nil { t.Fatal(err) } token, err := assertion.Sign(f.key, assertion.Claims{Version: 1, Issuer: bridgeIssuer, Audience: audience, Subject: subject, KeyID: "key", ID: id, Nonce: nonce, IssuedAt: now, ExpiresAt: now + 120, AuthTime: now - 600}) if err != nil { t.Fatal(err) } return token } func nativeRequestFor(t *testing.T, body any) *http.Request { t.Helper() raw, ok := body.(string) if !ok { b, err := json.Marshal(body) if err != nil { t.Fatal(err) } raw = string(b) } r := httptest.NewRequest(http.MethodPost, bridgeOrigin+NativeExchangePath, strings.NewReader(raw)) r.Header.Set("Content-Type", "application/json") return r } func (f *bridgeFixture) exchange(t *testing.T, r *http.Request) *httptest.ResponseRecorder { t.Helper() w := httptest.NewRecorder() f.b.NativeExchange(w, r) if len(w.Result().Cookies()) != 0 { t.Fatal("the native exchange set a cookie") } if w.Header().Get("Cache-Control") != "no-store" || w.Header().Get("Content-Type") != "application/json" { t.Fatalf("headers %v", w.Header()) } return w } func (f *bridgeFixture) post(t *testing.T, subject string, extra map[string]string) *httptest.ResponseRecorder { t.Helper() verifier := newVerifier(t) body := map[string]string{"assertion": f.nativeAssertion(t, subject, verifier), "verifier": verifier} for k, v := range extra { body[k] = v } return f.exchange(t, nativeRequestFor(t, body)) } func (f *bridgeFixture) replayRows(t *testing.T) int { t.Helper() var n int if err := f.db.QueryRow("SELECT COUNT(*) FROM oficina_handoff_replay").Scan(&n); err != nil { t.Fatal(err) } return n } func wantState(t *testing.T, w *httptest.ResponseRecorder, code int, state string) { t.Helper() if w.Code != code || w.Body.String() != `{"state":"`+state+`"}` { t.Fatalf("got %d %s, want %d %s", w.Code, w.Body.String(), code, state) } } // signedSession reads the session an ok answer carries. func (f *bridgeFixture) signedSession(t *testing.T, w *httptest.ResponseRecorder) (Session, *http.Cookie) { t.Helper() if w.Code != 200 { t.Fatalf("exchange=%d %s", w.Code, w.Body.String()) } var out struct { State string `json:"state"` Name string `json:"name"` Value string `json:"value"` Target string `json:"target"` ExpiresAt int64 `json:"expires_at"` } if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil || out.State != "ok" || out.Name != f.b.sessionCookie || out.Value == "" { t.Fatalf("answer %s: %v", w.Body.String(), err) } if d := time.Until(time.Unix(out.ExpiresAt, 0)); d < NativeLifetime-time.Minute || d > NativeLifetime { t.Fatalf("expires_at in %v", d) } cookie := &http.Cookie{Name: out.Name, Value: out.Value} s, ok := f.sessions.From(bridgeRequest(http.MethodGet, "/", []*http.Cookie{cookie})) if !ok { t.Fatal("no session behind the answer") } return s, cookie } func TestNativeExchangeSignsInALinkedPerson(t *testing.T) { f, h := newNativeFixture(t, true) local := f.local(t, "one@example.com", "magiclink", time.Now().Add(-time.Minute)) f.link(t, local, "pr_linked") // choice is ignored for a subject who already has a person here. w := f.post(t, "pr_linked", map[string]string{"choice": "new"}) s, cookie := f.signedSession(t, w) if s.Method != NativeMethod || s.Subject != "pr_linked" || time.Since(s.AuthTime) < 9*time.Minute { t.Fatalf("session %+v", s) } p, err := f.b.ResolveSession(bridgeRequest(http.MethodGet, "/", []*http.Cookie{cookie})) if err != nil || p.Label != "one@example.com" { t.Fatal(p, err) } if h.admitted != 0 || h.unlinked != 0 || f.replayRows(t) != 2 { t.Fatalf("admitted=%d unlinked=%d replay=%d", h.admitted, h.unlinked, f.replayRows(t)) } } func TestNativeExchangeWithoutHooksSignsInLinkedPeople(t *testing.T) { f, _ := newNativeFixture(t, false) local := f.local(t, "one@example.com", "magiclink", time.Now().Add(-time.Minute)) f.link(t, local, "pr_linked") f.signedSession(t, f.post(t, "pr_linked", nil)) wantState(t, f.post(t, "pr_stranger", nil), 403, "unknown") } // A Member with no person here: 409 with no choice, and nothing allocated // or burned; choice:"new" allocates once. func TestNativeMemberChooses(t *testing.T) { f, h := newNativeFixture(t, true) wantState(t, f.post(t, "pr_member", nil), 409, "choose") if h.count(t) != 0 || h.unlinked != 0 || f.replayRows(t) != 0 { t.Fatalf("409 allocated %d, unlinked %d, replay %d", h.count(t), h.unlinked, f.replayRows(t)) } s, _ := f.signedSession(t, f.post(t, "pr_member", map[string]string{"choice": "new"})) if s.Method != NativeMethod || h.count(t) != 1 || h.unlinked != 1 || f.replayRows(t) != 1 { t.Fatalf("new: %+v people=%d unlinked=%d", s, h.count(t), h.unlinked) } // Next time the person is found: no choice needed, nothing allocated. f.signedSession(t, f.post(t, "pr_member", nil)) if h.count(t) != 1 || h.unlinked != 1 { t.Fatal("allocated again") } } // Non-members, with or without choice, and instances without the hooks all // get the same 403: status, body and headers. func TestNativeUnknownIsByteIdentical(t *testing.T) { team, h := newNativeFixture(t, true) h.admission = ErrNoPerson plain, _ := newNativeFixture(t, false) answers := []*httptest.ResponseRecorder{ team.post(t, "pr_stranger", nil), team.post(t, "pr_other", map[string]string{"choice": "new"}), plain.post(t, "pr_stranger", nil), plain.post(t, "pr_other", map[string]string{"choice": "new"}), } for i, w := range answers { wantState(t, w, 403, "unknown") if shape(w.Header()) != shape(answers[0].Header()) { t.Fatalf("answer %d headers differ:\n%s\n%s", i, shape(w.Header()), shape(answers[0].Header())) } } if h.count(t) != 0 || h.unlinked != 0 || team.replayRows(t) != 0 || plain.replayRows(t) != 0 { t.Fatal("a non-member allocated or burned something") } } func TestNativeRosterUnavailableIs503(t *testing.T) { f, h := newNativeFixture(t, true) h.admission = errors.New("roster unknown") wantState(t, f.post(t, "pr_member", map[string]string{"choice": "new"}), 503, "unavailable") if h.count(t) != 0 || f.replayRows(t) != 0 { t.Fatal("undecided allocated or burned") } } // Unlinked refusing after the roster said Member: re-resolve, then 403 or // 503, with no jti kept. func TestNativeAllocationRefusedAfterMember(t *testing.T) { for _, c := range []struct { decision error code int state string }{{ErrNoPerson, 403, "unknown"}, {errors.New("disk"), 503, "unavailable"}} { f, h := newNativeFixture(t, true) h.decision = c.decision wantState(t, f.post(t, "pr_member", map[string]string{"choice": "new"}), c.code, c.state) if f.replayRows(t) != 0 || h.unlinked != 1 { t.Fatalf("%v: replay=%d unlinked=%d", c.decision, f.replayRows(t), h.unlinked) } } } // The admission recheck after the reservation: a Home-only person the // roster no longer lists gets the unknown answer. func TestNativeRechecksAHomeOnlyPersonsStanding(t *testing.T) { f, h := newNativeFixture(t, true) f.signedSession(t, f.post(t, "pr_member", map[string]string{"choice": "new"})) h.admission = ErrNoPerson wantState(t, f.post(t, "pr_member", nil), 403, "unknown") h.admission = errors.New("roster unknown") wantState(t, f.post(t, "pr_member", nil), 503, "unavailable") } func TestNativeExchangeRefusesTheWrongAssertion(t *testing.T) { f, _ := newNativeFixture(t, true) local := f.local(t, "one@example.com", "magiclink", time.Now().Add(-time.Minute)) f.link(t, local, "pr_linked") before := f.replayRows(t) verifier := newVerifier(t) good := f.nativeAssertion(t, "pr_linked", verifier) webNonce, _ := assertion.RandomID() for name, body := range map[string]map[string]string{ "another verifier": {"assertion": good, "verifier": newVerifier(t)}, "a browser nonce": {"assertion": f.signed(t, "pr_linked", webNonce, bridgeOrigin), "verifier": verifier}, "another audience": {"assertion": f.nativeAssertionFor(t, "pr_linked", verifier, "https://red.docs.oficina.works"), "verifier": verifier}, "a corrupted token": {"assertion": corrupt(good), "verifier": verifier}, "a stranger's token": {"assertion": strings.Repeat("x", 200), "verifier": verifier}, } { t.Run(name, func(t *testing.T) { wantState(t, f.exchange(t, nativeRequestFor(t, body)), 401, "failed") }) } if f.replayRows(t) != before { t.Fatal("a refused assertion burned a jti") } ok := map[string]string{"assertion": good, "verifier": verifier} f.signedSession(t, f.exchange(t, nativeRequestFor(t, ok))) wantState(t, f.exchange(t, nativeRequestFor(t, ok)), 401, "failed") } // corrupt changes one character inside the token's signature, always to a // different one: a middle character carries six full bits, so the decoded // signature differs whatever the original was. func corrupt(token string) string { i := len(token) - 10 c := byte('A') if token[i] == 'A' { c = 'B' } return token[:i] + string(c) + token[i+1:] } func (f *bridgeFixture) nativeAssertionFor(t *testing.T, subject, verifier, audience string) string { t.Helper() challenge, _ := handoff.NativeChallenge(verifier) nonce, _ := handoff.NativeNonce(challenge) return f.signed(t, subject, nonce, audience) } func TestNativeExchangeRefusesBrowsersAndMalformedRequests(t *testing.T) { f, h := newNativeFixture(t, true) verifier := newVerifier(t) token := f.nativeAssertion(t, "pr_member", verifier) good := `{"assertion":"` + token + `","verifier":"` + verifier + `"}` for name, adjust := range map[string]func(*http.Request){ "Origin": func(r *http.Request) { r.Header.Set("Origin", bridgeOrigin) }, "Sec-Fetch-Site": func(r *http.Request) { r.Header.Set("Sec-Fetch-Site", "same-origin") }, "form": func(r *http.Request) { r.Header.Set("Content-Type", "application/x-www-form-urlencoded") }, "text": func(r *http.Request) { r.Header.Set("Content-Type", "text/plain") }, "query": func(r *http.Request) { r.URL.RawQuery = "x=1" }, } { r := nativeRequestFor(t, good) adjust(r) t.Run(name, func(t *testing.T) { wantState(t, f.exchange(t, r), 400, "invalid") }) } for name, body := range map[string]string{ "unknown field": `{"assertion":"` + token + `","verifier":"` + verifier + `","extra":1}`, "duplicate field": `{"assertion":"` + token + `","assertion":"` + token + `","verifier":"` + verifier + `"}`, "trailing value": good + `{}`, "bad verifier": `{"assertion":"` + token + `","verifier":"short"}`, "bad choice": `{"assertion":"` + token + `","verifier":"` + verifier + `","choice":"old"}`, "foreign target": `{"assertion":"` + token + `","verifier":"` + verifier + `","target":"//evil.example/"}`, "auth target": `{"assertion":"` + token + `","verifier":"` + verifier + `","target":"/auth/start"}`, "no assertion": `{"verifier":"` + verifier + `"}`, "huge": `{"assertion":"` + strings.Repeat("a", 13*1024) + `","verifier":"` + verifier + `"}`, } { t.Run(name, func(t *testing.T) { wantState(t, f.exchange(t, nativeRequestFor(t, body)), 400, "invalid") }) } get := httptest.NewRecorder() f.b.NativeExchange(get, httptest.NewRequest(http.MethodGet, bridgeOrigin+NativeExchangePath, nil)) if get.Code != 405 || get.Header().Get("Allow") != "POST" { t.Fatalf("GET=%d", get.Code) } if h.admitted != 0 || f.replayRows(t) != 0 { t.Fatal("a refused request reached the roster or burned a jti") } } func TestNativeExchangeEchoesAValidTarget(t *testing.T) { f, _ := newNativeFixture(t, true) w := f.post(t, "pr_member", map[string]string{"choice": "new", "target": "/d/abc?view=1"}) f.signedSession(t, w) if !bytes.Contains(w.Body.Bytes(), []byte(`"target":"/d/abc?view=1"`)) { t.Fatal(w.Body.String()) } } func TestNativeExchangeIsOffWithoutAMint(t *testing.T) { f, _ := newHomeOnlyFixture(t) w := httptest.NewRecorder() f.b.NativeExchange(w, nativeRequestFor(t, `{}`)) if w.Code != 404 { t.Fatalf("exchange without MintNativeSession=%d", w.Code) } } // A jti burned with no session (the mint failed after the reservation) is // not usable again; the client's fresh assertion is. func TestNativeBurnedJTIIsRetriedWithAFreshAssertion(t *testing.T) { failing := true h := &homeOnlyHooks{} f := newBridgeFixtureWith(t, func(f *bridgeFixture, c *Config) { h.install(f, c) c.MintNativeSession = func(_ context.Context, s Session) (string, error) { if failing { return "", errors.New("disk") } return f.sessions.Mint(s) } }) verifier := newVerifier(t) body := map[string]string{"assertion": f.nativeAssertion(t, "pr_member", verifier), "verifier": verifier, "choice": "new"} wantState(t, f.exchange(t, nativeRequestFor(t, body)), 503, "unavailable") failing = false wantState(t, f.exchange(t, nativeRequestFor(t, body)), 401, "failed") f.signedSession(t, f.post(t, "pr_member", nil)) if h.count(t) != 1 { t.Fatal("the retry allocated again") } } // Two exchanges choosing "new" for one subject at once make one person. func TestNativeConcurrentChoicesMakeOnePerson(t *testing.T) { f, h := newNativeFixture(t, true) var mu sync.Mutex inner := f.b.mintNative f.b.mintNative = func(ctx context.Context, s Session) (string, error) { mu.Lock() defer mu.Unlock() return inner(ctx, s) } h.db.SetMaxOpenConns(4) codes := make(chan int, 4) var wg sync.WaitGroup for range 4 { verifier := newVerifier(t) body := map[string]string{"assertion": f.nativeAssertion(t, "pr_member", verifier), "verifier": verifier, "choice": "new"} r := nativeRequestFor(t, body) wg.Go(func() { w := httptest.NewRecorder() f.b.NativeExchange(w, r) codes <- w.Code }) } wg.Wait() close(codes) for c := range codes { if c != 200 { t.Fatalf("a concurrent choice answered %d", c) } } if h.count(t) != 1 { t.Fatalf("%d people", h.count(t)) } } // No hook and no mint is ever called with connect holding the writer. On a // single-connection pool (Docs' writer), each hook needs the connection; a // transaction held across it would make the hook wait forever. The probe // waits a second instead, and a hook that finds the writer held fails the // test there and then, before it or anything after it touches the pool. // Every hook runs on the test goroutine (the handlers are called directly), // so Fatalf is safe here. func TestNoHookRunsWithTheWriterHeld(t *testing.T) { var probe func(string) bool h := &homeOnlyHooks{} f := newBridgeFixtureWith(t, func(f *bridgeFixture, c *Config) { h.install(f, c) f.db.SetMaxOpenConns(1) probe = func(string) bool { ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() _, err := f.db.ExecContext(ctx, "UPDATE home_link_clock SET high_water = high_water WHERE id = 1") return err != nil } free := func(name string) { if probe(name) { t.Fatalf("called with the writer held: [%s]", name) } } admit, unlinked, homeOnly, mint := c.Admit, c.Unlinked, c.HomeOnly, c.MintHomeSession c.Admit = func(ctx context.Context, i, s string) error { free("Admit"); return admit(ctx, i, s) } c.Unlinked = func(ctx context.Context, i, s string) (Person, error) { free("Unlinked"); return unlinked(ctx, i, s) } c.HomeOnly = func(ctx context.Context, i, s string) (Person, error) { free("HomeOnly"); return homeOnly(ctx, i, s) } c.MintHomeSession = func(w http.ResponseWriter, r *http.Request, s Session) error { free("MintHomeSession") return mint(w, r, s) } c.MintNativeSession = func(_ context.Context, s Session) (string, error) { free("MintNativeSession") return f.sessions.Mint(s) } }) // The probe does notice a held writer. tx, err := f.db.Begin() if err != nil { t.Fatal(err) } seen := probe("self-check") tx.Rollback() if !seen { t.Fatal("the probe cannot see a held writer") } // The browser path: finish, the choose page, "I'm new here"; then a // known person's finish (HomeOnly and MintHomeSession in complete). f.signInNew(t, "pr_browser") if w := f.finishAs(t, "pr_browser", nil); w.Code != 303 || w.Header().Get("Location") != "/next" { t.Fatalf("known person's finish=%d %q", w.Code, w.Header().Get("Location")) } // The native path: 409, then choice "new", then a known person. wantState(t, f.post(t, "pr_native", nil), 409, "choose") f.signedSession(t, f.post(t, "pr_native", map[string]string{"choice": "new"})) f.signedSession(t, f.post(t, "pr_native", nil)) if h.admitted == 0 || h.unlinked != 2 || h.homeOnly == 0 { t.Fatalf("hooks not exercised: admit=%d unlinked=%d homeOnly=%d", h.admitted, h.unlinked, h.homeOnly) } }