Compare commits

...

4 Commits

Author SHA1 Message Date
TheFox0x7
4d2323183d
fix users being able bypass limits with repo transfers (#34031)
prevent user from being able to transfer repo to user who cannot have
more repositories
2025-03-31 20:19:32 +00:00
Lunny Xiao
a2e8a289b2
Improve pull request list api (#34052)
The pull request list API is slow, for every pull request, it needs to
open a git repository. Assume it has 30 records, there will be 30 sub
processes back because every repository will open a git cat-file --batch
sub process. This PR use base git repository to get the head commit id
rather than read it from head repository to avoid open any head git
repository.
2025-03-31 12:54:31 -07:00
Simon Priet
342432e52a
fix(#34076):replace assgniee translation key (#34077)
Fix the typo on the `filter_assginee_no_assigne` key used in
translations.

The typo itself doesn't produce a bug (as it's there both on the code
and on the locales)

Side Note: Github UI is not the best to bulk change this :/ Squashing
commits on the PR should be adequate.

Closes #34076 .

---------

Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2025-03-31 19:11:15 +00:00
Kerwin Bryant
741b53eb30
[Fix] Resolve the problem of commit_statuses not being loaded at the top - right when switching files from the file tree (#34079)
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
2025-03-31 18:39:08 +00:00
14 changed files with 146 additions and 87 deletions

View File

@ -21,3 +21,11 @@
repo_id: 32
created_unix: 1553610671
updated_unix: 1553610671
-
id: 4
doer_id: 3
recipient_id: 1
repo_id: 5
created_unix: 1553610671
updated_unix: 1553610671

View File

@ -173,6 +173,18 @@ func GetBranch(ctx context.Context, repoID int64, branchName string) (*Branch, e
return &branch, nil
}
// IsBranchExist returns true if the branch exists in the repository.
func IsBranchExist(ctx context.Context, repoID int64, branchName string) (bool, error) {
var branch Branch
has, err := db.GetEngine(ctx).Where("repo_id=?", repoID).And("name=?", branchName).Get(&branch)
if err != nil {
return false, err
} else if !has {
return false, nil
}
return !branch.IsDeleted, nil
}
func GetBranches(ctx context.Context, repoID int64, branchNames []string, includeDeleted bool) ([]*Branch, error) {
branches := make([]*Branch, 0, len(branchNames))

View File

@ -1551,7 +1551,7 @@ issues.filter_project = Project
issues.filter_project_all = All projects
issues.filter_project_none = No project
issues.filter_assignee = Assignee
issues.filter_assginee_no_assignee = Assigned to nobody
issues.filter_assignee_no_assignee = Assigned to nobody
issues.filter_assignee_any_assignee = Assigned to anybody
issues.filter_poster = Author
issues.filter_user_placeholder = Search users

View File

@ -108,22 +108,19 @@ func Transfer(ctx *context.APIContext) {
oldFullname := ctx.Repo.Repository.FullName()
if err := repo_service.StartRepositoryTransfer(ctx, ctx.Doer, newOwner, ctx.Repo.Repository, teams); err != nil {
if repo_model.IsErrRepoTransferInProgress(err) {
switch {
case repo_model.IsErrRepoTransferInProgress(err):
ctx.APIError(http.StatusConflict, err)
return
}
if repo_model.IsErrRepoAlreadyExist(err) {
case repo_model.IsErrRepoAlreadyExist(err):
ctx.APIError(http.StatusUnprocessableEntity, err)
case repo_service.IsRepositoryLimitReached(err):
ctx.APIError(http.StatusForbidden, err)
case errors.Is(err, user_model.ErrBlockedUser):
ctx.APIError(http.StatusForbidden, err)
default:
ctx.APIErrorInternal(err)
return
}
if errors.Is(err, user_model.ErrBlockedUser) {
ctx.APIError(http.StatusForbidden, err)
} else {
ctx.APIErrorInternal(err)
}
return
}
if ctx.Repo.Repository.Status == repo_model.RepositoryPendingTransfer {
@ -169,6 +166,8 @@ func AcceptTransfer(ctx *context.APIContext) {
ctx.APIError(http.StatusNotFound, err)
case errors.Is(err, util.ErrPermissionDenied):
ctx.APIError(http.StatusForbidden, err)
case repo_service.IsRepositoryLimitReached(err):
ctx.APIError(http.StatusForbidden, err)
default:
ctx.APIErrorInternal(err)
}

View File

@ -305,11 +305,15 @@ func CreatePost(ctx *context.Context) {
}
func handleActionError(ctx *context.Context, err error) {
if errors.Is(err, user_model.ErrBlockedUser) {
switch {
case errors.Is(err, user_model.ErrBlockedUser):
ctx.Flash.Error(ctx.Tr("repo.action.blocked_user"))
} else if errors.Is(err, util.ErrPermissionDenied) {
case repo_service.IsRepositoryLimitReached(err):
limit := err.(repo_service.LimitReachedError).Limit
ctx.Flash.Error(ctx.TrN(limit, "repo.form.reach_limit_of_creation_1", "repo.form.reach_limit_of_creation_n", limit))
case errors.Is(err, util.ErrPermissionDenied):
ctx.HTTPError(http.StatusNotFound)
} else {
default:
ctx.ServerError(fmt.Sprintf("Action (%s)", ctx.PathParam("action")), err)
}
}

View File

@ -848,6 +848,9 @@ func handleSettingsPostTransfer(ctx *context.Context) {
ctx.RenderWithErr(ctx.Tr("repo.settings.new_owner_has_same_repo"), tplSettingsOptions, nil)
} else if repo_model.IsErrRepoTransferInProgress(err) {
ctx.RenderWithErr(ctx.Tr("repo.settings.transfer_in_progress"), tplSettingsOptions, nil)
} else if repo_service.IsRepositoryLimitReached(err) {
limit := err.(repo_service.LimitReachedError).Limit
ctx.RenderWithErr(ctx.TrN(limit, "repo.form.reach_limit_of_creation_1", "repo.form.reach_limit_of_creation_n", limit), tplSettingsOptions, nil)
} else if errors.Is(err, user_model.ErrBlockedUser) {
ctx.RenderWithErr(ctx.Tr("repo.settings.transfer.blocked_user"), tplSettingsOptions, nil)
} else {

View File

@ -389,7 +389,7 @@ func ToAPIPullRequests(ctx context.Context, baseRepo *repo_model.Repository, prs
},
Head: &api.PRBranchInfo{
Name: pr.HeadBranch,
Ref: fmt.Sprintf("%s%d/head", git.PullPrefix, pr.Index),
Ref: pr.GetGitRefName(),
RepoID: -1,
},
}
@ -422,72 +422,43 @@ func ToAPIPullRequests(ctx context.Context, baseRepo *repo_model.Repository, prs
return nil, err
}
}
if baseBranch != nil {
apiPullRequest.Base.Sha = baseBranch.CommitID
}
if pr.Flow == issues_model.PullRequestFlowAGit {
apiPullRequest.Head.Sha, err = gitRepo.GetRefCommitID(pr.GetGitRefName())
// pull request head branch, both repository and branch could not exist
if pr.HeadRepo != nil {
apiPullRequest.Head.RepoID = pr.HeadRepo.ID
exist, err := git_model.IsBranchExist(ctx, pr.HeadRepo.ID, pr.HeadBranch)
if err != nil {
log.Error("GetRefCommitID[%s]: %v", pr.GetGitRefName(), err)
log.Error("IsBranchExist[%d]: %v", pr.HeadRepo.ID, err)
return nil, err
}
apiPullRequest.Head.RepoID = pr.BaseRepoID
apiPullRequest.Head.Repository = apiPullRequest.Base.Repository
apiPullRequest.Head.Name = ""
if exist {
apiPullRequest.Head.Ref = pr.HeadBranch
}
}
if apiPullRequest.Head.Ref == "" {
apiPullRequest.Head.Ref = pr.GetGitRefName()
}
var headGitRepo *git.Repository
if pr.HeadRepo != nil && pr.Flow == issues_model.PullRequestFlowGithub {
if pr.HeadRepoID == pr.BaseRepoID {
apiPullRequest.Head.RepoID = pr.HeadRepo.ID
apiPullRequest.Head.Repository = apiRepo
headGitRepo = gitRepo
} else {
p, err := access_model.GetUserRepoPermission(ctx, pr.HeadRepo, doer)
if err != nil {
log.Error("GetUserRepoPermission[%d]: %v", pr.HeadRepoID, err)
p.AccessMode = perm.AccessModeNone
}
apiPullRequest.Head.RepoID = pr.HeadRepo.ID
apiPullRequest.Head.Repository = ToRepo(ctx, pr.HeadRepo, p)
headGitRepo, err = gitrepo.OpenRepository(ctx, pr.HeadRepo)
if err != nil {
log.Error("OpenRepository[%s]: %v", pr.HeadRepo.RepoPath(), err)
return nil, err
}
defer headGitRepo.Close()
if pr.HeadRepoID == pr.BaseRepoID {
apiPullRequest.Head.Repository = apiPullRequest.Base.Repository
} else {
p, err := access_model.GetUserRepoPermission(ctx, pr.HeadRepo, doer)
if err != nil {
log.Error("GetUserRepoPermission[%d]: %v", pr.HeadRepoID, err)
p.AccessMode = perm.AccessModeNone
}
apiPullRequest.Head.Repository = ToRepo(ctx, pr.HeadRepo, p)
}
headBranch, err := headGitRepo.GetBranch(pr.HeadBranch)
if err != nil && !git.IsErrBranchNotExist(err) {
log.Error("GetBranch[%s]: %v", pr.HeadBranch, err)
return nil, err
}
if git.IsErrBranchNotExist(err) {
headCommitID, err := headGitRepo.GetRefCommitID(apiPullRequest.Head.Ref)
if err != nil && !git.IsErrNotExist(err) {
log.Error("GetCommit[%s]: %v", pr.HeadBranch, err)
return nil, err
}
if err == nil {
apiPullRequest.Head.Sha = headCommitID
}
} else {
commit, err := headBranch.GetCommit()
if err != nil && !git.IsErrNotExist(err) {
log.Error("GetCommit[%s]: %v", headBranch.Name, err)
return nil, err
}
if err == nil {
apiPullRequest.Head.Ref = pr.HeadBranch
apiPullRequest.Head.Sha = commit.ID.String()
}
}
if pr.Flow == issues_model.PullRequestFlowAGit {
apiPullRequest.Head.Name = ""
}
apiPullRequest.Head.Sha, err = gitRepo.GetRefCommitID(pr.GetGitRefName())
if err != nil {
log.Error("GetRefCommitID[%s]: %v", pr.GetGitRefName(), err)
}
if len(apiPullRequest.Head.Sha) == 0 && len(apiPullRequest.Head.Ref) != 0 {

View File

@ -20,10 +20,22 @@ import (
"code.gitea.io/gitea/modules/gitrepo"
"code.gitea.io/gitea/modules/globallock"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/util"
notify_service "code.gitea.io/gitea/services/notify"
)
type LimitReachedError struct{ Limit int }
func (LimitReachedError) Error() string {
return "Repository limit has been reached"
}
func IsRepositoryLimitReached(err error) bool {
_, ok := err.(LimitReachedError)
return ok
}
func getRepoWorkingLockKey(repoID int64) string {
return fmt.Sprintf("repo_working_%d", repoID)
}
@ -49,6 +61,11 @@ func AcceptTransferOwnership(ctx context.Context, repo *repo_model.Repository, d
return err
}
if !doer.IsAdmin && !repoTransfer.Recipient.CanCreateRepo() {
limit := util.Iif(repoTransfer.Recipient.MaxRepoCreation >= 0, repoTransfer.Recipient.MaxRepoCreation, setting.Repository.MaxCreationLimit)
return LimitReachedError{Limit: limit}
}
if !repoTransfer.CanUserAcceptOrRejectTransfer(ctx, doer) {
return util.ErrPermissionDenied
}
@ -399,6 +416,11 @@ func StartRepositoryTransfer(ctx context.Context, doer, newOwner *user_model.Use
return err
}
if !doer.IsAdmin && !newOwner.CanCreateRepo() {
limit := util.Iif(newOwner.MaxRepoCreation >= 0, newOwner.MaxRepoCreation, setting.Repository.MaxCreationLimit)
return LimitReachedError{Limit: limit}
}
var isDirectTransfer bool
oldOwnerName := repo.OwnerName

View File

@ -1,4 +1,4 @@
// Copyright 2019 The Gitea Authors. All rights reserved.
// Copyright 2025 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package repository
@ -14,11 +14,14 @@ import (
repo_model "code.gitea.io/gitea/models/repo"
"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"
"code.gitea.io/gitea/modules/util"
"code.gitea.io/gitea/services/feed"
notify_service "code.gitea.io/gitea/services/notify"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var notifySync sync.Once
@ -125,3 +128,40 @@ func TestRepositoryTransfer(t *testing.T) {
err = RejectRepositoryTransfer(db.DefaultContext, repo2, doer)
assert.True(t, repo_model.IsErrNoPendingTransfer(err))
}
// Test transfer rejections
func TestRepositoryTransferRejection(t *testing.T) {
require.NoError(t, unittest.PrepareTestDatabase())
// Set limit to 0 repositories so no repositories can be transferred
defer test.MockVariableValue(&setting.Repository.MaxCreationLimit, 0)()
// Admin case
doerAdmin := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 5})
transfer, err := repo_model.GetPendingRepositoryTransfer(db.DefaultContext, repo)
require.NoError(t, err)
require.NotNil(t, transfer)
require.NoError(t, transfer.LoadRecipient(db.DefaultContext))
require.True(t, transfer.Recipient.CanCreateRepo()) // admin is not subject to limits
// Administrator should not be affected by the limits so transfer should be successful
assert.NoError(t, AcceptTransferOwnership(db.DefaultContext, repo, doerAdmin))
// Non admin user case
doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 10})
repo = unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 21})
transfer, err = repo_model.GetPendingRepositoryTransfer(db.DefaultContext, repo)
require.NoError(t, err)
require.NotNil(t, transfer)
require.NoError(t, transfer.LoadRecipient(db.DefaultContext))
require.False(t, transfer.Recipient.CanCreateRepo()) // regular user is subject to limits
// Cannot accept because of the limit
err = AcceptTransferOwnership(db.DefaultContext, repo, doer)
assert.Error(t, err)
assert.True(t, IsRepositoryLimitReached(err))
}

View File

@ -13,7 +13,7 @@
"UserSearchList" $.Assignees
"SelectedUserId" $.AssigneeID
"TextFilterTitle" (ctx.Locale.Tr "repo.issues.filter_assignee")
"TextFilterMatchNone" (ctx.Locale.Tr "repo.issues.filter_assginee_no_assignee")
"TextFilterMatchNone" (ctx.Locale.Tr "repo.issues.filter_assignee_no_assignee")
"TextFilterMatchAny" (ctx.Locale.Tr "repo.issues.filter_assignee_any_assignee")
}}
</div>

View File

@ -1,10 +1,10 @@
{{if .Statuses}}
{{if and (eq (len .Statuses) 1) .Status.TargetURL}}
<a class="flex-text-inline tw-no-underline {{.AdditionalClasses}}" data-tippy="commit-statuses" href="{{.Status.TargetURL}}">
<a class="flex-text-inline tw-no-underline {{.AdditionalClasses}}" data-global-init="initCommitStatuses" href="{{.Status.TargetURL}}">
{{template "repo/commit_status" .Status}}
</a>
{{else}}
<span class="flex-text-inline {{.AdditionalClasses}}" data-tippy="commit-statuses" tabindex="0">
<span class="flex-text-inline {{.AdditionalClasses}}" data-global-init="initCommitStatuses" tabindex="0">
{{template "repo/commit_status" .Status}}
</span>
{{end}}

View File

@ -94,7 +94,7 @@
"UserSearchList" $.Assignees
"SelectedUserId" $.AssigneeID
"TextFilterTitle" (ctx.Locale.Tr "repo.issues.filter_assignee")
"TextFilterMatchNone" (ctx.Locale.Tr "repo.issues.filter_assginee_no_assignee")
"TextFilterMatchNone" (ctx.Locale.Tr "repo.issues.filter_assignee_no_assignee")
"TextFilterMatchAny" (ctx.Locale.Tr "repo.issues.filter_assignee_any_assignee")
}}

View File

@ -240,7 +240,7 @@ func TestRepoCommitsStatusMultiple(t *testing.T) {
resp = session.MakeRequest(t, req, http.StatusOK)
doc = NewHTMLParser(t, resp.Body)
// Check that the data-tippy="commit-statuses" (for trigger) and commit-status (svg) are present
sel := doc.doc.Find("#commits-table .message [data-tippy=\"commit-statuses\"] .commit-status")
// Check that the data-global-init="initCommitStatuses" (for trigger) and commit-status (svg) are present
sel := doc.doc.Find(`#commits-table .message [data-global-init="initCommitStatuses"] .commit-status`)
assert.Equal(t, 1, sel.Length())
}

View File

@ -1,6 +1,6 @@
import {createTippy} from '../modules/tippy.ts';
import {toggleElem} from '../utils/dom.ts';
import {registerGlobalEventFunc} from '../modules/observer.ts';
import {registerGlobalEventFunc, registerGlobalInitFunc} from '../modules/observer.ts';
export function initRepoEllipsisButton() {
registerGlobalEventFunc('click', 'onRepoEllipsisButtonClick', async (el: HTMLInputElement, e: Event) => {
@ -12,15 +12,15 @@ export function initRepoEllipsisButton() {
}
export function initCommitStatuses() {
for (const element of document.querySelectorAll('[data-tippy="commit-statuses"]')) {
const top = document.querySelector('.repository.file.list') || document.querySelector('.repository.diff');
createTippy(element, {
content: element.nextElementSibling,
placement: top ? 'top-start' : 'bottom-start',
registerGlobalInitFunc('initCommitStatuses', (el: HTMLElement) => {
const nextEl = el.nextElementSibling;
if (!nextEl.matches('.tippy-target')) throw new Error('Expected next element to be a tippy target');
createTippy(el, {
content: nextEl,
placement: 'bottom-start',
interactive: true,
role: 'dialog',
theme: 'box-with-header',
});
}
});
}