diff --git a/modules/git/commit.go b/modules/git/commit.go index e67e02777bd..8b705217436 100644 --- a/modules/git/commit.go +++ b/modules/git/commit.go @@ -248,3 +248,14 @@ func GetFullCommitID(ctx context.Context, repo RepositoryFacade, shortID string) } return strings.TrimSpace(commitID), nil } + +func AddObjectMessageArgument(cmd *gitcmd.Command, typ ObjectType, message string) error { + if len(message) > 512*1024 { + // It doesn't make sense to store very large messages in git objects, + // and it never succeeded in the past due to the command line argument limit (e.g.: 128K on Linux). + // If any real world user would complain about the limit, let them explain why, then make the limit configurable. + return util.NewInvalidArgumentErrorf("git %s message is too long", typ) + } + cmd.AddArguments("--file=-").WithStdinBytes([]byte(message)) + return nil +} diff --git a/modules/git/gitcmd/pipe.go b/modules/git/gitcmd/pipe.go index 95b1a9205f5..7f625d3b22c 100644 --- a/modules/git/gitcmd/pipe.go +++ b/modules/git/gitcmd/pipe.go @@ -8,11 +8,6 @@ import ( "os" ) -type PipeBufferReader interface { - Read(p []byte) (n int, err error) - Bytes() []byte -} - type PipeBufferWriter interface { Write(p []byte) (n int, err error) Bytes() []byte diff --git a/modules/git/repo_commit_nogogit.go b/modules/git/repo_commit_nogogit.go index ac71df58a1b..9100c61706f 100644 --- a/modules/git/repo_commit_nogogit.go +++ b/modules/git/repo_commit_nogogit.go @@ -9,32 +9,10 @@ import ( "context" "errors" "io" - "strings" - "gitea.dev/modules/git/gitcmd" - "gitea.dev/modules/log" + "gitea.dev/modules/setting" ) -// ResolveReference resolves a name to a reference -func (repo *Repository) ResolveReference(ctx context.Context, name string) (string, error) { - stdout, _, err := gitcmd.NewCommand("show-ref", "--hash"). - AddDynamicArguments(name). - WithRepo(repo). - RunStdString(ctx) - if err != nil { - if strings.Contains(err.Error(), "not a valid ref") { - return "", ErrNotExist{name, ""} - } - return "", err - } - stdout = strings.TrimSpace(stdout) - if stdout == "" { - return "", ErrNotExist{name, ""} - } - - return stdout, nil -} - // GetRefCommitID returns the last commit ID string of given reference (branch or tag). func (repo *Repository) GetRefCommitID(ctx context.Context, name string) (string, error) { batch, cancel, err := repo.CatFileBatch() @@ -60,6 +38,15 @@ func (repo *Repository) getCommit(ctx context.Context, id ObjectID) (*Commit, er return repo.getCommitWithBatch(batch, id) } +func limitDiscardReader(rd BufferedReader, full, limit int64) (io.Reader, func() error) { + return io.LimitReader(rd, min(full, limit)), func() error { + if full > limit { + return DiscardFull(rd, full-limit) + } + return nil + } +} + func (repo *Repository) getCommitWithBatch(batch CatFileBatch, id ObjectID) (*Commit, error) { info, rd, err := batch.QueryContent(id.String()) if err != nil { @@ -73,12 +60,14 @@ func (repo *Repository) getCommitWithBatch(batch CatFileBatch, id ObjectID) (*Co case "missing": return nil, ErrNotExist{ID: id.String()} case "tag": - // then we need to parse the tag - // and load the commit - data, err := io.ReadAll(io.LimitReader(rd, info.Size)) + limitReader, limitDiscard := limitDiscardReader(rd, info.Size, MaxGitObjectSize) + data, err := io.ReadAll(limitReader) if err != nil { return nil, err } + if err = limitDiscard(); err != nil { + return nil, err + } _, err = rd.Discard(1) if err != nil { return nil, err @@ -89,10 +78,14 @@ func (repo *Repository) getCommitWithBatch(batch CatFileBatch, id ObjectID) (*Co } return repo.getCommitWithBatch(batch, tag.Object) case "commit": - commit, err := CommitFromReader(id, io.LimitReader(rd, info.Size)) + limitReader, limitDiscard := limitDiscardReader(rd, info.Size, MaxGitObjectSize) + commit, err := CommitFromReader(id, limitReader) if err != nil { return nil, err } + if err = limitDiscard(); err != nil { + return nil, err + } _, err = rd.Discard(1) if err != nil { return nil, err @@ -100,7 +93,9 @@ func (repo *Repository) getCommitWithBatch(batch CatFileBatch, id ObjectID) (*Co return commit, nil default: - log.Debug("Unknown cat-file object type: %s", info.Type) + if info.Type != "blob" && info.Type != "tree" { + setting.PanicInDevOrTesting("Unknown cat-file object type %s for object %s in repo %s", info.Type, id.String(), repo.LogString()) + } if err := DiscardFull(rd, info.Size+1); err != nil { return nil, err } diff --git a/modules/git/repo_index.go b/modules/git/repo_index.go index dfc58b2b678..8675ec2a35d 100644 --- a/modules/git/repo_index.go +++ b/modules/git/repo_index.go @@ -73,12 +73,6 @@ func (repo *Repository) ReadTreeToTemporaryIndex(ctx context.Context, treeish st return tmpIndexFilename, tmpDir, cancel, nil } -// EmptyIndex empties the index -func (repo *Repository) EmptyIndex(ctx context.Context) error { - _, _, err := gitcmd.NewCommand("read-tree", "--empty").WithRepo(repo).RunStdString(ctx) - return err -} - // LsFiles checks if the given filenames are in the index func (repo *Repository) LsFiles(ctx context.Context, filenames ...string) ([]string, error) { cmd := gitcmd.NewCommand("ls-files", "-z").AddDashesAndList(filenames...) diff --git a/modules/git/repo_object.go b/modules/git/repo_object.go index c3fb286d694..7f47d8b446c 100644 --- a/modules/git/repo_object.go +++ b/modules/git/repo_object.go @@ -11,6 +11,10 @@ import ( "gitea.dev/modules/git/gitcmd" ) +// MaxGitObjectSize is used to avoid OOM when reading a large git object. +// GitHub has a limit (100M) for pushing, but Gitea doesn't have such a limit yet. +var MaxGitObjectSize int64 = 100 * 1024 * 1024 + // ObjectType git object type type ObjectType string diff --git a/modules/git/repo_tag.go b/modules/git/repo_tag.go index 028764d9d3d..ee2da5f43e3 100644 --- a/modules/git/repo_tag.go +++ b/modules/git/repo_tag.go @@ -27,11 +27,11 @@ func (repo *Repository) CreateTag(ctx context.Context, name, revision string) er // CreateAnnotatedTag create one annotated tag in the repository func (repo *Repository) CreateAnnotatedTag(ctx context.Context, name, message, revision string) error { - _, _, err := gitcmd.NewCommand("tag", "-a", "-m"). - AddDynamicArguments(message). - AddDashesAndList(name, revision). - WithRepo(repo). - RunStdString(ctx) + cmd := gitcmd.NewCommand("tag", "--annotate") + if err := AddObjectMessageArgument(cmd, ObjectTag, message); err != nil { + return err + } + _, _, err := cmd.AddDashesAndList(name, revision).WithRepo(repo).RunStdString(ctx) return err } diff --git a/modules/git/repo_tag_nogogit.go b/modules/git/repo_tag_nogogit.go index 524eed7a43c..c6026fcd3f9 100644 --- a/modules/git/repo_tag_nogogit.go +++ b/modules/git/repo_tag_nogogit.go @@ -106,12 +106,15 @@ func (repo *Repository) getTag(ctx context.Context, tagID ObjectID, name string) return nil, ErrNotExist{ID: tagID.String()} } - // then we need to parse the tag - // and load the commit - data, err := io.ReadAll(io.LimitReader(rd, size)) + // then we need to parse the tag and load the commit + limitReader, limitDiscard := limitDiscardReader(rd, info.Size, MaxGitObjectSize) + data, err := io.ReadAll(limitReader) if err != nil { return nil, err } + if err = limitDiscard(); err != nil { + return nil, err + } _, err = rd.Discard(1) if err != nil { return nil, err diff --git a/modules/httplib/request.go b/modules/httplib/client_request.go similarity index 100% rename from modules/httplib/request.go rename to modules/httplib/client_request.go diff --git a/modules/httplib/url.go b/modules/httplib/server_request.go similarity index 93% rename from modules/httplib/url.go rename to modules/httplib/server_request.go index cbd6a44e347..6e79df4c739 100644 --- a/modules/httplib/url.go +++ b/modules/httplib/server_request.go @@ -5,6 +5,8 @@ package httplib import ( "context" + "errors" + "io" "net" "net/http" "net/url" @@ -240,3 +242,28 @@ func ParseGiteaSiteURL(ctx context.Context, s string) *GiteaSiteURL { } return ret } + +func IsGiteaFetchActionRequest(req *http.Request) bool { + return req.Header.Get("X-Gitea-Fetch-Action") != "" +} + +func IsClientOrNetworkError(ctx context.Context, err error) bool { + if err == nil { + return false + } + + if ctx.Err() != nil || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + return true + } + + // client request corrupted (e.g.: Content-Length is sent but body is incomplete) + if errors.Is(err, io.ErrUnexpectedEOF) { + return true + } + + // network error + if _, ok := errors.AsType[net.Error](err); ok { + return true + } + return false +} diff --git a/modules/httplib/url_test.go b/modules/httplib/server_request_test.go similarity index 100% rename from modules/httplib/url_test.go rename to modules/httplib/server_request_test.go diff --git a/modules/web/middleware/cookie.go b/modules/web/middleware/cookie.go index 7b3ba6c7e41..1db79582ff2 100644 --- a/modules/web/middleware/cookie.go +++ b/modules/web/middleware/cookie.go @@ -9,6 +9,7 @@ import ( "net/url" "strings" + "gitea.dev/modules/httplib" "gitea.dev/modules/session" "gitea.dev/modules/setting" "gitea.dev/modules/util" @@ -35,7 +36,7 @@ func DeleteRedirectToCookie(resp http.ResponseWriter) { } func RedirectLinkUserLogin(req *http.Request) string { - if req.Header.Get("X-Gitea-Fetch-Action") != "" { + if httplib.IsGiteaFetchActionRequest(req) { // when building the redirect link for a fetch request, the current link might be a partial page, // so we only redirect to the login page without redirect_to parameter return setting.AppSubURL + "/user/login" diff --git a/services/context/base.go b/services/context/base.go index 3bf7d8b319c..a353fdce5dd 100644 --- a/services/context/base.go +++ b/services/context/base.go @@ -161,7 +161,7 @@ func (b *Base) Redirect(location string, status ...int) { } // In case the request is made by "fetch-action" module, make JS redirect to the new location // Otherwise, the JS fetch will follow the redirection and read a "login" page, embed it to the current page, which is not expected. - if b.Req.Header.Get("X-Gitea-Fetch-Action") != "" { + if httplib.IsGiteaFetchActionRequest(b.Req) { b.JSON(http.StatusOK, map[string]any{"redirect": location}) return } diff --git a/services/context/base_test.go b/services/context/base_test.go index 03192e423f7..583e123888a 100644 --- a/services/context/base_test.go +++ b/services/context/base_test.go @@ -6,6 +6,7 @@ package context import ( "net/http" "net/http/httptest" + "os" "testing" "gitea.dev/modules/setting" @@ -13,8 +14,12 @@ import ( "github.com/stretchr/testify/assert" ) -func TestRedirect(t *testing.T) { +func TestMain(m *testing.M) { setting.IsInTesting = true + os.Exit(m.Run()) +} + +func TestRedirect(t *testing.T) { req, _ := http.NewRequest(http.MethodGet, "/", nil) cases := []struct { diff --git a/services/context/context.go b/services/context/context.go index 99e40ea72e6..8969188675a 100644 --- a/services/context/context.go +++ b/services/context/context.go @@ -270,8 +270,12 @@ func (ctx *Context) JSONErrorAuto(err error) { ctx.JSON(httpCode, buildJsonErrorMap(errMsg)) return } - log.ErrorWithSkip(1, "JSONErrorAuto: server internal error: %v", err) - ctx.JSON(http.StatusInternalServerError, buildJsonErrorMap(ctx.Locale.TrString("error.occurred"))) + + logLevel := util.Iif(httplib.IsClientOrNetworkError(ctx, err), log.DEBUG, log.ERROR) + log.Log(1, logLevel, "JSONErrorAuto: server internal error: %v", err) + + userErrorMsg := ctx.buildUserErrorMessage("internal server error", err) + ctx.JSON(http.StatusInternalServerError, buildJsonErrorMap(userErrorMsg)) } func (ctx *Context) JSONError[T string | template.HTML](msg T) { diff --git a/services/context/context_response.go b/services/context/context_response.go index 9916f340cb2..4d03ae754a9 100644 --- a/services/context/context_response.go +++ b/services/context/context_response.go @@ -7,13 +7,11 @@ import ( "errors" "fmt" "html/template" - "net" "net/http" "net/url" "path" "strconv" "strings" - "syscall" "time" user_model "gitea.dev/models/user" @@ -90,7 +88,7 @@ func (ctx *Context) HTML(status int, name templates.TplName) { } err := ctx.Render.HTML(ctx.Resp, status, name, ctx.Data, ctx.TemplateContext) - if err == nil || errors.Is(err, syscall.EPIPE) { + if err == nil || httplib.IsClientOrNetworkError(ctx, err) { return } @@ -126,13 +124,13 @@ func (ctx *Context) RenderWithErrDeprecated(msg any, tpl templates.TplName, form // NotFound displays a 404 (Not Found) page and prints the given error, if any. func (ctx *Context) NotFound(logErr error) { - ctx.notFoundInternal("", logErr) + ctx.notFoundInternal(1, "", logErr) } -func (ctx *Context) notFoundInternal(logMsg string, logErr error) { +func (ctx *Context) notFoundInternal(skip int, logMsg string, logErr error) { // TODO: it's safe to show the error message to end users if the error is fully controlled by our error system if logErr != nil { - log.Log(2, log.DEBUG, "%s: %v", logMsg, logErr) + log.Log(skip+1, log.DEBUG, "%s: %v", logMsg, logErr) } // response simple message if Accept isn't text/html @@ -155,32 +153,41 @@ func (ctx *Context) notFoundInternal(logMsg string, logErr error) { ctx.HTML(http.StatusNotFound, "status/404") } +func (ctx *Context) buildUserErrorMessage(msg string, err error) (userErrorMsg string) { + // it's safe to show internal error to admin users, and it helps + if !setting.IsProd || (ctx.Doer != nil && ctx.Doer.IsAdmin) { + userErrorMsg = msg + if err != nil { + userErrorMsg += ", error: " + err.Error() + } + } + return util.IfZero(userErrorMsg, ctx.Locale.TrString("error.occurred")) +} + // ServerError displays a 500 (Internal Server Error) page and prints the given error, if any. // If the error is controlled by our error system, a related 404 page can be displayed instead. func (ctx *Context) ServerError(logMsg string, logErr error) { if errors.Is(logErr, util.ErrNotExist) { - ctx.notFoundInternal(logMsg, logErr) + ctx.notFoundInternal(1, logMsg, logErr) return } - ctx.serverErrorInternal(logMsg, logErr) + ctx.serverErrorInternal(1, logMsg, logErr) } -func (ctx *Context) serverErrorInternal(logMsg string, logErr error) { +func (ctx *Context) serverErrorInternal(skip int, logMsg string, logErr error) { if logErr != nil { - log.ErrorWithSkip(2, "%s: %v", logMsg, logErr) - if _, ok := logErr.(*net.OpError); ok || errors.Is(logErr, &net.OpError{}) { - // This is an error within the underlying connection - // and further rendering will not work so just return - return - } + logLevel := util.Iif(httplib.IsClientOrNetworkError(ctx, logErr), log.DEBUG, log.ERROR) + log.Log(skip+1, logLevel, "%s: %v", logMsg, logErr) + } - // it's safe to show internal error to admin users, and it helps - if !setting.IsProd || (ctx.Doer != nil && ctx.Doer.IsAdmin) { - ctx.Data["ErrorMsg"] = fmt.Sprintf("%s, %s", logMsg, logErr) - } + userErrorMsg := ctx.buildUserErrorMessage(logMsg, logErr) + if httplib.IsGiteaFetchActionRequest(ctx.Req) { + ctx.JSON(http.StatusInternalServerError, buildJsonErrorMap(userErrorMsg)) + return } ctx.Data["Title"] = "Internal Server Error" + ctx.Data["ErrorMsg"] = userErrorMsg ctx.HTML(http.StatusInternalServerError, tplStatus500) } @@ -190,8 +197,8 @@ func (ctx *Context) serverErrorInternal(logMsg string, logErr error) { // TODO: remove the "errCheck" and use util.ErrNotFound to check func (ctx *Context) NotFoundOrServerError(logMsg string, errCheck func(error) bool, logErr error) { if errCheck(logErr) { - ctx.notFoundInternal(logMsg, logErr) + ctx.notFoundInternal(1, logMsg, logErr) return } - ctx.serverErrorInternal(logMsg, logErr) + ctx.serverErrorInternal(1, logMsg, logErr) } diff --git a/services/context/context_test.go b/services/context/context_test.go index 8e56007347c..8944f8c8195 100644 --- a/services/context/context_test.go +++ b/services/context/context_test.go @@ -4,6 +4,7 @@ package context import ( + "errors" "net/http" "net/http/httptest" "net/url" @@ -27,8 +28,18 @@ func TestRemoveSessionCookieHeader(t *testing.T) { assert.Contains(t, "other=bar", w.Header().Get("Set-Cookie")) } +func TestServerErrorFetchActionRespondsJSON(t *testing.T) { + req, _ := http.NewRequest(http.MethodPost, "/", nil) + req.Header.Add("X-Gitea-Fetch-Action", "1") + resp := httptest.NewRecorder() + ctx := NewWebContext(NewBaseContextForTest(t, resp, req), nil, nil) + ctx.ServerError("test", errors.New("boom")) + assert.Equal(t, http.StatusInternalServerError, resp.Code) + assert.Contains(t, resp.Header().Get("Content-Type"), "application/json") + assert.JSONEq(t, `{"errorMessage":"test, error: boom","renderFormat":"text"}`, resp.Body.String()) +} + func TestRedirectToCurrentSite(t *testing.T) { - setting.IsInTesting = true defer test.MockVariableValue(&setting.AppURL, "http://localhost:3000/sub/")() defer test.MockVariableValue(&setting.AppSubURL, "/sub")() cases := []struct { @@ -53,7 +64,6 @@ func TestRedirectToCurrentSite(t *testing.T) { } func TestAppFullLink(t *testing.T) { - setting.IsInTesting = true defer test.MockVariableValue(&setting.AppURL, "https://gitea.example.com/sub/")() defer test.MockVariableValue(&setting.AppSubURL, "/sub")() defer test.MockVariableValue(&setting.PublicURLDetection, setting.PublicURLNever)() diff --git a/services/pull/merge.go b/services/pull/merge.go index d48fa95da35..7117bfdcdd5 100644 --- a/services/pull/merge.go +++ b/services/pull/merge.go @@ -460,7 +460,10 @@ func doMergeAndPush(ctx context.Context, pr *issues_model.PullRequest, doer *use } func commitAndSignNoAuthor(ctx *mergeContext, message string) error { - cmdCommit := gitcmd.NewCommand("commit").AddOptionFormat("--message=%s", message) + cmdCommit := gitcmd.NewCommand("commit") + if err := git.AddObjectMessageArgument(cmdCommit, git.ObjectCommit, message); err != nil { + return err + } addCommitSigningOptions(cmdCommit, ctx.signKey) if err := ctx.PrepareGitCmd(cmdCommit).RunWithStderr(ctx); err != nil { return fmt.Errorf("git commit %v: %w\n%s", ctx.pr, err, ctx.outbuf.String()) diff --git a/services/pull/merge_rebase.go b/services/pull/merge_rebase.go index 6695e98ff81..1de4683440a 100644 --- a/services/pull/merge_rebase.go +++ b/services/pull/merge_rebase.go @@ -73,8 +73,10 @@ func doMergeRebaseFastForward(ctx *mergeContext) error { } if newMessage != "" { - cmdCommit := gitcmd.NewCommand("commit", "--amend"). - AddOptionFormat("--message=%s", newMessage) + cmdCommit := gitcmd.NewCommand("commit", "--amend") + if err = git.AddObjectMessageArgument(cmdCommit, git.ObjectCommit, newMessage); err != nil { + return err + } addCommitSigningOptions(cmdCommit, ctx.signKey) if err := cmdCommit.WithRepo(ctx.tmpRepo).Run(ctx); err != nil { log.Error("Unable to amend commit message: %v", err) diff --git a/services/pull/merge_squash.go b/services/pull/merge_squash.go index e738b66b401..5ad3eaa466c 100644 --- a/services/pull/merge_squash.go +++ b/services/pull/merge_squash.go @@ -67,10 +67,11 @@ func doMergeStyleSquash(ctx *mergeContext, message string) error { if setting.Repository.PullRequest.AddCoCommitterTrailers && ctx.committer.String() != sig.String() { message = AddCommitMessageTailer(message, git.CoAuthoredByTrailer, sig.String()) } - cmdCommit := gitcmd.NewCommand("commit"). - AddOptionFormat("--author='%s <%s>'", sig.Name, sig.Email). - AddOptionFormat("--message=%s", message). - AddArguments("--allow-empty") + cmdCommit := gitcmd.NewCommand("commit", "--allow-empty"). + AddOptionFormat("--author='%s <%s>'", sig.Name, sig.Email) + if err = git.AddObjectMessageArgument(cmdCommit, git.ObjectCommit, message); err != nil { + return err + } addCommitSigningOptions(cmdCommit, ctx.signKey) if err := ctx.PrepareGitCmd(cmdCommit).RunWithStderr(ctx); err != nil { log.Error("git commit %-v: %v\n%s\n%s", ctx.pr, err, ctx.outbuf.String(), err.Stderr()) diff --git a/tests/integration/api_repo_git_tags_test.go b/tests/integration/api_repo_git_tags_test.go index c43696eb113..4442ae1ba4f 100644 --- a/tests/integration/api_repo_git_tags_test.go +++ b/tests/integration/api_repo_git_tags_test.go @@ -6,6 +6,7 @@ package integration import ( "fmt" "net/http" + "strings" "testing" auth_model "gitea.dev/models/auth" @@ -14,6 +15,7 @@ import ( user_model "gitea.dev/models/user" "gitea.dev/modules/git" api "gitea.dev/modules/structs" + "gitea.dev/modules/test" "gitea.dev/tests" "github.com/stretchr/testify/assert" @@ -36,20 +38,17 @@ func TestAPIGitTags(t *testing.T) { commit, _ := gitRepo.GetBranchCommit(t.Context(), "master") lTagName := "lightweightTag" - gitRepo.CreateTag(t.Context(), lTagName, commit.ID.String()) + _ = gitRepo.CreateTag(t.Context(), lTagName, commit.ID.String()) aTagName := "annotatedTag" - aTagMessage := "my annotated message" - gitRepo.CreateAnnotatedTag(t.Context(), aTagName, aTagMessage, commit.ID.String()) + aTagMessage := strings.Repeat("very long " /*10bytes*/, 20*1024) + "annotated message" + _ = gitRepo.CreateAnnotatedTag(t.Context(), aTagName, aTagMessage, commit.ID.String()) aTag, _ := gitRepo.GetTag(t.Context(), aTagName) // SHOULD work for annotated tags - req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/tags/%s", user.Name, repo.Name, aTag.ID.String()). - AddTokenAuth(token) - res := MakeRequest(t, req, http.StatusOK) - - tag := DecodeJSON(t, res, &api.AnnotatedTag{}) - + req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/tags/%s", user.Name, repo.Name, aTag.ID.String()).AddTokenAuth(token) + resp := MakeRequest(t, req, http.StatusOK) + tag := DecodeJSON(t, resp, &api.AnnotatedTag{}) assert.Equal(t, aTagName, tag.Tag) assert.Equal(t, aTag.ID.String(), tag.SHA) assert.Equal(t, commit.ID.String(), tag.Object.SHA) @@ -58,6 +57,16 @@ func TestAPIGitTags(t *testing.T) { assert.Equal(t, user.Email, tag.Tagger.Email) assert.Equal(t, repo.APIURL()+"/git/tags/"+aTag.ID.String(), tag.URL) + if !git.DefaultFeatures().UsingGogit { + defer test.MockVariableValue(&git.MaxGitObjectSize, 1024)() + req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/tags/%s", user.Name, repo.Name, aTag.ID.String()).AddTokenAuth(token) + resp = MakeRequest(t, req, http.StatusOK) + tag = DecodeJSON(t, resp, &api.AnnotatedTag{}) + assert.True(t, strings.HasPrefix(aTagMessage, tag.Message)) + assert.Less(t, len(tag.Message), len(aTagMessage)) + assert.Less(t, len(tag.Message), 1024) + } + // Should NOT work for lightweight tags badReq := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/tags/%s", user.Name, repo.Name, commit.ID.String()). AddTokenAuth(token) diff --git a/tests/integration/pull_merge_test.go b/tests/integration/pull_merge_test.go index 4c83200c987..c4c99f2e6bd 100644 --- a/tests/integration/pull_merge_test.go +++ b/tests/integration/pull_merge_test.go @@ -51,6 +51,7 @@ type MergeOptions struct { Style repo_model.MergeStyle HeadCommitID string DeleteBranch bool + Message string } func testPullMerge(t *testing.T, session *TestSession, user, repo, pullNum string, mergeOptions MergeOptions) *httptest.ResponseRecorder { @@ -58,6 +59,7 @@ func testPullMerge(t *testing.T, session *TestSession, user, repo, pullNum strin "do": string(mergeOptions.Style), "head_commit_id": mergeOptions.HeadCommitID, "delete_branch_after_merge": util.Iif(mergeOptions.DeleteBranch, "on", ""), + "merge_message_field": mergeOptions.Message, } var resp *httptest.ResponseRecorder require.Eventually(t, func() bool { @@ -77,6 +79,15 @@ func testPullMerge(t *testing.T, session *TestSession, user, repo, pullNum strin assert.NoError(t, err) assert.True(t, pull.HasMerged) + if mergeOptions.Message != "" { + gitRepo, err := git.OpenRepository(t.Context(), repository) + require.NoError(t, err) + defer gitRepo.Close() + commit, err := gitRepo.GetCommit(t.Context(), pull.MergedCommitID) + require.NoError(t, err) + assert.Contains(t, commit.CommitMessage.MessageRaw, mergeOptions.Message) + } + return resp } @@ -116,8 +127,8 @@ func TestPullMerge(t *testing.T) { elem := strings.Split(test.RedirectURL(resp), "/") assert.Equal(t, "pulls", elem[3]) testPullMerge(t, session, elem[1], elem[2], elem[4], MergeOptions{ - Style: repo_model.MergeStyleMerge, - DeleteBranch: false, + Style: repo_model.MergeStyleMerge, + Message: strings.Repeat("x", 200*1024), }) repo = unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repo.ID})