A Q&A platform software for teams at any scales. Whether it's a community forum, help center, or knowledge management platform, you can always count on Apache Answer.
fix: strengthen request safeguards
LinkinStarse8ded23a4acb
diff --git a/internal/base/middleware/header.go b/internal/base/middleware/header.goindex 717d2ac0..15de54df 100644--- a/internal/base/middleware/header.go+++ b/internal/base/middleware/header.go@@ -25,8 +25,12 @@ import ("github.com/gin-gonic/gin")+const contentSecurityPolicy = "default-src 'self'; base-uri 'self'; frame-ancestors 'none'; form-action 'self'; object-src 'none'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: http: https:; font-src 'self' data:; connect-src 'self'"+func HeadersByRequestURI() gin.HandlerFunc {return func(c *gin.Context) {+ c.Header("Content-Security-Policy", contentSecurityPolicy)+ c.Header("X-Content-Type-Options", "nosniff")if strings.HasPrefix(c.Request.RequestURI, "/static/") {c.Header("cache-control", "public, max-age=31536000")}diff --git a/internal/base/middleware/header_test.go b/internal/base/middleware/header_test.gonew file mode 100644index 00000000..9f838aeb--- /dev/null+++ b/internal/base/middleware/header_test.go@@ -0,0 +1,45 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++package middleware++import (+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/gin-gonic/gin"+)++func TestHeadersByRequestURI(t *testing.T) {+ gin.SetMode(gin.TestMode)+ router := gin.New()+ router.Use(HeadersByRequestURI())+ router.GET("/", func(ctx *gin.Context) { ctx.Status(http.StatusNoContent) })++ response := httptest.NewRecorder()+ router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/", nil))++ if got := response.Header().Get("X-Content-Type-Options"); got != "nosniff" {+ t.Fatalf("X-Content-Type-Options = %q, want nosniff", got)+ }+ if got := response.Header().Get("Content-Security-Policy"); got != contentSecurityPolicy {+ t.Fatalf("Content-Security-Policy = %q, want %q", got, contentSecurityPolicy)+ }+}diff --git a/internal/base/middleware/visit_img_auth.go b/internal/base/middleware/visit_img_auth.goindex bfd157a9..b2aea6b8 100644--- a/internal/base/middleware/visit_img_auth.go+++ b/internal/base/middleware/visit_img_auth.go@@ -43,6 +43,7 @@ func (am *AuthUserMiddleware) VisitAuth() gin.HandlerFunc {siteSecurity, err := am.siteInfoCommonService.GetSiteSecurity(ctx)if err != nil {+ ctx.AbortWithStatus(http.StatusInternalServerError)return}if !siteSecurity.LoginRequired {diff --git a/internal/base/server/http.go b/internal/base/server/http.goindex 8db55744..22e7afdb 100644--- a/internal/base/server/http.go+++ b/internal/base/server/http.go@@ -78,7 +78,7 @@ func NewHTTPServer(debug bool,rootGroup := r.Group("")swaggerRouter.Register(rootGroup)static := r.Group(uiConf.APIBaseURL)- static.Use(avatarMiddleware.AvatarThumb(), authUserMiddleware.VisitAuth())+ static.Use(authUserMiddleware.VisitAuth(), avatarMiddleware.AvatarThumb())staticRouter.RegisterStaticRouter(static)// The route must be available without logging indiff --git a/internal/controller/question_controller.go b/internal/controller/question_controller.goindex 644e3097..c83fd578 100644--- a/internal/controller/question_controller.go+++ b/internal/controller/question_controller.go@@ -998,6 +998,7 @@ func (qc *QuestionController) GetQuestionLink(ctx *gin.Context) {return}req.LoginUserID = middleware.GetLoginUserIDFromContext(ctx)+ req.IsAdminModerator = middleware.GetUserIsAdminModerator(ctx)req.QuestionID = uid.DeShortID(req.QuestionID)questions, total, err := qc.questionService.GetQuestionLink(ctx, req)if err != nil {diff --git a/internal/repo/question/question_repo.go b/internal/repo/question/question_repo.goindex 3449efb8..3f38fc6c 100644--- a/internal/repo/question/question_repo.go+++ b/internal/repo/question/question_repo.go@@ -817,10 +817,9 @@ func (qr *questionRepo) UpdateQuestionLinkStatus(ctx context.Context, status int}// GetQuestionLink get linked question to questionID-func (qr *questionRepo) GetQuestionLink(ctx context.Context, page, pageSize int, questionID string, orderCond string, inDays int) (questionList []*entity.Question, total int64, err error) {+func (qr *questionRepo) GetQuestionLink(ctx context.Context, page, pageSize int, questionID, loginUserID string, isAdminModerator bool, orderCond string, inDays int) (questionList []*entity.Question, total int64, err error) {questionList = make([]*entity.Question, 0)questionID = uid.DeShortID(questionID)- questionStatus := []int{entity.QuestionStatusAvailable, entity.QuestionStatusClosed, entity.QuestionStatusPending}if questionID == "0" {return nil, 0, errors.InternalServer(reason.DatabaseError).WithError(fmt.Errorf("questionID is empty"),@@ -833,8 +832,14 @@ func (qr *questionRepo) GetQuestionLink(ctx context.Context, page, pageSize int,Where("question_link.to_question_id = ? AND question.show = ?", questionID, entity.QuestionShow).Distinct("question.id").Where("question_link.status = ?", entity.QuestionLinkStatusAvailable).- Select("question.*").- In("question.status", questionStatus)+ Select("question.*")+ if isAdminModerator {+ session.Where("question.status IN (?, ?, ?)", entity.QuestionStatusAvailable, entity.QuestionStatusClosed, entity.QuestionStatusPending)+ } else if loginUserID != "" {+ session.Where("(question.status IN (?, ?) OR (question.status = ? AND question.user_id = ?))", entity.QuestionStatusAvailable, entity.QuestionStatusClosed, entity.QuestionStatusPending, loginUserID)+ } else {+ session.In("question.status", []int{entity.QuestionStatusAvailable, entity.QuestionStatusClosed})+ }switch orderCond {case "newest":diff --git a/internal/repo/repo_test/question_link_security_test.go b/internal/repo/repo_test/question_link_security_test.gonew file mode 100644index 00000000..3c38448b--- /dev/null+++ b/internal/repo/repo_test/question_link_security_test.go@@ -0,0 +1,85 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++package repo_test++import (+ "context"+ "testing"++ "github.com/apache/answer/internal/entity"+ "github.com/apache/answer/internal/repo/question"+ "github.com/apache/answer/internal/repo/unique"+ "github.com/stretchr/testify/require"+)++func TestQuestionRepoGetQuestionLinkRespectsPendingVisibility(t *testing.T) {+ ctx := context.Background()+ questionRepo := question.NewQuestionRepo(testDataSource, unique.NewUniqueIDRepo(testDataSource))++ newQuestion := func(userID, title string, status, show int) *entity.Question {+ q := &entity.Question{+ UserID: userID,+ Title: title,+ OriginalText: title,+ ParsedText: title,+ Status: status,+ Show: show,+ }+ require.NoError(t, questionRepo.AddQuestion(ctx, q))+ return q+ }++ target := newQuestion("link-target-owner", "link target", entity.QuestionStatusAvailable, entity.QuestionShow)+ available := newQuestion("link-author", "available", entity.QuestionStatusAvailable, entity.QuestionShow)+ pendingOwner := newQuestion("link-author", "pending owner", entity.QuestionStatusPending, entity.QuestionShow)+ pendingOther := newQuestion("link-other", "pending other", entity.QuestionStatusPending, entity.QuestionShow)+ hidden := newQuestion("link-author", "hidden", entity.QuestionStatusAvailable, entity.QuestionHide)+ questions := []*entity.Question{target, available, pendingOwner, pendingOther, hidden}++ for _, from := range questions[1:] {+ _, err := testDataSource.DB.Context(ctx).Insert(&entity.QuestionLink{+ FromQuestionID: from.ID,+ ToQuestionID: target.ID,+ Status: entity.QuestionLinkStatusAvailable,+ })+ require.NoError(t, err)+ }+ t.Cleanup(func() {+ _, _ = testDataSource.DB.Context(ctx).Where("to_question_id = ?", target.ID).Delete(&entity.QuestionLink{})+ for _, q := range questions {+ _, _ = testDataSource.DB.Context(ctx).ID(q.ID).Delete(&entity.Question{})+ }+ })++ assertLinkedIDs := func(loginUserID string, isAdminModerator bool, want ...string) {+ got, _, err := questionRepo.GetQuestionLink(ctx, 1, 20, target.ID, loginUserID, isAdminModerator, "newest", 0)+ require.NoError(t, err)+ gotIDs := make([]string, 0, len(got))+ for _, q := range got {+ gotIDs = append(gotIDs, q.ID)+ }+ require.ElementsMatch(t, want, gotIDs)+ }++ assertLinkedIDs("", false, available.ID)+ assertLinkedIDs("link-author", false, available.ID, pendingOwner.ID)+ assertLinkedIDs("link-other", false, available.ID, pendingOther.ID)+ assertLinkedIDs("link-moderator", true, available.ID, pendingOwner.ID, pendingOther.ID)+}diff --git a/internal/router/static_router.go b/internal/router/static_router.goindex a6c80fc0..e16002cf 100644--- a/internal/router/static_router.go+++ b/internal/router/static_router.go@@ -53,10 +53,11 @@ func (a *StaticRouter) RegisterStaticRouter(r *gin.RouterGroup) {filePath := c.Param("filepath")// The original filename is 123.pdforiginalFilename := filepath.Base(filePath)- // The real filename is hash.pdf- realFilename := strings.TrimSuffix(filePath, "/"+originalFilename) + filepath.Ext(originalFilename)- // The file local path is /uploads/files/post/hash.pdf- fileLocalPath := filepath.Join(a.serviceConfig.UploadPath, constant.FilesPostSubPath, realFilename)+ fileLocalPath, ok := attachmentFileLocalPath(a.serviceConfig.UploadPath, filePath, originalFilename)+ if !ok {+ c.Redirect(http.StatusFound, "/404")+ return+ }// If the file is not exist, return 404if !dir.CheckFileExist(fileLocalPath) {c.Redirect(http.StatusFound, "/404")@@ -65,3 +66,14 @@ func (a *StaticRouter) RegisterStaticRouter(r *gin.RouterGroup) {c.FileAttachment(fileLocalPath, originalFilename)})}++func attachmentFileLocalPath(uploadPath, requestPath, originalFilename string) (string, bool) {+ realFilename := strings.TrimSuffix(requestPath, "/"+originalFilename) + filepath.Ext(originalFilename)+ attachmentRoot := filepath.Join(uploadPath, constant.FilesPostSubPath)+ fileLocalPath := filepath.Join(attachmentRoot, realFilename)+ relPath, err := filepath.Rel(attachmentRoot, fileLocalPath)+ if err != nil || filepath.IsAbs(relPath) || relPath == ".." || strings.HasPrefix(relPath, ".."+string(filepath.Separator)) {+ return "", false+ }+ return fileLocalPath, true+}diff --git a/internal/router/static_router_test.go b/internal/router/static_router_test.gonew file mode 100644index 00000000..b123c95d--- /dev/null+++ b/internal/router/static_router_test.go@@ -0,0 +1,46 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++package router++import (+ "path/filepath"+ "testing"++ "github.com/apache/answer/internal/base/constant"+)++func TestAttachmentFileLocalPathRejectsTraversal(t *testing.T) {+ uploadPath := t.TempDir()++ filePath, ok := attachmentFileLocalPath(uploadPath, "/hash/report.pdf", "report.pdf")+ if !ok {+ t.Fatal("valid attachment path was rejected")+ }+ want := filepath.Join(uploadPath, constant.FilesPostSubPath, "hash.pdf")+ if filePath != want {+ t.Fatalf("attachment path = %q, want %q", filePath, want)+ }++ for _, requestPath := range []string{"/../../outside/secret.txt", "/hash/../../../secret.txt"} {+ if _, ok := attachmentFileLocalPath(uploadPath, requestPath, filepath.Base(requestPath)); ok {+ t.Fatalf("traversal path %q was accepted", requestPath)+ }+ }+}diff --git a/internal/schema/email_template.go b/internal/schema/email_template.goindex d7e4b929..57f1ac3c 100644--- a/internal/schema/email_template.go+++ b/internal/schema/email_template.go@@ -28,7 +28,7 @@ import (const (AccountActivationSourceType EmailSourceType = "account-activation"PasswordResetSourceType EmailSourceType = "password-reset"- ConfirmNewEmailSourceType EmailSourceType = "password-reset"+ ConfirmNewEmailSourceType EmailSourceType = "confirm-new-email"UnsubscribeSourceType EmailSourceType = "unsubscribe"BindingSourceType EmailSourceType = "binding")@@ -56,6 +56,15 @@ func (r *EmailCodeContent) FromJSONString(data string) error {return json.Unmarshal([]byte(data), &r)}+func (r *EmailCodeContent) IsSourceType(sourceTypes ...EmailSourceType) bool {+ for _, sourceType := range sourceTypes {+ if r.SourceType == sourceType {+ return true+ }+ }+ return false+}+type RegisterTemplateData struct {SiteName stringRegisterUrl stringdiff --git a/internal/schema/email_template_test.go b/internal/schema/email_template_test.gonew file mode 100644index 00000000..8a11738d--- /dev/null+++ b/internal/schema/email_template_test.go@@ -0,0 +1,41 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++package schema++import "testing"++func TestEmailCodeContentIsSourceType(t *testing.T) {+ if PasswordResetSourceType == ConfirmNewEmailSourceType {+ t.Fatal("password reset and confirm new email source types must be distinct")+ }++ passwordResetCode := &EmailCodeContent{SourceType: PasswordResetSourceType}+ if !passwordResetCode.IsSourceType(PasswordResetSourceType) {+ t.Fatal("password reset code should match the password reset source type")+ }+ if passwordResetCode.IsSourceType(UnsubscribeSourceType, ConfirmNewEmailSourceType) {+ t.Fatal("password reset code must not match another source type")+ }++ unsubscribeCode := &EmailCodeContent{SourceType: UnsubscribeSourceType}+ if unsubscribeCode.IsSourceType(PasswordResetSourceType, AccountActivationSourceType) {+ t.Fatal("unsubscribe code must not match an account credential source type")+ }+}diff --git a/internal/schema/question_schema.go b/internal/schema/question_schema.goindex 4c231385..4c6d2ead 100644--- a/internal/schema/question_schema.go+++ b/internal/schema/question_schema.go@@ -514,13 +514,13 @@ type PersonalCollectionPageReq struct {}type GetQuestionLinkReq struct {- Page int `validate:"omitempty,min=1" form:"page"`- PageSize int `validate:"omitempty,min=1,max=100" form:"page_size"`- QuestionID string `validate:"required" form:"question_id"`- OrderCond string `validate:"omitempty,oneof=newest active hot score unanswered recommend frequent" form:"order"`- InDays int `validate:"omitempty,min=1" form:"in_days"`-- LoginUserID string `json:"-"`+ Page int `validate:"omitempty,min=1" form:"page"`+ PageSize int `validate:"omitempty,min=1,max=100" form:"page_size"`+ QuestionID string `validate:"required" form:"question_id"`+ OrderCond string `validate:"omitempty,oneof=newest active hot score unanswered recommend frequent" form:"order"`+ InDays int `validate:"omitempty,min=1" form:"in_days"`+ LoginUserID string `json:"-"`+ IsAdminModerator bool `json:"-"`}type GetQuestionLinkResp struct {diff --git a/internal/service/content/question_service.go b/internal/service/content/question_service.goindex 73f66a4c..b172018b 100644--- a/internal/service/content/question_service.go+++ b/internal/service/content/question_service.go@@ -1748,7 +1748,7 @@ func (qs *QuestionService) GetQuestionLink(ctx context.Context, req *schema.GetQreq.InDays = schema.HotInDays}- questionList, total, err := qs.questionRepo.GetQuestionLink(ctx, req.Page, req.PageSize, req.QuestionID, req.OrderCond, req.InDays)+ questionList, total, err := qs.questionRepo.GetQuestionLink(ctx, req.Page, req.PageSize, req.QuestionID, req.LoginUserID, req.IsAdminModerator, req.OrderCond, req.InDays)if err != nil {return nil, 0, err}diff --git a/internal/service/content/user_service.go b/internal/service/content/user_service.goindex c1f800ff..f556fa17 100644--- a/internal/service/content/user_service.go+++ b/internal/service/content/user_service.go@@ -227,8 +227,9 @@ func (us *UserService) RetrievePassWord(ctx context.Context, req *schema.UserRet// send emaildata := &schema.EmailCodeContent{- Email: req.Email,- UserID: userInfo.ID,+ SourceType: schema.PasswordResetSourceType,+ Email: req.Email,+ UserID: userInfo.ID,}code := token.GenerateToken()verifyEmailURL := fmt.Sprintf("%s/users/password-reset?code=%s", us.getSiteUrl(ctx), code)@@ -247,6 +248,9 @@ func (us *UserService) UpdatePasswordWhenForgot(ctx context.Context, req *schemaif err != nil {return errors.BadRequest(reason.EmailVerifyURLExpired)}+ if !data.IsSourceType(schema.PasswordResetSourceType) {+ return errors.BadRequest(reason.EmailVerifyURLExpired)+ }userInfo, exist, err := us.userRepo.GetByEmail(ctx, data.Email)if err != nil {@@ -598,8 +602,9 @@ func applyRegistrationVerification(func (us *UserService) sendRegistrationActivationEmail(ctx context.Context, userInfo *entity.User) error {data := &schema.EmailCodeContent{- Email: userInfo.EMail,- UserID: userInfo.ID,+ SourceType: schema.AccountActivationSourceType,+ Email: userInfo.EMail,+ UserID: userInfo.ID,}code := token.GenerateToken()verifyEmailURL := fmt.Sprintf("%s/users/account-activation?code=%s", us.getSiteUrl(ctx), code)@@ -621,8 +626,9 @@ func (us *UserService) UserVerifyEmailSend(ctx context.Context, userID string) e}data := &schema.EmailCodeContent{- Email: userInfo.EMail,- UserID: userInfo.ID,+ SourceType: schema.AccountActivationSourceType,+ Email: userInfo.EMail,+ UserID: userInfo.ID,}code := token.GenerateToken()verifyEmailURL := fmt.Sprintf("%s/users/account-activation?code=%s", us.getSiteUrl(ctx), code)@@ -640,6 +646,9 @@ func (us *UserService) UserVerifyEmail(ctx context.Context, req *schema.UserVeriif err != nil {return nil, errors.BadRequest(reason.EmailVerifyURLExpired)}+ if !data.IsSourceType(schema.AccountActivationSourceType, schema.BindingSourceType) {+ return nil, errors.BadRequest(reason.EmailVerifyURLExpired)+ }userInfo, has, err := us.userRepo.GetByEmail(ctx, data.Email)if err != nil {@@ -736,8 +745,9 @@ func (us *UserService) UserChangeEmailSendCode(ctx context.Context, req *schema.}data := &schema.EmailCodeContent{- Email: req.Email,- UserID: req.UserID,+ SourceType: schema.ConfirmNewEmailSourceType,+ Email: req.Email,+ UserID: req.UserID,}code := token.GenerateToken()var title, body string@@ -763,6 +773,9 @@ func (us *UserService) UserChangeEmailVerify(ctx context.Context, content stringif err != nil {return nil, errors.BadRequest(reason.EmailVerifyURLExpired)}+ if !data.IsSourceType(schema.ConfirmNewEmailSourceType) {+ return nil, errors.BadRequest(reason.EmailVerifyURLExpired)+ }_, exist, err := us.userRepo.GetByEmail(ctx, data.Email)if err != nil {@@ -896,7 +909,7 @@ func (us *UserService) UserUnsubscribeNotification(ctx context.Context, req *schema.UserUnsubscribeNotificationReq) (err error) {data := &schema.EmailCodeContent{}err = data.FromJSONString(req.Content)- if err != nil || len(data.UserID) == 0 {+ if err != nil || len(data.UserID) == 0 || !data.IsSourceType(schema.UnsubscribeSourceType) {return errors.BadRequest(reason.EmailVerifyURLExpired)}diff --git a/internal/service/content/user_service_test.go b/internal/service/content/user_service_test.goindex d77a1c44..9c654aaa 100644--- a/internal/service/content/user_service_test.go+++ b/internal/service/content/user_service_test.go@@ -20,14 +20,57 @@package contentimport (+ "context""errors""testing""github.com/apache/answer/internal/entity"+ "github.com/apache/answer/internal/schema""github.com/stretchr/testify/assert""github.com/stretchr/testify/require")+func TestEmailCodePurposeIsEnforcedBeforeUserMutation(t *testing.T) {+ service := &UserService{}+ ctx := context.Background()++ t.Run("password reset rejects a code issued for another purpose", func(t *testing.T) {+ content := (&schema.EmailCodeContent{+ SourceType: schema.UnsubscribeSourceType,+ Email: "[email protected]",+ }).ToJSONString()++ err := service.UpdatePasswordWhenForgot(ctx, &schema.UserRePassWordRequest{Content: content})+ if err == nil {+ t.Fatal("password reset accepted an unsubscribe code")+ }+ })++ t.Run("email activation rejects a password reset code", func(t *testing.T) {+ content := (&schema.EmailCodeContent{+ SourceType: schema.PasswordResetSourceType,+ Email: "[email protected]",+ }).ToJSONString()++ _, err := service.UserVerifyEmail(ctx, &schema.UserVerifyEmailReq{Content: content})+ if err == nil {+ t.Fatal("email activation accepted a password reset code")+ }+ })++ t.Run("change email rejects a password reset code", func(t *testing.T) {+ content := (&schema.EmailCodeContent{+ SourceType: schema.PasswordResetSourceType,+ Email: "[email protected]",+ }).ToJSONString()++ _, err := service.UserChangeEmailVerify(ctx, content)+ if err == nil {+ t.Fatal("change email accepted a password reset code")+ }+ })+}+func TestApplyRegistrationVerification(t *testing.T) {t.Run("required sends activation email and leaves email pending", func(t *testing.T) {userInfo := &entity.User{}diff --git a/internal/service/question_common/question.go b/internal/service/question_common/question.goindex 3a730634..8a45f1ed 100644--- a/internal/service/question_common/question.go+++ b/internal/service/question_common/question.go@@ -88,7 +88,7 @@ type QuestionRepo interface {RemoveQuestionLink(ctx context.Context, link ...*entity.QuestionLink) (err error)RecoverQuestionLink(ctx context.Context, link ...*entity.QuestionLink) (err error)UpdateQuestionLinkStatus(ctx context.Context, status int, links ...*entity.QuestionLink) (err error)- GetQuestionLink(ctx context.Context, page, pageSize int, questionID string, orderCond string, inDays int) (questions []*entity.Question, total int64, err error)+ GetQuestionLink(ctx context.Context, page, pageSize int, questionID, loginUserID string, isAdminModerator bool, orderCond string, inDays int) (questions []*entity.Question, total int64, err error)}// QuestionCommon user servicediff --git a/internal/service/uploader/upload.go b/internal/service/uploader/upload.goindex 58f80846..72901b55 100644--- a/internal/service/uploader/upload.go+++ b/internal/service/uploader/upload.go@@ -319,13 +319,13 @@ func (us *uploaderService) uploadImageFile(ctx *gin.Context, file *multipart.Filif err := ctx.SaveUploadedFile(file, filePath); err != nil {return "", errors.InternalServer(reason.UnknownError).WithError(err).WithStack()}-- src, err := file.Open()- if err != nil {- return "", errors.InternalServer(reason.UnknownError).WithError(err).WithStack()- }+ saved := falsedefer func() {- _ = src.Close()+ if !saved {+ if removeErr := os.Remove(filePath); removeErr != nil && !os.IsNotExist(removeErr) {+ log.Errorf("remove failed uploaded file failed: %v", removeErr)+ }+ }}()if !checker.DecodeAndCheckImageFile(filePath, siteAdvanced.GetMaxImageMegapixel()) {@@ -337,6 +337,7 @@ func (us *uploaderService) uploadImageFile(ctx *gin.Context, file *multipart.Fil}url = fmt.Sprintf("%s/uploads/%s", siteGeneral.SiteUrl, fileSubPath)+ saved = truereturn url, nil}diff --git a/internal/service/user_admin/user_backyard.go b/internal/service/user_admin/user_backyard.goindex 29e33804..072feec9 100644--- a/internal/service/user_admin/user_backyard.go+++ b/internal/service/user_admin/user_backyard.go@@ -597,8 +597,9 @@ func (us *UserAdminService) GetUserActivation(ctx context.Context, req *schema.G}data := &schema.EmailCodeContent{- Email: userInfo.EMail,- UserID: userInfo.ID,+ SourceType: schema.AccountActivationSourceType,+ Email: userInfo.EMail,+ UserID: userInfo.ID,}code := token.GenerateToken()us.emailService.SaveCode(ctx, userInfo.ID, code, data.ToJSONString())@@ -624,8 +625,9 @@ func (us *UserAdminService) SendUserActivation(ctx context.Context, req *schema.}data := &schema.EmailCodeContent{- Email: userInfo.EMail,- UserID: userInfo.ID,+ SourceType: schema.AccountActivationSourceType,+ Email: userInfo.EMail,+ UserID: userInfo.ID,}code := token.GenerateToken()verifyEmailURL := fmt.Sprintf("%s/users/account-activation?code=%s", general.SiteUrl, code)diff --git a/pkg/checker/file_type.go b/pkg/checker/file_type.goindex 19999ef1..c324fd34 100644--- a/pkg/checker/file_type.go+++ b/pkg/checker/file_type.go@@ -61,6 +61,8 @@ func DecodeAndCheckImageFile(localFilePath string, maxImageMegapixel int) bool {if !decodeAndCheckImageFile(localFilePath, maxImageMegapixel, ext, webpImageCheck) {return false}+ default:+ return false}return true}diff --git a/pkg/checker/file_type_test.go b/pkg/checker/file_type_test.gonew file mode 100644index 00000000..3b47de55--- /dev/null+++ b/pkg/checker/file_type_test.go@@ -0,0 +1,36 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++package checker++import (+ "os"+ "path/filepath"+ "testing"+)++func TestDecodeAndCheckImageFileRejectsUnsupportedExtension(t *testing.T) {+ filePath := filepath.Join(t.TempDir(), "not-an-image.svg")+ if err := os.WriteFile(filePath, []byte("<svg></svg>"), 0o600); err != nil {+ t.Fatal(err)+ }+ if DecodeAndCheckImageFile(filePath, 1_000_000) {+ t.Fatal("unsupported image extensions must be rejected")+ }+}