Skip to content

Commit 8eb1cd9

Browse files
qwerty2876543
andauthored
Add "Allow edits from maintainer" feature (#18002)
Adds a feature [like GitHub has](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request-from-a-fork) (step 7). If you create a new PR from a forked repo, you can select (and change later, but only if you are the PR creator/poster) the "Allow edits from maintainers" option. Then users with write access to the base branch get more permissions on this branch: * use the update pull request button * push directly from the command line (`git push`) * edit/delete/upload files via web UI * use related API endpoints You can't merge PRs to this branch with this enabled, you'll need "full" code write permissions. This feature has a pretty big impact on the permission system. I might forgot changing some things or didn't find security vulnerabilities. In this case, please leave a review or comment on this PR. Closes #17728 Co-authored-by: 6543 <[email protected]>
1 parent 92dfbad commit 8eb1cd9

File tree

29 files changed

+359
-60
lines changed

29 files changed

+359
-60
lines changed

models/migrations/migrations.go

+3
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ type Version struct {
6161
// update minDBVersion accordingly
6262
var migrations = []Migration{
6363
// Gitea 1.5.0 ends at v69
64+
6465
// v70 -> v71
6566
NewMigration("add issue_dependencies", addIssueDependencies),
6667
// v71 -> v72
@@ -380,6 +381,8 @@ var migrations = []Migration{
380381
NewMigration("Create ForeignReference table", createForeignReferenceTable),
381382
// v212 -> v213
382383
NewMigration("Add package tables", addPackageTables),
384+
// v213 -> v214
385+
NewMigration("Add allow edits from maintainers to PullRequest table", addAllowMaintainerEdit),
383386
}
384387

385388
// GetCurrentDBVersion returns the current db version

models/migrations/v213.go

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// Copyright 2022 The Gitea Authors. All rights reserved.
2+
// Use of this source code is governed by a MIT-style
3+
// license that can be found in the LICENSE file.
4+
5+
package migrations
6+
7+
import (
8+
"xorm.io/xorm"
9+
)
10+
11+
func addAllowMaintainerEdit(x *xorm.Engine) error {
12+
// PullRequest represents relation between pull request and repositories.
13+
type PullRequest struct {
14+
AllowMaintainerEdit bool `xorm:"NOT NULL DEFAULT false"`
15+
}
16+
17+
return x.Sync2(new(PullRequest))
18+
}

models/pull.go

+18-9
Original file line numberDiff line numberDiff line change
@@ -69,15 +69,16 @@ type PullRequest struct {
6969
Issue *Issue `xorm:"-"`
7070
Index int64
7171

72-
HeadRepoID int64 `xorm:"INDEX"`
73-
HeadRepo *repo_model.Repository `xorm:"-"`
74-
BaseRepoID int64 `xorm:"INDEX"`
75-
BaseRepo *repo_model.Repository `xorm:"-"`
76-
HeadBranch string
77-
HeadCommitID string `xorm:"-"`
78-
BaseBranch string
79-
ProtectedBranch *ProtectedBranch `xorm:"-"`
80-
MergeBase string `xorm:"VARCHAR(40)"`
72+
HeadRepoID int64 `xorm:"INDEX"`
73+
HeadRepo *repo_model.Repository `xorm:"-"`
74+
BaseRepoID int64 `xorm:"INDEX"`
75+
BaseRepo *repo_model.Repository `xorm:"-"`
76+
HeadBranch string
77+
HeadCommitID string `xorm:"-"`
78+
BaseBranch string
79+
ProtectedBranch *ProtectedBranch `xorm:"-"`
80+
MergeBase string `xorm:"VARCHAR(40)"`
81+
AllowMaintainerEdit bool `xorm:"NOT NULL DEFAULT false"`
8182

8283
HasMerged bool `xorm:"INDEX"`
8384
MergedCommitID string `xorm:"VARCHAR(40)"`
@@ -711,6 +712,14 @@ func (pr *PullRequest) GetHeadBranchHTMLURL() string {
711712
return pr.HeadRepo.HTMLURL() + "/src/branch/" + util.PathEscapeSegments(pr.HeadBranch)
712713
}
713714

715+
// UpdateAllowEdits update if PR can be edited from maintainers
716+
func UpdateAllowEdits(ctx context.Context, pr *PullRequest) error {
717+
if _, err := db.GetEngine(ctx).ID(pr.ID).Cols("allow_maintainer_edit").Update(pr); err != nil {
718+
return err
719+
}
720+
return nil
721+
}
722+
714723
// Mergeable returns if the pullrequest is mergeable.
715724
func (pr *PullRequest) Mergeable() bool {
716725
// If a pull request isn't mergable if it's:

models/repo_permission.go

+34
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,39 @@ func (p *Permission) CanWriteIssuesOrPulls(isPull bool) bool {
103103
return p.CanWrite(unit.TypeIssues)
104104
}
105105

106+
// CanWriteToBranch checks if the branch is writable by the user
107+
func (p *Permission) CanWriteToBranch(user *user_model.User, branch string) bool {
108+
if p.CanWrite(unit.TypeCode) {
109+
return true
110+
}
111+
112+
if len(p.Units) < 1 {
113+
return false
114+
}
115+
116+
prs, err := GetUnmergedPullRequestsByHeadInfo(p.Units[0].RepoID, branch)
117+
if err != nil {
118+
return false
119+
}
120+
121+
for _, pr := range prs {
122+
if pr.AllowMaintainerEdit {
123+
err = pr.LoadBaseRepo()
124+
if err != nil {
125+
continue
126+
}
127+
prPerm, err := GetUserRepoPermission(db.DefaultContext, pr.BaseRepo, user)
128+
if err != nil {
129+
continue
130+
}
131+
if prPerm.CanWrite(unit.TypeCode) {
132+
return true
133+
}
134+
}
135+
}
136+
return false
137+
}
138+
106139
// ColorFormat writes a colored string for these Permissions
107140
func (p *Permission) ColorFormat(s fmt.State) {
108141
noColor := log.ColorBytes(log.Reset)
@@ -160,6 +193,7 @@ func GetUserRepoPermission(ctx context.Context, repo *repo_model.Repository, use
160193
perm)
161194
}()
162195
}
196+
163197
// anonymous user visit private repo.
164198
// TODO: anonymous user visit public unit of private repo???
165199
if user == nil && repo.IsPrivate {

modules/context/permission.go

+10
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,16 @@ func RequireRepoWriter(unitType unit.Type) func(ctx *Context) {
2929
}
3030
}
3131

32+
// CanEnableEditor checks if the user is allowed to write to the branch of the repo
33+
func CanEnableEditor() func(ctx *Context) {
34+
return func(ctx *Context) {
35+
if !ctx.Repo.Permission.CanWriteToBranch(ctx.Doer, ctx.Repo.BranchName) {
36+
ctx.NotFound("CanWriteToBranch denies permission", nil)
37+
return
38+
}
39+
}
40+
}
41+
3242
// RequireRepoWriterOr returns a middleware for requiring repository write to one of the unit permission
3343
func RequireRepoWriterOr(unitTypes ...unit.Type) func(ctx *Context) {
3444
return func(ctx *Context) {

modules/context/repo.go

+4-4
Original file line numberDiff line numberDiff line change
@@ -78,8 +78,8 @@ type Repository struct {
7878
}
7979

8080
// CanEnableEditor returns true if repository is editable and user has proper access level.
81-
func (r *Repository) CanEnableEditor() bool {
82-
return r.Permission.CanWrite(unit_model.TypeCode) && r.Repository.CanEnableEditor() && r.IsViewBranch && !r.Repository.IsArchived
81+
func (r *Repository) CanEnableEditor(user *user_model.User) bool {
82+
return r.IsViewBranch && r.Permission.CanWriteToBranch(user, r.BranchName) && r.Repository.CanEnableEditor() && !r.Repository.IsArchived
8383
}
8484

8585
// CanCreateBranch returns true if repository is editable and user has proper access level.
@@ -123,7 +123,7 @@ func (r *Repository) CanCommitToBranch(ctx context.Context, doer *user_model.Use
123123

124124
sign, keyID, _, err := asymkey_service.SignCRUDAction(ctx, r.Repository.RepoPath(), doer, r.Repository.RepoPath(), git.BranchPrefix+r.BranchName)
125125

126-
canCommit := r.CanEnableEditor() && userCanPush
126+
canCommit := r.CanEnableEditor(doer) && userCanPush
127127
if requireSigned {
128128
canCommit = canCommit && sign
129129
}
@@ -139,7 +139,7 @@ func (r *Repository) CanCommitToBranch(ctx context.Context, doer *user_model.Use
139139

140140
return CanCommitToBranchResults{
141141
CanCommitToBranch: canCommit,
142-
EditorEnabled: r.CanEnableEditor(),
142+
EditorEnabled: r.CanEnableEditor(doer),
143143
UserCanPush: userCanPush,
144144
RequireSigned: requireSigned,
145145
WillSign: sign,

modules/convert/convert.go

+8-1
Original file line numberDiff line numberDiff line change
@@ -41,12 +41,19 @@ func ToEmail(email *user_model.EmailAddress) *api.Email {
4141
func ToBranch(repo *repo_model.Repository, b *git.Branch, c *git.Commit, bp *models.ProtectedBranch, user *user_model.User, isRepoAdmin bool) (*api.Branch, error) {
4242
if bp == nil {
4343
var hasPerm bool
44+
var canPush bool
4445
var err error
4546
if user != nil {
4647
hasPerm, err = models.HasAccessUnit(user, repo, unit.TypeCode, perm.AccessModeWrite)
4748
if err != nil {
4849
return nil, err
4950
}
51+
52+
perms, err := models.GetUserRepoPermission(db.DefaultContext, repo, user)
53+
if err != nil {
54+
return nil, err
55+
}
56+
canPush = perms.CanWriteToBranch(user, b.Name)
5057
}
5158

5259
return &api.Branch{
@@ -56,7 +63,7 @@ func ToBranch(repo *repo_model.Repository, b *git.Branch, c *git.Commit, bp *mod
5663
RequiredApprovals: 0,
5764
EnableStatusCheck: false,
5865
StatusCheckContexts: []string{},
59-
UserCanPush: hasPerm,
66+
UserCanPush: canPush,
6067
UserCanMerge: hasPerm,
6168
}, nil
6269
}

modules/convert/pull.go

+2
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,8 @@ func ToAPIPullRequest(ctx context.Context, pr *models.PullRequest, doer *user_mo
7373
Created: pr.Issue.CreatedUnix.AsTimePtr(),
7474
Updated: pr.Issue.UpdatedUnix.AsTimePtr(),
7575

76+
AllowMaintainerEdit: pr.AllowMaintainerEdit,
77+
7678
Base: &api.PRBranchInfo{
7779
Name: pr.BaseBranch,
7880
Ref: pr.BaseBranch,

modules/structs/pull.go

+7-5
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,10 @@ type PullRequest struct {
3131
Mergeable bool `json:"mergeable"`
3232
HasMerged bool `json:"merged"`
3333
// swagger:strfmt date-time
34-
Merged *time.Time `json:"merged_at"`
35-
MergedCommitID *string `json:"merge_commit_sha"`
36-
MergedBy *User `json:"merged_by"`
34+
Merged *time.Time `json:"merged_at"`
35+
MergedCommitID *string `json:"merge_commit_sha"`
36+
MergedBy *User `json:"merged_by"`
37+
AllowMaintainerEdit bool `json:"allow_maintainer_edit"`
3738

3839
Base *PRBranchInfo `json:"base"`
3940
Head *PRBranchInfo `json:"head"`
@@ -90,6 +91,7 @@ type EditPullRequestOption struct {
9091
Labels []int64 `json:"labels"`
9192
State *string `json:"state"`
9293
// swagger:strfmt date-time
93-
Deadline *time.Time `json:"due_date"`
94-
RemoveDeadline *bool `json:"unset_due_date"`
94+
Deadline *time.Time `json:"due_date"`
95+
RemoveDeadline *bool `json:"unset_due_date"`
96+
AllowMaintainerEdit *bool `json:"allow_maintainer_edit"`
9597
}

modules/structs/repo_file.go

+20
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,11 @@ type CreateFileOptions struct {
3030
Content string `json:"content"`
3131
}
3232

33+
// Branch returns branch name
34+
func (o *CreateFileOptions) Branch() string {
35+
return o.FileOptions.BranchName
36+
}
37+
3338
// DeleteFileOptions options for deleting files (used for other File structs below)
3439
// Note: `author` and `committer` are optional (if only one is given, it will be used for the other, otherwise the authenticated user will be used)
3540
type DeleteFileOptions struct {
@@ -39,6 +44,11 @@ type DeleteFileOptions struct {
3944
SHA string `json:"sha" binding:"Required"`
4045
}
4146

47+
// Branch returns branch name
48+
func (o *DeleteFileOptions) Branch() string {
49+
return o.FileOptions.BranchName
50+
}
51+
4252
// UpdateFileOptions options for updating files
4353
// Note: `author` and `committer` are optional (if only one is given, it will be used for the other, otherwise the authenticated user will be used)
4454
type UpdateFileOptions struct {
@@ -50,6 +60,16 @@ type UpdateFileOptions struct {
5060
FromPath string `json:"from_path" binding:"MaxSize(500)"`
5161
}
5262

63+
// Branch returns branch name
64+
func (o *UpdateFileOptions) Branch() string {
65+
return o.FileOptions.BranchName
66+
}
67+
68+
// FileOptionInterface provides a unified interface for the different file options
69+
type FileOptionInterface interface {
70+
Branch() string
71+
}
72+
5373
// ApplyDiffPatchFileOptions options for applying a diff patch
5474
// Note: `author` and `committer` are optional (if only one is given, it will be used for the other, otherwise the authenticated user will be used)
5575
type ApplyDiffPatchFileOptions struct {

options/locale/locale_en-US.ini

+3
Original file line numberDiff line numberDiff line change
@@ -1488,6 +1488,9 @@ pulls.desc = Enable pull requests and code reviews.
14881488
pulls.new = New Pull Request
14891489
pulls.view = View Pull Request
14901490
pulls.compare_changes = New Pull Request
1491+
pulls.allow_edits_from_maintainers = Allow edits from maintainers
1492+
pulls.allow_edits_from_maintainers_desc = Users with write access to the base branch can also push to this branch
1493+
pulls.allow_edits_from_maintainers_err = Updating failed
14911494
pulls.compare_changes_desc = Select the branch to merge into and the branch to pull from.
14921495
pulls.compare_base = merge into
14931496
pulls.compare_compare = pull from

routers/api/v1/api.go

+13-4
Original file line numberDiff line numberDiff line change
@@ -283,6 +283,15 @@ func reqRepoWriter(unitTypes ...unit.Type) func(ctx *context.APIContext) {
283283
}
284284
}
285285

286+
// reqRepoBranchWriter user should have a permission to write to a branch, or be a site admin
287+
func reqRepoBranchWriter(ctx *context.APIContext) {
288+
options, ok := web.GetForm(ctx).(api.FileOptionInterface)
289+
if !ok || (!ctx.Repo.CanWriteToBranch(ctx.Doer, options.Branch()) && !ctx.IsUserSiteAdmin()) {
290+
ctx.Error(http.StatusForbidden, "reqRepoBranchWriter", "user should have a permission to write to this branch")
291+
return
292+
}
293+
}
294+
286295
// reqRepoReader user should have specific read permission or be a repo admin or a site admin
287296
func reqRepoReader(unitType unit.Type) func(ctx *context.APIContext) {
288297
return func(ctx *context.APIContext) {
@@ -1021,10 +1030,10 @@ func Routes() *web.Route {
10211030
m.Get("", repo.GetContentsList)
10221031
m.Get("/*", repo.GetContents)
10231032
m.Group("/*", func() {
1024-
m.Post("", bind(api.CreateFileOptions{}), repo.CreateFile)
1025-
m.Put("", bind(api.UpdateFileOptions{}), repo.UpdateFile)
1026-
m.Delete("", bind(api.DeleteFileOptions{}), repo.DeleteFile)
1027-
}, reqRepoWriter(unit.TypeCode), reqToken())
1033+
m.Post("", bind(api.CreateFileOptions{}), reqRepoBranchWriter, repo.CreateFile)
1034+
m.Put("", bind(api.UpdateFileOptions{}), reqRepoBranchWriter, repo.UpdateFile)
1035+
m.Delete("", bind(api.DeleteFileOptions{}), reqRepoBranchWriter, repo.DeleteFile)
1036+
}, reqToken())
10281037
}, reqRepoReader(unit.TypeCode))
10291038
m.Get("/signing-key.gpg", misc.SigningKey)
10301039
m.Group("/topics", func() {

routers/api/v1/repo/file.go

+6-4
Original file line numberDiff line numberDiff line change
@@ -173,8 +173,10 @@ func GetEditorconfig(ctx *context.APIContext) {
173173
}
174174

175175
// canWriteFiles returns true if repository is editable and user has proper access level.
176-
func canWriteFiles(r *context.Repository) bool {
177-
return r.Permission.CanWrite(unit.TypeCode) && !r.Repository.IsMirror && !r.Repository.IsArchived
176+
func canWriteFiles(ctx *context.APIContext, branch string) bool {
177+
return ctx.Repo.Permission.CanWriteToBranch(ctx.Doer, branch) &&
178+
!ctx.Repo.Repository.IsMirror &&
179+
!ctx.Repo.Repository.IsArchived
178180
}
179181

180182
// canReadFiles returns true if repository is readable and user has proper access level.
@@ -376,7 +378,7 @@ func handleCreateOrUpdateFileError(ctx *context.APIContext, err error) {
376378

377379
// Called from both CreateFile or UpdateFile to handle both
378380
func createOrUpdateFile(ctx *context.APIContext, opts *files_service.UpdateRepoFileOptions) (*api.FileResponse, error) {
379-
if !canWriteFiles(ctx.Repo) {
381+
if !canWriteFiles(ctx, opts.OldBranch) {
380382
return nil, models.ErrUserDoesNotHaveAccessToRepo{
381383
UserID: ctx.Doer.ID,
382384
RepoName: ctx.Repo.Repository.LowerName,
@@ -433,7 +435,7 @@ func DeleteFile(ctx *context.APIContext) {
433435
// "$ref": "#/responses/error"
434436

435437
apiOpts := web.GetForm(ctx).(*api.DeleteFileOptions)
436-
if !canWriteFiles(ctx.Repo) {
438+
if !canWriteFiles(ctx, apiOpts.BranchName) {
437439
ctx.Error(http.StatusForbidden, "DeleteFile", models.ErrUserDoesNotHaveAccessToRepo{
438440
UserID: ctx.Doer.ID,
439441
RepoName: ctx.Repo.Repository.LowerName,

routers/api/v1/repo/patch.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ func ApplyDiffPatch(ctx *context.APIContext) {
7777
opts.Message = "apply-patch"
7878
}
7979

80-
if !canWriteFiles(ctx.Repo) {
80+
if !canWriteFiles(ctx, apiOpts.BranchName) {
8181
ctx.Error(http.StatusInternalServerError, "ApplyPatch", models.ErrUserDoesNotHaveAccessToRepo{
8282
UserID: ctx.Doer.ID,
8383
RepoName: ctx.Repo.Repository.LowerName,

routers/api/v1/repo/pull.go

+12
Original file line numberDiff line numberDiff line change
@@ -616,6 +616,18 @@ func EditPullRequest(ctx *context.APIContext) {
616616
notification.NotifyPullRequestChangeTargetBranch(ctx.Doer, pr, form.Base)
617617
}
618618

619+
// update allow edits
620+
if form.AllowMaintainerEdit != nil {
621+
if err := pull_service.SetAllowEdits(ctx, ctx.Doer, pr, *form.AllowMaintainerEdit); err != nil {
622+
if errors.Is(pull_service.ErrUserHasNoPermissionForAction, err) {
623+
ctx.Error(http.StatusForbidden, "SetAllowEdits", fmt.Sprintf("SetAllowEdits: %s", err))
624+
return
625+
}
626+
ctx.ServerError("SetAllowEdits", err)
627+
return
628+
}
629+
}
630+
619631
// Refetch from database
620632
pr, err = models.GetPullRequestByIndex(ctx.Repo.Repository.ID, pr.Index)
621633
if err != nil {

0 commit comments

Comments
 (0)