forked from hinterland/hearth
feat: vendor gitea 1.16.2
This commit is contained in:
@@ -10,22 +10,20 @@ import (
|
||||
actions_model "code.gitea.io/gitea/models/actions"
|
||||
repo_model "code.gitea.io/gitea/models/repo"
|
||||
"code.gitea.io/gitea/modules/actions"
|
||||
"code.gitea.io/gitea/modules/httplib"
|
||||
"code.gitea.io/gitea/modules/util"
|
||||
"code.gitea.io/gitea/services/context"
|
||||
)
|
||||
|
||||
func DownloadActionsRunJobLogsWithIndex(ctx *context.Base, ctxRepo *repo_model.Repository, runID, jobIndex int64) error {
|
||||
runJobs, err := actions_model.GetRunJobsByRunID(ctx, runID)
|
||||
func DownloadActionsRunJobLogsWithID(ctx *context.Base, ctxRepo *repo_model.Repository, runID, jobID int64) error {
|
||||
job, err := actions_model.GetRunJobByRunAndID(ctx, runID, jobID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("GetRunJobsByRunID: %w", err)
|
||||
return err
|
||||
}
|
||||
if err = runJobs.LoadRepos(ctx); err != nil {
|
||||
return fmt.Errorf("LoadRepos: %w", err)
|
||||
if err := job.LoadRepo(ctx); err != nil {
|
||||
return fmt.Errorf("LoadRepo: %w", err)
|
||||
}
|
||||
if jobIndex < 0 || jobIndex >= int64(len(runJobs)) {
|
||||
return util.NewNotExistErrorf("job index is out of range: %d", jobIndex)
|
||||
}
|
||||
return DownloadActionsRunJobLogs(ctx, ctxRepo, runJobs[jobIndex])
|
||||
return DownloadActionsRunJobLogs(ctx, ctxRepo, job)
|
||||
}
|
||||
|
||||
func DownloadActionsRunJobLogs(ctx *context.Base, ctxRepo *repo_model.Repository, curJob *actions_model.ActionRunJob) error {
|
||||
@@ -60,12 +58,11 @@ func DownloadActionsRunJobLogs(ctx *context.Base, ctxRepo *repo_model.Repository
|
||||
if p := strings.Index(workflowName, "."); p > 0 {
|
||||
workflowName = workflowName[0:p]
|
||||
}
|
||||
ctx.ServeContent(reader, &context.ServeHeaderOptions{
|
||||
ctx.ServeContent(reader, context.ServeHeaderOptions{
|
||||
Filename: fmt.Sprintf("%v-%v-%v.log", workflowName, curJob.Name, task.ID),
|
||||
ContentLength: &task.LogSize,
|
||||
ContentType: "text/plain",
|
||||
ContentTypeCharset: "utf-8",
|
||||
Disposition: "attachment",
|
||||
ContentType: "text/plain; charset=utf-8",
|
||||
ContentDisposition: httplib.ContentDispositionAttachment,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -38,8 +38,8 @@ func AuthShared(ctx *context.Base, sessionStore auth_service.SessionStore, authM
|
||||
|
||||
// VerifyOptions contains required or check options
|
||||
type VerifyOptions struct {
|
||||
SignInRequired bool
|
||||
SignOutRequired bool
|
||||
AdminRequired bool
|
||||
DisableCSRF bool
|
||||
SignInRequired bool
|
||||
SignOutRequired bool
|
||||
AdminRequired bool
|
||||
DisableCrossOriginProtection bool
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ func BlockExpensive() func(next http.Handler) http.Handler {
|
||||
ret := determineRequestPriority(reqctx.FromContext(req.Context()))
|
||||
if !ret.SignedIn {
|
||||
if ret.Expensive || ret.LongPolling {
|
||||
http.Redirect(w, req, setting.AppSubURL+"/user/login", http.StatusSeeOther)
|
||||
http.Redirect(w, req, middleware.RedirectLinkUserLogin(req), http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,22 +5,94 @@ package common
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
repo_model "code.gitea.io/gitea/models/repo"
|
||||
user_model "code.gitea.io/gitea/models/user"
|
||||
"code.gitea.io/gitea/modules/git"
|
||||
pull_service "code.gitea.io/gitea/services/pull"
|
||||
"code.gitea.io/gitea/modules/util"
|
||||
)
|
||||
|
||||
// CompareInfo represents the collected results from ParseCompareInfo
|
||||
type CompareInfo struct {
|
||||
HeadUser *user_model.User
|
||||
HeadRepo *repo_model.Repository
|
||||
HeadGitRepo *git.Repository
|
||||
CompareInfo *pull_service.CompareInfo
|
||||
BaseBranch string
|
||||
HeadBranch string
|
||||
DirectComparison bool
|
||||
type CompareRouterReq struct {
|
||||
BaseOriRef string
|
||||
BaseOriRefSuffix string
|
||||
|
||||
CompareSeparator string
|
||||
|
||||
HeadOwner string
|
||||
HeadRepoName string
|
||||
HeadOriRef string
|
||||
}
|
||||
|
||||
func (cr *CompareRouterReq) DirectComparison() bool {
|
||||
// FIXME: the design of "DirectComparison" is wrong, it loses the information of `^`
|
||||
// To correctly handle the comparison, developers should use `ci.CompareSeparator` directly, all "DirectComparison" related code should be rewritten.
|
||||
return cr.CompareSeparator == ".."
|
||||
}
|
||||
|
||||
func parseHead(head string) (headOwnerName, headRepoName, headRef string) {
|
||||
paths := strings.SplitN(head, ":", 2)
|
||||
if len(paths) == 1 {
|
||||
return "", "", paths[0]
|
||||
}
|
||||
ownerRepo := strings.SplitN(paths[0], "/", 2)
|
||||
if len(ownerRepo) == 1 {
|
||||
return paths[0], "", paths[1]
|
||||
}
|
||||
return ownerRepo[0], ownerRepo[1], paths[1]
|
||||
}
|
||||
|
||||
// ParseCompareRouterParam Get compare information from the router parameter.
|
||||
// A full compare url is of the form:
|
||||
//
|
||||
// 0. /{:baseOwner}/{:baseRepoName}/compare
|
||||
// 1. /{:baseOwner}/{:baseRepoName}/compare/{:baseBranch}...{:headBranch}
|
||||
// 2. /{:baseOwner}/{:baseRepoName}/compare/{:baseBranch}...{:headOwner}:{:headBranch}
|
||||
// 3. /{:baseOwner}/{:baseRepoName}/compare/{:baseBranch}...{:headOwner}/{:headRepoName}:{:headBranch}
|
||||
// 4. /{:baseOwner}/{:baseRepoName}/compare/{:headBranch}
|
||||
// 5. /{:baseOwner}/{:baseRepoName}/compare/{:headOwner}:{:headBranch}
|
||||
// 6. /{:baseOwner}/{:baseRepoName}/compare/{:headOwner}/{:headRepoName}:{:headBranch}
|
||||
//
|
||||
// Here we obtain the infoPath "{:baseBranch}...[{:headOwner}/{:headRepoName}:]{:headBranch}" as ctx.PathParam("*")
|
||||
// with the :baseRepo in ctx.Repo.
|
||||
//
|
||||
// Note: Generally :headRepoName is not provided here - we are only passed :headOwner.
|
||||
//
|
||||
// How do we determine the :headRepo?
|
||||
//
|
||||
// 1. If :headOwner is not set then the :headRepo = :baseRepo
|
||||
// 2. If :headOwner is set - then look for the fork of :baseRepo owned by :headOwner
|
||||
// 3. But... :baseRepo could be a fork of :headOwner's repo - so check that
|
||||
// 4. Now, :baseRepo and :headRepos could be forks of the same repo - so check that
|
||||
//
|
||||
// format: <base branch>...[<head repo>:]<head branch>
|
||||
// base<-head: master...head:feature
|
||||
// same repo: master...feature
|
||||
func ParseCompareRouterParam(routerParam string) *CompareRouterReq {
|
||||
if routerParam == "" {
|
||||
return &CompareRouterReq{}
|
||||
}
|
||||
|
||||
sep := "..."
|
||||
basePart, headPart, ok := strings.Cut(routerParam, sep)
|
||||
if !ok {
|
||||
sep = ".."
|
||||
basePart, headPart, ok = strings.Cut(routerParam, sep)
|
||||
if !ok {
|
||||
headOwnerName, headRepoName, headRef := parseHead(routerParam)
|
||||
return &CompareRouterReq{
|
||||
HeadOriRef: headRef,
|
||||
HeadOwner: headOwnerName,
|
||||
HeadRepoName: headRepoName,
|
||||
CompareSeparator: "...",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ci := &CompareRouterReq{CompareSeparator: sep}
|
||||
ci.BaseOriRef, ci.BaseOriRefSuffix = git.ParseRefSuffix(basePart)
|
||||
ci.HeadOwner, ci.HeadRepoName, ci.HeadOriRef = parseHead(headPart)
|
||||
return ci
|
||||
}
|
||||
|
||||
// maxForkTraverseLevel defines the maximum levels to traverse when searching for the head repository.
|
||||
@@ -45,9 +117,51 @@ func FindHeadRepo(ctx context.Context, baseRepo *repo_model.Repository, headUser
|
||||
return findHeadRepoFromRootBase(ctx, baseRepo, headUserID, maxForkTraverseLevel)
|
||||
}
|
||||
|
||||
func GetHeadOwnerAndRepo(ctx context.Context, baseRepo *repo_model.Repository, compareReq *CompareRouterReq) (headOwner *user_model.User, headRepo *repo_model.Repository, err error) {
|
||||
if compareReq.HeadOwner == "" {
|
||||
if compareReq.HeadRepoName != "" { // unsupported syntax
|
||||
return nil, nil, util.ErrorWrap(util.ErrInvalidArgument, "head owner must be specified when head repo name is given")
|
||||
}
|
||||
|
||||
return baseRepo.Owner, baseRepo, nil
|
||||
}
|
||||
|
||||
if compareReq.HeadOwner == baseRepo.Owner.Name {
|
||||
headOwner = baseRepo.Owner
|
||||
} else {
|
||||
headOwner, err = user_model.GetUserByName(ctx, compareReq.HeadOwner)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
if compareReq.HeadRepoName == "" {
|
||||
if headOwner.ID == baseRepo.OwnerID {
|
||||
headRepo = baseRepo
|
||||
} else {
|
||||
headRepo, err = FindHeadRepo(ctx, baseRepo, headOwner.ID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if headRepo == nil {
|
||||
return nil, nil, util.ErrorWrap(util.ErrInvalidArgument, "the user %s does not have a fork of the base repository", headOwner.Name)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if compareReq.HeadOwner == baseRepo.Owner.Name && compareReq.HeadRepoName == baseRepo.Name {
|
||||
headRepo = baseRepo
|
||||
} else {
|
||||
headRepo, err = repo_model.GetRepositoryByName(ctx, headOwner.ID, compareReq.HeadRepoName)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
return headOwner, headRepo, nil
|
||||
}
|
||||
|
||||
func findHeadRepoFromRootBase(ctx context.Context, baseRepo *repo_model.Repository, headUserID int64, traverseLevel int) (*repo_model.Repository, error) {
|
||||
if traverseLevel == 0 {
|
||||
return nil, nil
|
||||
return nil, nil //nolint:nilnil // return nil to indicate that the object does not exist
|
||||
}
|
||||
// test if we are lucky
|
||||
repo, err := repo_model.GetUserFork(ctx, baseRepo.ID, headUserID)
|
||||
@@ -71,5 +185,5 @@ func findHeadRepoFromRootBase(ctx context.Context, baseRepo *repo_model.Reposito
|
||||
return forked, nil
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
return nil, nil //nolint:nilnil // return nil to indicate that the object does not exist
|
||||
}
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
// Copyright 2025 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package common
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestCompareRouterReq(t *testing.T) {
|
||||
cases := []struct {
|
||||
input string
|
||||
CompareRouterReq *CompareRouterReq
|
||||
}{
|
||||
{
|
||||
input: "",
|
||||
CompareRouterReq: &CompareRouterReq{},
|
||||
},
|
||||
{
|
||||
input: "v1.0...v1.1",
|
||||
CompareRouterReq: &CompareRouterReq{
|
||||
BaseOriRef: "v1.0",
|
||||
CompareSeparator: "...",
|
||||
HeadOriRef: "v1.1",
|
||||
},
|
||||
},
|
||||
{
|
||||
input: "main..develop",
|
||||
CompareRouterReq: &CompareRouterReq{
|
||||
BaseOriRef: "main",
|
||||
CompareSeparator: "..",
|
||||
HeadOriRef: "develop",
|
||||
},
|
||||
},
|
||||
{
|
||||
input: "main^...develop",
|
||||
CompareRouterReq: &CompareRouterReq{
|
||||
BaseOriRef: "main",
|
||||
BaseOriRefSuffix: "^",
|
||||
CompareSeparator: "...",
|
||||
HeadOriRef: "develop",
|
||||
},
|
||||
},
|
||||
{
|
||||
input: "main^^^^^...develop",
|
||||
CompareRouterReq: &CompareRouterReq{
|
||||
BaseOriRef: "main",
|
||||
BaseOriRefSuffix: "^^^^^",
|
||||
CompareSeparator: "...",
|
||||
HeadOriRef: "develop",
|
||||
},
|
||||
},
|
||||
{
|
||||
input: "develop",
|
||||
CompareRouterReq: &CompareRouterReq{
|
||||
CompareSeparator: "...",
|
||||
HeadOriRef: "develop",
|
||||
},
|
||||
},
|
||||
{
|
||||
input: "teabot:feature1",
|
||||
CompareRouterReq: &CompareRouterReq{
|
||||
CompareSeparator: "...",
|
||||
HeadOwner: "teabot",
|
||||
HeadOriRef: "feature1",
|
||||
},
|
||||
},
|
||||
{
|
||||
input: "lunny/forked_repo:develop",
|
||||
CompareRouterReq: &CompareRouterReq{
|
||||
CompareSeparator: "...",
|
||||
HeadOwner: "lunny",
|
||||
HeadRepoName: "forked_repo",
|
||||
HeadOriRef: "develop",
|
||||
},
|
||||
},
|
||||
{
|
||||
input: "main...lunny/forked_repo:develop",
|
||||
CompareRouterReq: &CompareRouterReq{
|
||||
BaseOriRef: "main",
|
||||
CompareSeparator: "...",
|
||||
HeadOwner: "lunny",
|
||||
HeadRepoName: "forked_repo",
|
||||
HeadOriRef: "develop",
|
||||
},
|
||||
},
|
||||
{
|
||||
input: "main^...lunny/forked_repo:develop",
|
||||
CompareRouterReq: &CompareRouterReq{
|
||||
BaseOriRef: "main",
|
||||
BaseOriRefSuffix: "^",
|
||||
CompareSeparator: "...",
|
||||
HeadOwner: "lunny",
|
||||
HeadRepoName: "forked_repo",
|
||||
HeadOriRef: "develop",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
assert.Equal(t, c.CompareRouterReq, ParseCompareRouterParam(c.input), "input: %s", c.input)
|
||||
}
|
||||
}
|
||||
@@ -4,12 +4,16 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
user_model "code.gitea.io/gitea/models/user"
|
||||
"code.gitea.io/gitea/modules/httpcache"
|
||||
"code.gitea.io/gitea/modules/log"
|
||||
"code.gitea.io/gitea/modules/reqctx"
|
||||
"code.gitea.io/gitea/modules/setting"
|
||||
"code.gitea.io/gitea/modules/templates"
|
||||
"code.gitea.io/gitea/modules/web/middleware"
|
||||
@@ -19,37 +23,57 @@ import (
|
||||
|
||||
const tplStatus500 templates.TplName = "status/500"
|
||||
|
||||
// RenderPanicErrorPage renders a 500 page, and it never panics
|
||||
func RenderPanicErrorPage(w http.ResponseWriter, req *http.Request, err any) {
|
||||
combinedErr := fmt.Sprintf("%v\n%s", err, log.Stack(2))
|
||||
log.Error("PANIC: %s", combinedErr)
|
||||
func renderServerErrorPage(w http.ResponseWriter, req *http.Request, respCode int, tmpl templates.TplName, ctxData map[string]any, plainMsg string) {
|
||||
acceptsHTML := false
|
||||
for _, part := range req.Header["Accept"] {
|
||||
if strings.Contains(part, "text/html") {
|
||||
acceptsHTML = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
httpcache.SetCacheControlInHeader(w.Header(), &httpcache.CacheControlOptions{NoTransform: true})
|
||||
if setting.Security.XFrameOptions != "unset" {
|
||||
w.Header().Set(`X-Frame-Options`, setting.Security.XFrameOptions)
|
||||
}
|
||||
|
||||
tmplCtx := context.NewTemplateContextForWeb(reqctx.FromContext(req.Context()), req, middleware.Locale(w, req))
|
||||
w.WriteHeader(respCode)
|
||||
|
||||
outBuf := &bytes.Buffer{}
|
||||
if acceptsHTML {
|
||||
err := templates.PageRenderer().HTML(outBuf, respCode, tmpl, ctxData, tmplCtx)
|
||||
if err != nil {
|
||||
_, _ = w.Write([]byte("Internal server error but failed to render error page template, please collect error logs and report to Gitea issue tracker"))
|
||||
return
|
||||
}
|
||||
} else {
|
||||
outBuf.WriteString(plainMsg)
|
||||
}
|
||||
_, _ = io.Copy(w, outBuf)
|
||||
}
|
||||
|
||||
// renderPanicErrorPage renders a 500 page with the recovered panic value, it handles the stack trace, and it never panics
|
||||
func renderPanicErrorPage(w http.ResponseWriter, req *http.Request, recovered any) {
|
||||
combinedErr := fmt.Errorf("%v\n%s", recovered, log.Stack(2))
|
||||
log.Error("PANIC: %v", combinedErr)
|
||||
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
log.Error("Panic occurs again when rendering error page: %v. Stack:\n%s", err, log.Stack(2))
|
||||
log.Error("Panic occurs again when rendering error page: %v. Stack:\n%s", combinedErr, log.Stack(2))
|
||||
}
|
||||
}()
|
||||
|
||||
routing.UpdatePanicError(req.Context(), err)
|
||||
routing.UpdatePanicError(req.Context(), combinedErr)
|
||||
|
||||
httpcache.SetCacheControlInHeader(w.Header(), &httpcache.CacheControlOptions{NoTransform: true})
|
||||
w.Header().Set(`X-Frame-Options`, setting.CORSConfig.XFrameOptions)
|
||||
|
||||
tmplCtx := context.TemplateContext{}
|
||||
tmplCtx["Locale"] = middleware.Locale(w, req)
|
||||
plainMsg := "Internal Server Error"
|
||||
ctxData := middleware.GetContextData(req.Context())
|
||||
|
||||
// This recovery handler could be called without Gitea's web context, so we shouldn't touch that context too much.
|
||||
// Otherwise, the 500-page may cause new panics, eg: cache.GetContextWithData, it makes the developer&users couldn't find the original panic.
|
||||
user, _ := ctxData[middleware.ContextDataKeySignedUser].(*user_model.User)
|
||||
if !setting.IsProd || (user != nil && user.IsAdmin) {
|
||||
ctxData["ErrorMsg"] = "PANIC: " + combinedErr
|
||||
}
|
||||
|
||||
err = templates.HTMLRenderer().HTML(w, http.StatusInternalServerError, tplStatus500, ctxData, tmplCtx)
|
||||
if err != nil {
|
||||
log.Error("Error occurs again when rendering error page: %v", err)
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
_, _ = w.Write([]byte("Internal server error, please collect error logs and report to Gitea issue tracker"))
|
||||
plainMsg = "PANIC: " + combinedErr.Error()
|
||||
ctxData["ErrorMsg"] = plainMsg
|
||||
}
|
||||
renderServerErrorPage(w, req, http.StatusInternalServerError, tplStatus500, ctxData, plainMsg)
|
||||
}
|
||||
|
||||
@@ -18,19 +18,28 @@ import (
|
||||
)
|
||||
|
||||
func TestRenderPanicErrorPage(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
req := &http.Request{URL: &url.URL{}}
|
||||
req = req.WithContext(reqctx.NewRequestContextForTest(t.Context()))
|
||||
RenderPanicErrorPage(w, req, errors.New("fake panic error (for test only)"))
|
||||
respContent := w.Body.String()
|
||||
assert.Contains(t, respContent, `class="page-content status-page-500"`)
|
||||
assert.Contains(t, respContent, `</html>`)
|
||||
assert.Contains(t, respContent, `lang="en-US"`) // make sure the locale work
|
||||
t.Run("HTML", func(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
req := &http.Request{URL: &url.URL{}, Header: http.Header{"Accept": []string{"text/html"}}}
|
||||
req = req.WithContext(reqctx.NewRequestContextForTest(t.Context()))
|
||||
renderPanicErrorPage(w, req, errors.New("fake panic error (for test only)"))
|
||||
respContent := w.Body.String()
|
||||
assert.Contains(t, respContent, `class="page-content status-page-500"`)
|
||||
assert.Contains(t, respContent, `</html>`)
|
||||
assert.Contains(t, respContent, `lang="en-US"`) // make sure the locale work
|
||||
|
||||
// the 500 page doesn't have normal pages footer, it makes it easier to distinguish a normal page and a failed page.
|
||||
// especially when a sub-template causes page error, the HTTP response code is still 200,
|
||||
// the different "footer" is the only way to know whether a page is fully rendered without error.
|
||||
assert.False(t, test.IsNormalPageCompleted(respContent))
|
||||
// the 500 page doesn't have normal pages footer, it makes it easier to distinguish a normal page and a failed page.
|
||||
// especially when a sub-template causes page error, the HTTP response code is still 200,
|
||||
// the different "footer" is the only way to know whether a page is fully rendered without error.
|
||||
assert.False(t, test.IsNormalPageCompleted(respContent))
|
||||
})
|
||||
t.Run("Plain", func(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
req := &http.Request{URL: &url.URL{}}
|
||||
req = req.WithContext(reqctx.NewRequestContextForTest(t.Context()))
|
||||
renderServiceUnavailable(w, req)
|
||||
assert.Equal(t, "Service Unavailable", w.Body.String())
|
||||
})
|
||||
}
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
// Copyright 2025 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package common
|
||||
|
||||
import (
|
||||
"code.gitea.io/gitea/modules/optional"
|
||||
)
|
||||
|
||||
func ParseIssueFilterStateIsClosed(state string) optional.Option[bool] {
|
||||
switch state {
|
||||
case "all":
|
||||
return optional.None[bool]()
|
||||
case "closed":
|
||||
return optional.Some(true)
|
||||
case "", "open":
|
||||
return optional.Some(false)
|
||||
default:
|
||||
return optional.Some(false) // unknown state, undefined behavior
|
||||
}
|
||||
}
|
||||
|
||||
func ParseIssueFilterTypeIsPull(typ string) optional.Option[bool] {
|
||||
return optional.FromMapLookup(map[string]bool{"pulls": true, "issues": false}, typ)
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package common
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"code.gitea.io/gitea/modules/container"
|
||||
"code.gitea.io/gitea/modules/setting"
|
||||
)
|
||||
|
||||
func MaintenanceModeHandler() func(h http.Handler) http.Handler {
|
||||
allowedPrefixes := []string{
|
||||
"/.well-known/",
|
||||
"/assets/",
|
||||
"/avatars/",
|
||||
|
||||
// admin: "/-/admin"
|
||||
// general-purpose URLs: "/-/fetch-redirect", "/-/markup", etc.
|
||||
"/-/",
|
||||
|
||||
// internal APIs
|
||||
"/api/internal/",
|
||||
|
||||
// user login (for admin to login): "/user/login", "/user/logout", "/catpcha/..."
|
||||
"/user/",
|
||||
"/captcha/",
|
||||
}
|
||||
allowedPaths := container.SetOf(
|
||||
"/api/healthz",
|
||||
)
|
||||
isMaintenanceModeAllowedRequest := func(req *http.Request) bool {
|
||||
for _, prefix := range allowedPrefixes {
|
||||
if strings.HasPrefix(req.URL.Path, prefix) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return allowedPaths.Contains(req.URL.Path)
|
||||
}
|
||||
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
|
||||
maintenanceMode := setting.Config().Instance.MaintenanceMode.Value(req.Context())
|
||||
if maintenanceMode.IsActive() && !isMaintenanceModeAllowedRequest(req) {
|
||||
renderServiceUnavailable(resp, req)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(resp, req)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -6,14 +6,13 @@ package common
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"path"
|
||||
"strings"
|
||||
|
||||
"code.gitea.io/gitea/models/renderhelper"
|
||||
"code.gitea.io/gitea/models/repo"
|
||||
"code.gitea.io/gitea/modules/httplib"
|
||||
"code.gitea.io/gitea/modules/log"
|
||||
"code.gitea.io/gitea/modules/markup"
|
||||
"code.gitea.io/gitea/modules/markup/markdown"
|
||||
"code.gitea.io/gitea/modules/setting"
|
||||
@@ -31,20 +30,18 @@ func RenderMarkup(ctx *context.Base, ctxRepo *context.Repository, mode, text, ur
|
||||
// and the urlPathContext is "/gitea/owner/repo/src/branch/features/feat-123/doc"
|
||||
|
||||
if mode == "" || mode == "markdown" {
|
||||
// raw markdown doesn't need any special handling
|
||||
baseLink := urlPathContext
|
||||
if baseLink == "" {
|
||||
baseLink = fmt.Sprintf("%s%s", httplib.GuessCurrentHostURL(ctx), urlPathContext)
|
||||
}
|
||||
rctx := renderhelper.NewRenderContextSimpleDocument(ctx, baseLink).WithUseAbsoluteLink(true).
|
||||
// raw Markdown doesn't do any special handling
|
||||
// TODO: raw markdown doesn't do any link processing, so "urlPathContext" doesn't take effect
|
||||
rctx := renderhelper.NewRenderContextSimpleDocument(ctx, urlPathContext).WithUseAbsoluteLink(true).
|
||||
WithMarkupType(markdown.MarkupName)
|
||||
if err := markdown.RenderRaw(rctx, strings.NewReader(text), ctx.Resp); err != nil {
|
||||
ctx.HTTPError(http.StatusInternalServerError, err.Error())
|
||||
log.Error("RenderMarkupRaw: %v", err)
|
||||
ctx.HTTPError(http.StatusInternalServerError, "failed to render raw markup")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Ideally, this handler should be called with RepoAssigment and get the related repo from context "/owner/repo/markup"
|
||||
// Ideally, this handler should be called with RepoAssignment and get the related repo from context "/owner/repo/markup"
|
||||
// then render could use the repo to do various things (the permission check has passed)
|
||||
//
|
||||
// However, this handler is also exposed as "/markup" without any repo context,
|
||||
@@ -92,7 +89,7 @@ func RenderMarkup(ctx *context.Base, ctxRepo *context.Repository, mode, text, ur
|
||||
})
|
||||
rctx = rctx.WithMarkupType("").WithRelativePath(filePath) // render the repo file content by its extension
|
||||
default:
|
||||
ctx.HTTPError(http.StatusUnprocessableEntity, "Unknown mode: "+mode)
|
||||
ctx.HTTPError(http.StatusUnprocessableEntity, "unsupported render mode: "+mode)
|
||||
return
|
||||
}
|
||||
rctx = rctx.WithUseAbsoluteLink(true)
|
||||
@@ -100,7 +97,8 @@ func RenderMarkup(ctx *context.Base, ctxRepo *context.Repository, mode, text, ur
|
||||
if errors.Is(err, util.ErrInvalidArgument) {
|
||||
ctx.HTTPError(http.StatusUnprocessableEntity, err.Error())
|
||||
} else {
|
||||
ctx.HTTPError(http.StatusInternalServerError, err.Error())
|
||||
log.Error("RenderMarkup: %v", err)
|
||||
ctx.HTTPError(http.StatusInternalServerError, "failed to render markup")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
@@ -11,6 +11,8 @@ import (
|
||||
"code.gitea.io/gitea/modules/cache"
|
||||
"code.gitea.io/gitea/modules/gtprof"
|
||||
"code.gitea.io/gitea/modules/httplib"
|
||||
"code.gitea.io/gitea/modules/log"
|
||||
"code.gitea.io/gitea/modules/public"
|
||||
"code.gitea.io/gitea/modules/reqctx"
|
||||
"code.gitea.io/gitea/modules/setting"
|
||||
"code.gitea.io/gitea/modules/web/routing"
|
||||
@@ -39,6 +41,10 @@ func ProtocolMiddlewares() (handlers []any) {
|
||||
handlers = append(handlers, context.AccessLogger())
|
||||
}
|
||||
|
||||
if !setting.IsProd {
|
||||
handlers = append(handlers, public.ViteDevMiddleware)
|
||||
}
|
||||
|
||||
return handlers
|
||||
}
|
||||
|
||||
@@ -62,8 +68,8 @@ func RequestContextHandler() func(h http.Handler) http.Handler {
|
||||
}()
|
||||
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
RenderPanicErrorPage(respWriter, req, err) // it should never panic
|
||||
if recovered := recover(); recovered != nil {
|
||||
renderPanicErrorPage(respWriter, req, recovered) // it should never panic, and it handles the stack trace internally
|
||||
}
|
||||
}()
|
||||
|
||||
@@ -71,8 +77,10 @@ func RequestContextHandler() func(h http.Handler) http.Handler {
|
||||
req = req.WithContext(cache.WithCacheContext(ctx))
|
||||
ds.SetContextValue(httplib.RequestContextKey, req)
|
||||
ds.AddCleanUp(func() {
|
||||
// The req in context might have changed due to the new req.WithContext calls
|
||||
// TODO: GOLANG-HTTP-TMPDIR: Golang saves the uploaded files to temp directory (TMPDIR) when parsing multipart-form.
|
||||
// The "req" might have changed due to the new "req.WithContext" calls
|
||||
// For example: in NewBaseContext, a new "req" with context is created, and the multipart-form is parsed there.
|
||||
// So we always use the latest "req" from the data store.
|
||||
ctxReq := ds.GetContextValue(httplib.RequestContextKey).(*http.Request)
|
||||
if ctxReq.MultipartForm != nil {
|
||||
_ = ctxReq.MultipartForm.RemoveAll() // remove the temp files buffered to tmp directory
|
||||
@@ -110,8 +118,12 @@ func ForwardedHeadersHandler(limit int, trustedProxies []string) func(h http.Han
|
||||
return proxy.ForwardedHeaders(opt)
|
||||
}
|
||||
|
||||
func Sessioner() func(next http.Handler) http.Handler {
|
||||
return session.Sessioner(session.Options{
|
||||
func MustInitSessioner() func(next http.Handler) http.Handler {
|
||||
// TODO: CHI-SESSION-GOB-REGISTER: chi-session has a design problem: it calls gob.Register for "Set"
|
||||
// But if the server restarts, then the first "Get" will fail to decode the previously stored session data because the structs are not registered yet.
|
||||
// So each package should make sure their structs are registered correctly during startup for session storage.
|
||||
|
||||
middleware, err := session.Sessioner(session.Options{
|
||||
Provider: setting.SessionConfig.Provider,
|
||||
ProviderConfig: setting.SessionConfig.ProviderConfig,
|
||||
CookieName: setting.SessionConfig.CookieName,
|
||||
@@ -122,4 +134,8 @@ func Sessioner() func(next http.Handler) http.Handler {
|
||||
SameSite: setting.SessionConfig.SameSite,
|
||||
Domain: setting.SessionConfig.Domain,
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatal("common.Sessioner failed: %v", err)
|
||||
}
|
||||
return middleware
|
||||
}
|
||||
|
||||
@@ -14,7 +14,6 @@ import (
|
||||
"code.gitea.io/gitea/modules/setting"
|
||||
"code.gitea.io/gitea/modules/templates"
|
||||
"code.gitea.io/gitea/modules/web/middleware"
|
||||
giteacontext "code.gitea.io/gitea/services/context"
|
||||
|
||||
"github.com/bohde/codel"
|
||||
"github.com/go-chi/chi/v5"
|
||||
@@ -119,27 +118,6 @@ func requestPriority(ctx context.Context) Priority {
|
||||
// renderServiceUnavailable will render an HTTP 503 Service
|
||||
// Unavailable page, providing HTML if the client accepts it.
|
||||
func renderServiceUnavailable(w http.ResponseWriter, req *http.Request) {
|
||||
acceptsHTML := false
|
||||
for _, part := range req.Header["Accept"] {
|
||||
if strings.Contains(part, "text/html") {
|
||||
acceptsHTML = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// If the client doesn't accept HTML, then render a plain text response
|
||||
if !acceptsHTML {
|
||||
http.Error(w, "503 Service Unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
|
||||
tmplCtx := giteacontext.TemplateContext{}
|
||||
tmplCtx["Locale"] = middleware.Locale(w, req)
|
||||
ctxData := middleware.GetContextData(req.Context())
|
||||
err := templates.HTMLRenderer().HTML(w, http.StatusServiceUnavailable, tplStatus503, ctxData, tmplCtx)
|
||||
if err != nil {
|
||||
log.Error("Error occurs again when rendering service unavailable page: %v", err)
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
_, _ = w.Write([]byte("Internal server error, please collect error logs and report to Gitea issue tracker"))
|
||||
}
|
||||
renderServerErrorPage(w, req, http.StatusServiceUnavailable, tplStatus503, ctxData, "Service Unavailable")
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
user_model "code.gitea.io/gitea/models/user"
|
||||
@@ -62,30 +61,3 @@ func TestRequestPriority(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderServiceUnavailable(t *testing.T) {
|
||||
t.Run("HTML", func(t *testing.T) {
|
||||
ctx, resp := contexttest.MockContext(t, "")
|
||||
ctx.Req.Header.Set("Accept", "text/html")
|
||||
|
||||
renderServiceUnavailable(resp, ctx.Req)
|
||||
assert.Equal(t, http.StatusServiceUnavailable, resp.Code)
|
||||
assert.Contains(t, resp.Header().Get("Content-Type"), "text/html")
|
||||
|
||||
body := resp.Body.String()
|
||||
assert.Contains(t, body, `lang="en-US"`)
|
||||
assert.Contains(t, body, "503 Service Unavailable")
|
||||
})
|
||||
|
||||
t.Run("plain", func(t *testing.T) {
|
||||
ctx, resp := contexttest.MockContext(t, "")
|
||||
ctx.Req.Header.Set("Accept", "text/plain")
|
||||
|
||||
renderServiceUnavailable(resp, ctx.Req)
|
||||
assert.Equal(t, http.StatusServiceUnavailable, resp.Code)
|
||||
assert.Contains(t, resp.Header().Get("Content-Type"), "text/plain")
|
||||
|
||||
body := resp.Body.String()
|
||||
assert.Contains(t, body, "503 Service Unavailable")
|
||||
})
|
||||
}
|
||||
|
||||
@@ -16,11 +16,12 @@ func FetchRedirectDelegate(resp http.ResponseWriter, req *http.Request) {
|
||||
// 2. when use "window.reload()", the hash is not respected, the newly loaded page won't scroll to the hash target.
|
||||
// The typical page is "issue comment" page. The backend responds "/owner/repo/issues/1#comment-2",
|
||||
// then frontend needs this delegate to redirect to the new location with hash correctly.
|
||||
redirect := req.PostFormValue("redirect")
|
||||
if !httplib.IsCurrentGiteaSiteURL(req.Context(), redirect) {
|
||||
resp.WriteHeader(http.StatusBadRequest)
|
||||
redirect := req.FormValue("redirect")
|
||||
if req.Method != http.MethodPost || !httplib.IsCurrentGiteaSiteURL(req.Context(), redirect) {
|
||||
http.Error(resp, "Bad Request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
resp.Header().Add("Location", redirect)
|
||||
// no OpenRedirect, the "redirect" is validated by "IsCurrentGiteaSiteURL" above
|
||||
resp.Header().Set("Location", redirect)
|
||||
resp.WriteHeader(http.StatusSeeOther)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
// Copyright 2026 The Gitea Authors. All rights reserved.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package common
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"code.gitea.io/gitea/modules/setting"
|
||||
"code.gitea.io/gitea/modules/test"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestFetchRedirectDelegate(t *testing.T) {
|
||||
defer test.MockVariableValue(&setting.AppURL, "https://gitea/")()
|
||||
|
||||
cases := []struct {
|
||||
method string
|
||||
input string
|
||||
status int
|
||||
}{
|
||||
{method: "POST", input: "/foo?k=v", status: http.StatusSeeOther},
|
||||
{method: "GET", input: "/foo?k=v", status: http.StatusBadRequest},
|
||||
{method: "POST", input: `\/foo?k=v`, status: http.StatusBadRequest},
|
||||
{method: "POST", input: `\\/foo?k=v`, status: http.StatusBadRequest},
|
||||
{method: "POST", input: "https://gitea/xxx", status: http.StatusSeeOther},
|
||||
{method: "POST", input: "https://other/xxx", status: http.StatusBadRequest},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.method+" "+c.input, func(t *testing.T) {
|
||||
resp := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(c.method, "/?redirect="+url.QueryEscape(c.input), nil)
|
||||
FetchRedirectDelegate(resp, req)
|
||||
assert.Equal(t, c.status, resp.Code)
|
||||
if c.status == http.StatusSeeOther {
|
||||
assert.Equal(t, c.input, resp.Header().Get("Location"))
|
||||
} else {
|
||||
assert.Empty(t, resp.Header().Get("Location"))
|
||||
assert.Equal(t, "Bad Request", strings.TrimSpace(resp.Body.String()))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,6 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"io"
|
||||
"path"
|
||||
"time"
|
||||
|
||||
@@ -12,7 +11,6 @@ import (
|
||||
"code.gitea.io/gitea/modules/git"
|
||||
"code.gitea.io/gitea/modules/httpcache"
|
||||
"code.gitea.io/gitea/modules/httplib"
|
||||
"code.gitea.io/gitea/modules/log"
|
||||
"code.gitea.io/gitea/modules/setting"
|
||||
"code.gitea.io/gitea/modules/structs"
|
||||
"code.gitea.io/gitea/services/context"
|
||||
@@ -20,33 +18,28 @@ import (
|
||||
|
||||
// ServeBlob download a git.Blob
|
||||
func ServeBlob(ctx *context.Base, repo *repo_model.Repository, filePath string, blob *git.Blob, lastModified *time.Time) error {
|
||||
if httpcache.HandleGenericETagTimeCache(ctx.Req, ctx.Resp, `"`+blob.ID.String()+`"`, lastModified) {
|
||||
if httpcache.HandleGenericETagPrivateCache(ctx.Req, ctx.Resp, `"`+blob.ID.String()+`"`, lastModified) {
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := repo.LoadOwner(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dataRc, err := blob.DataAsync()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
if err = dataRc.Close(); err != nil {
|
||||
log.Error("ServeBlob: Close: %v", err)
|
||||
}
|
||||
}()
|
||||
defer dataRc.Close()
|
||||
|
||||
_ = repo.LoadOwner(ctx)
|
||||
httplib.ServeContentByReader(ctx.Req, ctx.Resp, blob.Size(), dataRc, &httplib.ServeHeaderOptions{
|
||||
if lastModified == nil {
|
||||
lastModified = new(time.Time)
|
||||
}
|
||||
httplib.ServeUserContentByReader(ctx.Req, ctx.Resp, blob.Size(), dataRc, httplib.ServeHeaderOptions{
|
||||
Filename: path.Base(filePath),
|
||||
CacheIsPublic: !repo.IsPrivate && repo.Owner != nil && repo.Owner.Visibility == structs.VisibleTypePublic,
|
||||
CacheIsPublic: !repo.IsPrivate && repo.Owner.Visibility == structs.VisibleTypePublic,
|
||||
CacheDuration: setting.StaticCacheTime,
|
||||
LastModified: *lastModified,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
func ServeContentByReader(ctx *context.Base, filePath string, size int64, reader io.Reader) {
|
||||
httplib.ServeContentByReader(ctx.Req, ctx.Resp, size, reader, &httplib.ServeHeaderOptions{Filename: path.Base(filePath)})
|
||||
}
|
||||
|
||||
func ServeContentByReadSeeker(ctx *context.Base, filePath string, modTime *time.Time, reader io.ReadSeeker) {
|
||||
httplib.ServeContentByReadSeeker(ctx.Req, ctx.Resp, modTime, reader, &httplib.ServeHeaderOptions{Filename: path.Base(filePath)})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user