| 1 | package setup |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "net/http" |
| 6 | "net/http/httptest" |
| 7 | "strings" |
| 8 | "testing" |
| 9 | "time" |
| 10 | ) |
| 11 | |
| 12 | func TestInviteCookieGuards(t *testing.T) { |
| 13 | now := time.Now() |
| 14 | expired, invalid := errors.New("expired"), errors.New("invalid") |
| 15 | h := &Handler{Key: "test-key", Now: func() time.Time { return now }, Expired: expired, Invalid: invalid} |
| 16 | w := httptest.NewRecorder() |
| 17 | if err := h.issueCookie(w, "invitation-id", "random-secret"); err != nil { |
| 18 | t.Fatal(err) |
| 19 | } |
| 20 | c := w.Result().Cookies()[0] |
| 21 | if !c.Secure || !c.HttpOnly || c.SameSite != http.SameSiteLaxMode || c.Path != "/invites/invitation-id" || c.MaxAge != 900 { |
| 22 | t.Fatal("unsafe cookie") |
| 23 | } |
| 24 | request := func(value string) *http.Request { |
| 25 | r := httptest.NewRequest("POST", "/invites/invitation-id/accept", nil) |
| 26 | r.AddCookie(&http.Cookie{Name: c.Name, Value: value}) |
| 27 | return r |
| 28 | } |
| 29 | if secret, err := h.cookieSecret(request(c.Value), "invitation-id"); err != nil || secret != "random-secret" { |
| 30 | t.Fatal("cookie exchange failed", err) |
| 31 | } |
| 32 | if _, err := h.cookieSecret(request(c.Value), "another-id"); !errors.Is(err, invalid) { |
| 33 | t.Fatal("cookie crossed invitations", err) |
| 34 | } |
| 35 | if _, err := h.cookieSecret(request("x"+c.Value), "invitation-id"); !errors.Is(err, invalid) { |
| 36 | t.Fatal("tampered cookie accepted", err) |
| 37 | } |
| 38 | if _, err := h.cookieSecret(httptest.NewRequest("POST", "/", nil), "invitation-id"); !errors.Is(err, invalid) { |
| 39 | t.Fatal("missing cookie accepted", err) |
| 40 | } |
| 41 | now = now.Add(15 * time.Minute) |
| 42 | if _, err := h.cookieSecret(request(c.Value), "invitation-id"); !errors.Is(err, expired) { |
| 43 | t.Fatal("expired cookie accepted", err) |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | func TestInviteReturnPathBound(t *testing.T) { |
| 48 | for _, id := range []string{"", "../signin", "//evil.example", "x?secret=x", "x#fragment", "x\\evil", strings.Repeat("x", 129)} { |
| 49 | if validInviteID(id) { |
| 50 | t.Fatalf("unsafe return path ID %q", id) |
| 51 | } |
| 52 | } |
| 53 | if !validInviteID("safe-ID_123") { |
| 54 | t.Fatal("valid ID rejected") |
| 55 | } |
| 56 | } |
| 57 | |