fix: reading a single article follows the same rule as the list: anyone can read an online article, a verified user can also read an offline one, and an unknown or hidden id returns 404
This commit is contained in:
1 parent
2ee28203ab
commit
81c4b62175
11 files changed
+510
-28
No files matched your search
@@ -0,0 +1,268 @@
|
||||
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"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-chi/jwtauth/v5"
|
||||
)
|
||||
|
||||
func newPublicArticleReadRouter(articleRepo *mockArticleRepo, userRepo *mockUserRepo, token *jwtauth.JWTAuth) *chi.Mux {
|
||||
getUserUseCase := useCases.NewGetUserUseCase(userRepo)
|
||||
articleHandler := article.NewHandler(
|
||||
useCases.NewCreateArticleUseCase(articleRepo),
|
||||
useCases.NewGetArticleUseCase(articleRepo),
|
||||
useCases.NewListArticlesUseCase(articleRepo),
|
||||
useCases.NewDeleteArticleUseCase(articleRepo, newMockImageRepo()),
|
||||
useCases.NewUpdateArticleUseCase(articleRepo),
|
||||
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 seedPublicArticleReadRepo() *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
|
||||
}
|
||||
|
||||
func newPublicArticleReadUserRepo(isVerified bool) *mockUserRepo {
|
||||
repo := newMockUserRepo()
|
||||
repo.users[1] = domainUser.User{ID: 1, IsVerified: isVerified}
|
||||
return repo
|
||||
}
|
||||
|
||||
func mintPublicArticleReadCookie(t *testing.T, token *jwtauth.JWTAuth, userId uint32) *http.Cookie {
|
||||
t.Helper()
|
||||
_, tokenString, err := token.Encode(map[string]any{"user_id": userId})
|
||||
if err != nil {
|
||||
t.Fatalf("failed to encode jwt: %v", err)
|
||||
}
|
||||
return &http.Cookie{Name: "jwt", Value: tokenString}
|
||||
}
|
||||
|
||||
func assertPublicArticleReadResponse(t *testing.T, rec *httptest.ResponseRecorder, expectedId uint32) {
|
||||
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(rec.Body.Bytes(), &got); err != nil {
|
||||
t.Fatalf("failed to decode response: %v", err)
|
||||
}
|
||||
if got.ID != expectedId {
|
||||
t.Errorf("expected article id %d, got %d", expectedId, got.ID)
|
||||
}
|
||||
}
|
||||
|
||||
func assertPublicArticleReadNotFound(t *testing.T, rec *httptest.ResponseRecorder) {
|
||||
t.Helper()
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("expected status 404, got %d, body %q", rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec.Body.String() != apperr.ArticleNotFoundErrorMessage+"\n" {
|
||||
t.Errorf("unexpected body: %q", rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublicArticleReadHttp(t *testing.T) {
|
||||
validator.InitValidator()
|
||||
token := jwtauth.New("HS256", []byte("test-secret"), nil)
|
||||
|
||||
t.Run("An anonymous visitor can read an online article", func(t *testing.T) {
|
||||
router := newPublicArticleReadRouter(seedPublicArticleReadRepo(), newMockUserRepo(), token)
|
||||
req := httptest.NewRequest(http.MethodGet, "/v1/article/1", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
|
||||
assertPublicArticleReadResponse(t, rec, 1)
|
||||
})
|
||||
|
||||
t.Run("An anonymous visitor is told an offline article does not exist", func(t *testing.T) {
|
||||
router := newPublicArticleReadRouter(seedPublicArticleReadRepo(), newMockUserRepo(), token)
|
||||
req := httptest.NewRequest(http.MethodGet, "/v1/article/2", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
|
||||
assertPublicArticleReadNotFound(t, rec)
|
||||
})
|
||||
|
||||
t.Run("An anonymous visitor is told an unknown id does not exist", func(t *testing.T) {
|
||||
router := newPublicArticleReadRouter(seedPublicArticleReadRepo(), newMockUserRepo(), token)
|
||||
req := httptest.NewRequest(http.MethodGet, "/v1/article/9999", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
|
||||
assertPublicArticleReadNotFound(t, rec)
|
||||
})
|
||||
|
||||
t.Run("A verified user can open their own offline draft", func(t *testing.T) {
|
||||
router := newPublicArticleReadRouter(seedPublicArticleReadRepo(), newPublicArticleReadUserRepo(true), token)
|
||||
req := httptest.NewRequest(http.MethodGet, "/v1/article/2", nil)
|
||||
req.AddCookie(mintPublicArticleReadCookie(t, token, 1))
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
|
||||
assertPublicArticleReadResponse(t, rec, 2)
|
||||
})
|
||||
|
||||
t.Run("A verified user still reads an online article normally", func(t *testing.T) {
|
||||
router := newPublicArticleReadRouter(seedPublicArticleReadRepo(), newPublicArticleReadUserRepo(true), token)
|
||||
req := httptest.NewRequest(http.MethodGet, "/v1/article/1", nil)
|
||||
req.AddCookie(mintPublicArticleReadCookie(t, token, 1))
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
|
||||
assertPublicArticleReadResponse(t, rec, 1)
|
||||
})
|
||||
|
||||
t.Run("A verified user requesting an unknown id gets the same not-found response", func(t *testing.T) {
|
||||
router := newPublicArticleReadRouter(seedPublicArticleReadRepo(), newPublicArticleReadUserRepo(true), token)
|
||||
req := httptest.NewRequest(http.MethodGet, "/v1/article/9999", nil)
|
||||
req.AddCookie(mintPublicArticleReadCookie(t, token, 1))
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
|
||||
assertPublicArticleReadNotFound(t, rec)
|
||||
})
|
||||
|
||||
t.Run("An authenticated but unverified user is told an offline article does not exist, not refused with 403", func(t *testing.T) {
|
||||
router := newPublicArticleReadRouter(seedPublicArticleReadRepo(), newPublicArticleReadUserRepo(false), token)
|
||||
req := httptest.NewRequest(http.MethodGet, "/v1/article/2", nil)
|
||||
req.AddCookie(mintPublicArticleReadCookie(t, token, 1))
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
|
||||
assertPublicArticleReadNotFound(t, rec)
|
||||
})
|
||||
|
||||
t.Run("A malformed or expired jwt cookie falls back to the public online-only visibility", func(t *testing.T) {
|
||||
router := newPublicArticleReadRouter(seedPublicArticleReadRepo(), newMockUserRepo(), token)
|
||||
cookie := &http.Cookie{Name: "jwt", Value: "not-a-real-token"}
|
||||
|
||||
onlineReq := httptest.NewRequest(http.MethodGet, "/v1/article/1", nil)
|
||||
onlineReq.AddCookie(cookie)
|
||||
onlineRec := httptest.NewRecorder()
|
||||
router.ServeHTTP(onlineRec, onlineReq)
|
||||
if onlineRec.Code != http.StatusOK {
|
||||
t.Fatalf("expected status 200, got %d, body %q", onlineRec.Code, onlineRec.Body.String())
|
||||
}
|
||||
|
||||
offlineReq := httptest.NewRequest(http.MethodGet, "/v1/article/2", nil)
|
||||
offlineReq.AddCookie(cookie)
|
||||
offlineRec := httptest.NewRecorder()
|
||||
router.ServeHTTP(offlineRec, offlineReq)
|
||||
assertPublicArticleReadNotFound(t, offlineRec)
|
||||
})
|
||||
|
||||
t.Run("An id that isn't a valid uint32 still answers 400, regardless of caller", func(t *testing.T) {
|
||||
router := newPublicArticleReadRouter(seedPublicArticleReadRepo(), newMockUserRepo(), token)
|
||||
req := httptest.NewRequest(http.MethodGet, "/v1/article/not-a-number", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("expected status 400, got %d, body %q", rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec.Body.String() != apperr.IdUint32ErrorMessage+"\n" {
|
||||
t.Errorf("unexpected body: %q", rec.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
protectedRouteCases := []struct {
|
||||
method string
|
||||
path string
|
||||
}{
|
||||
{http.MethodPost, "/v1/article/"},
|
||||
{http.MethodDelete, "/v1/article/1"},
|
||||
{http.MethodPatch, "/v1/article/1"},
|
||||
{http.MethodPatch, "/v1/article/1/publish"},
|
||||
{http.MethodPatch, "/v1/article/1/unpublish"},
|
||||
}
|
||||
for _, tc := range protectedRouteCases {
|
||||
t.Run("The rest of the article routes still require a verified account: "+tc.method+" "+tc.path, func(t *testing.T) {
|
||||
router := newPublicArticleReadRouter(seedPublicArticleReadRepo(), newMockUserRepo(), token)
|
||||
req := httptest.NewRequest(tc.method, tc.path, nil)
|
||||
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 response write failure is reported instead of crashing the handler", func(t *testing.T) {
|
||||
router := newPublicArticleReadRouter(seedPublicArticleReadRepo(), newMockUserRepo(), token)
|
||||
req := httptest.NewRequest(http.MethodGet, "/v1/article/1", nil)
|
||||
|
||||
originalStdout := os.Stdout
|
||||
readEnd, writeEnd, err := os.Pipe()
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create pipe: %v", err)
|
||||
}
|
||||
os.Stdout = writeEnd
|
||||
|
||||
router.ServeHTTP(&erroringResponseWriter{}, req)
|
||||
|
||||
writeEnd.Close()
|
||||
os.Stdout = originalStdout
|
||||
var captured bytes.Buffer
|
||||
if _, err := io.Copy(&captured, readEnd); err != nil {
|
||||
t.Fatalf("failed to read captured stdout: %v", err)
|
||||
}
|
||||
|
||||
if !strings.Contains(captured.String(), "Failed to write response") {
|
||||
t.Errorf("expected the write failure to be reported, got %q", captured.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("A repository failure still answers 500 regardless of caller state", func(t *testing.T) {
|
||||
repo := seedPublicArticleReadRepo()
|
||||
repo.fail.failNext("Get")
|
||||
router := newPublicArticleReadRouter(repo, newMockUserRepo(), token)
|
||||
req := httptest.NewRequest(http.MethodGet, "/v1/article/1", nil)
|
||||
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())
|
||||
}
|
||||
})
|
||||
}
|
||||
Reference in new issue
Block a user