Files
RenewCMS/test/verified_account_required_http_test.go
T

325 lines
13 KiB
Go

package test
import (
"RenewCMS/api/handlers/article"
"RenewCMS/api/middleware"
"RenewCMS/api/pkg/apperr"
validator "RenewCMS/api/pkg/validator"
domainArticle "RenewCMS/internal/domain/article"
domainUser "RenewCMS/internal/domain/user"
"RenewCMS/internal/infrastructure/useCases"
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/go-chi/chi/v5"
"github.com/go-chi/jwtauth/v5"
)
func newVerifiedAccountRequiredRouter(articleRepo *mockArticleRepo, userRepo *mockUserRepo, token *jwtauth.JWTAuth) *chi.Mux {
getUserUseCase := useCases.NewGetUserUseCase(userRepo)
articleHandler := article.NewHandler(
useCases.NewCreateArticleUseCase(articleRepo, &fakeBodyRenderer{}, discardRecorder, plainSites()),
useCases.NewGetArticleUseCase(articleRepo, &fakeBodyRenderer{}),
useCases.NewListArticlesUseCase(articleRepo, &fakeBodyRenderer{}, plainSites()),
useCases.NewDeleteArticleUseCase(articleRepo, discardRecorder),
useCases.NewUpdateArticleUseCase(articleRepo, &fakeBodyRenderer{}, discardRecorder, plainSites()),
getUserUseCase,
)
r := chi.NewRouter()
r.Route("/v1", func(r chi.Router) {
r.Route("/article", func(r chi.Router) {
r.Use(jwtauth.Verifier(token))
r.Get("/", articleHandler.ListArticles)
r.Get("/{id}", articleHandler.GetArticle)
r.Group(func(r chi.Router) {
r.Use(jwtauth.Authenticator(token))
r.Use(middleware.RequireVerifiedUser(getUserUseCase))
r.Post("/", articleHandler.PostArticle)
r.Delete("/{id}", articleHandler.DeleteArticle)
r.Patch("/{id}", articleHandler.UpdateArticleBody)
r.Patch("/{id}/publish", articleHandler.PublishArticle)
r.Patch("/{id}/unpublish", articleHandler.UnpublishArticle)
})
})
})
return r
}
func seedVerifiedAccountRequiredArticleRepo() *mockArticleRepo {
repo := newMockArticleRepo()
repo.articles[1] = domainArticle.Article{ID: 1, Title: "Backyard Renovation Update"}
return repo
}
func seedVerifiedAccountRequiredUserRepo(isVerified bool) *mockUserRepo {
repo := newMockUserRepo()
repo.users[1] = domainUser.User{ID: 1, IsVerified: isVerified}
return repo
}
func mintVerifiedAccountRequiredCookie(t *testing.T, token *jwtauth.JWTAuth, claims map[string]any) *http.Cookie {
t.Helper()
_, tokenString, err := token.Encode(claims)
if err != nil {
t.Fatalf("failed to encode jwt: %v", err)
}
return &http.Cookie{Name: "jwt", Value: tokenString}
}
func newVerifiedAccountRequiredRequest(method, target string, body string) *http.Request {
if body == "" {
return httptest.NewRequest(method, target, nil)
}
req := httptest.NewRequest(method, target, bytes.NewBufferString(body))
req.Header.Set("Content-Type", "application/json")
return req
}
func TestVerifiedAccountRequiredHttp(t *testing.T) {
validator.InitValidator()
token := jwtauth.New("HS256", []byte("test-secret"), nil)
protectedRouteCases := []struct {
method string
path string
body string
}{
{http.MethodPost, "/v1/article/", `{"title": "Valid Title", "body": "Some content"}`},
{http.MethodDelete, "/v1/article/1", ""},
{http.MethodPatch, "/v1/article/1", `{"body": "Updated"}`},
{http.MethodPatch, "/v1/article/1/publish", ""},
{http.MethodPatch, "/v1/article/1/unpublish", ""},
}
for _, tc := range protectedRouteCases {
t.Run("An authenticated but unverified user is refused on every protected article route: "+tc.method+" "+tc.path, func(t *testing.T) {
articleRepo := seedVerifiedAccountRequiredArticleRepo()
userRepo := seedVerifiedAccountRequiredUserRepo(false)
router := newVerifiedAccountRequiredRouter(articleRepo, userRepo, token)
req := newVerifiedAccountRequiredRequest(tc.method, tc.path, tc.body)
req.AddCookie(mintVerifiedAccountRequiredCookie(t, token, map[string]any{"user_id": uint32(1)}))
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusForbidden {
t.Fatalf("expected status 403, got %d, body %q", rec.Code, rec.Body.String())
}
if rec.Body.String() != apperr.VerificationRequiredErrorMessage+"\n" {
t.Errorf("unexpected body: %q", rec.Body.String())
}
if got := articleRepo.articles[1]; got.Title != "Backyard Renovation Update" || got.Body != "" || got.IsOnline {
t.Errorf("expected article 1 to be untouched, got %+v", got)
}
})
}
t.Run("A verified user still exercises the protected routes exactly as before", func(t *testing.T) {
articleRepo := newMockArticleRepo()
userRepo := seedVerifiedAccountRequiredUserRepo(true)
router := newVerifiedAccountRequiredRouter(articleRepo, userRepo, token)
req := newVerifiedAccountRequiredRequest(http.MethodPost, "/v1/article/", `{"title": "Valid Title", "body": "Some content"}`)
req.AddCookie(mintVerifiedAccountRequiredCookie(t, token, map[string]any{"user_id": uint32(1)}))
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusCreated {
t.Fatalf("expected status 201, got %d, body %q", rec.Code, rec.Body.String())
}
var got domainArticle.Article
if err := json.Unmarshal(articleItemsJSON(rec.Body.Bytes()), &got); err != nil {
t.Fatalf("failed to decode response: %v", err)
}
if got.Title != "Valid Title" || got.Body != "Some content" {
t.Errorf("unexpected article: %+v", got)
}
})
unresolvableTokenCases := []struct {
name string
claims map[string]any
}{
{"a validly signed jwt cookie whose claims carry no user_id key at all", map[string]any{"role": "user"}},
{`a validly signed jwt cookie whose user_id claim is the string "one"`, map[string]any{"user_id": "one"}},
{"a validly signed jwt cookie whose user_id claim is the number 999, which does not match any user", map[string]any{"user_id": uint32(999)}},
{"a validly signed jwt cookie whose user_id claim is the number -1", map[string]any{"user_id": -1.0}},
{"a validly signed jwt cookie whose user_id claim is the number 4294967296 (one past the uint32 max)", map[string]any{"user_id": float64(4294967296)}},
}
for _, tc := range unresolvableTokenCases {
t.Run("A token that resolves to no usable account still answers 401, never 403: "+tc.name, func(t *testing.T) {
articleRepo := seedVerifiedAccountRequiredArticleRepo()
userRepo := seedVerifiedAccountRequiredUserRepo(false)
router := newVerifiedAccountRequiredRouter(articleRepo, userRepo, token)
req := newVerifiedAccountRequiredRequest(http.MethodPost, "/v1/article/", `{"title": "Valid Title", "body": "Some content"}`)
req.AddCookie(mintVerifiedAccountRequiredCookie(t, token, tc.claims))
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("expected status 401, got %d, body %q", rec.Code, rec.Body.String())
}
if rec.Body.String() != apperr.UnauthorizedErrorMessage+"\n" {
t.Errorf("unexpected body: %q", rec.Body.String())
}
})
}
t.Run("A fractional user_id claim is never truncated into impersonating a different real user", func(t *testing.T) {
articleRepo := newMockArticleRepo()
userRepo := newMockUserRepo()
userRepo.users[7] = domainUser.User{ID: 7, IsVerified: true}
router := newVerifiedAccountRequiredRouter(articleRepo, userRepo, token)
req := newVerifiedAccountRequiredRequest(http.MethodPost, "/v1/article/", `{"title": "Valid Title", "body": "Some content"}`)
req.AddCookie(mintVerifiedAccountRequiredCookie(t, token, map[string]any{"user_id": 7.5}))
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("expected status 401, got %d, body %q", rec.Code, rec.Body.String())
}
if rec.Body.String() != apperr.UnauthorizedErrorMessage+"\n" {
t.Errorf("unexpected body: %q", rec.Body.String())
}
if len(articleRepo.articles) != 0 {
t.Errorf("expected no article to be created, got %+v", articleRepo.articles)
}
})
noCookieCases := []struct {
method string
path string
}{
{http.MethodPost, "/v1/article/"},
}
for _, tc := range noCookieCases {
t.Run("A request with no jwt cookie is still refused with 401, never 403: "+tc.method+" "+tc.path, func(t *testing.T) {
articleRepo := seedVerifiedAccountRequiredArticleRepo()
userRepo := seedVerifiedAccountRequiredUserRepo(false)
router := newVerifiedAccountRequiredRouter(articleRepo, userRepo, token)
req := newVerifiedAccountRequiredRequest(tc.method, tc.path, "")
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("expected status 401, got %d, body %q", rec.Code, rec.Body.String())
}
})
}
t.Run("A repository failure while resolving the caller's verification status answers 500", func(t *testing.T) {
articleRepo := seedVerifiedAccountRequiredArticleRepo()
userRepo := seedVerifiedAccountRequiredUserRepo(false)
userRepo.fail.failNext("Get")
router := newVerifiedAccountRequiredRouter(articleRepo, userRepo, token)
req := newVerifiedAccountRequiredRequest(http.MethodDelete, "/v1/article/1", "")
req.AddCookie(mintVerifiedAccountRequiredCookie(t, token, map[string]any{"user_id": uint32(1)}))
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusInternalServerError {
t.Fatalf("expected status 500, got %d, body %q", rec.Code, rec.Body.String())
}
if rec.Body.String() != "Internal server error\n" {
t.Errorf("unexpected body: %q", rec.Body.String())
}
if _, exists := articleRepo.articles[1]; !exists {
t.Errorf("expected article 1 to still exist")
}
})
seedListingArticleRepo := func() *mockArticleRepo {
repo := newMockArticleRepo()
repo.articles[1] = domainArticle.Article{ID: 1, Title: "Backyard Renovation Update", IsOnline: true}
repo.articles[2] = domainArticle.Article{ID: 2, Title: "Draft: Kitchen Remodel", IsOnline: false}
return repo
}
assertOnlyArticleOneListed := func(t *testing.T, rec *httptest.ResponseRecorder) {
t.Helper()
if rec.Code != http.StatusOK {
t.Fatalf("expected status 200, got %d, body %q", rec.Code, rec.Body.String())
}
var got []domainArticle.Article
if err := json.Unmarshal(articleItemsJSON(rec.Body.Bytes()), &got); err != nil {
t.Fatalf("failed to decode response: %v", err)
}
if len(got) != 1 || got[0].ID != 1 {
t.Errorf("expected exactly the article with id 1, got %+v", got)
}
}
t.Run("Listing falls back to the online-only list for an authenticated but unverified caller", func(t *testing.T) {
articleRepo := seedListingArticleRepo()
userRepo := seedVerifiedAccountRequiredUserRepo(false)
router := newVerifiedAccountRequiredRouter(articleRepo, userRepo, token)
req := newVerifiedAccountRequiredRequest(http.MethodGet, "/v1/article/", "")
req.AddCookie(mintVerifiedAccountRequiredCookie(t, token, map[string]any{"user_id": uint32(1)}))
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
assertOnlyArticleOneListed(t, rec)
})
t.Run("Listing still returns every article for an authenticated and verified caller", func(t *testing.T) {
articleRepo := seedListingArticleRepo()
userRepo := seedVerifiedAccountRequiredUserRepo(true)
router := newVerifiedAccountRequiredRouter(articleRepo, userRepo, token)
req := newVerifiedAccountRequiredRequest(http.MethodGet, "/v1/article/", "")
req.AddCookie(mintVerifiedAccountRequiredCookie(t, token, map[string]any{"user_id": uint32(1)}))
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("expected status 200, got %d, body %q", rec.Code, rec.Body.String())
}
var got []domainArticle.Article
if err := json.Unmarshal(articleItemsJSON(rec.Body.Bytes()), &got); err != nil {
t.Fatalf("failed to decode response: %v", err)
}
ids := map[uint32]bool{}
for _, a := range got {
ids[a.ID] = true
}
if !ids[1] || !ids[2] {
t.Errorf("expected ids 1 and 2, got %+v", got)
}
})
t.Run("Listing falls back to the online-only list when the caller's account no longer exists", func(t *testing.T) {
articleRepo := seedListingArticleRepo()
userRepo := newMockUserRepo()
router := newVerifiedAccountRequiredRouter(articleRepo, userRepo, token)
req := newVerifiedAccountRequiredRequest(http.MethodGet, "/v1/article/", "")
req.AddCookie(mintVerifiedAccountRequiredCookie(t, token, map[string]any{"user_id": uint32(999)}))
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
assertOnlyArticleOneListed(t, rec)
})
t.Run("Listing falls back to the online-only list rather than failing when the user lookup errors", func(t *testing.T) {
articleRepo := seedListingArticleRepo()
userRepo := seedVerifiedAccountRequiredUserRepo(true)
userRepo.fail.failNext("Get")
router := newVerifiedAccountRequiredRouter(articleRepo, userRepo, token)
req := newVerifiedAccountRequiredRequest(http.MethodGet, "/v1/article/", "")
req.AddCookie(mintVerifiedAccountRequiredCookie(t, token, map[string]any{"user_id": uint32(1)}))
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
assertOnlyArticleOneListed(t, rec)
})
}