From 72b6bc8cafe1d64ff30481170cd68b85a710c67e Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Wed, 10 Jul 2024 19:37:16 +0800 Subject: [PATCH 1/3] Refactor webhook (#31587) A more complete fix for #31588 1. Make "generic" code more readable 2. Clarify HTML or Markdown for the payload content --- models/activities/action_test.go | 4 +- models/repo/repo.go | 9 ++- routers/web/repo/repo.go | 2 +- services/convert/repository.go | 2 +- services/webhook/dingtalk.go | 19 +++--- services/webhook/discord.go | 24 +++---- services/webhook/feishu.go | 9 ++- services/webhook/general.go | 32 ++++----- services/webhook/general_test.go | 8 +-- services/webhook/matrix.go | 6 +- services/webhook/msteams.go | 17 +++-- services/webhook/notifier.go | 2 +- services/webhook/packagist.go | 12 ++-- services/webhook/payloader.go | 8 +-- services/webhook/slack.go | 22 +++--- services/webhook/telegram.go | 107 ++++++++++++++---------------- services/webhook/telegram_test.go | 55 +++++++++------ services/webhook/wechatwork.go | 17 +++-- 18 files changed, 173 insertions(+), 182 deletions(-) diff --git a/models/activities/action_test.go b/models/activities/action_test.go index 557415dcda2fb..36a38c7863971 100644 --- a/models/activities/action_test.go +++ b/models/activities/action_test.go @@ -15,6 +15,7 @@ import ( "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/setting" + "code.gitea.io/gitea/modules/test" "github.com/stretchr/testify/assert" ) @@ -33,7 +34,8 @@ func TestAction_GetRepoLink(t *testing.T) { owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) comment := unittest.AssertExistsAndLoadBean(t, &issue_model.Comment{ID: 2}) action := &activities_model.Action{RepoID: repo.ID, CommentID: comment.ID} - setting.AppSubURL = "/suburl" + defer test.MockVariableValue(&setting.AppURL, "https://try.gitea.io/suburl/")() + defer test.MockVariableValue(&setting.AppSubURL, "/suburl")() expected := path.Join(setting.AppSubURL, owner.Name, repo.Name) assert.Equal(t, expected, action.GetRepoLink(db.DefaultContext)) assert.Equal(t, repo.HTMLURL(), action.GetRepoAbsoluteLink(db.DefaultContext)) diff --git a/models/repo/repo.go b/models/repo/repo.go index 189c4aba6cad7..a5b36dd8a17b5 100644 --- a/models/repo/repo.go +++ b/models/repo/repo.go @@ -18,6 +18,7 @@ import ( user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/git" + "code.gitea.io/gitea/modules/httplib" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/markup" "code.gitea.io/gitea/modules/optional" @@ -321,8 +322,12 @@ func (repo *Repository) FullName() string { } // HTMLURL returns the repository HTML URL -func (repo *Repository) HTMLURL() string { - return setting.AppURL + url.PathEscape(repo.OwnerName) + "/" + url.PathEscape(repo.Name) +func (repo *Repository) HTMLURL(ctxs ...context.Context) string { + ctx := context.TODO() + if len(ctxs) > 0 { + ctx = ctxs[0] + } + return httplib.MakeAbsoluteURL(ctx, repo.Link()) } // CommitLink make link to by commit full ID diff --git a/routers/web/repo/repo.go b/routers/web/repo/repo.go index 70dcbae0e17c8..2ef548b5b2492 100644 --- a/routers/web/repo/repo.go +++ b/routers/web/repo/repo.go @@ -668,7 +668,7 @@ func SearchRepo(ctx *context.Context) { Template: repo.IsTemplate, Mirror: repo.IsMirror, Stars: repo.NumStars, - HTMLURL: repo.HTMLURL(), + HTMLURL: repo.HTMLURL(ctx), Link: repo.Link(), Internal: !repo.IsPrivate && repo.Owner.Visibility == api.VisibleTypePrivate, }, diff --git a/services/convert/repository.go b/services/convert/repository.go index d7568e8d088f0..751260a45d3d9 100644 --- a/services/convert/repository.go +++ b/services/convert/repository.go @@ -191,7 +191,7 @@ func innerToRepo(ctx context.Context, repo *repo_model.Repository, permissionInR Fork: repo.IsFork, Parent: parent, Mirror: repo.IsMirror, - HTMLURL: repo.HTMLURL(), + HTMLURL: repo.HTMLURL(ctx), URL: repoAPIURL, SSHURL: cloneLink.SSH, CloneURL: cloneLink.HTTPS, diff --git a/services/webhook/dingtalk.go b/services/webhook/dingtalk.go index f6018f7374cdd..e382f5a9df732 100644 --- a/services/webhook/dingtalk.go +++ b/services/webhook/dingtalk.go @@ -20,8 +20,8 @@ import ( ) type ( - // DingtalkPayload represents - DingtalkPayload dingtalk.Payload + DingtalkPayload dingtalk.Payload + dingtalkConvertor struct{} ) // Create implements PayloadConvertor Create method @@ -92,9 +92,9 @@ func (dc dingtalkConvertor) Push(p *api.PushPayload) (DingtalkPayload, error) { // Issue implements PayloadConvertor Issue method func (dc dingtalkConvertor) Issue(p *api.IssuePayload) (DingtalkPayload, error) { - text, issueTitle, attachmentText, _ := getIssuesPayloadInfo(p, noneLinkFormatter, true) + text, issueTitle, extraMarkdown, _ := getIssuesPayloadInfo(p, noneLinkFormatter, true) - return createDingtalkPayload(issueTitle, text+"\r\n\r\n"+attachmentText, "view issue", p.Issue.HTMLURL), nil + return createDingtalkPayload(issueTitle, text+"\r\n\r\n"+extraMarkdown, "view issue", p.Issue.HTMLURL), nil } // Wiki implements PayloadConvertor Wiki method @@ -114,9 +114,9 @@ func (dc dingtalkConvertor) IssueComment(p *api.IssueCommentPayload) (DingtalkPa // PullRequest implements PayloadConvertor PullRequest method func (dc dingtalkConvertor) PullRequest(p *api.PullRequestPayload) (DingtalkPayload, error) { - text, issueTitle, attachmentText, _ := getPullRequestPayloadInfo(p, noneLinkFormatter, true) + text, issueTitle, extraMarkdown, _ := getPullRequestPayloadInfo(p, noneLinkFormatter, true) - return createDingtalkPayload(issueTitle, text+"\r\n\r\n"+attachmentText, "view pull request", p.PullRequest.HTMLURL), nil + return createDingtalkPayload(issueTitle, text+"\r\n\r\n"+extraMarkdown, "view pull request", p.PullRequest.HTMLURL), nil } // Review implements PayloadConvertor Review method @@ -186,10 +186,7 @@ func createDingtalkPayload(title, text, singleTitle, singleURL string) DingtalkP } } -type dingtalkConvertor struct{} - -var _ payloadConvertor[DingtalkPayload] = dingtalkConvertor{} - func newDingtalkRequest(_ context.Context, w *webhook_model.Webhook, t *webhook_model.HookTask) (*http.Request, []byte, error) { - return newJSONRequest(dingtalkConvertor{}, w, t, true) + var pc payloadConvertor[DingtalkPayload] = dingtalkConvertor{} + return newJSONRequest(pc, w, t, true) } diff --git a/services/webhook/discord.go b/services/webhook/discord.go index 31332396f2cef..f27b39dac3716 100644 --- a/services/webhook/discord.go +++ b/services/webhook/discord.go @@ -100,6 +100,11 @@ var ( redColor = color("ff3232") ) +type discordConvertor struct { + Username string + AvatarURL string +} + // Create implements PayloadConvertor Create method func (d discordConvertor) Create(p *api.CreatePayload) (DiscordPayload, error) { // created tag/branch @@ -162,9 +167,9 @@ func (d discordConvertor) Push(p *api.PushPayload) (DiscordPayload, error) { // Issue implements PayloadConvertor Issue method func (d discordConvertor) Issue(p *api.IssuePayload) (DiscordPayload, error) { - title, _, text, color := getIssuesPayloadInfo(p, noneLinkFormatter, false) + title, _, extraMarkdown, color := getIssuesPayloadInfo(p, noneLinkFormatter, false) - return d.createPayload(p.Sender, title, text, p.Issue.HTMLURL, color), nil + return d.createPayload(p.Sender, title, extraMarkdown, p.Issue.HTMLURL, color), nil } // IssueComment implements PayloadConvertor IssueComment method @@ -176,9 +181,9 @@ func (d discordConvertor) IssueComment(p *api.IssueCommentPayload) (DiscordPaylo // PullRequest implements PayloadConvertor PullRequest method func (d discordConvertor) PullRequest(p *api.PullRequestPayload) (DiscordPayload, error) { - title, _, text, color := getPullRequestPayloadInfo(p, noneLinkFormatter, false) + title, _, extraMarkdown, color := getPullRequestPayloadInfo(p, noneLinkFormatter, false) - return d.createPayload(p.Sender, title, text, p.PullRequest.HTMLURL, color), nil + return d.createPayload(p.Sender, title, extraMarkdown, p.PullRequest.HTMLURL, color), nil } // Review implements PayloadConvertor Review method @@ -253,23 +258,16 @@ func (d discordConvertor) Package(p *api.PackagePayload) (DiscordPayload, error) return d.createPayload(p.Sender, text, "", p.Package.HTMLURL, color), nil } -type discordConvertor struct { - Username string - AvatarURL string -} - -var _ payloadConvertor[DiscordPayload] = discordConvertor{} - func newDiscordRequest(_ context.Context, w *webhook_model.Webhook, t *webhook_model.HookTask) (*http.Request, []byte, error) { meta := &DiscordMeta{} if err := json.Unmarshal([]byte(w.Meta), meta); err != nil { return nil, nil, fmt.Errorf("newDiscordRequest meta json: %w", err) } - sc := discordConvertor{ + var pc payloadConvertor[DiscordPayload] = discordConvertor{ Username: meta.Username, AvatarURL: meta.IconURL, } - return newJSONRequest(sc, w, t, true) + return newJSONRequest(pc, w, t, true) } func parseHookPullRequestEventType(event webhook_module.HookEventType) (string, error) { diff --git a/services/webhook/feishu.go b/services/webhook/feishu.go index 38f324aa7b5a4..7ca7d1cf5f369 100644 --- a/services/webhook/feishu.go +++ b/services/webhook/feishu.go @@ -36,6 +36,8 @@ func newFeishuTextPayload(text string) FeishuPayload { } } +type feishuConvertor struct{} + // Create implements PayloadConvertor Create method func (fc feishuConvertor) Create(p *api.CreatePayload) (FeishuPayload, error) { // created tag/branch @@ -164,10 +166,7 @@ func (fc feishuConvertor) Package(p *api.PackagePayload) (FeishuPayload, error) return newFeishuTextPayload(text), nil } -type feishuConvertor struct{} - -var _ payloadConvertor[FeishuPayload] = feishuConvertor{} - func newFeishuRequest(_ context.Context, w *webhook_model.Webhook, t *webhook_model.HookTask) (*http.Request, []byte, error) { - return newJSONRequest(feishuConvertor{}, w, t, true) + var pc payloadConvertor[FeishuPayload] = feishuConvertor{} + return newJSONRequest(pc, w, t, true) } diff --git a/services/webhook/general.go b/services/webhook/general.go index 69b944f4bd5e6..dde43bb3495c6 100644 --- a/services/webhook/general.go +++ b/services/webhook/general.go @@ -91,12 +91,11 @@ func getIssuesCommentInfo(p *api.IssueCommentPayload) (title, link, by, operator return title, link, by, operator } -func getIssuesPayloadInfo(p *api.IssuePayload, linkFormatter linkFormatter, withSender bool) (string, string, string, int) { - repoLink := linkFormatter(p.Repository.HTMLURL, p.Repository.FullName) - issueTitle := fmt.Sprintf("#%d %s", p.Index, p.Issue.Title) +func getIssuesPayloadInfo(p *api.IssuePayload, linkFormatter linkFormatter, withSender bool) (text, issueTitle, extraMarkdown string, color int) { + color = yellowColor + issueTitle = fmt.Sprintf("#%d %s", p.Index, p.Issue.Title) titleLink := linkFormatter(fmt.Sprintf("%s/issues/%d", p.Repository.HTMLURL, p.Index), issueTitle) - var text string - color := yellowColor + repoLink := linkFormatter(p.Repository.HTMLURL, p.Repository.FullName) switch p.Action { case api.HookIssueOpened: @@ -135,26 +134,23 @@ func getIssuesPayloadInfo(p *api.IssuePayload, linkFormatter linkFormatter, with text += fmt.Sprintf(" by %s", linkFormatter(setting.AppURL+url.PathEscape(p.Sender.UserName), p.Sender.UserName)) } - var attachmentText string if p.Action == api.HookIssueOpened || p.Action == api.HookIssueEdited { - attachmentText = p.Issue.Body + extraMarkdown = p.Issue.Body } - return text, issueTitle, attachmentText, color + return text, issueTitle, extraMarkdown, color } -func getPullRequestPayloadInfo(p *api.PullRequestPayload, linkFormatter linkFormatter, withSender bool) (string, string, string, int) { - repoLink := linkFormatter(p.Repository.HTMLURL, p.Repository.FullName) - issueTitle := fmt.Sprintf("#%d %s", p.Index, p.PullRequest.Title) +func getPullRequestPayloadInfo(p *api.PullRequestPayload, linkFormatter linkFormatter, withSender bool) (text, issueTitle, extraMarkdown string, color int) { + color = yellowColor + issueTitle = fmt.Sprintf("#%d %s", p.Index, p.PullRequest.Title) titleLink := linkFormatter(p.PullRequest.URL, issueTitle) - var text string - var attachmentText string - color := yellowColor + repoLink := linkFormatter(p.Repository.HTMLURL, p.Repository.FullName) switch p.Action { case api.HookIssueOpened: text = fmt.Sprintf("[%s] Pull request opened: %s", repoLink, titleLink) - attachmentText = p.PullRequest.Body + extraMarkdown = p.PullRequest.Body color = greenColor case api.HookIssueClosed: if p.PullRequest.HasMerged { @@ -168,7 +164,7 @@ func getPullRequestPayloadInfo(p *api.PullRequestPayload, linkFormatter linkForm text = fmt.Sprintf("[%s] Pull request re-opened: %s", repoLink, titleLink) case api.HookIssueEdited: text = fmt.Sprintf("[%s] Pull request edited: %s", repoLink, titleLink) - attachmentText = p.PullRequest.Body + extraMarkdown = p.PullRequest.Body case api.HookIssueAssigned: list := make([]string, len(p.PullRequest.Assignees)) for i, user := range p.PullRequest.Assignees { @@ -193,7 +189,7 @@ func getPullRequestPayloadInfo(p *api.PullRequestPayload, linkFormatter linkForm text = fmt.Sprintf("[%s] Pull request milestone cleared: %s", repoLink, titleLink) case api.HookIssueReviewed: text = fmt.Sprintf("[%s] Pull request reviewed: %s", repoLink, titleLink) - attachmentText = p.Review.Content + extraMarkdown = p.Review.Content case api.HookIssueReviewRequested: text = fmt.Sprintf("[%s] Pull request review requested: %s", repoLink, titleLink) case api.HookIssueReviewRequestRemoved: @@ -203,7 +199,7 @@ func getPullRequestPayloadInfo(p *api.PullRequestPayload, linkFormatter linkForm text += fmt.Sprintf(" by %s", linkFormatter(setting.AppURL+p.Sender.UserName, p.Sender.UserName)) } - return text, issueTitle, attachmentText, color + return text, issueTitle, extraMarkdown, color } func getReleasePayloadInfo(p *api.ReleasePayload, linkFormatter linkFormatter, withSender bool) (text string, color int) { diff --git a/services/webhook/general_test.go b/services/webhook/general_test.go index 41bac3fd04d23..fc6e7140e7be0 100644 --- a/services/webhook/general_test.go +++ b/services/webhook/general_test.go @@ -424,10 +424,10 @@ func TestGetIssuesPayloadInfo(t *testing.T) { for i, c := range cases { p.Action = c.action - text, issueTitle, attachmentText, color := getIssuesPayloadInfo(p, noneLinkFormatter, true) + text, issueTitle, extraMarkdown, color := getIssuesPayloadInfo(p, noneLinkFormatter, true) assert.Equal(t, c.text, text, "case %d", i) assert.Equal(t, c.issueTitle, issueTitle, "case %d", i) - assert.Equal(t, c.attachmentText, attachmentText, "case %d", i) + assert.Equal(t, c.attachmentText, extraMarkdown, "case %d", i) assert.Equal(t, c.color, color, "case %d", i) } } @@ -523,10 +523,10 @@ func TestGetPullRequestPayloadInfo(t *testing.T) { for i, c := range cases { p.Action = c.action - text, issueTitle, attachmentText, color := getPullRequestPayloadInfo(p, noneLinkFormatter, true) + text, issueTitle, extraMarkdown, color := getPullRequestPayloadInfo(p, noneLinkFormatter, true) assert.Equal(t, c.text, text, "case %d", i) assert.Equal(t, c.issueTitle, issueTitle, "case %d", i) - assert.Equal(t, c.attachmentText, attachmentText, "case %d", i) + assert.Equal(t, c.attachmentText, extraMarkdown, "case %d", i) assert.Equal(t, c.color, color, "case %d", i) } } diff --git a/services/webhook/matrix.go b/services/webhook/matrix.go index e649a0760943a..5e9f808d8b6cb 100644 --- a/services/webhook/matrix.go +++ b/services/webhook/matrix.go @@ -29,10 +29,10 @@ func newMatrixRequest(_ context.Context, w *webhook_model.Webhook, t *webhook_mo if err := json.Unmarshal([]byte(w.Meta), meta); err != nil { return nil, nil, fmt.Errorf("GetMatrixPayload meta json: %w", err) } - mc := matrixConvertor{ + var pc payloadConvertor[MatrixPayload] = matrixConvertor{ MsgType: messageTypeText[meta.MessageType], } - payload, err := newPayload(mc, []byte(t.PayloadContent), t.EventType) + payload, err := newPayload(pc, []byte(t.PayloadContent), t.EventType) if err != nil { return nil, nil, err } @@ -87,8 +87,6 @@ type MatrixPayload struct { Commits []*api.PayloadCommit `json:"io.gitea.commits,omitempty"` } -var _ payloadConvertor[MatrixPayload] = matrixConvertor{} - type matrixConvertor struct { MsgType string } diff --git a/services/webhook/msteams.go b/services/webhook/msteams.go index b052b9da100ed..7ef96ffa2734c 100644 --- a/services/webhook/msteams.go +++ b/services/webhook/msteams.go @@ -58,6 +58,8 @@ type ( } ) +type msteamsConvertor struct{} + // Create implements PayloadConvertor Create method func (m msteamsConvertor) Create(p *api.CreatePayload) (MSTeamsPayload, error) { // created tag/branch @@ -152,13 +154,13 @@ func (m msteamsConvertor) Push(p *api.PushPayload) (MSTeamsPayload, error) { // Issue implements PayloadConvertor Issue method func (m msteamsConvertor) Issue(p *api.IssuePayload) (MSTeamsPayload, error) { - title, _, attachmentText, color := getIssuesPayloadInfo(p, noneLinkFormatter, false) + title, _, extraMarkdown, color := getIssuesPayloadInfo(p, noneLinkFormatter, false) return createMSTeamsPayload( p.Repository, p.Sender, title, - attachmentText, + extraMarkdown, p.Issue.HTMLURL, color, &MSTeamsFact{"Issue #:", fmt.Sprintf("%d", p.Issue.ID)}, @@ -182,13 +184,13 @@ func (m msteamsConvertor) IssueComment(p *api.IssueCommentPayload) (MSTeamsPaylo // PullRequest implements PayloadConvertor PullRequest method func (m msteamsConvertor) PullRequest(p *api.PullRequestPayload) (MSTeamsPayload, error) { - title, _, attachmentText, color := getPullRequestPayloadInfo(p, noneLinkFormatter, false) + title, _, extraMarkdown, color := getPullRequestPayloadInfo(p, noneLinkFormatter, false) return createMSTeamsPayload( p.Repository, p.Sender, title, - attachmentText, + extraMarkdown, p.PullRequest.HTMLURL, color, &MSTeamsFact{"Pull request #:", fmt.Sprintf("%d", p.PullRequest.ID)}, @@ -343,10 +345,7 @@ func createMSTeamsPayload(r *api.Repository, s *api.User, title, text, actionTar } } -type msteamsConvertor struct{} - -var _ payloadConvertor[MSTeamsPayload] = msteamsConvertor{} - func newMSTeamsRequest(_ context.Context, w *webhook_model.Webhook, t *webhook_model.HookTask) (*http.Request, []byte, error) { - return newJSONRequest(msteamsConvertor{}, w, t, true) + var pc payloadConvertor[MSTeamsPayload] = msteamsConvertor{} + return newJSONRequest(pc, w, t, true) } diff --git a/services/webhook/notifier.go b/services/webhook/notifier.go index 587caf62ff305..53b1cc8c9cf72 100644 --- a/services/webhook/notifier.go +++ b/services/webhook/notifier.go @@ -23,7 +23,7 @@ import ( ) func init() { - notify_service.RegisterNotifier(&webhookNotifier{}) + notify_service.RegisterNotifier(NewNotifier()) } type webhookNotifier struct { diff --git a/services/webhook/packagist.go b/services/webhook/packagist.go index 593b97a174105..4d809ab3a6a5f 100644 --- a/services/webhook/packagist.go +++ b/services/webhook/packagist.go @@ -40,6 +40,10 @@ func GetPackagistHook(w *webhook_model.Webhook) *PackagistMeta { return s } +type packagistConvertor struct { + PackageURL string +} + // Create implements PayloadConvertor Create method func (pc packagistConvertor) Create(_ *api.CreatePayload) (PackagistPayload, error) { return PackagistPayload{}, nil @@ -106,18 +110,12 @@ func (pc packagistConvertor) Package(_ *api.PackagePayload) (PackagistPayload, e return PackagistPayload{}, nil } -type packagistConvertor struct { - PackageURL string -} - -var _ payloadConvertor[PackagistPayload] = packagistConvertor{} - func newPackagistRequest(_ context.Context, w *webhook_model.Webhook, t *webhook_model.HookTask) (*http.Request, []byte, error) { meta := &PackagistMeta{} if err := json.Unmarshal([]byte(w.Meta), meta); err != nil { return nil, nil, fmt.Errorf("newpackagistRequest meta json: %w", err) } - pc := packagistConvertor{ + var pc payloadConvertor[PackagistPayload] = packagistConvertor{ PackageURL: meta.PackageURL, } return newJSONRequest(pc, w, t, true) diff --git a/services/webhook/payloader.go b/services/webhook/payloader.go index 54a11a58682d2..ab280a25b661e 100644 --- a/services/webhook/payloader.go +++ b/services/webhook/payloader.go @@ -30,16 +30,15 @@ type payloadConvertor[T any] interface { Package(*api.PackagePayload) (T, error) } -func convertUnmarshalledJSON[T, P any](convert func(P) (T, error), data []byte) (T, error) { +func convertUnmarshalledJSON[T, P any](convert func(P) (T, error), data []byte) (t T, err error) { var p P - if err := json.Unmarshal(data, &p); err != nil { - var t T + if err = json.Unmarshal(data, &p); err != nil { return t, fmt.Errorf("could not unmarshal payload: %w", err) } return convert(p) } -func newPayload[T any](rc payloadConvertor[T], data []byte, event webhook_module.HookEventType) (T, error) { +func newPayload[T any](rc payloadConvertor[T], data []byte, event webhook_module.HookEventType) (t T, err error) { switch event { case webhook_module.HookEventCreate: return convertUnmarshalledJSON(rc.Create, data) @@ -79,7 +78,6 @@ func newPayload[T any](rc payloadConvertor[T], data []byte, event webhook_module case webhook_module.HookEventPackage: return convertUnmarshalledJSON(rc.Package, data) } - var t T return t, fmt.Errorf("newPayload unsupported event: %s", event) } diff --git a/services/webhook/slack.go b/services/webhook/slack.go index ffa2936bea74c..c905e7a89f48f 100644 --- a/services/webhook/slack.go +++ b/services/webhook/slack.go @@ -118,17 +118,17 @@ func (s slackConvertor) Fork(p *api.ForkPayload) (SlackPayload, error) { // Issue implements payloadConvertor Issue method func (s slackConvertor) Issue(p *api.IssuePayload) (SlackPayload, error) { - text, issueTitle, attachmentText, color := getIssuesPayloadInfo(p, SlackLinkFormatter, true) + text, issueTitle, extraMarkdown, color := getIssuesPayloadInfo(p, SlackLinkFormatter, true) var attachments []SlackAttachment - if attachmentText != "" { - attachmentText = SlackTextFormatter(attachmentText) + if extraMarkdown != "" { + extraMarkdown = SlackTextFormatter(extraMarkdown) issueTitle = SlackTextFormatter(issueTitle) attachments = append(attachments, SlackAttachment{ Color: fmt.Sprintf("%x", color), Title: issueTitle, TitleLink: p.Issue.HTMLURL, - Text: attachmentText, + Text: extraMarkdown, }) } @@ -210,17 +210,17 @@ func (s slackConvertor) Push(p *api.PushPayload) (SlackPayload, error) { // PullRequest implements payloadConvertor PullRequest method func (s slackConvertor) PullRequest(p *api.PullRequestPayload) (SlackPayload, error) { - text, issueTitle, attachmentText, color := getPullRequestPayloadInfo(p, SlackLinkFormatter, true) + text, issueTitle, extraMarkdown, color := getPullRequestPayloadInfo(p, SlackLinkFormatter, true) var attachments []SlackAttachment - if attachmentText != "" { - attachmentText = SlackTextFormatter(p.PullRequest.Body) + if extraMarkdown != "" { + extraMarkdown = SlackTextFormatter(p.PullRequest.Body) issueTitle = SlackTextFormatter(issueTitle) attachments = append(attachments, SlackAttachment{ Color: fmt.Sprintf("%x", color), Title: issueTitle, TitleLink: p.PullRequest.HTMLURL, - Text: attachmentText, + Text: extraMarkdown, }) } @@ -281,20 +281,18 @@ type slackConvertor struct { Color string } -var _ payloadConvertor[SlackPayload] = slackConvertor{} - func newSlackRequest(_ context.Context, w *webhook_model.Webhook, t *webhook_model.HookTask) (*http.Request, []byte, error) { meta := &SlackMeta{} if err := json.Unmarshal([]byte(w.Meta), meta); err != nil { return nil, nil, fmt.Errorf("newSlackRequest meta json: %w", err) } - sc := slackConvertor{ + var pc payloadConvertor[SlackPayload] = slackConvertor{ Channel: meta.Channel, Username: meta.Username, IconURL: meta.IconURL, Color: meta.Color, } - return newJSONRequest(sc, w, t, true) + return newJSONRequest(pc, w, t, true) } var slackChannel = regexp.MustCompile(`^#?[a-z0-9_-]{1,80}$`) diff --git a/services/webhook/telegram.go b/services/webhook/telegram.go index de6c878dad64d..e54d6f2947d21 100644 --- a/services/webhook/telegram.go +++ b/services/webhook/telegram.go @@ -6,6 +6,7 @@ package webhook import ( "context" "fmt" + "html" "net/http" "strings" @@ -13,7 +14,9 @@ import ( "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/json" "code.gitea.io/gitea/modules/log" + "code.gitea.io/gitea/modules/markup" api "code.gitea.io/gitea/modules/structs" + "code.gitea.io/gitea/modules/util" webhook_module "code.gitea.io/gitea/modules/webhook" ) @@ -42,41 +45,43 @@ func GetTelegramHook(w *webhook_model.Webhook) *TelegramMeta { return s } +type telegramConvertor struct{} + // Create implements PayloadConvertor Create method func (t telegramConvertor) Create(p *api.CreatePayload) (TelegramPayload, error) { // created tag/branch refName := git.RefName(p.Ref).ShortName() - title := fmt.Sprintf(`[%s] %s %s created`, p.Repo.HTMLURL, p.Repo.FullName, p.RefType, - p.Repo.HTMLURL+"/src/"+refName, refName) + title := fmt.Sprintf(`[%s] %s %s created`, + htmlLinkFormatter(p.Repo.HTMLURL, p.Repo.FullName), + html.EscapeString(p.RefType), + htmlLinkFormatter(p.Repo.HTMLURL+"/src/"+util.PathEscapeSegments(refName), refName), + ) - return createTelegramPayload(title), nil + return createTelegramPayloadHTML(title), nil } // Delete implements PayloadConvertor Delete method func (t telegramConvertor) Delete(p *api.DeletePayload) (TelegramPayload, error) { // created tag/branch refName := git.RefName(p.Ref).ShortName() - title := fmt.Sprintf(`[%s] %s %s deleted`, p.Repo.HTMLURL, p.Repo.FullName, p.RefType, - p.Repo.HTMLURL+"/src/"+refName, refName) - - return createTelegramPayload(title), nil + title := fmt.Sprintf(`[%s] %s %s deleted`, + htmlLinkFormatter(p.Repo.HTMLURL, p.Repo.FullName), + html.EscapeString(p.RefType), + htmlLinkFormatter(p.Repo.HTMLURL+"/src/"+util.PathEscapeSegments(refName), refName), + ) + return createTelegramPayloadHTML(title), nil } // Fork implements PayloadConvertor Fork method func (t telegramConvertor) Fork(p *api.ForkPayload) (TelegramPayload, error) { - title := fmt.Sprintf(`%s is forked to %s`, p.Forkee.FullName, p.Repo.HTMLURL, p.Repo.FullName) - - return createTelegramPayload(title), nil + title := fmt.Sprintf(`%s is forked to %s`, html.EscapeString(p.Forkee.FullName), htmlLinkFormatter(p.Repo.HTMLURL, p.Repo.FullName)) + return createTelegramPayloadHTML(title), nil } // Push implements PayloadConvertor Push method func (t telegramConvertor) Push(p *api.PushPayload) (TelegramPayload, error) { - var ( - branchName = git.RefName(p.Ref).ShortName() - commitDesc string - ) - - var titleLink string + branchName := git.RefName(p.Ref).ShortName() + var titleLink, commitDesc string if p.TotalCommits == 1 { commitDesc = "1 new commit" titleLink = p.Commits[0].URL @@ -85,52 +90,42 @@ func (t telegramConvertor) Push(p *api.PushPayload) (TelegramPayload, error) { titleLink = p.CompareURL } if titleLink == "" { - titleLink = p.Repo.HTMLURL + "/src/" + branchName + titleLink = p.Repo.HTMLURL + "/src/" + util.PathEscapeSegments(branchName) } - title := fmt.Sprintf(`[%s:%s] %s`, p.Repo.HTMLURL, p.Repo.FullName, titleLink, branchName, commitDesc) + title := fmt.Sprintf(`[%s:%s] %s`, htmlLinkFormatter(p.Repo.HTMLURL, p.Repo.FullName), htmlLinkFormatter(titleLink, branchName), html.EscapeString(commitDesc)) - var text string - // for each commit, generate attachment text - for i, commit := range p.Commits { - var authorName string + var htmlCommits string + for _, commit := range p.Commits { + htmlCommits += fmt.Sprintf("\n[%s] %s", htmlLinkFormatter(commit.URL, commit.ID[:7]), html.EscapeString(strings.TrimRight(commit.Message, "\r\n"))) if commit.Author != nil { - authorName = " - " + commit.Author.Name - } - text += fmt.Sprintf(`[%s] %s`, commit.URL, commit.ID[:7], - strings.TrimRight(commit.Message, "\r\n")) + authorName - // add linebreak to each commit but the last - if i < len(p.Commits)-1 { - text += "\n" + htmlCommits += " - " + html.EscapeString(commit.Author.Name) } } - - return createTelegramPayload(title + "\n" + text), nil + return createTelegramPayloadHTML(title + htmlCommits), nil } // Issue implements PayloadConvertor Issue method func (t telegramConvertor) Issue(p *api.IssuePayload) (TelegramPayload, error) { - text, _, attachmentText, _ := getIssuesPayloadInfo(p, htmlLinkFormatter, true) - - return createTelegramPayload(text + "\n\n" + attachmentText), nil + text, _, extraMarkdown, _ := getIssuesPayloadInfo(p, htmlLinkFormatter, true) + // TODO: at the moment the markdown can't be rendered easily because it has context-aware links (eg: attachments) + return createTelegramPayloadHTML(text + "\n\n" + html.EscapeString(extraMarkdown)), nil } // IssueComment implements PayloadConvertor IssueComment method func (t telegramConvertor) IssueComment(p *api.IssueCommentPayload) (TelegramPayload, error) { text, _, _ := getIssueCommentPayloadInfo(p, htmlLinkFormatter, true) - - return createTelegramPayload(text + "\n" + p.Comment.Body), nil + return createTelegramPayloadHTML(text + "\n" + html.EscapeString(p.Comment.Body)), nil } // PullRequest implements PayloadConvertor PullRequest method func (t telegramConvertor) PullRequest(p *api.PullRequestPayload) (TelegramPayload, error) { - text, _, attachmentText, _ := getPullRequestPayloadInfo(p, htmlLinkFormatter, true) - - return createTelegramPayload(text + "\n" + attachmentText), nil + text, _, extraMarkdown, _ := getPullRequestPayloadInfo(p, htmlLinkFormatter, true) + return createTelegramPayloadHTML(text + "\n" + html.EscapeString(extraMarkdown)), nil } // Review implements PayloadConvertor Review method func (t telegramConvertor) Review(p *api.PullRequestPayload, event webhook_module.HookEventType) (TelegramPayload, error) { - var text, attachmentText string + var text, extraMarkdown string switch p.Action { case api.HookIssueReviewed: action, err := parseHookPullRequestEventType(event) @@ -138,11 +133,11 @@ func (t telegramConvertor) Review(p *api.PullRequestPayload, event webhook_modul return TelegramPayload{}, err } - text = fmt.Sprintf("[%s] Pull request review %s: #%d %s", p.Repository.FullName, action, p.Index, p.PullRequest.Title) - attachmentText = p.Review.Content + text = fmt.Sprintf("[%s] Pull request review %s: #%d %s", html.EscapeString(p.Repository.FullName), html.EscapeString(action), p.Index, html.EscapeString(p.PullRequest.Title)) + extraMarkdown = p.Review.Content } - return createTelegramPayload(text + "\n" + attachmentText), nil + return createTelegramPayloadHTML(text + "\n" + html.EscapeString(extraMarkdown)), nil } // Repository implements PayloadConvertor Repository method @@ -150,11 +145,11 @@ func (t telegramConvertor) Repository(p *api.RepositoryPayload) (TelegramPayload var title string switch p.Action { case api.HookRepoCreated: - title = fmt.Sprintf(`[%s] Repository created`, p.Repository.HTMLURL, p.Repository.FullName) - return createTelegramPayload(title), nil + title = fmt.Sprintf(`[%s] Repository created`, htmlLinkFormatter(p.Repository.HTMLURL, p.Repository.FullName)) + return createTelegramPayloadHTML(title), nil case api.HookRepoDeleted: - title = fmt.Sprintf("[%s] Repository deleted", p.Repository.FullName) - return createTelegramPayload(title), nil + title = fmt.Sprintf("[%s] Repository deleted", html.EscapeString(p.Repository.FullName)) + return createTelegramPayloadHTML(title), nil } return TelegramPayload{}, nil } @@ -163,34 +158,32 @@ func (t telegramConvertor) Repository(p *api.RepositoryPayload) (TelegramPayload func (t telegramConvertor) Wiki(p *api.WikiPayload) (TelegramPayload, error) { text, _, _ := getWikiPayloadInfo(p, htmlLinkFormatter, true) - return createTelegramPayload(text), nil + return createTelegramPayloadHTML(text), nil } // Release implements PayloadConvertor Release method func (t telegramConvertor) Release(p *api.ReleasePayload) (TelegramPayload, error) { text, _ := getReleasePayloadInfo(p, htmlLinkFormatter, true) - return createTelegramPayload(text), nil + return createTelegramPayloadHTML(text), nil } func (t telegramConvertor) Package(p *api.PackagePayload) (TelegramPayload, error) { text, _ := getPackagePayloadInfo(p, htmlLinkFormatter, true) - return createTelegramPayload(text), nil + return createTelegramPayloadHTML(text), nil } -func createTelegramPayload(message string) TelegramPayload { +func createTelegramPayloadHTML(msgHTML string) TelegramPayload { + // https://core.telegram.org/bots/api#formatting-options return TelegramPayload{ - Message: strings.TrimSpace(message), + Message: strings.TrimSpace(markup.Sanitize(msgHTML)), ParseMode: "HTML", DisableWebPreview: true, } } -type telegramConvertor struct{} - -var _ payloadConvertor[TelegramPayload] = telegramConvertor{} - func newTelegramRequest(_ context.Context, w *webhook_model.Webhook, t *webhook_model.HookTask) (*http.Request, []byte, error) { - return newJSONRequest(telegramConvertor{}, w, t, true) + var pc payloadConvertor[TelegramPayload] = telegramConvertor{} + return newJSONRequest(pc, w, t, true) } diff --git a/services/webhook/telegram_test.go b/services/webhook/telegram_test.go index 2fe5161b22879..7ba81f1564771 100644 --- a/services/webhook/telegram_test.go +++ b/services/webhook/telegram_test.go @@ -20,11 +20,12 @@ func TestTelegramPayload(t *testing.T) { tc := telegramConvertor{} t.Run("Correct webhook params", func(t *testing.T) { - p := createTelegramPayload("testMsg ") - - assert.Equal(t, "HTML", p.ParseMode) - assert.Equal(t, true, p.DisableWebPreview) - assert.Equal(t, "testMsg", p.Message) + p := createTelegramPayloadHTML(`testMsg `) + assert.Equal(t, TelegramPayload{ + Message: `testMsg`, + ParseMode: "HTML", + DisableWebPreview: true, + }, p) }) t.Run("Create", func(t *testing.T) { @@ -33,7 +34,7 @@ func TestTelegramPayload(t *testing.T) { pl, err := tc.Create(p) require.NoError(t, err) - assert.Equal(t, `[test/repo] branch test created`, pl.Message) + assert.Equal(t, `[test/repo] branch test created`, pl.Message) }) t.Run("Delete", func(t *testing.T) { @@ -42,7 +43,7 @@ func TestTelegramPayload(t *testing.T) { pl, err := tc.Delete(p) require.NoError(t, err) - assert.Equal(t, `[test/repo] branch test deleted`, pl.Message) + assert.Equal(t, `[test/repo] branch test deleted`, pl.Message) }) t.Run("Fork", func(t *testing.T) { @@ -51,7 +52,7 @@ func TestTelegramPayload(t *testing.T) { pl, err := tc.Fork(p) require.NoError(t, err) - assert.Equal(t, `test/repo2 is forked to test/repo`, pl.Message) + assert.Equal(t, `test/repo2 is forked to test/repo`, pl.Message) }) t.Run("Push", func(t *testing.T) { @@ -60,7 +61,9 @@ func TestTelegramPayload(t *testing.T) { pl, err := tc.Push(p) require.NoError(t, err) - assert.Equal(t, "[test/repo:test] 2 new commits\n[2020558] commit message - user1\n[2020558] commit message - user1", pl.Message) + assert.Equal(t, `[test/repo:test] 2 new commits +[2020558] commit message - user1 +[2020558] commit message - user1`, pl.Message) }) t.Run("Issue", func(t *testing.T) { @@ -70,13 +73,15 @@ func TestTelegramPayload(t *testing.T) { pl, err := tc.Issue(p) require.NoError(t, err) - assert.Equal(t, "[test/repo] Issue opened: #2 crash by user1\n\nissue body", pl.Message) + assert.Equal(t, `[test/repo] Issue opened: #2 crash by user1 + +issue body`, pl.Message) p.Action = api.HookIssueClosed pl, err = tc.Issue(p) require.NoError(t, err) - assert.Equal(t, `[test/repo] Issue closed: #2 crash by user1`, pl.Message) + assert.Equal(t, `[test/repo] Issue closed: #2 crash by user1`, pl.Message) }) t.Run("IssueComment", func(t *testing.T) { @@ -85,7 +90,8 @@ func TestTelegramPayload(t *testing.T) { pl, err := tc.IssueComment(p) require.NoError(t, err) - assert.Equal(t, "[test/repo] New comment on issue #2 crash by user1\nmore info needed", pl.Message) + assert.Equal(t, `[test/repo] New comment on issue #2 crash by user1 +more info needed`, pl.Message) }) t.Run("PullRequest", func(t *testing.T) { @@ -94,7 +100,8 @@ func TestTelegramPayload(t *testing.T) { pl, err := tc.PullRequest(p) require.NoError(t, err) - assert.Equal(t, "[test/repo] Pull request opened: #12 Fix bug by user1\nfixes bug #2", pl.Message) + assert.Equal(t, `[test/repo] Pull request opened: #12 Fix bug by user1 +fixes bug #2`, pl.Message) }) t.Run("PullRequestComment", func(t *testing.T) { @@ -103,7 +110,8 @@ func TestTelegramPayload(t *testing.T) { pl, err := tc.IssueComment(p) require.NoError(t, err) - assert.Equal(t, "[test/repo] New comment on pull request #12 Fix bug by user1\nchanges requested", pl.Message) + assert.Equal(t, `[test/repo] New comment on pull request #12 Fix bug by user1 +changes requested`, pl.Message) }) t.Run("Review", func(t *testing.T) { @@ -113,7 +121,8 @@ func TestTelegramPayload(t *testing.T) { pl, err := tc.Review(p, webhook_module.HookEventPullRequestReviewApproved) require.NoError(t, err) - assert.Equal(t, "[test/repo] Pull request review approved: #12 Fix bug\ngood job", pl.Message) + assert.Equal(t, `[test/repo] Pull request review approved: #12 Fix bug +good job`, pl.Message) }) t.Run("Repository", func(t *testing.T) { @@ -122,7 +131,7 @@ func TestTelegramPayload(t *testing.T) { pl, err := tc.Repository(p) require.NoError(t, err) - assert.Equal(t, `[test/repo] Repository created`, pl.Message) + assert.Equal(t, `[test/repo] Repository created`, pl.Message) }) t.Run("Package", func(t *testing.T) { @@ -131,7 +140,7 @@ func TestTelegramPayload(t *testing.T) { pl, err := tc.Package(p) require.NoError(t, err) - assert.Equal(t, `Package created: GiteaContainer:latest by user1`, pl.Message) + assert.Equal(t, `Package created: GiteaContainer:latest by user1`, pl.Message) }) t.Run("Wiki", func(t *testing.T) { @@ -141,19 +150,19 @@ func TestTelegramPayload(t *testing.T) { pl, err := tc.Wiki(p) require.NoError(t, err) - assert.Equal(t, `[test/repo] New wiki page 'index' (Wiki change comment) by user1`, pl.Message) + assert.Equal(t, `[test/repo] New wiki page 'index' (Wiki change comment) by user1`, pl.Message) p.Action = api.HookWikiEdited pl, err = tc.Wiki(p) require.NoError(t, err) - assert.Equal(t, `[test/repo] Wiki page 'index' edited (Wiki change comment) by user1`, pl.Message) + assert.Equal(t, `[test/repo] Wiki page 'index' edited (Wiki change comment) by user1`, pl.Message) p.Action = api.HookWikiDeleted pl, err = tc.Wiki(p) require.NoError(t, err) - assert.Equal(t, `[test/repo] Wiki page 'index' deleted by user1`, pl.Message) + assert.Equal(t, `[test/repo] Wiki page 'index' deleted by user1`, pl.Message) }) t.Run("Release", func(t *testing.T) { @@ -162,7 +171,7 @@ func TestTelegramPayload(t *testing.T) { pl, err := tc.Release(p) require.NoError(t, err) - assert.Equal(t, `[test/repo] Release created: v1.0 by user1`, pl.Message) + assert.Equal(t, `[test/repo] Release created: v1.0 by user1`, pl.Message) }) } @@ -198,5 +207,7 @@ func TestTelegramJSONPayload(t *testing.T) { var body TelegramPayload err = json.NewDecoder(req.Body).Decode(&body) assert.NoError(t, err) - assert.Equal(t, "[test/repo:test] 2 new commits\n[2020558] commit message - user1\n[2020558] commit message - user1", body.Message) + assert.Equal(t, `[test/repo:test] 2 new commits +[2020558] commit message - user1 +[2020558] commit message - user1`, body.Message) } diff --git a/services/webhook/wechatwork.go b/services/webhook/wechatwork.go index 2e9d31cb7cef1..1d8c1d7dacd83 100644 --- a/services/webhook/wechatwork.go +++ b/services/webhook/wechatwork.go @@ -41,6 +41,8 @@ func newWechatworkMarkdownPayload(title string) WechatworkPayload { } } +type wechatworkConvertor struct{} + // Create implements PayloadConvertor Create method func (wc wechatworkConvertor) Create(p *api.CreatePayload) (WechatworkPayload, error) { // created tag/branch @@ -97,9 +99,9 @@ func (wc wechatworkConvertor) Push(p *api.PushPayload) (WechatworkPayload, error // Issue implements PayloadConvertor Issue method func (wc wechatworkConvertor) Issue(p *api.IssuePayload) (WechatworkPayload, error) { - text, issueTitle, attachmentText, _ := getIssuesPayloadInfo(p, noneLinkFormatter, true) + text, issueTitle, extraMarkdown, _ := getIssuesPayloadInfo(p, noneLinkFormatter, true) var content string - content += fmt.Sprintf(" >%s\n >%s \n > %s \n [%s](%s)", text, attachmentText, issueTitle, p.Issue.HTMLURL, p.Issue.HTMLURL) + content += fmt.Sprintf(" >%s\n >%s \n > %s \n [%s](%s)", text, extraMarkdown, issueTitle, p.Issue.HTMLURL, p.Issue.HTMLURL) return newWechatworkMarkdownPayload(content), nil } @@ -115,9 +117,9 @@ func (wc wechatworkConvertor) IssueComment(p *api.IssueCommentPayload) (Wechatwo // PullRequest implements PayloadConvertor PullRequest method func (wc wechatworkConvertor) PullRequest(p *api.PullRequestPayload) (WechatworkPayload, error) { - text, issueTitle, attachmentText, _ := getPullRequestPayloadInfo(p, noneLinkFormatter, true) + text, issueTitle, extraMarkdown, _ := getPullRequestPayloadInfo(p, noneLinkFormatter, true) pr := fmt.Sprintf("> %s \r\n > %s \r\n > %s \r\n", - text, issueTitle, attachmentText) + text, issueTitle, extraMarkdown) return newWechatworkMarkdownPayload(pr), nil } @@ -173,10 +175,7 @@ func (wc wechatworkConvertor) Package(p *api.PackagePayload) (WechatworkPayload, return newWechatworkMarkdownPayload(text), nil } -type wechatworkConvertor struct{} - -var _ payloadConvertor[WechatworkPayload] = wechatworkConvertor{} - func newWechatworkRequest(_ context.Context, w *webhook_model.Webhook, t *webhook_model.HookTask) (*http.Request, []byte, error) { - return newJSONRequest(wechatworkConvertor{}, w, t, true) + var pc payloadConvertor[WechatworkPayload] = wechatworkConvertor{} + return newJSONRequest(pc, w, t, true) } From 436af472a9ea3e619e4362d261d2d6d3c85cea01 Mon Sep 17 00:00:00 2001 From: Lunny Xiao Date: Wed, 10 Jul 2024 23:47:32 +0800 Subject: [PATCH 2/3] Fix wrong merge on removing docs (#31605) --- .../config-cheat-sheet.en-us.md | 1475 ----------------- 1 file changed, 1475 deletions(-) delete mode 100644 docs/content/administration/config-cheat-sheet.en-us.md diff --git a/docs/content/administration/config-cheat-sheet.en-us.md b/docs/content/administration/config-cheat-sheet.en-us.md deleted file mode 100644 index b38e53d4ab213..0000000000000 --- a/docs/content/administration/config-cheat-sheet.en-us.md +++ /dev/null @@ -1,1475 +0,0 @@ ---- -date: "2016-12-26T16:00:00+02:00" -title: "Config Cheat Sheet" -slug: "config-cheat-sheet" -sidebar_position: 30 -toc: false -draft: false -aliases: - - /en-us/config-cheat-sheet -menu: - sidebar: - parent: "administration" - name: "Config Cheat Sheet" - sidebar_position: 30 - identifier: "config-cheat-sheet" ---- - -# Configuration Cheat Sheet - -This is a cheat sheet for the Gitea configuration file. It contains most of the settings -that can be configured as well as their default values. - -Any changes to the Gitea configuration file should be made in `custom/conf/app.ini` -or any corresponding location. When installing from a distribution, this will -typically be found at `/etc/gitea/conf/app.ini`. - -The defaults provided here are best-effort (not built automatically). They are -accurately recorded in [app.example.ini](https://github.com/go-gitea/gitea/blob/main/custom/conf/app.example.ini) -(s/main/\). Any string in the format `%(X)s` is a feature powered -by [ini](https://github.com/go-ini/ini/#recursive-values), for reading values recursively. - -In the default values below, a value in the form `$XYZ` refers to an environment variable. (However, see `environment-to-ini`.) Values in the form _`XxYyZz`_ refer to values listed as part of the default configuration. These notation forms will not work in your own `app.ini` file and are only listed here as documentation. - -Values containing `#` or `;` must be quoted using `` ` `` or `"""`. - -**Note:** A full restart is required for Gitea configuration changes to take effect. - -## Default Configuration (non-`app.ini` configuration) - -These values are environment-dependent but form the basis of a lot of values. They will be -reported as part of the default configuration when running `gitea help` or on start-up. The order they are emitted there is slightly different but we will list them here in the order they are set-up. - -- _`AppPath`_: This is the absolute path of the running gitea binary. -- _`AppWorkPath`_: This refers to "working path" of the `gitea` binary. It is determined by using the first set thing in the following hierarchy: - - The `WORK_PATH` option in `app.ini` - - The `--work-path` flag passed to the binary - - The environment variable `$GITEA_WORK_DIR` - - A built-in value set at build time (see building from source) - - Otherwise, it defaults to the directory of the _`AppPath`_ - - If any of the above are relative paths then they are made absolute against the directory of the _`AppPath`_ -- _`CustomPath`_: This is the base directory for custom templates and other options. -It is determined by using the first set thing in the following hierarchy: - - The `--custom-path` flag passed to the binary - - The environment variable `$GITEA_CUSTOM` - - A built-in value set at build time (see building from source) - - Otherwise, it defaults to _`AppWorkPath`_`/custom` - - If any of the above are relative paths then they are made absolute against the -the directory of the _`AppWorkPath`_ -- _`CustomConf`_: This is the path to the `app.ini` file. - - The `--config` flag passed to the binary - - A built-in value set at build time (see building from source) - - Otherwise, it defaults to _`CustomPath`_`/conf/app.ini` - - If any of the above are relative paths then they are made absolute against the directory of the _`CustomPath`_ - -In addition, there is _`StaticRootPath`_ which can be set as a built-in at build time, but will otherwise default to _`AppWorkPath`_ - -## Overall (`DEFAULT`) - -- `APP_NAME`: **Gitea: Git with a cup of tea**: Application name, used in the page title. -- `RUN_USER`: **_current OS username_/`$USER`/`$USERNAME` e.g. git**: The user Gitea will run as. - This should be a dedicated system (non-user) account. Setting this incorrectly will cause Gitea - to not start. -- `RUN_MODE`: **prod**: Application run mode, affects performance and debugging: `dev` or `prod`, default is `prod`. Mode `dev` makes Gitea easier to develop and debug, values other than `dev` are treated as `prod` which is for production use. -- `WORK_PATH`: **_the-work-path_**: The working directory, see the comment of AppWorkPath above. - -## Repository (`repository`) - -- `ROOT`: **%(APP_DATA_PATH)s/gitea-repositories**: Root path for storing all repository data. - A relative path is interpreted as **_`AppWorkPath`_/%(ROOT)s**. -- `SCRIPT_TYPE`: **bash**: The script type this server supports. Usually this is `bash`, - but some users report that only `sh` is available. -- `DETECTED_CHARSETS_ORDER`: **UTF-8, UTF-16BE, UTF-16LE, UTF-32BE, UTF-32LE, ISO-8859, windows-1252, ISO-8859, windows-1250, ISO-8859, ISO-8859, ISO-8859, windows-1253, ISO-8859, windows-1255, ISO-8859, windows-1251, windows-1256, KOI8-R, ISO-8859, windows-1254, Shift_JIS, GB18030, EUC-JP, EUC-KR, Big5, ISO-2022, ISO-2022, ISO-2022, IBM424_rtl, IBM424_ltr, IBM420_rtl, IBM420_ltr**: Tie-break order of detected charsets - if the detected charsets have equal confidence, charsets earlier in the list will be chosen in preference to those later. Adding `defaults` will place the unnamed charsets at that point. -- `ANSI_CHARSET`: **_empty_**: Default ANSI charset to override non-UTF-8 charsets to. -- `FORCE_PRIVATE`: **false**: Force every new repository to be private. -- `DEFAULT_PRIVATE`: **last**: Default private when creating a new repository. - \[last, private, public\] -- `DEFAULT_PUSH_CREATE_PRIVATE`: **true**: Default private when creating a new repository with push-to-create. -- `MAX_CREATION_LIMIT`: **-1**: Global maximum creation limit of repositories per user, - `-1` means no limit. -- `PREFERRED_LICENSES`: **Apache License 2.0,MIT License**: Preferred Licenses to place at - the top of the list. Name must match file name in options/license or custom/options/license. -- `DISABLE_HTTP_GIT`: **false**: Disable the ability to interact with repositories over the - HTTP protocol. -- `USE_COMPAT_SSH_URI`: **false**: Force ssh:// clone url instead of scp-style uri when - default SSH port is used. -- `GO_GET_CLONE_URL_PROTOCOL`: **https**: Value for the "go get" request returns the repository url as https or ssh - default is https. -- `ACCESS_CONTROL_ALLOW_ORIGIN`: **_empty_**: Value for Access-Control-Allow-Origin header, - default is not to present. **WARNING**: This maybe harmful to you website if you do not - give it a right value. -- `DEFAULT_CLOSE_ISSUES_VIA_COMMITS_IN_ANY_BRANCH`: **false**: Close an issue if a commit on a non default branch marks it as closed. -- `ENABLE_PUSH_CREATE_USER`: **false**: Allow users to push local repositories to Gitea and have them automatically created for a user. -- `ENABLE_PUSH_CREATE_ORG`: **false**: Allow users to push local repositories to Gitea and have them automatically created for an org. -- `DISABLED_REPO_UNITS`: **_empty_**: Comma separated list of globally disabled repo units. Allowed values: \[repo.issues, repo.ext_issues, repo.pulls, repo.wiki, repo.ext_wiki, repo.projects, repo.packages, repo.actions\] -- `DEFAULT_REPO_UNITS`: **repo.code,repo.releases,repo.issues,repo.pulls,repo.wiki,repo.projects,repo.packages,repo.actions**: Comma separated list of default new repo units. Allowed values: \[repo.code, repo.releases, repo.issues, repo.pulls, repo.wiki, repo.projects, repo.packages, repo.actions\]. Note: Code and Releases can currently not be deactivated. If you specify default repo units you should still list them for future compatibility. External wiki and issue tracker can't be enabled by default as it requires additional settings. Disabled repo units will not be added to new repositories regardless if it is in the default list. -- `DEFAULT_FORK_REPO_UNITS`: **repo.code,repo.pulls**: Comma separated list of default forked repo units. The set of allowed values and rules is the same as `DEFAULT_REPO_UNITS`. -- `PREFIX_ARCHIVE_FILES`: **true**: Prefix archive files by placing them in a directory named after the repository. -- `DISABLE_MIGRATIONS`: **false**: Disable migrating feature. -- `DISABLE_STARS`: **false**: Disable stars feature. -- `DEFAULT_BRANCH`: **main**: Default branch name of all repositories. -- `ALLOW_ADOPTION_OF_UNADOPTED_REPOSITORIES`: **false**: Allow non-admin users to adopt unadopted repositories -- `ALLOW_DELETION_OF_UNADOPTED_REPOSITORIES`: **false**: Allow non-admin users to delete unadopted repositories -- `DISABLE_DOWNLOAD_SOURCE_ARCHIVES`: **false**: Don't allow download source archive files from UI -- `ALLOW_FORK_WITHOUT_MAXIMUM_LIMIT`: **true**: Allow fork repositories without maximum number limit - -### Repository - Editor (`repository.editor`) - -- `LINE_WRAP_EXTENSIONS`: **.txt,.md,.markdown,.mdown,.mkd,.livemd,**: List of file extensions for which lines should be wrapped in the Monaco editor. Separate extensions with a comma. To line wrap files without an extension, just put a comma -- `PREVIEWABLE_FILE_MODES`: **markdown**: Valid file modes that have a preview API associated with them, such as `api/v1/markdown`. Separate the values by commas. The preview tab in edit mode won't be displayed if the file extension doesn't match. - -### Repository - Pull Request (`repository.pull-request`) - -- `WORK_IN_PROGRESS_PREFIXES`: **WIP:,\[WIP\]**: List of prefixes used in Pull Request - title to mark them as Work In Progress. These are matched in a case-insensitive manner. -- `CLOSE_KEYWORDS`: **close**, **closes**, **closed**, **fix**, **fixes**, **fixed**, **resolve**, **resolves**, **resolved**: List of - keywords used in Pull Request comments to automatically close a related issue -- `REOPEN_KEYWORDS`: **reopen**, **reopens**, **reopened**: List of keywords used in Pull Request comments to automatically reopen - a related issue -- `DEFAULT_MERGE_STYLE`: **merge**: Set default merge style for repository creating, valid options: `merge`, `rebase`, `rebase-merge`, `squash`, `fast-forward-only` -- `DEFAULT_MERGE_MESSAGE_COMMITS_LIMIT`: **50**: In the default merge message for squash commits include at most this many commits. Set to `-1` to include all commits -- `DEFAULT_MERGE_MESSAGE_SIZE`: **5120**: In the default merge message for squash commits limit the size of the commit messages. Set to `-1` to have no limit. Only used if `POPULATE_SQUASH_COMMENT_WITH_COMMIT_MESSAGES` is `true`. -- `DEFAULT_MERGE_MESSAGE_ALL_AUTHORS`: **false**: In the default merge message for squash commits walk all commits to include all authors in the Co-authored-by otherwise just use those in the limited list -- `DEFAULT_MERGE_MESSAGE_MAX_APPROVERS`: **10**: In default merge messages limit the number of approvers listed as `Reviewed-by:`. Set to `-1` to include all. -- `DEFAULT_MERGE_MESSAGE_OFFICIAL_APPROVERS_ONLY`: **true**: In default merge messages only include approvers who are officially allowed to review. -- `POPULATE_SQUASH_COMMENT_WITH_COMMIT_MESSAGES`: **false**: In default squash-merge messages include the commit message of all commits comprising the pull request. -- `ADD_CO_COMMITTER_TRAILERS`: **true**: Add co-authored-by and co-committed-by trailers to merge commit messages if committer does not match author. -- `TEST_CONFLICTING_PATCHES_WITH_GIT_APPLY`: **false**: PR patches are tested using a three-way merge method to discover if there are conflicts. If this setting is set to **true**, conflicting patches will be retested using `git apply` - This was the previous behaviour in 1.18 (and earlier) but is somewhat inefficient. Please report if you find that this setting is required. -- `RETARGET_CHILDREN_ON_MERGE`: **true**: Retarget child pull requests to the parent pull request branch target on merge of parent pull request. It only works on merged PRs where the head and base branch target the same repo. - -### Repository - Issue (`repository.issue`) - -- `LOCK_REASONS`: **Too heated,Off-topic,Resolved,Spam**: A list of reasons why a Pull Request or Issue can be locked -- `MAX_PINNED`: **3**: Maximum number of pinned Issues per Repo. Set to 0 to disable pinning Issues. - -### Repository - Upload (`repository.upload`) - -- `ENABLED`: **true**: Whether repository file uploads are enabled -- `TEMP_PATH`: **data/tmp/uploads**: Path for uploads (content gets deleted on Gitea restart) -- `ALLOWED_TYPES`: **_empty_**: Comma-separated list of allowed file extensions (`.zip`), mime types (`text/plain`) or wildcard type (`image/*`, `audio/*`, `video/*`). Empty value or `*/*` allows all types. -- `FILE_MAX_SIZE`: **50**: Max size of each file in megabytes. -- `MAX_FILES`: **5**: Max number of files per upload - -### Repository - Release (`repository.release`) - -- `ALLOWED_TYPES`: **_empty_**: Comma-separated list of allowed file extensions (`.zip`), mime types (`text/plain`) or wildcard type (`image/*`, `audio/*`, `video/*`). Empty value or `*/*` allows all types. -- `DEFAULT_PAGING_NUM`: **10**: The default paging number of releases user interface -- For settings related to file attachments on releases, see the `attachment` section. - -### Repository - Signing (`repository.signing`) - -- `SIGNING_KEY`: **default**: \[none, KEYID, default \]: Key to sign with. -- `SIGNING_NAME` & `SIGNING_EMAIL`: if a KEYID is provided as the `SIGNING_KEY`, use these as the Name and Email address of the signer. These should match publicized name and email address for the key. -- `INITIAL_COMMIT`: **always**: \[never, pubkey, twofa, always\]: Sign initial commit. - - `never`: Never sign - - `pubkey`: Only sign if the user has a public key - - `twofa`: Only sign if the user is logged in with twofa - - `always`: Always sign - - Options other than `never` and `always` can be combined as a comma separated list. -- `DEFAULT_TRUST_MODEL`: **collaborator**: \[collaborator, committer, collaboratorcommitter\]: The default trust model used for verifying commits. - - `collaborator`: Trust signatures signed by keys of collaborators. - - `committer`: Trust signatures that match committers (This matches GitHub and will force Gitea signed commits to have Gitea as the committer). - - `collaboratorcommitter`: Trust signatures signed by keys of collaborators which match the committer. -- `WIKI`: **never**: \[never, pubkey, twofa, always, parentsigned\]: Sign commits to wiki. -- `CRUD_ACTIONS`: **pubkey, twofa, parentsigned**: \[never, pubkey, twofa, parentsigned, always\]: Sign CRUD actions. - - Options as above, with the addition of: - - `parentsigned`: Only sign if the parent commit is signed. -- `MERGES`: **pubkey, twofa, basesigned, commitssigned**: \[never, pubkey, twofa, approved, basesigned, commitssigned, always\]: Sign merges. - - `approved`: Only sign approved merges to a protected branch. - - `basesigned`: Only sign if the parent commit in the base repo is signed. - - `headsigned`: Only sign if the head commit in the head branch is signed. - - `commitssigned`: Only sign if all the commits in the head branch to the merge point are signed. - -## Repository - Local (`repository.local`) - -- `LOCAL_COPY_PATH`: **tmp/local-repo**: Path for temporary local repository copies. Defaults to `tmp/local-repo` (content gets deleted on Gitea restart) - -## Repository - MIME type mapping (`repository.mimetype_mapping`) - -Configuration for set the expected MIME type based on file extensions of downloadable files. Configuration presents in key-value pairs and file extensions starts with leading `.`. - -The following configuration set `Content-Type: application/vnd.android.package-archive` header when downloading files with `.apk` file extension. - -```ini -.apk=application/vnd.android.package-archive -``` - -## CORS (`cors`) - -- `ENABLED`: **false**: enable cors headers (disabled by default) -- `ALLOW_DOMAIN`: **\***: list of requesting origins that are allowed, eg: "https://*.example.com" -- `METHODS`: **GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS**: list of methods allowed to request -- `MAX_AGE`: **10m**: max time to cache response -- `ALLOW_CREDENTIALS`: **false**: allow request with credentials -- `HEADERS`: **Content-Type,User-Agent**: additional headers that are permitted in requests -- `X_FRAME_OPTIONS`: **SAMEORIGIN**: Set the `X-Frame-Options` header value. - -## UI (`ui`) - -- `EXPLORE_PAGING_NUM`: **20**: Number of repositories that are shown in one explore page. -- `ISSUE_PAGING_NUM`: **20**: Number of issues that are shown in one page (for all pages that list issues, milestones, projects). -- `MEMBERS_PAGING_NUM`: **20**: Number of members that are shown in organization members. -- `FEED_MAX_COMMIT_NUM`: **5**: Number of maximum commits shown in one activity feed. -- `FEED_PAGING_NUM`: **20**: Number of items that are displayed in home feed. -- `SITEMAP_PAGING_NUM`: **20**: Number of items that are displayed in a single subsitemap. -- `GRAPH_MAX_COMMIT_NUM`: **100**: Number of maximum commits shown in the commit graph. -- `CODE_COMMENT_LINES`: **4**: Number of line of codes shown for a code comment. -- `DEFAULT_THEME`: **gitea-auto**: Set the default theme for the Gitea installation, custom themes could be provided by `{CustomPath}/public/assets/css/theme-*.css`. -- `SHOW_USER_EMAIL`: **true**: Whether the email of the user should be shown in the Explore Users page. -- `THEMES`: **_empty_**: All available themes by `{CustomPath}/public/assets/css/theme-*.css`. Allow users select personalized themes. -- `MAX_DISPLAY_FILE_SIZE`: **8388608**: Max size of files to be displayed (default is 8MiB) -- `AMBIGUOUS_UNICODE_DETECTION`: **true**: Detect ambiguous unicode characters in file contents and show warnings on the UI -- `REACTIONS`: All available reactions users can choose on issues/prs and comments - Values can be emoji alias (:smile:) or a unicode emoji. - For custom reactions, add a tightly cropped square image to public/assets/img/emoji/reaction_name.png -- `REACTION_MAX_USER_NUM`: **10**: Change the number of users that are displayed in reactions tooltip (triggered by mouse hover). -- `CUSTOM_EMOJIS`: **gitea, codeberg, gitlab, git, github, gogs**: Additional Emojis not defined in the utf8 standard. - By default, we support Gitea (:gitea:), to add more copy them to public/assets/img/emoji/emoji_name.png and - add it to this config. -- `DEFAULT_SHOW_FULL_NAME`: **false**: Whether the full name of the users should be shown where possible. If the full name isn't set, the username will be used. -- `SEARCH_REPO_DESCRIPTION`: **true**: Whether to search within description at repository search on explore page. -- `ONLY_SHOW_RELEVANT_REPOS`: **false**: Whether to only show relevant repos on the explore page when no keyword is specified and default sorting is used. - A repo is considered irrelevant if it's a fork or if it has no metadata (no description, no icon, no topic). -- `EXPLORE_PAGING_DEFAULT_SORT`: **recentupdate**: Change the sort type of the explore pages. Valid values are "recentupdate", "alphabetically", "reverselastlogin", "newest" and "oldest" -- `PREFERRED_TIMESTAMP_TENSE`: **mixed**: The tense all timestamps should be rendered in. Possible values are `absolute` time (i.e. 1970-01-01, 11:59) and `mixed`. `mixed` means most timestamps are rendered in relative time (i.e. 2 days ago). - -### UI - Admin (`ui.admin`) - -- `USER_PAGING_NUM`: **50**: Number of users that are shown in one page. -- `REPO_PAGING_NUM`: **50**: Number of repos that are shown in one page. -- `NOTICE_PAGING_NUM`: **25**: Number of notices that are shown in one page. -- `ORG_PAGING_NUM`: **50**: Number of organizations that are shown in one page. - -### UI - User (`ui.user`) - -- `REPO_PAGING_NUM`: **15**: Number of repos that are shown in one page. - -### UI - Metadata (`ui.meta`) - -- `AUTHOR`: **Gitea - Git with a cup of tea**: Author meta tag of the homepage. -- `DESCRIPTION`: **Gitea (Git with a cup of tea) is a painless self-hosted Git service written in Go**: Description meta tag of the homepage. -- `KEYWORDS`: **go,git,self-hosted,gitea**: Keywords meta tag of the homepage. - -### UI - Notification (`ui.notification`) - -- `MIN_TIMEOUT`: **10s**: These options control how often notification endpoint is polled to update the notification count. On page load the notification count will be checked after `MIN_TIMEOUT`. The timeout will increase to `MAX_TIMEOUT` by `TIMEOUT_STEP` if the notification count is unchanged. Set MIN_TIMEOUT to -1 to turn off. -- `MAX_TIMEOUT`: **60s**. -- `TIMEOUT_STEP`: **10s**. -- `EVENT_SOURCE_UPDATE_TIME`: **10s**: This setting determines how often the database is queried to update notification counts. If the browser client supports `EventSource` and `SharedWorker`, a `SharedWorker` will be used in preference to polling notification endpoint. Set to **-1** to disable the `EventSource`. - -### UI - SVG Images (`ui.svg`) - -- `ENABLE_RENDER`: **true**: Whether to render SVG files as images. If SVG rendering is disabled, SVG files are displayed as text and cannot be embedded in markdown files as images. - -### UI - CSV Files (`ui.csv`) - -- `MAX_FILE_SIZE`: **524288** (512kb): Maximum allowed file size in bytes to render CSV files as table. (Set to 0 for no limit). - -## Markdown (`markdown`) - -- `ENABLE_HARD_LINE_BREAK_IN_COMMENTS`: **true**: Render soft line breaks as hard line breaks in comments, which - means a single newline character between paragraphs will cause a line break and adding - trailing whitespace to paragraphs is not necessary to force a line break. -- `ENABLE_HARD_LINE_BREAK_IN_DOCUMENTS`: **false**: Render soft line breaks as hard line breaks in documents, which - means a single newline character between paragraphs will cause a line break and adding - trailing whitespace to paragraphs is not necessary to force a line break. -- `CUSTOM_URL_SCHEMES`: Use a comma separated list (ftp,git,svn) to indicate additional - URL hyperlinks to be rendered in Markdown. URLs beginning in http and https are - always displayed. If this entry is empty, all URL schemes are allowed -- `FILE_EXTENSIONS`: **.md,.markdown,.mdown,.mkd,.livemd**: List of file extensions that should be rendered/edited as Markdown. Separate the extensions with a comma. To render files without any extension as markdown, just put a comma. -- `ENABLE_MATH`: **true**: Enables detection of `\(...\)`, `\[...\]`, `$...$` and `$$...$$` blocks as math blocks. - -## Server (`server`) - -- `APP_DATA_PATH`: **_`AppWorkPath`_/data**: This is the default root path for storing data. -- `PROTOCOL`: **http**: \[http, https, fcgi, http+unix, fcgi+unix\] - - Note: Value must be lowercase. -- `USE_PROXY_PROTOCOL`: **false**: Expect PROXY protocol headers on connections -- `PROXY_PROTOCOL_TLS_BRIDGING`: **false**: When protocol is https, expect PROXY protocol headers after TLS negotiation. -- `PROXY_PROTOCOL_HEADER_TIMEOUT`: **5s**: Timeout to wait for PROXY protocol header (set to 0 to have no timeout) -- `PROXY_PROTOCOL_ACCEPT_UNKNOWN`: **false**: Accept PROXY protocol headers with Unknown type. -- `DOMAIN`: **localhost**: Domain name of this server. -- `ROOT_URL`: **%(PROTOCOL)s://%(DOMAIN)s:%(HTTP\_PORT)s/**: - Overwrite the automatically generated public URL. - This is useful if the internal and the external URL don't match (e.g. in Docker). -- `STATIC_URL_PREFIX`: **_empty_**: - Overwrite this option to request static resources from a different URL. - This includes CSS files, images, JS files and web fonts. - Avatar images are dynamic resources and still served by Gitea. - The option can be just a different path, as in `/static`, or another domain, as in `https://cdn.example.com`. - Requests are then made as `%(ROOT_URL)s/static/assets/css/index.css` or `https://cdn.example.com/assets/css/index.css` respectively. - The static files are located in the `public/` directory of the Gitea source repository. - You can proxy the STATIC_URL_PREFIX requests to Gitea server to serve the static - assets, or copy the manually built Gitea assets from `$GITEA_BUILD/public` to - the assets location, eg: `/var/www/assets`, make sure `$STATIC_URL_PREFIX/assets/css/index.css` - points to `/var/www/assets/css/index.css`. - -- `HTTP_ADDR`: **0.0.0.0**: HTTP listen address. - - If `PROTOCOL` is set to `fcgi`, Gitea will listen for FastCGI requests on TCP socket - defined by `HTTP_ADDR` and `HTTP_PORT` configuration settings. - - If `PROTOCOL` is set to `http+unix` or `fcgi+unix`, this should be the name of the Unix socket file to use. Relative paths will be made absolute against the _`AppWorkPath`_. -- `HTTP_PORT`: **3000**: HTTP listen port. - - If `PROTOCOL` is set to `fcgi`, Gitea will listen for FastCGI requests on TCP socket - defined by `HTTP_ADDR` and `HTTP_PORT` configuration settings. -- `UNIX_SOCKET_PERMISSION`: **666**: Permissions for the Unix socket. -- `LOCAL_ROOT_URL`: **%(PROTOCOL)s://%(HTTP_ADDR)s:%(HTTP_PORT)s/**: Local - (DMZ) URL for Gitea workers (such as SSH update) accessing web service. In - most cases you do not need to change the default value. Alter it only if - your SSH server node is not the same as HTTP node. For different protocol, the default - values are different. If `PROTOCOL` is `http+unix`, the default value is `http://unix/`. - If `PROTOCOL` is `fcgi` or `fcgi+unix`, the default value is `%(PROTOCOL)s://%(HTTP_ADDR)s:%(HTTP_PORT)s/`. - If listen on `0.0.0.0`, the default value is `%(PROTOCOL)s://localhost:%(HTTP_PORT)s/`, Otherwise the default - value is `%(PROTOCOL)s://%(HTTP_ADDR)s:%(HTTP_PORT)s/`. -- `LOCAL_USE_PROXY_PROTOCOL`: **%(USE_PROXY_PROTOCOL)s**: When making local connections pass the PROXY protocol header. - This should be set to false if the local connection will go through the proxy. -- `PER_WRITE_TIMEOUT`: **30s**: Timeout for any write to the connection. (Set to -1 to - disable all timeouts.) -- `PER_WRITE_PER_KB_TIMEOUT`: **10s**: Timeout per Kb written to connections. - -- `DISABLE_SSH`: **false**: Disable SSH feature when it's not available. -- `START_SSH_SERVER`: **false**: When enabled, use the built-in SSH server. -- `SSH_SERVER_USE_PROXY_PROTOCOL`: **false**: Expect PROXY protocol header on connections to the built-in SSH Server. -- `BUILTIN_SSH_SERVER_USER`: **%(RUN_USER)s**: Username to use for the built-in SSH Server. -- `SSH_USER`: **%(BUILTIN_SSH_SERVER_USER)s**: SSH username displayed in clone URLs. This is only for people who configure the SSH server themselves; in most cases, you want to leave this blank and modify the `BUILTIN_SSH_SERVER_USER`. -- `SSH_DOMAIN`: **%(DOMAIN)s**: Domain name of this server, used for displayed clone URL. -- `SSH_PORT`: **22**: SSH port displayed in clone URL. -- `SSH_LISTEN_HOST`: **0.0.0.0**: Listen address for the built-in SSH server. -- `SSH_LISTEN_PORT`: **%(SSH\_PORT)s**: Port for the built-in SSH server. -- `SSH_ROOT_PATH`: **~/.ssh**: Root path of SSH directory. -- `SSH_CREATE_AUTHORIZED_KEYS_FILE`: **true**: Gitea will create a authorized_keys file by default when it is not using the internal ssh server. If you intend to use the AuthorizedKeysCommand functionality then you should turn this off. -- `SSH_AUTHORIZED_KEYS_BACKUP`: **false**: Enable SSH Authorized Key Backup when rewriting all keys, default is false. -- `SSH_TRUSTED_USER_CA_KEYS`: **_empty_**: Specifies the public keys of certificate authorities that are trusted to sign user certificates for authentication. Multiple keys should be comma separated. E.g.`ssh- ` or `ssh- , ssh- `. For more information see `TrustedUserCAKeys` in the sshd config man pages. When empty no file will be created and `SSH_AUTHORIZED_PRINCIPALS_ALLOW` will default to `off`. -- `SSH_TRUSTED_USER_CA_KEYS_FILENAME`: **`RUN_USER`/.ssh/gitea-trusted-user-ca-keys.pem**: Absolute path of the `TrustedUserCaKeys` file Gitea will manage. If you're running your own ssh server and you want to use the Gitea managed file you'll also need to modify your sshd_config to point to this file. The official docker image will automatically work without further configuration. -- `SSH_AUTHORIZED_PRINCIPALS_ALLOW`: **off** or **username, email**: \[off, username, email, anything\]: Specify the principals values that users are allowed to use as principal. When set to `anything` no checks are done on the principal string. When set to `off` authorized principal are not allowed to be set. -- `SSH_CREATE_AUTHORIZED_PRINCIPALS_FILE`: **false/true**: Gitea will create a authorized_principals file by default when it is not using the internal ssh server and `SSH_AUTHORIZED_PRINCIPALS_ALLOW` is not `off`. -- `SSH_AUTHORIZED_PRINCIPALS_BACKUP`: **false/true**: Enable SSH Authorized Principals Backup when rewriting all keys, default is true if `SSH_AUTHORIZED_PRINCIPALS_ALLOW` is not `off`. -- `SSH_AUTHORIZED_KEYS_COMMAND_TEMPLATE`: **`{{.AppPath}} --config={{.CustomConf}} serv key-{{.Key.ID}}`**: Set the template for the command to passed on authorized keys. Possible keys are: AppPath, AppWorkPath, CustomConf, CustomPath, Key - where Key is a `models/asymkey.PublicKey` and the others are strings which are shellquoted. -- `SSH_SERVER_CIPHERS`: **chacha20-poly1305@openssh.com, aes128-ctr, aes192-ctr, aes256-ctr, aes128-gcm@openssh.com, aes256-gcm@openssh.com**: For the built-in SSH server, choose the ciphers to support for SSH connections, for system SSH this setting has no effect. -- `SSH_SERVER_KEY_EXCHANGES`: **curve25519-sha256, ecdh-sha2-nistp256, ecdh-sha2-nistp384, ecdh-sha2-nistp521, diffie-hellman-group14-sha256, diffie-hellman-group14-sha1**: For the built-in SSH server, choose the key exchange algorithms to support for SSH connections, for system SSH this setting has no effect. -- `SSH_SERVER_MACS`: **hmac-sha2-256-etm@openssh.com, hmac-sha2-256, hmac-sha1**: For the built-in SSH server, choose the MACs to support for SSH connections, for system SSH this setting has no effect -- `SSH_SERVER_HOST_KEYS`: **ssh/gitea.rsa, ssh/gogs.rsa**: For the built-in SSH server, choose the keypairs to offer as the host key. The private key should be at `SSH_SERVER_HOST_KEY` and the public `SSH_SERVER_HOST_KEY.pub`. Relative paths are made absolute relative to the `APP_DATA_PATH`. If no key exists a 4096 bit RSA key will be created for you. -- `SSH_KEY_TEST_PATH`: **/tmp**: Directory to create temporary files in when testing public keys using ssh-keygen, default is the system temporary directory. -- `SSH_KEYGEN_PATH`: **_empty_**: Use `ssh-keygen` to parse public SSH keys. The value is passed to the shell. By default, Gitea does the parsing itself. -- `SSH_EXPOSE_ANONYMOUS`: **false**: Enable exposure of SSH clone URL to anonymous visitors, default is false. -- `SSH_PER_WRITE_TIMEOUT`: **30s**: Timeout for any write to the SSH connections. (Set to - -1 to disable all timeouts.) -- `SSH_PER_WRITE_PER_KB_TIMEOUT`: **10s**: Timeout per Kb written to SSH connections. -- `MINIMUM_KEY_SIZE_CHECK`: **true**: Indicate whether to check minimum key size with corresponding type. - -- `OFFLINE_MODE`: **true**: Disables use of CDN for static files and Gravatar for profile pictures. -- `CERT_FILE`: **https/cert.pem**: Cert file path used for HTTPS. When chaining, the server certificate must come first, then intermediate CA certificates (if any). This is ignored if `ENABLE_ACME=true`. Paths are relative to `CUSTOM_PATH`. -- `KEY_FILE`: **https/key.pem**: Key file path used for HTTPS. This is ignored if `ENABLE_ACME=true`. Paths are relative to `CUSTOM_PATH`. -- `STATIC_ROOT_PATH`: **_`StaticRootPath`_**: Upper level of template and static files path. -- `APP_DATA_PATH`: **data** (**/data/gitea** on docker): Default path for application data. Relative paths will be made absolute against _`AppWorkPath`_. -- `STATIC_CACHE_TIME`: **6h**: Web browser cache time for static resources on `custom/`, `public/` and all uploaded avatars. Note that this cache is disabled when `RUN_MODE` is "dev". -- `ENABLE_GZIP`: **false**: Enable gzip compression for runtime-generated content, static resources excluded. -- `ENABLE_PPROF`: **false**: Application profiling (memory and cpu). For "web" command it listens on `localhost:6060`. For "serv" command it dumps to disk at `PPROF_DATA_PATH` as `(cpuprofile|memprofile)__` -- `PPROF_DATA_PATH`: **_`AppWorkPath`_/data/tmp/pprof**: `PPROF_DATA_PATH`, use an absolute path when you start Gitea as service -- `LANDING_PAGE`: **home**: Landing page for unauthenticated users \[home, explore, organizations, login, **custom**\]. Where custom would instead be any URL such as "/org/repo" or even `https://anotherwebsite.com` -- `LFS_START_SERVER`: **false**: Enables Git LFS support. -- `LFS_CONTENT_PATH`: **%(APP_DATA_PATH)s/lfs**: Default LFS content path. (if it is on local storage.) **DEPRECATED** use settings in `[lfs]`. -- `LFS_JWT_SECRET`: **_empty_**: LFS authentication secret, change this a unique string. -- `LFS_JWT_SECRET_URI`: **_empty_**: Instead of defining LFS_JWT_SECRET in the configuration, this configuration option can be used to give Gitea a path to a file that contains the secret (example value: `file:/etc/gitea/lfs_jwt_secret`) -- `LFS_HTTP_AUTH_EXPIRY`: **24h**: LFS authentication validity period in time.Duration, pushes taking longer than this may fail. -- `LFS_MAX_FILE_SIZE`: **0**: Maximum allowed LFS file size in bytes (Set to 0 for no limit). -- `LFS_LOCKS_PAGING_NUM`: **50**: Maximum number of LFS Locks returned per page. - -- `REDIRECT_OTHER_PORT`: **false**: If true and `PROTOCOL` is https, allows redirecting http requests on `PORT_TO_REDIRECT` to the https port Gitea listens on. -- `REDIRECTOR_USE_PROXY_PROTOCOL`: **%(USE_PROXY_PROTOCOL)s**: expect PROXY protocol header on connections to https redirector. -- `PORT_TO_REDIRECT`: **80**: Port for the http redirection service to listen on. Used when `REDIRECT_OTHER_PORT` is true. -- `SSL_MIN_VERSION`: **TLSv1.2**: Set the minimum version of ssl support. -- `SSL_MAX_VERSION`: **_empty_**: Set the maximum version of ssl support. -- `SSL_CURVE_PREFERENCES`: **X25519,P256**: Set the preferred curves, -- `SSL_CIPHER_SUITES`: **ecdhe_ecdsa_with_aes_256_gcm_sha384,ecdhe_rsa_with_aes_256_gcm_sha384,ecdhe_ecdsa_with_aes_128_gcm_sha256,ecdhe_rsa_with_aes_128_gcm_sha256,ecdhe_ecdsa_with_chacha20_poly1305,ecdhe_rsa_with_chacha20_poly1305**: Set the preferred cipher suites. - - If there is no hardware support for AES suites, by default the ChaCha suites will be preferred over the AES suites. - - supported suites as of Go 1.18 are: - - TLS 1.0 - 1.2 cipher suites - - "rsa_with_rc4_128_sha" - - "rsa_with_3des_ede_cbc_sha" - - "rsa_with_aes_128_cbc_sha" - - "rsa_with_aes_256_cbc_sha" - - "rsa_with_aes_128_cbc_sha256" - - "rsa_with_aes_128_gcm_sha256" - - "rsa_with_aes_256_gcm_sha384" - - "ecdhe_ecdsa_with_rc4_128_sha" - - "ecdhe_ecdsa_with_aes_128_cbc_sha" - - "ecdhe_ecdsa_with_aes_256_cbc_sha" - - "ecdhe_rsa_with_rc4_128_sha" - - "ecdhe_rsa_with_3des_ede_cbc_sha" - - "ecdhe_rsa_with_aes_128_cbc_sha" - - "ecdhe_rsa_with_aes_256_cbc_sha" - - "ecdhe_ecdsa_with_aes_128_cbc_sha256" - - "ecdhe_rsa_with_aes_128_cbc_sha256" - - "ecdhe_rsa_with_aes_128_gcm_sha256" - - "ecdhe_ecdsa_with_aes_128_gcm_sha256" - - "ecdhe_rsa_with_aes_256_gcm_sha384" - - "ecdhe_ecdsa_with_aes_256_gcm_sha384" - - "ecdhe_rsa_with_chacha20_poly1305_sha256" - - "ecdhe_ecdsa_with_chacha20_poly1305_sha256" - - TLS 1.3 cipher suites - - "aes_128_gcm_sha256" - - "aes_256_gcm_sha384" - - "chacha20_poly1305_sha256" - - Aliased names - - "ecdhe_rsa_with_chacha20_poly1305" is an alias for "ecdhe_rsa_with_chacha20_poly1305_sha256" - - "ecdhe_ecdsa_with_chacha20_poly1305" is alias for "ecdhe_ecdsa_with_chacha20_poly1305_sha256" -- `ENABLE_ACME`: **false**: Flag to enable automatic certificate management via an ACME capable Certificate Authority (CA) server (default: Lets Encrypt). If enabled, `CERT_FILE` and `KEY_FILE` are ignored, and the CA must resolve `DOMAIN` to this gitea server. Ensure that DNS records are set and either port `80` or port `443` are accessible by the CA server (the public internet by default), and redirected to the appropriate ports `PORT_TO_REDIRECT` or `HTTP_PORT` respectively. -- `ACME_URL`: **_empty_**: The CA's ACME directory URL, e.g. for a self-hosted [smallstep CA server](https://github.com/smallstep/certificates), it can look like `https://ca.example.com/acme/acme/directory`. If left empty, it defaults to using Let's Encerypt's production CA (check `LETSENCRYPT_ACCEPTTOS` as well). -- `ACME_ACCEPTTOS`: **false**: This is an explicit check that you accept the terms of service of the ACME provider. The default is Lets Encrypt [terms of service](https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf). -- `ACME_DIRECTORY`: **https**: Directory that the certificate manager will use to cache information such as certs and private keys. -- `ACME_EMAIL`: **_empty_**: Email used for the ACME registration. Usually it is to notify about problems with issued certificates. -- `ACME_CA_ROOT`: **_empty_**: The CA's root certificate. If left empty, it defaults to using the system's trust chain. -- `ALLOW_GRACEFUL_RESTARTS`: **true**: Perform a graceful restart on SIGHUP -- `GRACEFUL_HAMMER_TIME`: **60s**: After a restart the parent process will stop accepting new connections and will allow requests to finish before stopping. Shutdown will be forced if it takes longer than this time. -- `STARTUP_TIMEOUT`: **0**: Shutsdown the server if startup takes longer than the provided time. On Windows setting this sends a waithint to the SVC host to tell the SVC host startup may take some time. Please note startup is determined by the opening of the listeners - HTTP/HTTPS/SSH. Indexers may take longer to startup and can have their own timeouts. - -## Database (`database`) - -- `DB_TYPE`: **mysql**: The database type in use \[mysql, postgres, mssql, sqlite3\]. -- `HOST`: **127.0.0.1:3306**: Database host address and port or absolute path for unix socket \[mysql, postgres[^1]\] (ex: /var/run/mysqld/mysqld.sock). -- `NAME`: **gitea**: Database name. -- `USER`: **root**: Database username. -- `PASSWD`: **_empty_**: Database user password. Use \`your password\` or """your password""" for quoting if you use special characters in the password. -- `CHARSET_COLLATION`: **_empty_**: (MySQL/MSSQL only) Gitea expects to use a case-sensitive collation for database. Leave it empty to use the default collation decided by the Gitea. Don't change it unless you clearly know what you need. -- `SCHEMA`: **_empty_**: For PostgreSQL only, schema to use if different from "public". The schema must exist beforehand, - the user must have creation privileges on it, and the user search path must be set to the look into the schema first - (e.g. `ALTER USER user SET SEARCH_PATH = schema_name,"$user",public;`). -- `SSL_MODE`: **disable**: SSL/TLS encryption mode for connecting to the database. This option is only applied for PostgreSQL and MySQL. - - Valid values for MySQL: - - `true`: Enable TLS with verification of the database server certificate against its root certificate. When selecting this option make sure that the root certificate required to validate the database server certificate (e.g. the CA certificate) is on the system certificate store of both the database and Gitea servers. See your system documentation for instructions on how to add a CA certificate to the certificate store. - - `false`: Disable TLS. - - `disable`: Alias for `false`, for compatibility with PostgreSQL. - - `skip-verify`: Enable TLS without database server certificate verification. Use this option if you have self-signed or invalid certificate on the database server. - - `prefer`: Enable TLS with fallback to non-TLS connection. - - Valid values for PostgreSQL: - - `disable`: Disable TLS. - - `require`: Enable TLS without any verifications. - - `verify-ca`: Enable TLS with verification of the database server certificate against its root certificate. - - `verify-full`: Enable TLS and verify the database server name matches the given certificate in either the `Common Name` or `Subject Alternative Name` fields. -- `SQLITE_TIMEOUT`: **500**: Query timeout for SQLite3 only. -- `SQLITE_JOURNAL_MODE`: **""**: Change journal mode for SQlite3. Can be used to enable [WAL mode](https://www.sqlite.org/wal.html) when high load causes write congestion. See [SQlite3 docs](https://www.sqlite.org/pragma.html#pragma_journal_mode) for possible values. Defaults to the default for the database file, often DELETE. -- `ITERATE_BUFFER_SIZE`: **50**: Internal buffer size for iterating. -- `PATH`: **data/gitea.db**: For SQLite3 only, the database file path. -- `LOG_SQL`: **false**: Log the executed SQL. -- `DB_RETRIES`: **10**: How many ORM init / DB connect attempts allowed. -- `DB_RETRY_BACKOFF`: **3s**: time.Duration to wait before trying another ORM init / DB connect attempt, if failure occurred. -- `MAX_OPEN_CONNS` **0**: Database maximum open connections - default is 0, meaning there is no limit. -- `MAX_IDLE_CONNS` **2**: Max idle database connections on connection pool, default is 2 - this will be capped to `MAX_OPEN_CONNS`. -- `CONN_MAX_LIFETIME` **0 or 3s**: Sets the maximum amount of time a DB connection may be reused - default is 0, meaning there is no limit (except on MySQL where it is 3s - see #6804 & #7071). -- `AUTO_MIGRATION` **true**: Whether execute database models migrations automatically. -- `SLOW_QUERY_THRESHOLD` **5s**: Threshold value in seconds beyond which query execution time is logged as a warning in the xorm logger. - -[^1]: It may be necessary to specify a hostport even when listening on a unix socket, as the port is part of the socket name. see [#24552](https://github.com/go-gitea/gitea/issues/24552#issuecomment-1681649367) for additional details. - -Please see #8540 & #8273 for further discussion of the appropriate values for `MAX_OPEN_CONNS`, `MAX_IDLE_CONNS` & `CONN_MAX_LIFETIME` and their -relation to port exhaustion. - -## Indexer (`indexer`) - -- `ISSUE_INDEXER_TYPE`: **bleve**: Issue indexer type, currently supported: `bleve`, `db`, `elasticsearch` or `meilisearch`. -- `ISSUE_INDEXER_CONN_STR`: ****: Issue indexer connection string, available when ISSUE_INDEXER_TYPE is elasticsearch (e.g. http://elastic:password@localhost:9200) or meilisearch (e.g. http://:apikey@localhost:7700) -- `ISSUE_INDEXER_NAME`: **gitea_issues**: Issue indexer name, available when ISSUE_INDEXER_TYPE is elasticsearch or meilisearch. -- `ISSUE_INDEXER_PATH`: **indexers/issues.bleve**: Index file used for issue search; available when ISSUE_INDEXER_TYPE is bleve and elasticsearch. Relative paths will be made absolute against _`AppWorkPath`_. - -- `REPO_INDEXER_ENABLED`: **false**: Enables code search (uses a lot of disk space, about 6 times more than the repository size). -- `REPO_INDEXER_REPO_TYPES`: **sources,forks,mirrors,templates**: Repo indexer units. The items to index could be `sources`, `forks`, `mirrors`, `templates` or any combination of them separated by a comma. If empty then it defaults to `sources` only, as if you'd like to disable fully please see `REPO_INDEXER_ENABLED`. -- `REPO_INDEXER_TYPE`: **bleve**: Code search engine type, could be `bleve` or `elasticsearch`. -- `REPO_INDEXER_PATH`: **indexers/repos.bleve**: Index file used for code search. -- `REPO_INDEXER_CONN_STR`: ****: Code indexer connection string, available when `REPO_INDEXER_TYPE` is elasticsearch. i.e. http://elastic:password@localhost:9200 -- `REPO_INDEXER_NAME`: **gitea_codes**: Code indexer name, available when `REPO_INDEXER_TYPE` is elasticsearch - -- `REPO_INDEXER_INCLUDE`: **empty**: A comma separated list of glob patterns (see https://github.com/gobwas/glob) to **include** in the index. Use `**.txt` to match any files with .txt extension. An empty list means include all files. -- `REPO_INDEXER_EXCLUDE`: **empty**: A comma separated list of glob patterns (see https://github.com/gobwas/glob) to **exclude** from the index. Files that match this list will not be indexed, even if they match in `REPO_INDEXER_INCLUDE`. -- `REPO_INDEXER_EXCLUDE_VENDORED`: **true**: Exclude vendored files from index. -- `MAX_FILE_SIZE`: **1048576**: Maximum size in bytes of files to be indexed. -- `STARTUP_TIMEOUT`: **30s**: If the indexer takes longer than this timeout to start - fail. (This timeout will be added to the hammer time above for child processes - as bleve will not start until the previous parent is shutdown.) Set to -1 to never timeout. - -## Queue (`queue` and `queue.*`) - -Configuration at `[queue]` will set defaults for queues with overrides for individual queues at `[queue.*]`. (However see below.) - -- `TYPE`: **level**: General queue type, currently support: `level` (uses a LevelDB internally), `channel`, `redis`, `dummy`. Invalid types are treated as `level`. -- `DATADIR`: **queues/common**: Base DataDir for storing level queues. `DATADIR` for individual queues can be set in `queue.name` sections. Relative paths will be made absolute against `%(APP_DATA_PATH)s`. -- `LENGTH`: **100000**: Maximal queue size before channel queues block -- `BATCH_LENGTH`: **20**: Batch data before passing to the handler -- `CONN_STR`: **redis://127.0.0.1:6379/0**: Connection string for the redis queue type. If you're running a Redis cluster, use `redis+cluster://127.0.0.1:6379/0`. Options can be set using query params. Similarly, LevelDB options can also be set using: **leveldb://relative/path?option=value** or **leveldb:///absolute/path?option=value**, and will override `DATADIR` -- `QUEUE_NAME`: **_queue**: The suffix for default redis and disk queue name. Individual queues will default to **`name`**`QUEUE_NAME` but can be overridden in the specific `queue.name` section. -- `SET_NAME`: **_unique**: The suffix that will be added to the default redis and disk queue `set` name for unique queues. Individual queues will default to **`name`**`QUEUE_NAME`_`SET_NAME`_ but can be overridden in the specific `queue.name` section. -- `MAX_WORKERS`: **(dynamic)**: Maximum number of worker go-routines for the queue. Default value is "CpuNum/2" clipped to between 1 and 10. - -Gitea creates the following non-unique queues: - -- `code_indexer` -- `issue_indexer` -- `notification-service` -- `task` -- `mail` -- `push_update` - -And the following unique queues: - -- `repo_stats_update` -- `repo-archive` -- `mirror` -- `pr_patch_checker` - -## Admin (`admin`) - -- `DEFAULT_EMAIL_NOTIFICATIONS`: **enabled**: Default configuration for email notifications for users (user configurable). Options: enabled, onmention, disabled -- `DISABLE_REGULAR_ORG_CREATION`: **false**: Disallow regular (non-admin) users from creating organizations. -- `USER_DISABLED_FEATURES`: **_empty_** Disabled features for users, could be `deletion`, `manage_ssh_keys`, `manage_gpg_keys`, `manage_mfa`, `manage_credentials` and more features can be added in future. - - `deletion`: User cannot delete their own account. - - `manage_ssh_keys`: User cannot configure ssh keys. - - `manage_gpg_keys`: User cannot configure gpg keys. - - `manage_mfa`: a User cannot configure mfa devices. - - `manage_credentials`: a user cannot configure emails, passwords, or openid -- `EXTERNAL_USER_DISABLE_FEATURES`: **_empty_**: Comma separated list of disabled features ONLY if the user has an external login type (eg. LDAP, Oauth, etc.), could be `deletion`, `manage_ssh_keys`, `manage_gpg_keys`, `manage_mfa`, `manage_credentials`. This setting is independent from `USER_DISABLED_FEATURES` and supplements its behavior. - - `deletion`: User cannot delete their own account. - - `manage_ssh_keys`: User cannot configure ssh keys. - - `manage_gpg_keys`: User cannot configure gpg keys. - - `manage_mfa`: a User cannot configure mfa devices. - - `manage_credentials`: a user cannot configure emails, passwords, or openid - -## Security (`security`) - -- `INSTALL_LOCK`: **false**: Controls access to the installation page. When set to "true", the installation page is not accessible. -- `SECRET_KEY`: **\**: Global secret key. This key is VERY IMPORTANT, if you lost it, the data encrypted by it (like 2FA secret) can't be decrypted anymore. -- `SECRET_KEY_URI`: **_empty_**: Instead of defining SECRET_KEY, this option can be used to use the key stored in a file (example value: `file:/etc/gitea/secret_key`). It shouldn't be lost like SECRET_KEY. -- `LOGIN_REMEMBER_DAYS`: **31**: How long to remember that a user is logged in before requiring relogin (in days). -- `COOKIE_REMEMBER_NAME`: **gitea\_incredible**: Name of cookie used to store authentication - information. -- `REVERSE_PROXY_AUTHENTICATION_USER`: **X-WEBAUTH-USER**: Header name for reverse proxy - authentication. -- `REVERSE_PROXY_AUTHENTICATION_EMAIL`: **X-WEBAUTH-EMAIL**: Header name for reverse proxy - authentication provided email. -- `REVERSE_PROXY_AUTHENTICATION_FULL_NAME`: **X-WEBAUTH-FULLNAME**: Header name for reverse proxy - authentication provided full name. -- `REVERSE_PROXY_LIMIT`: **1**: Interpret X-Forwarded-For header or the X-Real-IP header and set this as the remote IP for the request. - Number of trusted proxy count. Set to zero to not use these headers. -- `REVERSE_PROXY_TRUSTED_PROXIES`: **127.0.0.0/8,::1/128**: List of IP addresses and networks separated by comma of trusted proxy servers. Use `*` to trust all. -- `DISABLE_GIT_HOOKS`: **true**: Set to `false` to enable users with Git Hook privilege to create custom Git Hooks. - WARNING: Custom Git Hooks can be used to perform arbitrary code execution on the host operating system. - This enables the users to access and modify this config file and the Gitea database and interrupt the Gitea service. - By modifying the Gitea database, users can gain Gitea administrator privileges. - It also enables them to access other resources available to the user on the operating system that is running the - Gitea instance and perform arbitrary actions in the name of the Gitea OS user. - This maybe harmful to you website or your operating system. - Setting this to true does not change existing hooks in git repos; adjust it before if necessary. -- `DISABLE_WEBHOOKS`: **false**: Set to `true` to disable webhooks feature. -- `ONLY_ALLOW_PUSH_IF_GITEA_ENVIRONMENT_SET`: **true**: Set to `false` to allow local users to push to gitea-repositories without setting up the Gitea environment. This is not recommended and if you want local users to push to Gitea repositories you should set the environment appropriately. -- `IMPORT_LOCAL_PATHS`: **false**: Set to `false` to prevent all users (including admin) from importing local path on server. -- `INTERNAL_TOKEN`: **\**: Secret used to validate communication within Gitea binary. -- `INTERNAL_TOKEN_URI`: **_empty_**: Instead of defining INTERNAL_TOKEN in the configuration, this configuration option can be used to give Gitea a path to a file that contains the internal token (example value: `file:/etc/gitea/internal_token`) -- `PASSWORD_HASH_ALGO`: **pbkdf2**: The hash algorithm to use \[argon2, pbkdf2, pbkdf2_v1, pbkdf2_hi, scrypt, bcrypt\], argon2 and scrypt will spend significant amounts of memory. - - Note: The default parameters for `pbkdf2` hashing have changed - the previous settings are available as `pbkdf2_v1` but are not recommended. - - The hash functions may be tuned by using `$` after the algorithm: - - `argon2$