| new file mode 100644 |
| index 000000000..00ddb0de8 |
| --- /dev/null |
| +++ b/internal/console/demo_claim_signin_test.go |
| @@ -0,0 +1,303 @@ |
| +package console |
| + |
| +import ( |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "reflect" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func claimSigninFixture(t *testing.T) (*Server, *fakeKeymail, *claimBrowser) { |
| + t.Helper() |
| + seed, _, token := claimTestServer(t) |
| + fk := newFakeKeymail(t, "claimant@keymail.dev") |
| + cfg := seed.cfg |
| + cfg.Keymail = fk.srv.URL |
| + s, err := NewServer(cfg, seed.store) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + s.demoClaimTestEnabled = true |
| + return s, fk, newClaimBrowser(t, s, token) |
| +} |
| + |
| +func claimSigninStart(t *testing.T, b *claimBrowser) *httptest.ResponseRecorder { |
| + t.Helper() |
| + w := b.post("/demo/claim/prove", url.Values{"email": {"typed@" + b.s.km.Host()}}) |
| + if w.Code != 303 || w.Header().Get("Location") != "/auth/signin?next=%2Fdemo%2Fclaim" { |
| + t.Fatalf("claim discovery: %d %s", w.Code, w.Header().Get("Location")) |
| + } |
| + return b.request("GET", w.Header().Get("Location"), nil) |
| +} |
| + |
| +func claimSigninCallback(t *testing.T, b *claimBrowser, fk *fakeKeymail, start *httptest.ResponseRecorder, authTime time.Time, extraQuery string) *httptest.ResponseRecorder { |
| + t.Helper() |
| + if start.Code != 303 { |
| + t.Fatalf("signin: %d %s", start.Code, start.Body) |
| + } |
| + u, err := url.Parse(start.Header().Get("Location")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + q := u.Query() |
| + fk.mu.Lock() |
| + fk.challenge, fk.expectCode, fk.authTime = q.Get("code_challenge"), "claim-signin", authTime |
| + fk.mu.Unlock() |
| + w := b.request("GET", "/auth/callback?code=claim-signin&state="+url.QueryEscape(q.Get("state"))+extraQuery, nil) |
| + fk.mu.Lock() |
| + defer fk.mu.Unlock() |
| + if fk.stepUp { |
| + t.Error("sign-in exchange used the step-up redirect_uri") |
| + } |
| + return w |
| +} |
| + |
| +func TestDemoClaimSigninAuthorize(t *testing.T) { |
| + s, fk, b := claimSigninFixture(t) |
| + for _, next := range []string{"/demo/claim", "", "/auth/cli", "/demo/claim/", "/demo/claim?x=1", "/demo/claim#x", "//evil.example/demo/claim"} { |
| + t.Run(next, func(t *testing.T) { |
| + w := b.request("GET", "/auth/signin?next="+url.QueryEscape(next), nil) |
| + if w.Code != 303 { |
| + t.Fatalf("signin: %d", w.Code) |
| + } |
| + u, err := url.Parse(w.Header().Get("Location")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + c := b.cookies[authCookie] |
| + parts := strings.Split(c.Value, ".") |
| + fresh := next == "/demo/claim" |
| + wantParts := 2 |
| + if fresh { |
| + wantParts = 3 |
| + } |
| + if len(parts) != wantParts || parts[0] == "" || parts[1] == "" || (fresh && parts[2] != "f") { |
| + t.Fatalf("auth cookie parts = %v", parts) |
| + } |
| + if !c.HttpOnly || !c.Secure || c.SameSite != http.SameSiteLaxMode || c.Path != "/" || c.MaxAge != int(authFlowTTL.Seconds()) { |
| + t.Fatalf("auth cookie attributes: %+v", c) |
| + } |
| + want := url.Values{ |
| + "client_id": {s.cfg.Origin}, "redirect_uri": {s.cfg.Origin + "/auth/callback"}, |
| + "scope": {"identify send"}, "state": {parts[0]}, |
| + "code_challenge": {ChallengeS256(parts[1])}, "code_challenge_method": {"S256"}, |
| + } |
| + if fresh { |
| + want.Set("prompt", "login") |
| + want.Set("max_age", "300") |
| + } |
| + if !reflect.DeepEqual(u.Query(), want) || u.String() != fk.srv.URL+"/oauth/authorize?"+want.Encode() { |
| + t.Fatalf("authorize = %s, want %v", u, want) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDemoClaimSigninFreshness(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + age time.Duration |
| + zero, ordinary, wantFresh bool |
| + mapped, recordFailure bool |
| + }{ |
| + {name: "fresh", age: 9 * time.Second, wantFresh: true}, |
| + {name: "withinSkew", age: -stepUpSkew / 2, wantFresh: true}, |
| + {name: "missing", zero: true}, |
| + {name: "stale", age: StepUpWindow + time.Minute}, |
| + {name: "future", age: -stepUpSkew - time.Minute}, |
| + {name: "ordinaryWithFreshAuthTime", age: 9 * time.Second, ordinary: true}, |
| + {name: "mappedPerson", age: 9 * time.Second, mapped: true, wantFresh: true}, |
| + {name: "recordFailure", age: 9 * time.Second, recordFailure: true}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + s, fk, b := claimSigninFixture(t) |
| + person := "claimant@keymail.dev" |
| + if tc.mapped { |
| + person = "person@example.com" |
| + } |
| + other := &claimBrowser{t: t, s: s} |
| + other.login(person, MethodKeymail, false) |
| + if tc.mapped { |
| + if _, err := s.store.db.Exec(`INSERT INTO sign_in_methods (kind, subject, address, added_at) VALUES (?, ?, ?, ?)`, MethodKeymail, "claimant@keymail.dev", person, time.Now().Unix()); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if tc.recordFailure { |
| + if _, err := s.store.db.Exec(`CREATE TRIGGER refuse_step_up BEFORE INSERT ON step_ups BEGIN SELECT RAISE(FAIL, 'test record failure'); END`); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + a := claimAccount(t, s, 501, person, RoleOwner) |
| + var start *httptest.ResponseRecorder |
| + if tc.ordinary { |
| + start = b.request("GET", "/auth/signin", nil) |
| + // A landing cookie and callback query cannot upgrade an ordinary ceremony. |
| + b.cookies[nextCookie] = &http.Cookie{Name: nextCookie, Value: "/demo/claim", Path: "/"} |
| + } else { |
| + start = claimSigninStart(t, b) |
| + } |
| + authTime := time.Now().Add(-tc.age).Truncate(time.Second) |
| + if tc.zero { |
| + authTime = time.Time{} |
| + } |
| + b.session = other.session |
| + w := claimSigninCallback(t, b, fk, start, authTime, "&next=%2Fdemo%2Fclaim") |
| + if w.Code != 303 || w.Header().Get("Location") != "/demo/claim" || b.session == "" || b.session == other.session { |
| + t.Fatalf("callback: %d %s", w.Code, w.Body) |
| + } |
| + addr, method, ok := s.store.SessionInfo(b.session, time.Now()) |
| + if !ok || addr != person || method != MethodKeymail { |
| + t.Fatalf("session: %q %q %v", addr, method, ok) |
| + } |
| + wantRows := 0 |
| + if tc.wantFresh { |
| + wantRows = 1 |
| + } |
| + if got := claimBrowserCount(t, s, "step_ups"); got != wantRows { |
| + t.Fatalf("step-up rows = %d, want %d", got, wantRows) |
| + } |
| + if tc.wantFresh { |
| + var hash, address string |
| + var recordedAuth int64 |
| + if err := s.store.db.QueryRow(`SELECT session_hash,address,auth_time FROM step_ups`).Scan(&hash, &address, &recordedAuth); err != nil { |
| + t.Fatal(err) |
| + } |
| + if hash != hashToken(b.session) || address != addr || recordedAuth != authTime.Unix() { |
| + t.Fatalf("step-up row: %q %q %d", hash, address, recordedAuth) |
| + } |
| + if s.store.FreshStepUp(b.session, "typed@"+s.km.Host(), time.Now(), StepUpWindow) { |
| + t.Fatal("typed identity became fresh") |
| + } |
| + } |
| + if s.store.FreshStepUp(other.session, addr, time.Now(), StepUpWindow) { |
| + t.Fatal("another session became fresh") |
| + } |
| + if w = b.request("GET", "/demo/claim", nil); w.Code != 200 { |
| + t.Fatalf("claim page: %d", w.Code) |
| + } |
| + w = b.post("/demo/claim/select", url.Values{"accountId": {a.Sqid}}) |
| + if w.Code != 303 { |
| + t.Fatalf("select: %d %s", w.Code, w.Body) |
| + } |
| + if tc.wantFresh { |
| + if w.Header().Get("Location") != "/demo/claim" || claimBrowserCount(t, s, "demo_claim_ops") != 1 || claimBrowserCount(t, s, "pending_actions") != 0 { |
| + t.Fatalf("select requested another gesture: %s", w.Header().Get("Location")) |
| + } |
| + } else { |
| + u, err := url.Parse(w.Header().Get("Location")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !strings.HasPrefix(u.String(), fk.srv.URL+"/oauth/authorize?") || u.Query().Get("redirect_uri") != s.cfg.Origin+"/auth/stepup/callback" || claimBrowserCount(t, s, "demo_claim_ops") != 0 || claimBrowserCount(t, s, "pending_actions") != 1 { |
| + t.Fatalf("select bypassed step-up: %s", u) |
| + } |
| + } |
| + fk.mu.Lock() |
| + exchanges := fk.exchanges |
| + fk.mu.Unlock() |
| + if exchanges != 1 { |
| + t.Fatalf("exchanges = %d, want 1", exchanges) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDemoClaimSigninMalformedCookie(t *testing.T) { |
| + for _, value := range []string{"state.verifier.x", "state.verifier.f.extra", ".verifier", "state.", ".verifier.f", "state..f", "state.verifier.", "state", "state.verifier.f."} { |
| + t.Run(value, func(t *testing.T) { |
| + s, fk, b := claimSigninFixture(t) |
| + b.cookies[authCookie] = &http.Cookie{Name: authCookie, Value: value, Path: "/"} |
| + w := b.request("GET", "/auth/callback?state=state&code=unused&next=%2Fdemo%2Fclaim", nil) |
| + if w.Code != 400 || !strings.Contains(w.Body.String(), "Sign-in flow mismatch") { |
| + t.Fatalf("callback: %d %s", w.Code, w.Body) |
| + } |
| + if b.session != "" || claimBrowserCount(t, s, "step_ups") != 0 { |
| + t.Fatal("malformed cookie created proof") |
| + } |
| + fk.mu.Lock() |
| + exchanges := fk.exchanges |
| + fk.mu.Unlock() |
| + if exchanges != 0 { |
| + t.Fatal("malformed cookie reached exchange") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDemoClaimSigninMissingCookie(t *testing.T) { |
| + s, fk, b := claimSigninFixture(t) |
| + start := claimSigninStart(t, b) |
| + delete(b.cookies, authCookie) |
| + w := claimSigninCallback(t, b, fk, start, time.Now(), "&next=%2Fdemo%2Fclaim") |
| + if w.Code != 400 || !strings.Contains(w.Body.String(), "Sign-in flow expired") || b.session != "" || claimBrowserCount(t, s, "step_ups") != 0 { |
| + t.Fatalf("callback without server cookie: %d", w.Code) |
| + } |
| + fk.mu.Lock() |
| + defer fk.mu.Unlock() |
| + if fk.exchanges != 0 { |
| + t.Fatal("callback without server cookie exchanged a code") |
| + } |
| +} |
| + |
| +func TestStepUpAuthTimeBoundaries(t *testing.T) { |
| + now := time.Unix(1800000000, 0) |
| + for _, tc := range []struct { |
| + name string |
| + authTime time.Time |
| + want bool |
| + }{ |
| + {"missing", time.Time{}, false}, |
| + {"now", now, true}, |
| + {"window", now.Add(-StepUpWindow), true}, |
| + {"outsideWindow", now.Add(-StepUpWindow - time.Nanosecond), false}, |
| + {"skew", now.Add(stepUpSkew), true}, |
| + {"outsideSkew", now.Add(stepUpSkew + time.Nanosecond), false}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + if got := usableStepUpAuthTime(tc.authTime, now); got != tc.want { |
| + t.Fatalf("usableStepUpAuthTime = %v, want %v", got, tc.want) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// A Keymail that does not advertise re-authentication is never asked for a |
| +// fresh gesture: the claim gets the ordinary sign-in and records nothing. |
| +func TestDemoClaimSigninNoReauthFallsBack(t *testing.T) { |
| + s, fk, b := claimSigninFixture(t) |
| + fk.mu.Lock() |
| + fk.reauth = false |
| + fk.mu.Unlock() |
| + start := claimSigninStart(t, b) |
| + if parts := strings.Split(b.cookies[authCookie].Value, "."); len(parts) != 2 { |
| + t.Fatalf("auth cookie parts = %v, want the ordinary two", parts) |
| + } |
| + u, err := url.Parse(start.Header().Get("Location")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if q := u.Query(); q.Has("prompt") || q.Has("max_age") { |
| + t.Fatalf("fresh gesture asked of a deployment without reauth: %s", u) |
| + } |
| + claimSigninCallback(t, b, fk, start, time.Now(), "") |
| + if b.session == "" || claimBrowserCount(t, s, "step_ups") != 0 { |
| + t.Fatalf("session=%q step_ups=%d", b.session, claimBrowserCount(t, s, "step_ups")) |
| + } |
| +} |
| + |
| +// A later ordinary sign-in replaces the claim's marked cookie; the claim |
| +// ceremony's callback then fails the state check and records nothing. |
| +func TestDemoClaimSigninOverwrittenByOrdinary(t *testing.T) { |
| + s, fk, b := claimSigninFixture(t) |
| + start := claimSigninStart(t, b) |
| + if w := b.request("GET", "/auth/signin", nil); w.Code != 303 { |
| + t.Fatalf("ordinary signin: %d", w.Code) |
| + } |
| + w := claimSigninCallback(t, b, fk, start, time.Now(), "") |
| + if w.Code != 400 || !strings.Contains(w.Body.String(), "Sign-in flow mismatch") || b.session != "" || claimBrowserCount(t, s, "step_ups") != 0 { |
| + t.Fatalf("stale claim callback: %d session=%q", w.Code, b.session) |
| + } |
| +} |