package web import ( "net/http" "net/http/httptest" "net/url" "strings" "testing" "time" "supermarket/internal/config" "supermarket/internal/users" ) // newServerEdition is a test server run as the server edition. func newServerEdition(t *testing.T) (*Server, http.Handler) { t.Helper() s, h := newTestServer(t, nil) s.Config = &config.Config{Edition: config.Server} return s, h } // addUser makes an active user with a role and a password. func addUser(t *testing.T, s *Server, email string, role users.Role, modules map[string]users.Access) *users.User { t.Helper() u := &users.User{Email: email, Name: strings.Split(email, "@")[0], Status: users.Active} if err := users.Create(s.DB, u, time.Now()); err != nil { t.Fatal(err) } if err := users.SetPassword(s.DB, u, "a long enough one"); err != nil { t.Fatal(err) } if err := users.Join(s.DB, users.Team, u.ID, role, modules, time.Now()); err != nil { t.Fatal(err) } return u } // sessionFor signs a user in and returns their cookie. func sessionFor(t *testing.T, s *Server, u *users.User) *http.Cookie { t.Helper() token, _, err := users.StartSession(s.DB, u.ID, "", "", time.Now()) if err != nil { t.Fatal(err) } return &http.Cookie{Name: sessionCookie, Value: token} } // as makes a request with a session cookie. func as(h http.Handler, c *http.Cookie, method, target string, form url.Values) *httptest.ResponseRecorder { var req *http.Request if form != nil { req = httptest.NewRequest(method, target, strings.NewReader(form.Encode())) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") } else { req = httptest.NewRequest(method, target, nil) } req.Host = "localhost:8470" if c != nil { req.AddCookie(c) } if !safeMethod(method) { req.AddCookie(&http.Cookie{Name: csrfCookie, Value: testCSRF}) req.Header.Set(csrfHeader, testCSRF) req.Header.Set("Origin", "http://localhost:8470") } rec := httptest.NewRecorder() h.ServeHTTP(rec, req) return rec } func TestCSRF(t *testing.T) { _, h := newTestServer(t, nil) form := url.Values{"name": {"Acme"}, "description": {"x"}} // A page sets the cookie and puts the token in its forms. rec := do(h, http.MethodGet, "/settings/profile", nil, nil) var token string for _, c := range rec.Result().Cookies() { if c.Name == csrfCookie { token = c.Value if !c.HttpOnly || c.SameSite != http.SameSiteLaxMode { t.Errorf("cookie %+v", c) } } } if len(token) < 32 { t.Fatalf("no token cookie: %v", rec.Result().Cookies()) } body := rec.Body.String() if !strings.Contains(body, ``) { t.Error("the form has no token") } if !strings.Contains(body, ``) { t.Error("no token for htmx") } if strings.Contains(body, `role="search">
` out := string(addCSRF([]byte(in), "T0k")) want := `` if out != want { t.Errorf("got\n%s\nwant\n%s", out, want) } } func TestServerEditionNeedsSignIn(t *testing.T) { s, h := newServerEdition(t) owner := addUser(t, s, "owner@example.com", users.Owner, nil) // Not signed in: pages lead to the sign-in page; what's public stays so. rec := do(h, http.MethodGet, "/seo/check?site=0", nil, nil) if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/signin?next=%2Fseo%2Fcheck%3Fsite%3D0" { t.Errorf("page: %d %s", rec.Code, rec.Header().Get("Location")) } if rec := do(h, http.MethodGet, "/", nil, nil); rec.Header().Get("Location") != "/signin" { t.Errorf("home: %s", rec.Header().Get("Location")) } if rec := do(h, http.MethodGet, "/seo/audit/status", nil, map[string]string{"HX-Request": "true"}); rec.Code != http.StatusUnauthorized || rec.Header().Get("HX-Redirect") == "" { t.Errorf("htmx: %d %v", rec.Code, rec.Header()) } if rec := postForm(h, "/settings/profile", url.Values{"name": {"x"}}); rec.Code != http.StatusUnauthorized { t.Errorf("post: %d", rec.Code) } for _, p := range []string{"/healthz", "/static/app.css", "/favicon.ico"} { if rec := do(h, http.MethodGet, p, nil, nil); rec.Code != http.StatusOK { t.Errorf("%s: %d", p, rec.Code) } } // Signed in. c := sessionFor(t, s, owner) if rec := as(h, c, http.MethodGet, "/settings/profile", nil); rec.Code != http.StatusOK { t.Errorf("signed in: %d", rec.Code) } if rec := as(h, c, http.MethodPost, "/settings/profile", url.Values{"name": {"Acme"}, "description": {"x"}}); rec.Code != http.StatusSeeOther { t.Errorf("signed-in post: %d %s", rec.Code, rec.Body.String()) } // A made-up cookie, a disabled user, a user out of the team: not in. if rec := as(h, &http.Cookie{Name: sessionCookie, Value: "made-up"}, http.MethodGet, "/settings/profile", nil); rec.Code != http.StatusSeeOther { t.Errorf("made-up cookie: %d", rec.Code) } users.SetStatus(s.DB, owner.ID, users.Disabled) if rec := as(h, c, http.MethodGet, "/settings/profile", nil); rec.Code != http.StatusSeeOther { t.Errorf("disabled: %d", rec.Code) } users.SetStatus(s.DB, owner.ID, users.Active) s.DB.Exec(`DELETE FROM memberships WHERE user_id = ?`, owner.ID) if rec := as(h, c, http.MethodGet, "/settings/profile", nil); rec.Code != http.StatusSeeOther { t.Errorf("out of the team: %d", rec.Code) } } func TestSessionCookiesOverHTTPS(t *testing.T) { s, _ := newServerEdition(t) s.PublicURL = "https://sm.example.com" u := addUser(t, s, "pat@example.com", users.Owner, nil) req := httptest.NewRequest(http.MethodPost, "/signin", nil) rec := httptest.NewRecorder() if err := s.startSession(rec, req, u); err != nil { t.Fatal(err) } c := rec.Result().Cookies()[0] if c.Name != "__Host-sm_session" || !c.Secure || !c.HttpOnly || c.SameSite != http.SameSiteLaxMode || c.Path != "/" || c.Domain != "" { t.Errorf("cookie %+v", c) } if got, _ := users.ByID(s.DB, u.ID); got.SignedIn.IsZero() { t.Error("sign-in not recorded") } } func TestClientIP(t *testing.T) { r := httptest.NewRequest(http.MethodGet, "/", nil) r.RemoteAddr = "10.0.0.2:5555" if got := clientIP(r); got != "10.0.0.2" { t.Errorf("direct: %s", got) } r.Header.Set("X-Forwarded-For", "1.2.3.4, 203.0.113.9") if got := clientIP(r); got != "203.0.113.9" { t.Errorf("through the proxy: %s", got) } }