package web import ( "bytes" "context" "mime/multipart" "net/http" "net/http/httptest" "net/url" "regexp" "strconv" "strings" "testing" "time" "supermarket/internal/users" ) var inviteRe = regexp.MustCompile(`http://localhost:8470(/invite/[A-Za-z0-9_-]+)`) // invite has an admin invite someone, and returns the link's path. func invite(t *testing.T, s *Server, h http.Handler, admin *http.Cookie, form url.Values) string { t.Helper() n := 0 if s.Mail != nil { n = s.Mail.(interface{ Count() int }).Count() } rec := as(h, admin, http.MethodPost, "/settings/users", form) if rec.Code != http.StatusSeeOther { t.Fatalf("invite %v: %d %s", form, rec.Code, rec.Body.String()) } m := waitMail(t, s, form.Get("email"), n+1) p := inviteRe.FindStringSubmatch(m.Body) if p == nil { t.Fatalf("no link in %s", m.Body) } return p[1] } func TestInviteAndJoin(t *testing.T) { s, h := newServerEdition(t) owner := addUser(t, s, "owner@example.com", users.Owner, nil) oc := sessionFor(t, s, owner) // Mistakes. for _, f := range []url.Values{ {"email": {"not an address"}, "name": {"X"}, "role": {"admin"}}, {"email": {"x@example.com"}, "name": {""}, "role": {"admin"}}, {"email": {"x@example.com"}, "name": {"X"}, "role": {"member"}}, {"email": {"OWNER@example.com"}, "name": {"X"}, "role": {"admin"}}, } { if rec := as(h, oc, http.MethodPost, "/settings/users", f); rec.Code != http.StatusUnprocessableEntity { t.Errorf("%v: %d", f, rec.Code) } } adminLink := invite(t, s, h, oc, url.Values{"email": {"ada@example.com"}, "name": {"Ada"}, "role": {"admin"}}) memberLink := invite(t, s, h, oc, url.Values{"email": {"sam@example.com"}, "name": {"Sam"}, "role": {"member"}, "module:seo": {"edit"}, "module:metrics": {"bogus"}}) m, _ := users.ByEmail(s.DB, "sam@example.com") mm, _ := users.MembershipOf(s.DB, users.Team, m.ID) if m.Status != users.Invited || mm.Role != users.Member || len(mm.Modules) != 1 || mm.Modules["seo"] != users.Edit { t.Errorf("member %+v %+v", m, mm) } rec := as(h, oc, http.MethodGet, "/settings/users", nil) if !strings.Contains(rec.Body.String(), "Invited") || !strings.Contains(rec.Body.String(), ">SEO<") { t.Errorf("list: %s", rec.Body.String()) } // Not signed in: the invitation page is open; signed-in pages aren't. rec = do(h, http.MethodGet, memberLink, nil, nil) if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "sam@example.com") || !strings.Contains(rec.Body.String(), "SEO morning check") { t.Fatalf("invite page: %d %s", rec.Code, rec.Body.String()) } if rec := postForm(h, memberLink, url.Values{"name": {"Sam"}, "password": {"short"}, "password2": {"short"}}); rec.Code != http.StatusUnprocessableEntity { t.Errorf("short: %d", rec.Code) } rec = postForm(h, memberLink, url.Values{"name": {"Sam Lee"}, "title": {"Writer"}, "time_zone": {"Europe/Paris"}, "password": {"a long enough one"}, "password2": {"a long enough one"}, "emails": {"seo-check", "made-up"}}) if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/?msg=joined" || cookieOf(rec, sessionCookie) == nil { t.Fatalf("join: %d %s", rec.Code, rec.Body.String()) } m, _ = users.ByEmail(s.DB, "sam@example.com") if m.Status != users.Active || m.Name != "Sam Lee" || m.Title != "Writer" || len(m.Emails) != 1 || m.Emails[0] != "seo-check" { t.Errorf("joined %+v", m) } if rec := do(h, http.MethodGet, memberLink, nil, nil); rec.Code != http.StatusNotFound { t.Errorf("used twice: %d", rec.Code) } // A member can't manage users. mc := sessionFor(t, s, m) for _, p := range []string{"/settings/users", "/settings/users/" + strconv.FormatInt(owner.ID, 10)} { if rec := as(h, mc, http.MethodGet, p, nil); rec.Code != http.StatusForbidden { t.Errorf("member %s: %d", p, rec.Code) } } if rec := as(h, mc, http.MethodPost, "/settings/users", url.Values{"email": {"x@example.com"}, "name": {"X"}, "role": {"admin"}}); rec.Code != http.StatusForbidden { t.Errorf("member invites: %d", rec.Code) } // The invited admin, once joined, can. postForm(h, adminLink, url.Values{"name": {"Ada"}, "password": {"a long enough one"}, "password2": {"a long enough one"}}) ada, _ := users.ByEmail(s.DB, "ada@example.com") ac := sessionFor(t, s, ada) if rec := as(h, ac, http.MethodGet, "/settings/users", nil); rec.Code != http.StatusOK { t.Errorf("admin: %d", rec.Code) } } func TestUserActions(t *testing.T) { s, h := newServerEdition(t) owner := addUser(t, s, "owner@example.com", users.Owner, nil) admin := addUser(t, s, "ada@example.com", users.Admin, nil) sam := addUser(t, s, "sam@example.com", users.Member, map[string]users.Access{"seo": users.Edit}) ac := sessionFor(t, s, admin) sc := sessionFor(t, s, sam) path := func(u *users.User, action string) string { return "/settings/users/" + strconv.FormatInt(u.ID, 10) + "/" + action } // Nobody changes the owner, nor themselves. if rec := as(h, ac, http.MethodPost, path(owner, "disable"), url.Values{}); rec.Code != http.StatusForbidden { t.Errorf("disable the owner: %d", rec.Code) } if rec := as(h, ac, http.MethodPost, path(admin, "access"), url.Values{"role": {"member"}, "module:seo": {"view"}}); rec.Code != http.StatusForbidden { t.Errorf("change yourself: %d", rec.Code) } // Access: down to SEO view and Metrics; their SEO emails stay, as SEO // is still theirs. sam.Emails = []string{"seo-check"} users.SaveProfile(s.DB, sam) if rec := as(h, ac, http.MethodPost, path(sam, "access"), url.Values{"role": {"member"}, "module:seo": {"view"}, "module:metrics": {"edit"}}); rec.Code != http.StatusSeeOther { t.Errorf("access: %d", rec.Code) } m, _ := users.MembershipOf(s.DB, users.Team, sam.ID) if m.Modules["seo"] != users.View || m.Modules["metrics"] != users.Edit { t.Errorf("modules %v", m.Modules) } if got, _ := users.ByID(s.DB, sam.ID); len(got.Emails) != 1 { t.Errorf("emails %v", got.Emails) } // Losing SEO loses its emails. as(h, ac, http.MethodPost, path(sam, "access"), url.Values{"role": {"member"}, "module:metrics": {"edit"}}) if got, _ := users.ByID(s.DB, sam.ID); len(got.Emails) != 0 { t.Errorf("emails kept: %v", got.Emails) } // Lock, unlock. for i := 0; i < users.LockAfter; i++ { users.FailedSignIn(s.DB, sam, time.Now()) } if rec := as(h, ac, http.MethodGet, "/settings/users/"+strconv.FormatInt(sam.ID, 10), nil); !strings.Contains(rec.Body.String(), "/unlock") { t.Errorf("no unlock button: %s", rec.Body.String()) } as(h, ac, http.MethodPost, path(sam, "unlock"), url.Values{}) if got, _ := users.ByID(s.DB, sam.ID); got.Locked() { t.Error("still locked") } // Reset two-factor: off, and signed out. users.SetTwoFactor(s.DB, sam, true, []string{"x"}) s.Secrets.Set(map[string]string{users.TOTPSecretName(sam.ID): "ABCD"}) as(h, ac, http.MethodPost, path(sam, "reset-two-factor"), url.Values{}) if got, _ := users.ByID(s.DB, sam.ID); got.TwoFactor || s.Secrets.Get(users.TOTPSecretName(sam.ID)) != "" { t.Error("two-factor not reset") } if rec := as(h, sc, http.MethodGet, "/seo", nil); rec.Code != http.StatusSeeOther { t.Error("not signed out after the reset") } // Disable, enable. sc = sessionFor(t, s, sam) as(h, ac, http.MethodPost, path(sam, "disable"), url.Values{}) if rec := as(h, sc, http.MethodGet, "/seo", nil); rec.Code != http.StatusSeeOther { t.Error("disabled, still signed in") } as(h, ac, http.MethodPost, path(sam, "enable"), url.Values{}) if got, _ := users.ByID(s.DB, sam.ID); got.Status != users.Active { t.Errorf("enabled: %s", got.Status) } // Withdrawing an invitation removes it; removing someone, them. link := invite(t, s, h, ac, url.Values{"email": {"kim@example.com"}, "name": {"Kim"}, "role": {"admin"}}) kim, _ := users.ByEmail(s.DB, "kim@example.com") if rec := as(h, ac, http.MethodPost, path(kim, "withdraw"), url.Values{}); rec.Code != http.StatusSeeOther { t.Errorf("withdraw: %d", rec.Code) } if rec := do(h, http.MethodGet, link, nil, nil); rec.Code != http.StatusNotFound { t.Errorf("withdrawn link: %d", rec.Code) } as(h, ac, http.MethodPost, path(sam, "remove"), url.Values{}) if _, err := users.ByID(s.DB, sam.ID); err == nil { t.Error("not removed") } if n, _ := users.Count(s.DB); n != 2 { t.Errorf("%d users", n) } } func TestPhoto(t *testing.T) { s, h := newServerEdition(t) u := addUser(t, s, "owner@example.com", users.Owner, nil) c := sessionFor(t, s, u) upload := func(name string, data []byte, withToken bool) int { var body bytes.Buffer mw := multipart.NewWriter(&body) fw, _ := mw.CreateFormFile("photo", name) fw.Write(data) mw.Close() target := "/settings/account/photo" if withToken { target += "?csrf=" + testCSRF } req := httptest.NewRequest(http.MethodPost, target, &body) req.Host = "localhost:8470" req.Header.Set("Content-Type", mw.FormDataContentType()) req.Header.Set("Origin", "http://localhost:8470") req.AddCookie(c) req.AddCookie(&http.Cookie{Name: csrfCookie, Value: testCSRF}) rec := httptest.NewRecorder() h.ServeHTTP(rec, req) return rec.Code } // The page's upload form carries the token in its address. if rec := as(h, c, http.MethodGet, "/settings/account", nil); !strings.Contains(rec.Body.String(), `action="/settings/account/photo?csrf=`) { t.Error("upload form without its token") } png := []byte("\x89PNG\r\n\x1a\n" + strings.Repeat("\x00", 100)) if code := upload("me.png", png, false); code != http.StatusForbidden { t.Errorf("no token: %d", code) } if code := upload("me.txt", []byte("hello"), true); code != http.StatusUnprocessableEntity { t.Errorf("not a picture: %d", code) } if code := upload("big.png", append(png, make([]byte, maxPhoto)...), true); code != http.StatusUnprocessableEntity { t.Errorf("too big: %d", code) } if code := upload("me.png", png, true); code != http.StatusSeeOther { t.Fatalf("upload: %d", code) } got, _ := users.ByID(s.DB, u.ID) if !strings.HasPrefix(got.Photo, "photos/") || !strings.HasSuffix(got.Photo, ".png") { t.Fatalf("photo %q", got.Photo) } rec := as(h, c, http.MethodGet, "/users/"+strconv.FormatInt(u.ID, 10)+"/photo", nil) if rec.Code != http.StatusOK || rec.Header().Get("Content-Type") != "image/png" || !bytes.Equal(rec.Body.Bytes(), png) { t.Errorf("photo: %d %s", rec.Code, rec.Header().Get("Content-Type")) } if rec := do(h, http.MethodGet, "/users/"+strconv.FormatInt(u.ID, 10)+"/photo", nil, nil); rec.Code != http.StatusSeeOther { t.Errorf("not signed in: %d", rec.Code) } as(h, c, http.MethodPost, "/settings/account/photo?remove=1", url.Values{}) if got, _ := users.ByID(s.DB, u.ID); got.Photo != "" { t.Error("not removed") } if _, err := s.Files.Stat(context.Background(), got.Photo); err == nil { t.Error("old file kept") } }