refac: reamaining auth surface rewrite, T0
This commit is contained in:
1 parent
6d510d2805
commit
aa865af2e9
50 files changed
+3723
-149
No files matched your search
@@ -0,0 +1,352 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"RenewCMS/api/handlers/article"
|
||||
"RenewCMS/api/handlers/image"
|
||||
"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"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-chi/jwtauth/v5"
|
||||
)
|
||||
|
||||
func newVerifiedAccountRequiredRouter(articleRepo *mockArticleRepo, userRepo *mockUserRepo, imageRepo *mockImageRepo, token *jwtauth.JWTAuth) *chi.Mux {
|
||||
getUserUseCase := useCases.NewGetUserUseCase(userRepo)
|
||||
articleHandler := article.NewHandler(
|
||||
useCases.NewCreateArticleUseCase(articleRepo),
|
||||
useCases.NewGetArticleUseCase(articleRepo),
|
||||
useCases.NewListArticlesUseCase(articleRepo),
|
||||
useCases.NewDeleteArticleUseCase(articleRepo, imageRepo),
|
||||
useCases.NewUpdateArticleUseCase(articleRepo),
|
||||
getUserUseCase,
|
||||
)
|
||||
imageHandler := image.NewHandler(
|
||||
useCases.NewCreateImageUseCase(imageRepo),
|
||||
useCases.NewGetArticleUseCase(articleRepo),
|
||||
useCases.NewUpdateArticleUseCase(articleRepo),
|
||||
)
|
||||
|
||||
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.Group(func(r chi.Router) {
|
||||
r.Use(jwtauth.Authenticator(token))
|
||||
r.Use(middleware.RequireVerifiedUser(getUserUseCase))
|
||||
r.Get("/{id}", articleHandler.GetArticle)
|
||||
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)
|
||||
r.Post("/{id}/image", imageHandler.PostImage)
|
||||
})
|
||||
})
|
||||
})
|
||||
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.MethodGet, "/v1/article/1", ""},
|
||||
{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, newMockImageRepo(), 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("An unverified user is also refused when attaching an image", func(t *testing.T) {
|
||||
articleRepo := seedVerifiedAccountRequiredArticleRepo()
|
||||
userRepo := seedVerifiedAccountRequiredUserRepo(false)
|
||||
imageRepo := newMockImageRepo()
|
||||
router := newVerifiedAccountRequiredRouter(articleRepo, userRepo, imageRepo, token)
|
||||
|
||||
body := &bytes.Buffer{}
|
||||
writer := multipart.NewWriter(body)
|
||||
part, err := writer.CreatePart(map[string][]string{
|
||||
"Content-Disposition": {`form-data; name="file"; filename="before.png"`},
|
||||
"Content-Type": {"image/png"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create multipart part: %v", err)
|
||||
}
|
||||
if _, err := io.WriteString(part, "fake-image-data"); err != nil {
|
||||
t.Fatalf("failed to write file content: %v", err)
|
||||
}
|
||||
if err := writer.Close(); err != nil {
|
||||
t.Fatalf("failed to close multipart writer: %v", err)
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodPost, "/v1/article/1/image", body)
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
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 imageRepo.images == nil {
|
||||
t.Fatalf("expected imageRepo.images to be initialized")
|
||||
}
|
||||
if len(imageRepo.images) != 0 {
|
||||
t.Errorf("expected the image repository's Create to never be called, got %d images", len(imageRepo.images))
|
||||
}
|
||||
})
|
||||
|
||||
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, newMockImageRepo(), 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(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)}},
|
||||
}
|
||||
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, newMockImageRepo(), 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())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
noCookieCases := []struct {
|
||||
method string
|
||||
path string
|
||||
}{
|
||||
{http.MethodGet, "/v1/article/1"},
|
||||
{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, newMockImageRepo(), 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, newMockImageRepo(), 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(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, newMockImageRepo(), 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, newMockImageRepo(), 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(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, newMockImageRepo(), 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, newMockImageRepo(), 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)
|
||||
})
|
||||
}
|
||||
Reference in new issue
Block a user