Compare commits

..
9 Commits
Author SHA1 Message Date
Giteabotandsilverwind 4be850fef8 fix(gpg): verify OpenPGP v6 commit signatures (#40631) (#40646)
Backport #40631 by @silverwind

Commit verification skipped the salt that OpenPGP v6 signatures (RFC
9580) hash before the data, so v6-signed commits never verified. Use
go-crypto's `PrepareVerify`, which adds it. Post-quantum ML-DSA
signatures (RFC 9980) require v6 keys, so they now verify too.

Assisted-by: Claude Code:claude-opus-5-5

Co-authored-by: silverwind <me@silverwind.io>
2026-12-04 08:06:07 +00:00
wxiaoguangandsilverwind 41b3d0d4e3 fix: make FormStrings parse form data correctly (#40558) (#40560)
backport #40558

---------

Co-authored-by: silverwind <me@silverwind.io>
2026-11-27 12:53:45 +00:00
1cadf5338b fix(glob): treat escaped characters as literals (#40516) (#40561)
Backport #40516 by @karnati-praveen

The glob compiler wrote a backslash followed by the escaped character
into the generated regexp, so `\d`, `\w`, `\s` and `\b` were parsed as
regexp constructs instead of the literal character. `a\d` compiled to
`^a\d$` and matched "a5" instead of "ad"; `a\b` became a zero-width word
boundary. Escaping a character Go does not recognise, e.g. `\C`, made
the pattern fail to compile, and protected branch rules then fell back
to matching the raw rule text literally.

Escape only ASCII punctuation, which Go always reads as a literal, and
write letters, digits and non-ASCII characters as-is. This matches
gobwas/glob and act. Rules that relied on `\d` matching a digit since
https://github.com/go-gitea/gitea/pull/35478 now match a literal `d`.

Assisted-by: OpenCode (DeepSeek V4.1 Flash)
Assisted-by: Claude Code:claude-opus-5-5

Co-authored-by: karnati praveen <karnatipraveen17@gmail.com>
Co-authored-by: silverwind <me@silverwind.io>
2026-11-27 12:53:17 +00:00
bircni 38ce87a77e chore: stop accepting security reports by mail (#40544) (#40545)
Backport of https://github.com/go-gitea/gitea/pull/40544

The volume of reports sent to `security@gitea.io` can no longer be
handled, so vulnerability reports are now only accepted through GitHub
security advisories. The security policy says so explicitly, and the
README, contributing guide and issue templates point to the advisory
form instead of the mail address.

The address stays for security matters that are not vulnerability
reports, such as questions about the policy or coordinating the
disclosure of an existing advisory.
2026-11-26 14:43:13 +00:00
Giteabotandsilverwind 2d84f79e3b perf: avoid commit status summary full table scan (#40451) (#40459)
Backport #40451 by @silverwind

The dashboard repo list read the entire `commit_status_summary` table on
every load when the page held an empty repo and the other repos'
statuses were cached, about 1.2 s with 1M rows. Those other repos also
showed and cached the status of an arbitrary older commit.

Also fixes the MySQL upsert not updating `target_url`.

Assisted-by: Claude Code:claude-opus-5-5

Co-authored-by: silverwind <me@silverwind.io>
2026-11-20 11:41:12 +00:00
62e9f747e8 fix(web): redirect to the branch after applying a patch (#40450) (#40455)
Backport #40450 by @lazerg

After applying a patch in the web editor, Gitea redirected to
`/src/branch/<branch>/__dummy_for_EditRepoFileForm.TreePath(Required)__`,
which is a 404. The patch form only sends that placeholder `tree_path`
to pass form validation, but the handler still used it as the redirect
path. It now redirects to the branch root, like cherry-pick and revert
do.

Fixes: https://github.com/go-gitea/gitea/issues/40449

Assisted-by: Claude Code:claude-opus-5-5

Co-authored-by: Lazizbek Ergashev <lazerg2@gmail.com>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
2026-11-20 10:20:35 +00:00
93ae5fb35b fix(routing): remove unsynchronized write in GetFuncInfo (#40409) (#40421)
Backport #40409 by @lazerg

`GetFuncInfo` wrote the friendly name into `funcInfoNameMap` once
without holding `funcInfoMapMu`, right before the same locked write.
Concurrent requests hitting that branch could then crash the process
with `fatal error: concurrent map writes`. This drops the unlocked
write.

Fixes: https://github.com/go-gitea/gitea/issues/40407

Assisted-by: Claude Code:claude-opus-5-5

Co-authored-by: Lazizbek Ergashev <lazerg2@gmail.com>
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2026-11-17 23:33:05 +00:00
f8c4012ab8 fix(migrations): wait out GitHub rate limits and tolerate failed patch downloads (#40012) (#40397)
Backport https://github.com/go-gitea/gitea/pull/40012

Large GitHub migrations failed once the API budget ran out. A rejected
request never updated the downloader's rate state, so go-github refused
every retry locally.

- Record the rate limit from error responses too, so the next request
waits for the reset
- Retry repository-wide comment pages like the other downloader calls
- Stop `waitAndPickClient` spinning when the rate refresh fails
- Skip reaction requests when the reaction rollup reports none
- Log a failed patch download instead of failing the migration

Assisted-by: Claude Code:claude-opus-5-5

Co-authored-by: Phoenix <44333391+yuhongwei380@users.noreply.github.com>
Co-authored-by: bircni <bircni@icloud.com>
Co-authored-by: Giteabot <teabot@gitea.io>
2026-11-17 20:26:49 +00:00
silverwind a0f0c937c4 fix(packages): replace blakesmith/ar with an in-tree reader (#40401) (#40410)
Backport https://github.com/go-gitea/gitea/pull/40401

https://github.com/blakesmith/ar is unmaintained since 2019 and panics
on a negative member size (https://pkg.go.dev/vuln/GO-2026-6905), with
no fixed version. Debian packages only need a small subset of the `ar`
format, so this reads it in-tree.

- Malformed or truncated archives are rejected with a 400 instead of a
500 or a panic
- Parsing stops after the first `control.tar` member, deb(5) allows only
one

Assisted-by: Claude Code:claude-opus-5-5
2026-11-17 05:17:20 +00:00
35 changed files with 453 additions and 201 deletions

No files matched your search

+1 -1
View File
@@ -5,7 +5,7 @@ body:
- type: markdown
attributes:
value: |
- **Security issue?** Email security@gitea.io instead of opening a public issue.
- **Security issue?** Open a [security advisory](https://github.com/go-gitea/gitea/security/advisories/new) instead of a public issue.
- **Need help** with setup or configuration? Ask on [Discord](https://discord.gg/Gitea) or the [forum](https://forum.gitea.com).
- Search [existing issues](https://github.com/go-gitea/gitea/issues?q=is%3Aissue) first.
- type: input
+2 -2
View File
@@ -1,8 +1,8 @@
blank_issues_enabled: false
contact_links:
- name: Security Concern
url: https://tinyurl.com/security-gitea
about: For security concerns, please send a mail to security@gitea.io instead of opening a public issue.
url: https://github.com/go-gitea/gitea/security/advisories/new
about: Please report vulnerabilities privately through a GitHub security advisory instead of opening a public issue.
- name: Discord Server
url: https://discord.gg/Gitea
about: Please ask questions and discuss configuration or deployment problems here.
+2 -2
View File
@@ -46,7 +46,7 @@ This document explains how to contribute changes to the Gitea project. Topic-spe
## Introduction
It assumes you have followed the [installation instructions](https://docs.gitea.com/category/installation). \
Sensitive security-related issues should be reported to [security@gitea.io](mailto:security@gitea.io).
Sensitive security-related issues should be reported through a [GitHub security advisory](https://github.com/go-gitea/gitea/security/advisories/new), see the [security policy](SECURITY.md).
For configuring IDEs for Gitea development, see the [IDE setup notes](docs/development.md#ide-configuration) and the [contributed configurations](contrib/development/).
@@ -85,7 +85,7 @@ Please be kind—remember that Gitea comes at no cost to you, and you're getting
Typically, issues fall in one of the following categories:
- `bug`: Something in the frontend or backend behaves unexpectedly
- `security issue`: bug that has serious implications such as leaking another users data. Please do not file such issues on the public tracker and send a mail to security@gitea.io instead
- `security issue`: bug that has serious implications such as leaking another users data. Please do not file such issues on the public tracker and open a [GitHub security advisory](https://github.com/go-gitea/gitea/security/advisories/new) instead
- `feature`: Completely new functionality. You should describe this feature in enough detail that anyone who reads the issue can understand how it is supposed to be implemented
- `enhancement`: An existing feature should get an upgrade
- `refactoring`: Parts of the code base don't conform with other parts and should be changed to improve Gitea's maintainability
+1 -1
View File
@@ -54,7 +54,7 @@ Expected workflow is: Fork -> Patch -> Push -> Pull Request
>
> 1. **YOU MUST READ THE [CONTRIBUTORS GUIDE](CONTRIBUTING.md) BEFORE STARTING TO WORK ON A PULL REQUEST.**
> 2. New to the codebase? The [development guide](docs/development.md) walks through setting up a local environment and building from source.
> 3. If you have found a vulnerability in the project, please write privately to **security@gitea.io**. Thanks!
> 3. If you have found a vulnerability in the project, please report it privately through a [GitHub security advisory](https://github.com/go-gitea/gitea/security/advisories/new), see the [security policy](SECURITY.md). Thanks!
## Translating
+1 -1
View File
@@ -62,7 +62,7 @@
> [!注意]
>
> 1. **在开始进行 Pull Request 之前,您必须阅读 [贡献者指南](CONTRIBUTING.md)。**
> 2. 如果您在项目中发现了漏洞,请私下写信给 **security@gitea.io**。谢谢!
> 2. 如果您在项目中发现了漏洞,请通过 [GitHub 安全公告](https://github.com/go-gitea/gitea/security/advisories/new) 私下报告,详见[安全策略](SECURITY.md)。谢谢!
## 翻译
+1 -1
View File
@@ -62,7 +62,7 @@
> [!注意]
>
> 1. **在開始進行 Pull Request 之前,您必須閱讀 [貢獻者指南](CONTRIBUTING.md)。**
> 2. 如果您在項目中發現了漏洞,請私下寫信給 **security@gitea.io**。謝謝!
> 2. 如果您在項目中發現了漏洞,請透過 [GitHub 安全公告](https://github.com/go-gitea/gitea/security/advisories/new) 私下回報,詳見[安全政策](SECURITY.md)。謝謝!
## 翻譯
+4 -3
View File
@@ -14,15 +14,16 @@ Reports must be filed against a supported version. Before reporting, verify that
## Reporting a Vulnerability
Please **DO NOT** file a public issue. Instead, report the vulnerability privately by opening a [GitHub security advisory](https://github.com/go-gitea/gitea/security/advisories/new), or optionally by sending your report to `security@gitea.io`.
If reporting via GitHub, open an advisory per found issue. You can group the found issues if they relate to a single area (same feature, same fault present in multiple routes) but do not group unrelated reports into one as it makes it much harder to assess and track for duplicates.
Please **DO NOT** file a public issue. Instead, report the vulnerability privately by opening a [GitHub security advisory](https://github.com/go-gitea/gitea/security/advisories/new).
Due to the high volume of reports, we can no longer handle submissions by mail: reports sent by mail are not accepted and will not be processed. `security@gitea.io` is only for security matters that are not vulnerability reports, such as questions about this policy or coordinating the disclosure of an existing advisory.
Open an advisory per found issue. You can group the found issues if they relate to a single area (same feature, same fault present in multiple routes) but do not group unrelated reports into one as it makes it much harder to assess and track for duplicates.
Do not use LLM to write the reports. It's meant for people to read so take your time and use your own words to write it. If you have used LLM to find the bug, be transparent about it and verify that it is not hallucination before submitting the report.
If your report turns out to be a duplicate, you will be credited in the original report.
## Protecting Security Information
Due to the sensitive nature of security information, you can use the below GPG public key to encrypt your mail body.
Vulnerability details belong in the GitHub security advisory, not in a mail. If you need to send other sensitive information to `security@gitea.io`, you can use the below GPG public key to encrypt your mail body.
The PGP key is valid until July 23, 2027.
-5
View File
@@ -139,11 +139,6 @@
"path": "github.com/bits-and-blooms/bitset/LICENSE",
"licenseText": "Copyright (c) 2014 the bitset authors. All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n * Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above\ncopyright notice, this list of conditions and the following disclaimer\nin the documentation and/or other materials provided with the\ndistribution.\n * Neither the name of Google Inc. nor the names of its\ncontributors may be used to endorse or promote products derived from\nthis software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
},
{
"name": "github.com/blakesmith/ar",
"path": "github.com/blakesmith/ar/COPYING",
"licenseText": "Copyright (c) 2013 Blake Smith \u003cblakesmith0@gmail.com\u003e\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\n"
},
{
"name": "github.com/blevesearch/bleve/v2",
"path": "github.com/blevesearch/bleve/v2/LICENSE",
-1
View File
@@ -22,7 +22,6 @@ require (
github.com/PuerkitoBio/goquery v1.13.0
github.com/SaveTheRbtz/zstd-seekable-format-go/pkg v0.10.0
github.com/alecthomas/chroma/v2 v2.27.0
github.com/blakesmith/ar v0.0.0-20190502131153-809d4375e1fb
github.com/blevesearch/bleve/v2 v2.6.1
github.com/bohde/codel v0.2.0
github.com/buildkite/terminal-to-html/v3 v3.17.1
-2
View File
@@ -85,8 +85,6 @@ github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/bits-and-blooms/bitset v1.24.5 h1:654xBVHc23gJMAgOTkPNoCVfiRxuIOAUnAZFtopqJ4w=
github.com/bits-and-blooms/bitset v1.24.5/go.mod h1:7hO7Gc7Pp1vODcmWvKMRA9BNmbv6a/7QIWpPxHddWR8=
github.com/blakesmith/ar v0.0.0-20190502131153-809d4375e1fb h1:m935MPodAbYS46DG4pJSv7WO+VECIWUQ7OJYSoTrMh4=
github.com/blakesmith/ar v0.0.0-20190502131153-809d4375e1fb/go.mod h1:PkYb9DJNAwrSvRx5DYA+gUcOIgTGVMNkfSCbZM8cWpI=
github.com/blevesearch/bleve/v2 v2.6.1 h1:47vLskRTqxvQEtxVPYHjf5KpOgzD2msslXFjvUQCgWQ=
github.com/blevesearch/bleve/v2 v2.6.1/go.mod h1:Dvvx6ZoEBTOj6RSzfk0lEz0wce/qhe2yOUubXeuzd2c=
github.com/blevesearch/bleve_index_api v1.4.1 h1:CYIyecFlI+/RYjzUm+NmDjYbSvk870Bb7f+Vl4b12q8=
@@ -65,7 +65,7 @@ func verifySign(s *packet.Signature, h hash.Hash, k *GPGKey) error {
func hashAndVerify(sig *packet.Signature, payload string, k *GPGKey) (*GPGKey, error) {
// Generating hash of commit
hash, err := populateHash(sig.Hash, []byte(payload))
hash, err := populateHash(sig, []byte(payload))
if err != nil { // Skipping as failed to generate hash
log.Error("PopulateHash: %v", err)
return nil, err
+5 -3
View File
@@ -5,7 +5,6 @@ package asymkey
import (
"bytes"
"crypto"
"encoding/base64"
"errors"
"fmt"
@@ -100,8 +99,11 @@ func getExpiryTime(e *openpgp.Entity) time.Time {
return expiry
}
func populateHash(hashFunc crypto.Hash, msg []byte) (hash.Hash, error) {
h := hashFunc.New()
func populateHash(sig *packet.Signature, msg []byte) (hash.Hash, error) {
h, err := sig.PrepareVerify()
if err != nil {
return nil, err
}
if _, err := h.Write(msg); err != nil {
return nil, err
}
+15 -2
View File
@@ -4,6 +4,7 @@
package asymkey
import (
"strings"
"testing"
"time"
@@ -181,9 +182,9 @@ Unknown GPG key with good email
assert.NoError(t, err, "Could not parse a valid GPG armored signature", testBadSigArmor)
// Generating hash of commit
goodHash, err := populateHash(goodSig.Hash, []byte(testGoodPayload))
goodHash, err := populateHash(goodSig, []byte(testGoodPayload))
assert.NoError(t, err, "Could not generate a valid hash of payload", testGoodPayload)
badHash, err := populateHash(badSig.Hash, []byte(testBadPayload))
badHash, err := populateHash(badSig, []byte(testBadPayload))
assert.NoError(t, err, "Could not generate a valid hash of payload", testBadPayload)
// Verify
@@ -193,6 +194,18 @@ Unknown GPG key with good email
assert.Error(t, err, "Validate a bad signature")
err = verifySign(goodSig, goodHash, cannotsignkey)
assert.Error(t, err, "Validate a bad signature with a kay that can not sign")
v6Entity, err := openpgp.NewEntity("v6", "", "v6@example.com", &packet.Config{V6Keys: true, Algorithm: packet.PubKeyAlgoMldsa65Ed25519})
require.NoError(t, err)
var v6SigArmor strings.Builder
require.NoError(t, openpgp.ArmoredDetachSign(&v6SigArmor, v6Entity, strings.NewReader(testGoodPayload), nil))
v6Sig, err := ExtractSignature(v6SigArmor.String())
require.NoError(t, err)
v6Content, err := Base64EncPubKey(v6Entity.PrimaryKey)
require.NoError(t, err)
v6Hash, err := populateHash(v6Sig, []byte(testGoodPayload))
require.NoError(t, err)
assert.NoError(t, verifySign(v6Sig, v6Hash, &GPGKey{Content: v6Content, CanSign: true}))
}
func TestCheckGPGUserEmail(t *testing.T) {
+5 -2
View File
@@ -32,6 +32,9 @@ type RepoSHA struct {
}
func GetLatestCommitStatusForRepoAndSHAs(ctx context.Context, repoSHAs []RepoSHA) ([]*CommitStatus, error) {
if len(repoSHAs) == 0 {
return nil, nil
}
cond := builder.NewCond()
for _, rs := range repoSHAs {
cond = cond.Or(builder.Eq{"repo_id": rs.RepoID, "sha": rs.SHA})
@@ -67,8 +70,8 @@ func UpdateCommitStatusSummary(ctx context.Context, repoID int64, sha string) er
// mysql will return 0 when update a record which state hasn't been changed which behaviour is different from other database,
// so we need to use insert in on duplicate
if setting.Database.Type.IsMySQL() {
_, err := db.GetEngine(ctx).Exec("INSERT INTO commit_status_summary (repo_id,sha,state,target_url) VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE state=?",
repoID, sha, state.State, state.TargetURL, state.State)
_, err := db.GetEngine(ctx).Exec("INSERT INTO commit_status_summary (repo_id,sha,state,target_url) VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE state=?, target_url=?",
repoID, sha, state.State, state.TargetURL, state.State, state.TargetURL)
return err
}
+7
View File
@@ -89,6 +89,13 @@ func TestGetCommitStatuses(t *testing.T) {
"deploy/awesomeness": 5,
}, latestIndexes)
})
t.Run("GetLatestCommitStatusForRepoAndSHAsEmpty", func(t *testing.T) {
assert.NoError(t, git_model.UpdateCommitStatusSummary(t.Context(), repo1.ID, sha1))
statuses, err := git_model.GetLatestCommitStatusForRepoAndSHAs(t.Context(), nil)
assert.NoError(t, err)
assert.Empty(t, statuses)
})
}
func Test_CalcCommitStatus(t *testing.T) {
+11 -4
View File
@@ -9,6 +9,7 @@ import (
"regexp"
"slices"
"strings"
"unicode"
"gitea.dev/modules/util"
)
@@ -35,6 +36,14 @@ type globCompiler struct {
negativeFlip bool
}
// writeLiteral escapes only ASCII punctuation, an escaped letter like \d is a regexp class
func (g *globCompiler) writeLiteral(r rune) {
if r <= unicode.MaxASCII && !unicode.IsLetter(r) && !unicode.IsDigit(r) {
g.builder.WriteByte('\\')
}
g.builder.WriteRune(r)
}
// compileChars compiles character class patterns like [abc] or [!abc]
func (g *globCompiler) compileChars() error {
g.builder.WriteByte('[')
@@ -56,8 +65,7 @@ func (g *globCompiler) compileChars() error {
if g.pos >= len(g.globPattern) {
return errors.New("unterminated character class escape")
}
g.builder.WriteByte('\\')
g.builder.WriteRune(g.globPattern[g.pos])
g.writeLiteral(g.globPattern[g.pos])
g.pos++
} else {
g.builder.WriteRune(c)
@@ -135,8 +143,7 @@ func (g *globCompiler) compile(subPattern bool) error {
if g.pos >= len(g.globPattern) {
return errors.New("no character to escape")
}
g.builder.WriteByte('\\')
g.builder.WriteRune(g.globPattern[g.pos])
g.writeLiteral(g.globPattern[g.pos])
g.pos++
case '.', '^', '$', '(', ')', '|':
g.builder.WriteByte('\\')
+3
View File
@@ -90,6 +90,9 @@ func TestGlob(t *testing.T) {
glob(true, "?at", "fat"),
glob(true, "*", "abc"),
glob(true, `\*`, "*"),
glob(true, `a\d`, "ad"),
glob(true, `[\d]`, "d"),
glob(false, `[a\-z]`, "m"),
glob(true, "**", "a.b.c", '.'),
glob(false, "?at", "at"),
+15
View File
@@ -154,6 +154,21 @@ func (d *RetryDownloader) GetComments(ctx context.Context, commentable Commentab
return comments, isEnd, err
}
func (d *RetryDownloader) GetAllComments(ctx context.Context, page, perPage int) ([]*Comment, bool, error) {
var (
comments []*Comment
isEnd bool
err error
)
err = d.retry(ctx, func(ctx context.Context) error {
comments, isEnd, err = d.Downloader.GetAllComments(ctx, page, perPage)
return err
})
return comments, isEnd, err
}
// GetPullRequests returns a repository's pull requests with retry
func (d *RetryDownloader) GetPullRequests(ctx context.Context, page, perPage int) ([]*PullRequest, bool, error) {
var (
@@ -0,0 +1,29 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package migration
import (
"context"
"errors"
"testing"
"github.com/stretchr/testify/assert"
)
type failingCommentsDownloader struct {
NullDownloader
attempts int
}
func (d *failingCommentsDownloader) GetAllComments(_ctx context.Context, _page, _perPage int) ([]*Comment, bool, error) {
d.attempts++
return nil, false, errors.New("permission denied")
}
func TestRetryDownloaderExhaustsAttempts(t *testing.T) {
source := &failingCommentsDownloader{}
_, _, err := NewRetryDownloader(source, 3, 0).GetAllComments(t.Context(), 1, 50)
assert.EqualError(t, err, "permission denied")
assert.Equal(t, 3, source.attempts)
}
+43
View File
@@ -0,0 +1,43 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package debian
import (
"io"
"strconv"
"strings"
"gitea.dev/modules/util"
)
const arMagic = "!<arch>\n"
type arReader struct {
io.LimitedReader
pad int64
}
func newArReader(r io.Reader) (*arReader, error) {
var magic [len(arMagic)]byte
if _, err := io.ReadFull(r, magic[:]); err != nil || string(magic[:]) != arMagic {
return nil, GlobalVars().ErrInvalidArchive
}
return &arReader{LimitedReader: io.LimitedReader{R: r}}, nil
}
func (ar *arReader) next() (string, error) {
if _, err := io.CopyN(io.Discard, ar.R, ar.N+ar.pad); err != nil {
return "", GlobalVars().ErrInvalidArchive
}
var header [60]byte
if _, err := io.ReadFull(ar.R, header[:]); err != nil {
return "", util.Iif(err == io.EOF, err, GlobalVars().ErrInvalidArchive)
}
size, err := strconv.ParseInt(strings.TrimRight(string(header[48:58]), " "), 10, 64)
if err != nil || size < 0 || string(header[58:]) != "`\n" {
return "", GlobalVars().ErrInvalidArchive
}
ar.N, ar.pad = size, size%2
return strings.TrimSuffix(strings.TrimRight(string(header[:16]), " "), "/"), nil // GNU ar terminates names with a slash
}
+10 -8
View File
@@ -17,7 +17,6 @@ import (
"gitea.dev/modules/validation"
"gitea.dev/modules/zstd"
"github.com/blakesmith/ar"
"github.com/ulikunitz/xz"
)
@@ -38,6 +37,7 @@ const (
)
var GlobalVars = sync.OnceValue(func() (ret struct {
ErrInvalidArchive error
ErrMissingControlFile error
ErrUnsupportedCompression error
ErrInvalidName error
@@ -49,6 +49,7 @@ var GlobalVars = sync.OnceValue(func() (ret struct {
symbolPattern *regexp.Regexp
},
) {
ret.ErrInvalidArchive = util.NewInvalidArgumentErrorf("package archive is invalid")
ret.ErrMissingControlFile = util.NewInvalidArgumentErrorf("control file is missing")
ret.ErrUnsupportedCompression = util.NewInvalidArgumentErrorf("unsupported compression algorithm")
ret.ErrInvalidName = util.NewInvalidArgumentErrorf("package name is invalid")
@@ -90,10 +91,13 @@ func IsValidDistributionOrComponent(s string) bool {
// ParsePackage parses the Debian package file
// https://manpages.debian.org/bullseye/dpkg-dev/deb.5.en.html
func ParsePackage(r io.Reader) (*Package, error) {
arr := ar.NewReader(r)
arr, err := newArReader(r)
if err != nil {
return nil, err
}
for {
hd, err := arr.Next()
name, err := arr.next()
if err == io.EOF {
break
}
@@ -101,11 +105,9 @@ func ParsePackage(r io.Reader) (*Package, error) {
return nil, err
}
if strings.HasPrefix(hd.Name, controlTar) {
if strings.HasPrefix(name, controlTar) {
var inner io.Reader
// https://man7.org/linux/man-pages/man5/deb-split.5.html#FORMAT
// The file names might contain a trailing slash (since dpkg 1.15.6).
switch strings.TrimSuffix(hd.Name[len(controlTar):], "/") {
switch name[len(controlTar):] {
case "":
inner = arr
case ".gz":
@@ -142,7 +144,7 @@ func ParsePackage(r io.Reader) (*Package, error) {
for {
hd, err := tr.Next()
if err == io.EOF {
break
return nil, GlobalVars().ErrMissingControlFile
}
if err != nil {
return nil, err
+32 -50
View File
@@ -7,13 +7,14 @@ import (
"archive/tar"
"bytes"
"compress/gzip"
"fmt"
"io"
"strings"
"testing"
"gitea.dev/modules/util"
"gitea.dev/modules/zstd"
"github.com/blakesmith/ar"
"github.com/stretchr/testify/assert"
"github.com/ulikunitz/xz"
)
@@ -28,49 +29,39 @@ const (
)
func TestParsePackage(t *testing.T) {
createArchive := func(files map[string][]byte) io.Reader {
var buf bytes.Buffer
aw := ar.NewWriter(&buf)
aw.WriteGlobalHeader()
for filename, content := range files {
hdr := &ar.Header{
Name: filename,
Mode: 0o600,
Size: int64(len(content)),
}
aw.WriteHeader(hdr)
aw.Write(content)
}
return &buf
member := func(name, content string) string {
return fmt.Sprintf("%-48s%-10d`\n%s%s", name, len(content), content, strings.Repeat("\n", len(content)%2))
}
debianBinary := member("debian-binary", "2.0\n")
t.Run("MissingControlFile", func(t *testing.T) {
data := createArchive(map[string][]byte{"dummy.txt": {}})
var buf bytes.Buffer
tw := tar.NewWriter(&buf)
tw.WriteHeader(&tar.Header{
Name: "control",
Mode: 0o600,
Size: 50,
})
tw.Write([]byte("Package: gitea\nVersion: 1.0.0\nArchitecture: amd64\n"))
tw.Close()
p, err := ParsePackage(data)
assert.Nil(t, p)
assert.ErrorIs(t, err, GlobalVars().ErrMissingControlFile)
t.Run("Invalid", func(t *testing.T) {
for data, expected := range map[string]error{
"!<ARCH>\n" + debianBinary: GlobalVars().ErrInvalidArchive,
arMagic + debianBinary[:20]: GlobalVars().ErrInvalidArchive,
arMagic + debianBinary[:62]: GlobalVars().ErrInvalidArchive,
arMagic + member("control.tar", "")[:58] + "\n\n": GlobalVars().ErrInvalidArchive,
arMagic + fmt.Sprintf("%-48s%-10d`\n", "control.tar", -1): GlobalVars().ErrInvalidArchive,
arMagic + member("dummy.txt", "x"): GlobalVars().ErrMissingControlFile,
arMagic + member("control.tar", "") + member("control.tar", buf.String()): GlobalVars().ErrMissingControlFile,
arMagic + member("control.tar.foo", ""): GlobalVars().ErrUnsupportedCompression,
} {
p, err := ParsePackage(strings.NewReader(data))
assert.Nil(t, p)
assert.ErrorIs(t, err, expected, "%q", data)
}
})
t.Run("Compression", func(t *testing.T) {
t.Run("Unsupported", func(t *testing.T) {
data := createArchive(map[string][]byte{"control.tar.foo": {}})
p, err := ParsePackage(data)
assert.Nil(t, p)
assert.ErrorIs(t, err, GlobalVars().ErrUnsupportedCompression)
})
var buf bytes.Buffer
tw := tar.NewWriter(&buf)
tw.WriteHeader(&tar.Header{
Name: "control",
Mode: 0o600,
Size: 50,
})
tw.Write([]byte("Package: gitea\nVersion: 1.0.0\nArchitecture: amd64\n"))
tw.Close()
cases := []struct {
Extension string
WriterFactory func(io.Writer) io.WriteCloser
@@ -110,21 +101,12 @@ func TestParsePackage(t *testing.T) {
w.Write(buf.Bytes())
w.Close()
data := createArchive(map[string][]byte{"control.tar" + c.Extension: cbuf.Bytes()})
p, err := ParsePackage(data)
assert.NotNil(t, p)
assert.NoError(t, err)
assert.Equal(t, "gitea", p.Name)
t.Run("TrailingSlash", func(t *testing.T) {
data := createArchive(map[string][]byte{"control.tar" + c.Extension + "/": cbuf.Bytes()})
p, err := ParsePackage(data)
for _, suffix := range []string{"", "/"} {
p, err := ParsePackage(strings.NewReader(arMagic + debianBinary + member("control.tar"+c.Extension+suffix, cbuf.String())))
assert.NotNil(t, p)
assert.NoError(t, err)
assert.Equal(t, "gitea", p.Name)
})
}
})
}
})
-1
View File
@@ -62,7 +62,6 @@ func GetFuncInfo(fn any, friendlyName ...string) *FuncInfo {
info = copyFuncInfo(info)
info.shortName = name
funcInfoNameMap[name] = info
funcInfoMapMu.Lock()
funcInfoNameMap[name] = info
funcInfoMapMu.Unlock()
+1 -1
View File
@@ -48,5 +48,5 @@ func NewDiffPatchPost(ctx *context.Context) {
editorHandleFileOperationError(ctx, parsed.NewBranchName, err)
return
}
redirectForCommitChoice(ctx, parsed, parsed.form.TreePath)
redirectForCommitChoice(ctx, parsed, "")
}
+1 -1
View File
@@ -79,5 +79,5 @@ func CherryPickPost(ctx *context.Context) {
return
}
}
redirectForCommitChoice(ctx, parsed, parsed.form.TreePath)
redirectForCommitChoice(ctx, parsed, "")
}
+2 -9
View File
@@ -25,15 +25,8 @@ func (b *Base) FormString(key string, def ...string) string {
// FormStrings returns a values for the key in the form (including query parameters), similar to FormString
func (b *Base) FormStrings(key string) []string {
if b.Req.Form == nil {
if err := b.Req.ParseMultipartForm(32 << 20); err != nil {
return nil
}
}
if v, ok := b.Req.Form[key]; ok {
return v
}
return nil
_ = b.Req.ParseMultipartForm(ParseMultipartFormMaxMemory) // the same logic as http.Request.FormValue
return b.Req.Form[key]
}
func (b *Base) FormStringInt64s(key string) []int64 {
+9
View File
@@ -7,6 +7,7 @@ import (
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"gitea.dev/modules/setting"
@@ -50,3 +51,11 @@ func TestRedirect(t *testing.T) {
assert.JSONEq(t, `{"redirect":"/other"}`, resp.Body.String())
assert.Equal(t, http.StatusOK, resp.Code)
}
func TestFormStrings(t *testing.T) {
req, _ := http.NewRequest(http.MethodPost, "/?q=1", strings.NewReader("oid=a&oid=b"))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
b := NewBaseContextForTest(t, httptest.NewRecorder(), req)
assert.Equal(t, []string{"a", "b"}, b.FormStrings("oid"))
assert.Equal(t, []string{"1"}, b.FormStrings("q"))
}
+7 -8
View File
@@ -505,15 +505,15 @@ func (g *GiteaLocalUploader) CreateComments(ctx context.Context, comments ...*ba
}
case issues_model.CommentTypeChangeTitle:
if comment.Meta["OldTitle"] != nil {
cm.OldTitle = fmt.Sprint(comment.Meta["OldTitle"])
cm.OldTitle = util.TruncateRunes(fmt.Sprint(comment.Meta["OldTitle"]), 255)
}
if comment.Meta["NewTitle"] != nil {
cm.NewTitle = fmt.Sprint(comment.Meta["NewTitle"])
cm.NewTitle = util.TruncateRunes(fmt.Sprint(comment.Meta["NewTitle"]), 255)
}
case issues_model.CommentTypeChangeTargetBranch:
if comment.Meta["OldRef"] != nil && comment.Meta["NewRef"] != nil {
cm.OldRef = fmt.Sprint(comment.Meta["OldRef"])
cm.NewRef = fmt.Sprint(comment.Meta["NewRef"])
cm.OldRef = util.TruncateRunes(fmt.Sprint(comment.Meta["OldRef"]), 255)
cm.NewRef = util.TruncateRunes(fmt.Sprint(comment.Meta["NewRef"]), 255)
cm.Content = ""
}
case issues_model.CommentTypeMergePull:
@@ -581,7 +581,7 @@ func (g *GiteaLocalUploader) updateGitForPullRequest(ctx context.Context, pr *ba
}
// Anonymous function to download the patch file (allows us to use defer)
err = func() error {
if err := func() error {
// if the patchURL is empty there is nothing to download
if pr.PatchURL == "" {
return nil
@@ -607,9 +607,8 @@ func (g *GiteaLocalUploader) updateGitForPullRequest(ctx context.Context, pr *ba
_, err = io.Copy(f, ret)
return err
}()
if err != nil {
return "", err
}(); err != nil { // the patch is only a fallback for a missing head ref
log.Warn("PR #%d in %s/%s: unable to download patch: %v", pr.Number, g.repoOwner, g.repoName, err)
}
head = "unknown repository"
+110 -75
View File
@@ -173,6 +173,7 @@ func (g *GithubDownloaderV3) waitAndPickClient(ctx context.Context) {
err := g.RefreshRate(ctx)
if err != nil {
log.Error("g.getClient().RateLimit.Get: %s", err)
return // the stale reset time is in the past, so looping would spin
}
}
}
@@ -201,14 +202,20 @@ func (g *GithubDownloaderV3) setRate(rate *github.Rate) {
g.rates[g.curClientIdx] = rate
}
func (g *GithubDownloaderV3) setRateFromResponse(resp *github.Response) {
if resp != nil && resp.Rate.Limit > 0 {
g.setRate(&resp.Rate)
}
}
// GetRepoInfo returns a repository information
func (g *GithubDownloaderV3) GetRepoInfo(ctx context.Context) (*base.Repository, error) {
g.waitAndPickClient(ctx)
gr, resp, err := g.getClient().Repositories.Get(ctx, g.repoOwner, g.repoName)
g.setRateFromResponse(resp)
if err != nil {
return nil, err
}
g.setRate(&resp.Rate)
// convert github repo to stand Repo
return &base.Repository{
@@ -227,10 +234,10 @@ func (g *GithubDownloaderV3) GetRepoInfo(ctx context.Context) (*base.Repository,
func (g *GithubDownloaderV3) GetTopics(ctx context.Context) ([]string, error) {
g.waitAndPickClient(ctx)
r, resp, err := g.getClient().Repositories.Get(ctx, g.repoOwner, g.repoName)
g.setRateFromResponse(resp)
if err != nil {
return nil, err
}
g.setRate(&resp.Rate)
return r.Topics, nil
}
@@ -248,10 +255,10 @@ func (g *GithubDownloaderV3) GetMilestones(ctx context.Context) ([]*base.Milesto
PerPage: perPage,
},
})
g.setRateFromResponse(resp)
if err != nil {
return nil, err
}
g.setRate(&resp.Rate)
for _, m := range ms {
state := "open"
@@ -294,10 +301,10 @@ func (g *GithubDownloaderV3) GetLabels(ctx context.Context) ([]*base.Label, erro
Page: i,
PerPage: perPage,
})
g.setRateFromResponse(resp)
if err != nil {
return nil, err
}
g.setRate(&resp.Rate)
for _, label := range ls {
labels = append(labels, convertGithubLabel(label))
@@ -403,10 +410,10 @@ func (g *GithubDownloaderV3) GetReleases(ctx context.Context) ([]*base.Release,
Page: i,
PerPage: perPage,
})
g.setRateFromResponse(resp)
if err != nil {
return nil, err
}
g.setRate(&resp.Rate)
for _, release := range ls {
releases = append(releases, g.convertGithubRelease(ctx, release))
@@ -445,78 +452,102 @@ func (g *GithubDownloaderV3) GetIssues(ctx context.Context, page, perPage int) (
allIssues := make([]*base.Issue, 0, perPage)
g.waitAndPickClient(ctx)
issues, resp, err := g.getClient().Issues.ListByRepo(ctx, g.repoOwner, g.repoName, opt)
g.setRateFromResponse(resp)
if err != nil {
return nil, false, fmt.Errorf("GetIssues: %w", err)
}
log.Trace("Request get issues %d/%d, but in fact get %d", perPage, page, len(issues))
g.setRate(&resp.Rate)
for _, issue := range issues {
if issue.IsPullRequest() {
continue
}
labels := make([]*base.Label, 0, len(issue.Labels))
for _, l := range issue.Labels {
labels = append(labels, convertGithubLabel(l))
converted, err := g.convertGithubIssue(ctx, issue, perPage)
if err != nil {
return nil, false, err
}
// get reactions
var reactions []*base.Reaction
if !g.SkipReactions {
for i := 1; ; i++ {
g.waitAndPickClient(ctx)
res, resp, err := g.getClient().Reactions.ListIssueReactions(ctx, g.repoOwner, g.repoName, issue.GetNumber(), &github.ListReactionOptions{
ListOptions: github.ListOptions{
Page: i,
PerPage: perPage,
},
})
if err != nil {
return nil, false, err
}
g.setRate(&resp.Rate)
if len(res) == 0 {
break
}
for _, reaction := range res {
reactions = append(reactions, &base.Reaction{
UserID: reaction.User.GetID(),
UserName: reaction.User.GetLogin(),
Content: reaction.GetContent(),
})
}
}
}
var assignees []string
for i := range issue.Assignees {
assignees = append(assignees, issue.Assignees[i].GetLogin())
}
allIssues = append(allIssues, &base.Issue{
Title: *issue.Title,
Number: int64(*issue.Number),
PosterID: issue.GetUser().GetID(),
PosterName: issue.GetUser().GetLogin(),
PosterEmail: issue.GetUser().GetEmail(),
Content: issue.GetBody(),
Milestone: issue.GetMilestone().GetTitle(),
State: issue.GetState(),
Created: issue.GetCreatedAt().Time,
Updated: issue.GetUpdatedAt().Time,
Labels: labels,
Reactions: reactions,
Closed: issue.ClosedAt.GetTime(),
IsLocked: issue.GetLocked(),
Assignees: assignees,
ForeignIndex: int64(*issue.Number),
})
allIssues = append(allIssues, converted)
}
g.issuePage, g.issueCursor, g.nextIssueCursor = page, opt.After, resp.After
return allIssues, resp.NextPage == 0 && resp.After == "", nil
}
func (g *GithubDownloaderV3) convertGithubIssue(ctx context.Context, issue *github.Issue, perPage int) (*base.Issue, error) {
labels := make([]*base.Label, 0, len(issue.Labels))
for _, l := range issue.Labels {
labels = append(labels, convertGithubLabel(l))
}
// get reactions
var reactions []*base.Reaction
if !g.SkipReactions && (issue.Reactions == nil || issue.Reactions.TotalCount == nil || issue.Reactions.GetTotalCount() > 0) {
for i := 1; ; i++ {
g.waitAndPickClient(ctx)
res, resp, err := g.getClient().Reactions.ListIssueReactions(ctx, g.repoOwner, g.repoName, issue.GetNumber(), &github.ListReactionOptions{
ListOptions: github.ListOptions{
Page: i,
PerPage: perPage,
},
})
g.setRateFromResponse(resp)
if err != nil {
return nil, err
}
if len(res) == 0 {
break
}
for _, reaction := range res {
reactions = append(reactions, &base.Reaction{
UserID: reaction.User.GetID(),
UserName: reaction.User.GetLogin(),
Content: reaction.GetContent(),
})
}
}
}
var assignees []string
for i := range issue.Assignees {
assignees = append(assignees, issue.Assignees[i].GetLogin())
}
return &base.Issue{
Title: issue.GetTitle(),
Number: int64(issue.GetNumber()),
PosterID: issue.GetUser().GetID(),
PosterName: issue.GetUser().GetLogin(),
PosterEmail: issue.GetUser().GetEmail(),
Content: issue.GetBody(),
Milestone: issue.GetMilestone().GetTitle(),
State: issue.GetState(),
Created: issue.GetCreatedAt().Time,
Updated: issue.GetUpdatedAt().Time,
Labels: labels,
Reactions: reactions,
Closed: issue.ClosedAt.GetTime(),
IsLocked: issue.GetLocked(),
Assignees: assignees,
ForeignIndex: int64(issue.GetNumber()),
}, nil
}
// GetIssue recovers an issue omitted from the repository listing.
func (g *GithubDownloaderV3) GetIssue(ctx context.Context, number int64) (*base.Issue, error) {
g.waitAndPickClient(ctx)
issue, resp, err := g.getClient().Issues.Get(ctx, g.repoOwner, g.repoName, int(number))
g.setRateFromResponse(resp)
if err != nil {
return nil, err
}
if issue.IsPullRequest() {
return nil, fmt.Errorf("issue %d is a pull request", number)
}
if int64(issue.GetNumber()) != number {
return nil, fmt.Errorf("GitHub returned issue %d while recovering issue %d", issue.GetNumber(), number)
}
return g.convertGithubIssue(ctx, issue, g.maxPerPage)
}
// SupportGetRepoComments return true if it supports get repo comments
func (g *GithubDownloaderV3) SupportGetRepoComments() bool {
return true
@@ -544,14 +575,14 @@ func (g *GithubDownloaderV3) getComments(ctx context.Context, commentable base.C
for {
g.waitAndPickClient(ctx)
comments, resp, err := g.getClient().Issues.ListComments(ctx, g.repoOwner, g.repoName, int(commentable.GetForeignIndex()), opt)
g.setRateFromResponse(resp)
if err != nil {
return nil, fmt.Errorf("error while listing repos: %w", err)
}
g.setRate(&resp.Rate)
for _, comment := range comments {
// get reactions
var reactions []*base.Reaction
if !g.SkipReactions {
if !g.SkipReactions && mayHaveReactions(comment.Reactions) {
for i := 1; ; i++ {
g.waitAndPickClient(ctx)
res, resp, err := g.getClient().Reactions.ListIssueCommentReactions(ctx, g.repoOwner, g.repoName, comment.GetID(), &github.ListReactionOptions{
@@ -560,10 +591,10 @@ func (g *GithubDownloaderV3) getComments(ctx context.Context, commentable base.C
PerPage: g.maxPerPage,
},
})
g.setRateFromResponse(resp)
if err != nil {
return nil, err
}
g.setRate(&resp.Rate)
if len(res) == 0 {
break
}
@@ -618,17 +649,17 @@ func (g *GithubDownloaderV3) GetAllComments(ctx context.Context, page, perPage i
g.waitAndPickClient(ctx)
comments, resp, err := g.getClient().Issues.ListComments(ctx, g.repoOwner, g.repoName, 0, opt)
g.setRateFromResponse(resp)
if err != nil {
return nil, false, fmt.Errorf("error while listing repos: %w", err)
}
isEnd := resp.NextPage == 0
log.Trace("Request get comments %d/%d, but in fact get %d, next page is %d", perPage, page, len(comments), resp.NextPage)
g.setRate(&resp.Rate)
for _, comment := range comments {
// get reactions
var reactions []*base.Reaction
if !g.SkipReactions {
if !g.SkipReactions && mayHaveReactions(comment.Reactions) {
for i := 1; ; i++ {
g.waitAndPickClient(ctx)
res, resp, err := g.getClient().Reactions.ListIssueCommentReactions(ctx, g.repoOwner, g.repoName, comment.GetID(), &github.ListReactionOptions{
@@ -637,10 +668,10 @@ func (g *GithubDownloaderV3) GetAllComments(ctx context.Context, page, perPage i
PerPage: g.maxPerPage,
},
})
g.setRateFromResponse(resp)
if err != nil {
return nil, false, err
}
g.setRate(&resp.Rate)
if len(res) == 0 {
break
}
@@ -688,11 +719,11 @@ func (g *GithubDownloaderV3) GetPullRequests(ctx context.Context, page, perPage
allPRs := make([]*base.PullRequest, 0, perPage)
g.waitAndPickClient(ctx)
prs, resp, err := g.getClient().PullRequests.List(ctx, g.repoOwner, g.repoName, opt)
g.setRateFromResponse(resp)
if err != nil {
return nil, false, fmt.Errorf("error while listing repos: %w", err)
}
log.Trace("Request get pull requests %d/%d, but in fact get %d", perPage, page, len(prs))
g.setRate(&resp.Rate)
for _, pr := range prs {
labels := make([]*base.Label, 0, len(pr.Labels))
for _, l := range pr.Labels {
@@ -710,10 +741,10 @@ func (g *GithubDownloaderV3) GetPullRequests(ctx context.Context, page, perPage
PerPage: perPage,
},
})
g.setRateFromResponse(resp)
if err != nil {
return nil, false, err
}
g.setRate(&resp.Rate)
if len(res) == 0 {
break
}
@@ -773,6 +804,10 @@ func (g *GithubDownloaderV3) GetPullRequests(ctx context.Context, page, perPage
return allPRs, len(prs) < perPage, nil
}
func mayHaveReactions(reactions *github.Reactions) bool {
return reactions == nil || reactions.TotalCount == nil || *reactions.TotalCount > 0
}
func convertGithubReview(r *github.PullRequestReview) *base.Review {
return &base.Review{
ID: r.GetID(),
@@ -790,7 +825,7 @@ func (g *GithubDownloaderV3) convertGithubReviewComments(ctx context.Context, cs
for _, c := range cs {
// get reactions
var reactions []*base.Reaction
if !g.SkipReactions {
if !g.SkipReactions && mayHaveReactions(c.Reactions) {
for i := 1; ; i++ {
g.waitAndPickClient(ctx)
res, resp, err := g.getClient().Reactions.ListPullRequestCommentReactions(ctx, g.repoOwner, g.repoName, c.GetID(), &github.ListReactionOptions{
@@ -799,10 +834,10 @@ func (g *GithubDownloaderV3) convertGithubReviewComments(ctx context.Context, cs
PerPage: g.maxPerPage,
},
})
g.setRateFromResponse(resp)
if err != nil {
return nil, err
}
g.setRate(&resp.Rate)
if len(res) == 0 {
break
}
@@ -846,10 +881,10 @@ func (g *GithubDownloaderV3) GetReviews(ctx context.Context, reviewable base.Rev
for {
g.waitAndPickClient(ctx)
reviews, resp, err := g.getClient().PullRequests.ListReviews(ctx, g.repoOwner, g.repoName, int(reviewable.GetForeignIndex()), opt)
g.setRateFromResponse(resp)
if err != nil {
return nil, fmt.Errorf("error while listing repos: %w", err)
}
g.setRate(&resp.Rate)
for _, review := range reviews {
r := convertGithubReview(review)
r.IssueIndex = reviewable.GetLocalIndex()
@@ -860,10 +895,10 @@ func (g *GithubDownloaderV3) GetReviews(ctx context.Context, reviewable base.Rev
for {
g.waitAndPickClient(ctx)
reviewComments, resp, err := g.getClient().PullRequests.ListReviewComments(ctx, g.repoOwner, g.repoName, int(reviewable.GetForeignIndex()), review.GetID(), opt2)
g.setRateFromResponse(resp)
if err != nil {
return nil, fmt.Errorf("error while listing repos: %w", err)
}
g.setRate(&resp.Rate)
cs, err := g.convertGithubReviewComments(ctx, reviewComments)
if err != nil {
@@ -885,10 +920,10 @@ func (g *GithubDownloaderV3) GetReviews(ctx context.Context, reviewable base.Rev
// Get requested reviews
g.waitAndPickClient(ctx)
reviewers, resp, err := g.getClient().PullRequests.ListReviewers(ctx, g.repoOwner, g.repoName, int(reviewable.GetForeignIndex()))
g.setRateFromResponse(resp)
if err != nil {
return nil, fmt.Errorf("error while listing repos: %w", err)
}
g.setRate(&resp.Rate)
for _, user := range reviewers.Users {
r := &base.Review{
ReviewerID: user.GetID(),
@@ -0,0 +1,70 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package migrations
import (
"context"
"fmt"
base "gitea.dev/modules/migration"
)
type githubIssueRecoveryUploader struct {
base.Uploader
downloader *GithubDownloaderV3
issues map[int64]struct{}
}
func wrapGithubIssueRecoveryUploader(uploader base.Uploader, downloader base.Downloader) base.Uploader {
if retry, ok := downloader.(*base.RetryDownloader); ok {
downloader = retry.Downloader
}
github, ok := downloader.(*GithubDownloaderV3)
if !ok {
return uploader
}
return &githubIssueRecoveryUploader{
Uploader: uploader,
downloader: github,
issues: make(map[int64]struct{}),
}
}
func (g *githubIssueRecoveryUploader) CreateIssues(ctx context.Context, issues ...*base.Issue) error {
if err := g.Uploader.CreateIssues(ctx, issues...); err != nil {
return err
}
for _, issue := range issues {
g.issues[issue.Number] = struct{}{}
}
return nil
}
func (g *githubIssueRecoveryUploader) CreatePullRequests(ctx context.Context, prs ...*base.PullRequest) error {
if err := g.Uploader.CreatePullRequests(ctx, prs...); err != nil {
return err
}
for _, pr := range prs {
g.issues[pr.Number] = struct{}{}
}
return nil
}
func (g *githubIssueRecoveryUploader) CreateComments(ctx context.Context, comments ...*base.Comment) error {
for _, comment := range comments {
if _, ok := g.issues[comment.IssueIndex]; ok {
continue
}
issue, err := g.downloader.GetIssue(ctx, comment.IssueIndex)
if err != nil {
return fmt.Errorf("recover missing IssueIndex %d: %w", comment.IssueIndex, err)
}
if err := g.Uploader.CreateIssues(ctx, issue); err != nil {
return err
}
g.issues[issue.Number] = struct{}{}
}
return g.Uploader.CreateComments(ctx, comments...)
}
+51
View File
@@ -118,6 +118,57 @@ func TestGithubIssuePagination(t *testing.T) {
}
}
func TestGithubGetAllCommentsSkipsEmptyReactionsAndRecordsRateLimit(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "/api/v3/repos/o/r/issues/comments", r.URL.Path)
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-RateLimit-Limit", "5000")
w.Header().Set("X-RateLimit-Reset", "4102444800")
if r.URL.Query().Get("page") == "1" {
w.Header().Set("X-RateLimit-Remaining", "100")
_, _ = w.Write([]byte(`[{"issue_url":"https://api.github.com/repos/o/r/issues/7","reactions":{"total_count":0}}]`))
return
}
w.Header().Set("X-RateLimit-Remaining", "0")
w.WriteHeader(http.StatusForbidden)
}))
defer server.Close()
downloader, err := NewGithubDownloaderV3(t.Context(), server.URL, "", "", "", "o", "r")
require.NoError(t, err)
comments, _, err := downloader.GetAllComments(t.Context(), 1, 100)
require.NoError(t, err)
require.Len(t, comments, 1)
_, _, err = downloader.GetAllComments(t.Context(), 2, 100)
require.Error(t, err)
assert.Zero(t, downloader.rates[0].Remaining)
}
func TestGithubGetIssueRecoversIssueOmittedFromList(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch r.URL.Path {
case "/api/v3/repos/o/r/issues/123":
_, _ = w.Write([]byte(`{"number":123,"title":"recovered issue","user":{"id":1,"login":"user"},"created_at":"2024-08-12T08:38:46Z","updated_at":"2025-01-21T10:05:11Z","state":"closed"}`))
case "/api/v3/repos/o/r/issues/123/reactions":
_, _ = w.Write([]byte(`[]`))
default:
http.NotFound(w, r)
}
}))
defer server.Close()
downloader, err := NewGithubDownloaderV3(t.Context(), server.URL, "", "", "", "o", "r")
require.NoError(t, err)
issue, err := downloader.GetIssue(t.Context(), 123)
require.NoError(t, err)
assert.EqualValues(t, 123, issue.Number)
assert.Equal(t, "recovered issue", issue.Title)
}
func TestGitHubDownloadRepo(t *testing.T) {
token := os.Getenv("GITHUB_READ_TOKEN")
liveMode := token != ""
+1 -1
View File
@@ -96,7 +96,7 @@ func MigrateRepository(ctx context.Context, doer *user_model.User, ownerName str
uploader := NewGiteaLocalUploader(ctx, doer, ownerName, opts.RepoName)
uploader.gitServiceType = opts.GitServiceType
if err := migrateRepository(ctx, doer, downloader, uploader, opts, messenger); err != nil {
if err := migrateRepository(ctx, doer, downloader, wrapGithubIssueRecoveryUploader(uploader, downloader), opts, messenger); err != nil {
if err1 := uploader.Rollback(); err1 != nil {
log.Error("rollback failed: %v", err1)
}
-1
View File
@@ -15,7 +15,6 @@
<div class="breadcrumb-divider">:</div>
<a class="section" href="{{$.BranchLink}}">{{.BranchName}}</a>
<span>{{ctx.Locale.Tr "repo.editor.or"}} <a href="{{$.BranchLink}}">{{ctx.Locale.Tr "repo.editor.cancel_lower"}}</a></span>
<input type="hidden" name="tree_path" value="__dummy_for_EditRepoFileForm.TreePath(Required)__">
<input id="file-name" type="hidden" value="diff.patch">
</div>
</div>
+1 -10
View File
@@ -22,7 +22,6 @@ import (
packages_cleanup_service "gitea.dev/services/packages/cleanup"
"gitea.dev/tests"
"github.com/blakesmith/ar"
"github.com/stretchr/testify/assert"
)
@@ -49,15 +48,7 @@ func TestPackageDebian(t *testing.T) {
zw.Close()
var buf bytes.Buffer
aw := ar.NewWriter(&buf)
aw.WriteGlobalHeader()
hdr := &ar.Header{
Name: "control.tar.gz",
Mode: 0o600,
Size: int64(cbuf.Len()),
}
aw.WriteHeader(hdr)
aw.Write(cbuf.Bytes())
fmt.Fprintf(&buf, "!<arch>\n%-48s%-10d`\n%s%s", "control.tar.gz", cbuf.Len(), cbuf.Bytes(), strings.Repeat("\n", cbuf.Len()%2))
// if you'd like to do some tests manually, uncomment the WriteFile line, then you will get some "deb" package files:
// OWNER= PASS= DIST= COMP= ; curl -X PUT "http://$OWNER:$PASS@localhost:3000/api/packages/$OWNER/debian/pool/$DIST/$COMP/upload" -T /tmp/gitea_test_debian_gitea_1.0.3_amd64.deb
+12 -5
View File
@@ -209,12 +209,15 @@ index 0000000000..aaaaaaaaaa
+++ b/patch-file-1.txt
@@ -0,0 +1 @@
+`
testEditorActionPostRequest(t, session, "/user2/repo1/_diffpatch/master/", map[string]string{
resp := testEditorActionPostRequest(t, session, "/user2/repo1/_diffpatch/master/", map[string]string{
"content": pathContentCommon + "patched content\n",
"commit_choice": "commit-to-new-branch",
"new_branch_name": "patched-branch",
})
resp := MakeRequest(t, NewRequest(t, "GET", "/user2/repo1/raw/branch/patched-branch/patch-file-1.txt"), http.StatusOK)
assert.Equal(t, http.StatusOK, resp.Code)
assert.Equal(t, "/user2/repo1/compare/master...patched-branch", test.RedirectURL(resp))
resp = MakeRequest(t, NewRequest(t, "GET", "/user2/repo1/raw/branch/patched-branch/patch-file-1.txt"), http.StatusOK)
assert.Equal(t, "patched content\n", resp.Body.String())
// patch again, it should fail
@@ -223,6 +226,7 @@ index 0000000000..aaaaaaaaaa
"commit_choice": "commit-to-new-branch",
"new_branch_name": "patched-branch-1",
})
assert.Equal(t, http.StatusBadRequest, resp.Code)
assert.Equal(t, "Unable to apply patch", test.ParseJSONError(resp.Body.Bytes()).ErrorMessage)
}
@@ -334,9 +338,9 @@ func testEditorWebGitCommitEmail(t *testing.T) {
})
t.Run("ApplyPatchCherryPick", func(t *testing.T) {
testWebGit(t,
patchResp1, patchResp2 := testWebGit(t,
"/user2/repo1/_diffpatch/master", map[string]string{
"tree_path": "__dummy__",
"tree_path": "__dummy__", // the "tree_path" should be ignored and should not affect the redirect URL
"content": `diff --git a/patch-file-1.txt b/patch-file-1.txt
new file mode 100644
index 0000000000..aaaaaaaaaa
@@ -347,7 +351,6 @@ index 0000000000..aaaaaaaaaa
`,
},
"/user2/repo1/_diffpatch/master", map[string]string{
"tree_path": "__dummy__",
"content": `diff --git a/patch-file-2.txt b/patch-file-2.txt
new file mode 100644
index 0000000000..bbbbbbbbbb
@@ -358,6 +361,10 @@ index 0000000000..bbbbbbbbbb
`,
},
)
for _, resp := range []*httptest.ResponseRecorder{patchResp1, patchResp2} {
assert.Equal(t, http.StatusOK, resp.Code)
assert.Equal(t, "/user2/repo1/src/branch/master", test.RedirectURL(resp))
}
commit1, err := gitRepo.GetCommitByPath(t.Context(), "patch-file-1.txt")
require.NoError(t, err)