2025-11-21 combined security patches (#10037)

[CVSS 5.3 Medium](https://www.first.org/cvss/calculator/4-0#CVSS:4.0/AV:N/AC:L/AT:N/PR:L/UI:N/VC:L/VI:N/VA:N/SC:N/SI:N/SA:N) -- The `/repos/{owner}/{repo}/issues/{index}/dependencies` APIs allow a user to link an issue in one repository as "depending upon" an issue in another repository.  Forgejo's implementation had an incorrect permission check which would verify only that the user had write permissions on the issue being modified, and not on the issue it was linking to.  Due to the incorrect permission check, it was possible to view limited information (the existence of, and title of) an issue in a private repository that the user does not have access to view.  The permission check has been corrected to take into account visibility of the remote repository.

[CVSS 5.3 Medium](https://www.first.org/cvss/calculator/4-0#CVSS:4.0/AV:N/AC:L/AT:N/PR:L/UI:N/VC:L/VI:N/VA:N/SC:N/SI:N/SA:N) -- Fetching information about a release via the `/repos/{owner}/{repo}/releases/tag/{tag}` API endpoint did not check whether the release was a draft, allowing accessing to information about a draft release to users who could predict an upcoming release tag but didn't have access to view it.  The missing check has been added, returning a 404 response when the release is not published.

[CVSS 6.3 Medium](https://www.first.org/cvss/calculator/4-0#CVSS:4.0/AV:N/AC:L/AT:P/PR:N/UI:N/VC:N/VI:L/VA:N/SC:N/SI:N/SA:N) -- Forgejo's web interface allows deleting tags on a git repository through a form post.  The endpoint for this form post had misconfigured middleware handlers which enforce security rights, allowing an anonymous user, or a logged-in user without the correct permissions, to delete tags on repositories that they did not own by injecting arbitrary internal tag identifiers into the form.  The middleware handler configuration has been corrected.

[CVSS 2.1 Low](https://www.first.org/cvss/calculator/4-0#CVSS:4.0/AV:N/AC:L/AT:P/PR:H/UI:N/VC:N/VI:L/VA:N/SC:N/SI:N/SA:N) -- When the head branch of a pull request matches a branch protection rule, the head branch should be able to be merged or rebased only according to the "Push" rules defined in the protection rule.  An implementation error checked those branch protection rules in the context of the base repository rather than the head repository, allowing users with write access to the base repository to be considered able to push to the branch, bypassing the "Enable push" option's expected security control.

[CVSS 2.1 Low](https://www.first.org/cvss/calculator/4-0#CVSS:4.0/AV:N/AC:L/AT:P/PR:H/UI:N/VC:N/VI:L/VA:N/SC:N/SI:N/SA:N) -- An issue owner can manipulate form inputs to delete the content history of comments they did not create, as long as those comments are on issues that they own.  Although comment content is not affected, the history of edits on the comment can be trimmed.  The validation in the form handler was corrected.

[CVSS 5.1 Medium](https://www.first.org/cvss/calculator/4-0#CVSS:4.0/AV:N/AC:L/AT:N/PR:H/UI:N/VC:N/VI:L/VA:N/SC:N/SI:N/SA:N) -- When a repository is configured with tag protection rules, it should not be possible for a user that is outside the whitelisted users or teams from modifying the protected tags.  An incorrect parameter being passed to a security verification method allowed a user with write access to the repo to delete tags even if they were protected, as long as the tag was originally created by a user who is still authorized by the protection rules.

<!--start release-notes-assistant-->

## Release notes
<!--URL:https://codeberg.org/forgejo/forgejo-->
- Security bug fixes
  - [PR](https://codeberg.org/forgejo/forgejo/pulls/10037): <!--number 10037 --><!--line 0 --><!--description Zml4KGFwaSk6IGZpeCBkZXBlbmRlbmN5IHJlcG8gcGVybXMgaW4gQ3JlYXRlL1JlbW92ZUlzc3VlRGVwZW5kZW5jeQ==-->fix(api): fix dependency repo perms in Create/RemoveIssueDependency<!--description-->
  - [PR](https://codeberg.org/forgejo/forgejo/pulls/10037): <!--number 10037 --><!--line 1 --><!--description Zml4KGFwaSk6IGRyYWZ0IHJlbGVhc2VzIGNvdWxkIGJlIHJlYWQgYmVmb3JlIGJlaW5nIHB1Ymxpc2hlZA==-->fix(api): draft releases could be read before being published<!--description-->
  - [PR](https://codeberg.org/forgejo/forgejo/pulls/10037): <!--number 10037 --><!--line 2 --><!--description bWlzY29uZmlndXJlZCBzZWN1cml0eSBjaGVja3Mgb24gdGFnIGRlbGV0ZSB3ZWIgZm9ybQ==-->misconfigured security checks on tag delete web form<!--description-->
  - [PR](https://codeberg.org/forgejo/forgejo/pulls/10037): <!--number 10037 --><!--line 3 --><!--description aW5jb3JyZWN0IGxvZ2ljIGluICJVcGRhdGUgUFIiIGRpZCBub3QgZW5mb3JjZSBoZWFkIGJyYW5jaCBwcm90ZWN0aW9uIHJ1bGVzIGNvcnJlY3RseQ==-->incorrect logic in "Update PR" did not enforce head branch protection rules correctly<!--description-->
  - [PR](https://codeberg.org/forgejo/forgejo/pulls/10037): <!--number 10037 --><!--line 4 --><!--description aXNzdWUgb3duZXIgY2FuIGRlbGV0ZSBhbm90aGVyIHVzZXIncyBjb21tZW50J3MgZWRpdCBoaXN0b3J5IG9uIHNhbWUgaXNzdWU=-->issue owner can delete another user's comment's edit history on same issue<!--description-->
  - [PR](https://codeberg.org/forgejo/forgejo/pulls/10037): <!--number 10037 --><!--line 5 --><!--description dGFnIHByb3RlY3Rpb24gcnVsZXMgY2FuIGJlIGJ5cGFzc2VkIGR1cmluZyB0YWcgZGVsZXRlIG9wZXJhdGlvbg==-->tag protection rules can be bypassed during tag delete operation<!--description-->
<!--end release-notes-assistant-->

Co-authored-by: Joshua Rogers <MegaManSec@users.noreply.github.com>
Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/10037
Reviewed-by: 0ko <0ko@noreply.codeberg.org>
Co-authored-by: Mathieu Fenniak <mathieu@fenniak.net>
Co-committed-by: Mathieu Fenniak <mathieu@fenniak.net>
This commit is contained in:
Mathieu Fenniak 2025-11-21 05:23:43 +01:00 committed by Mathieu Fenniak
parent 01399f13d9
commit 6c43dcbe0a
15 changed files with 240 additions and 35 deletions

View file

@ -88,7 +88,7 @@ func (r *Route) wrapMiddlewareAndHandler(h []any) ([]func(http.Handler) http.Han
}
}
for _, m := range h {
if h != nil {
if m != nil {
handlerProviders = append(handlerProviders, toHandlerProvider(m))
}
}

6
release-notes/10037.md Normal file
View file

@ -0,0 +1,6 @@
fix(api): fix dependency repo perms in Create/RemoveIssueDependency
fix(api): draft releases could be read before being published
fix: misconfigured security checks on tag delete web form
fix: incorrect logic in "Update PR" did not enforce head branch protection rules correctly
fix: issue owner can delete another user's comment's edit history on same issue
fix: tag protection rules can be bypassed during tag delete operation

View file

@ -206,7 +206,7 @@ func CreateIssueDependency(ctx *context.APIContext) {
return
}
dependencyPerm := getPermissionForRepo(ctx, target.Repo)
dependencyPerm := getPermissionForRepo(ctx, dependency.Repo)
if ctx.Written() {
return
}
@ -268,7 +268,7 @@ func RemoveIssueDependency(ctx *context.APIContext) {
return
}
dependencyPerm := getPermissionForRepo(ctx, target.Repo)
dependencyPerm := getPermissionForRepo(ctx, dependency.Repo)
if ctx.Written() {
return
}

View file

@ -8,6 +8,7 @@ import (
"forgejo.org/models"
repo_model "forgejo.org/models/repo"
unit_model "forgejo.org/models/unit"
"forgejo.org/services/context"
"forgejo.org/services/convert"
releaseservice "forgejo.org/services/release"
@ -59,6 +60,13 @@ func GetReleaseByTag(ctx *context.APIContext) {
return
}
if release.IsDraft {
if !ctx.IsSigned || !ctx.Repo.CanWrite(unit_model.TypeReleases) {
ctx.NotFound()
return
}
}
if err = release.LoadAttributes(ctx); err != nil {
ctx.Error(http.StatusInternalServerError, "LoadAttributes", err)
return

View file

@ -210,12 +210,11 @@ func SoftDeleteContentHistory(ctx *context.Context) {
ctx.NotFound("CompareRepoID", issues_model.ErrCommentNotExist{})
return
}
if commentID != 0 {
if history.CommentID != commentID {
ctx.NotFound("CompareCommentID", issues_model.ErrCommentNotExist{})
return
}
if commentID != 0 {
if comment, err = issues_model.GetCommentByID(ctx, commentID); err != nil {
log.Error("can not get comment for issue content history %v. err=%v", historyID, err)
return

View file

@ -1335,8 +1335,8 @@ func registerRoutes(m *web.Route) {
m.Get(".atom", feedEnabled, repo.TagsListFeedAtom)
}, ctxDataSet("EnableFeed", setting.Other.EnableFeed),
repo.MustBeNotEmpty, reqRepoCodeReader, context.RepoRefByType(context.RepoRefTag, true))
m.Post("/tags/delete", repo.DeleteTag, reqSignIn,
repo.MustBeNotEmpty, context.RepoMustNotBeArchived(), reqRepoCodeWriter, context.RepoRef())
m.Post("/tags/delete", reqSignIn, repo.MustBeNotEmpty, context.RepoMustNotBeArchived(), reqRepoCodeWriter,
context.RepoRef(), repo.DeleteTag)
}, ignSignIn, context.RepoAssignment, context.UnitTypes())
// Releases

View file

@ -136,7 +136,7 @@ func IsUserAllowedToUpdate(ctx context.Context, pull *issues_model.PullRequest,
// Update function need push permission
if pb != nil {
pb.Repo = pull.BaseRepo
pb.Repo = pull.HeadRepo
if !pb.CanUserPush(ctx, user) {
return false, false, nil
}

View file

@ -399,7 +399,7 @@ func DeleteReleaseByID(ctx context.Context, repo *repo_model.Repository, rel *re
if err != nil {
return fmt.Errorf("GetProtectedTags: %w", err)
}
isAllowed, err := git_model.IsUserAllowedToControlTag(ctx, protectedTags, rel.TagName, rel.PublisherID)
isAllowed, err := git_model.IsUserAllowedToControlTag(ctx, protectedTags, rel.TagName, doer.ID)
if err != nil {
return err
}

View file

@ -813,3 +813,48 @@ func TestAPIInternalAndExternalIssueTracker(t *testing.T) {
runTest(t, externalIssueRepo, false)
runTest(t, disabledIssueRepo, false)
}
func TestAPIIssueDependencyPermissions(t *testing.T) {
defer tests.PrepareTestEnv(t)()
actingUser := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4})
token := getUserToken(t, actingUser.Name, auth_model.AccessTokenScopeAll)
actingUserRepo, _, reset := tests.CreateDeclarativeRepoWithOptions(t, actingUser, tests.DeclarativeRepoOptions{})
defer reset()
actingUserIssue := createIssue(t, actingUser, actingUserRepo, "source issue", "some content")
otherUser := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
otherUserRepo, _, reset := tests.CreateDeclarativeRepoWithOptions(t, otherUser, tests.DeclarativeRepoOptions{
IsPrivate: optional.Some(true),
})
defer reset()
otherUserIssue := createIssue(t, otherUser, otherUserRepo, "target issue", "some content")
apiEndpoint := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/dependencies", actingUserRepo.OwnerName, actingUserRepo.Name, actingUserIssue.Index)
req := NewRequest(t, "GET", apiEndpoint).AddTokenAuth(token)
resp := MakeRequest(t, req, http.StatusOK)
var blockingIssues []*api.Issue
DecodeJSON(t, resp, &blockingIssues)
require.Empty(t, blockingIssues)
req = NewRequestWithJSON(t, "POST", apiEndpoint, api.IssueMeta{
Owner: otherUserRepo.OwnerName,
Name: otherUserRepo.Name,
Index: otherUserIssue.Index,
}).AddTokenAuth(token)
MakeRequest(t, req, http.StatusNotFound) // as otherUserRepo is a private repo we can't link a dependency to it
req = NewRequest(t, "GET", apiEndpoint).AddTokenAuth(token)
resp = MakeRequest(t, req, http.StatusOK)
blockingIssues = []*api.Issue{} // reset
DecodeJSON(t, resp, &blockingIssues)
require.Empty(t, blockingIssues)
req = NewRequestWithJSON(t, "DELETE", apiEndpoint, api.IssueMeta{
Owner: otherUserRepo.OwnerName,
Name: otherUserRepo.Name,
Index: otherUserIssue.Index,
}).AddTokenAuth(token)
MakeRequest(t, req, http.StatusNotFound) // as otherUserRepo is a private repo we can't link a dependency to it
}

View file

@ -24,7 +24,7 @@ import (
"github.com/stretchr/testify/require"
)
func TestAPIListReleases(t *testing.T) {
func TestAPIReleaseList(t *testing.T) {
defer tests.PrepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
@ -102,7 +102,7 @@ func createNewReleaseUsingAPI(t *testing.T, token string, owner *user_model.User
return &newRelease
}
func TestAPICreateAndUpdateRelease(t *testing.T) {
func TestAPIReleaseCreateAndUpdate(t *testing.T) {
defer tests.PrepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
@ -159,7 +159,7 @@ func TestAPICreateAndUpdateRelease(t *testing.T) {
assert.True(t, newRelease.HideArchiveLinks)
}
func TestAPICreateProtectedTagRelease(t *testing.T) {
func TestAPIReleaseCreateProtectedTag(t *testing.T) {
defer tests.PrepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4})
@ -184,7 +184,7 @@ func TestAPICreateProtectedTagRelease(t *testing.T) {
MakeRequest(t, req, http.StatusUnprocessableEntity)
}
func TestAPICreateReleaseToDefaultBranch(t *testing.T) {
func TestAPIReleaseCreateToDefaultBranch(t *testing.T) {
defer tests.PrepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
@ -195,7 +195,7 @@ func TestAPICreateReleaseToDefaultBranch(t *testing.T) {
createNewReleaseUsingAPI(t, token, owner, repo, "v0.0.1", "", "v0.0.1", "test")
}
func TestAPICreateReleaseToDefaultBranchOnExistingTag(t *testing.T) {
func TestAPIReleaseCreateToDefaultBranchOnExistingTag(t *testing.T) {
defer tests.PrepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
@ -213,7 +213,7 @@ func TestAPICreateReleaseToDefaultBranchOnExistingTag(t *testing.T) {
createNewReleaseUsingAPI(t, token, owner, repo, "v0.0.1", "", "v0.0.1", "test")
}
func TestAPICreateReleaseGivenInvalidTarget(t *testing.T) {
func TestAPIReleaseCreateGivenInvalidTarget(t *testing.T) {
defer tests.PrepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
@ -231,7 +231,7 @@ func TestAPICreateReleaseGivenInvalidTarget(t *testing.T) {
MakeRequest(t, req, http.StatusNotFound)
}
func TestAPIGetLatestRelease(t *testing.T) {
func TestAPIReleaseGetLatest(t *testing.T) {
defer tests.PrepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
@ -246,7 +246,7 @@ func TestAPIGetLatestRelease(t *testing.T) {
assert.Equal(t, "testing-release", release.Title)
}
func TestAPIGetReleaseByTag(t *testing.T) {
func TestAPIReleaseGetByTag(t *testing.T) {
defer tests.PrepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
@ -266,13 +266,29 @@ func TestAPIGetReleaseByTag(t *testing.T) {
req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/%s", owner.Name, repo.Name, nonexistingtag))
resp = MakeRequest(t, req, http.StatusNotFound)
var err *api.APIError
DecodeJSON(t, resp, &err)
assert.NotEmpty(t, err.Message)
}
func TestAPIDeleteReleaseByTagName(t *testing.T) {
func TestAPIReleaseGetDraftByTag(t *testing.T) {
defer tests.PrepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
rel := unittest.AssertExistsAndLoadBean(t, &repo_model.Release{
RepoID: repo.ID,
TagName: "draft-release",
})
assert.True(t, rel.IsDraft)
req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/%s", repo.OwnerName, repo.Name, rel.TagName))
resp := MakeRequest(t, req, http.StatusNotFound)
var err *api.APIError
DecodeJSON(t, resp, &err)
assert.NotEmpty(t, err.Message)
}
func TestAPIReleaseDeleteByTagName(t *testing.T) {
defer tests.PrepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
@ -298,7 +314,7 @@ func TestAPIDeleteReleaseByTagName(t *testing.T) {
_ = MakeRequest(t, req, http.StatusNoContent)
}
func TestAPIUploadAssetRelease(t *testing.T) {
func TestAPIReleaseUploadAsset(t *testing.T) {
defer tests.PrepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
@ -362,7 +378,7 @@ func TestAPIUploadAssetRelease(t *testing.T) {
})
}
func TestAPIGetReleaseArchiveDownloadCount(t *testing.T) {
func TestAPIReleaseGetArchiveDownloadCount(t *testing.T) {
defer tests.PrepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
@ -398,7 +414,7 @@ func TestAPIGetReleaseArchiveDownloadCount(t *testing.T) {
assert.Equal(t, int64(0), release.ArchiveDownloadCount.Zip)
}
func TestAPIExternalAssetRelease(t *testing.T) {
func TestAPIReleaseExternalAsset(t *testing.T) {
defer tests.PrepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
@ -421,7 +437,7 @@ func TestAPIExternalAssetRelease(t *testing.T) {
assert.Equal(t, "external", attachment.Type)
}
func TestAPIAllowedAPIURLInRelease(t *testing.T) {
func TestAPIReleaseAllowedAPIURL(t *testing.T) {
defer tests.PrepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
@ -445,7 +461,7 @@ func TestAPIAllowedAPIURLInRelease(t *testing.T) {
assert.Equal(t, "external", attachment.Type)
}
func TestAPIDuplicateAssetRelease(t *testing.T) {
func TestAPIReleaseDuplicateAsset(t *testing.T) {
defer tests.PrepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
@ -466,7 +482,7 @@ func TestAPIDuplicateAssetRelease(t *testing.T) {
MakeRequest(t, req, http.StatusBadRequest)
}
func TestAPIMissingAssetRelease(t *testing.T) {
func TestAPIReleaseMissingAsset(t *testing.T) {
defer tests.PrepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})

View file

@ -16,6 +16,7 @@ import (
"forgejo.org/tests"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestAPIRepoTags(t *testing.T) {
@ -154,3 +155,55 @@ func TestAPIGetTagsPaginated(t *testing.T) {
assert.Contains(t, link, "rel=\"next\"")
assert.Contains(t, link, "page=2")
}
func TestAPIRepoTagDeleteProtection(t *testing.T) {
defer tests.PrepareTestEnv(t)()
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
// Login as User2.
session := loginUser(t, user.Name)
token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository)
repoName := "repo1"
req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/tags", user.Name, repoName).
AddTokenAuth(token)
resp := MakeRequest(t, req, http.StatusOK)
var tags []*api.Tag
DecodeJSON(t, resp, &tags)
require.Len(t, tags, 1)
require.Equal(t, "v1.1", tags[0].Name)
// Create a tag protection rule for the repo so that `user2` cannot create/remove tags, even if they have write
// perms to the repo... which they do becase they own it.
req = NewRequestWithJSON(t, "POST",
fmt.Sprintf("/api/v1/repos/%s/%s/tag_protections", user.Name, repoName),
&api.CreateTagProtectionOption{
NamePattern: "v*",
WhitelistUsernames: []string{"user1"},
}).
AddTokenAuth(token)
resp = MakeRequest(t, req, http.StatusCreated)
var tagProtection api.TagProtection
DecodeJSON(t, resp, &tagProtection)
require.Equal(t, "v*", tagProtection.NamePattern)
// Delete the release associated with v1.1, so that it's possible to delete the tag.
delReq := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/releases/tags/%s", user.Name, repoName, tags[0].Name).
AddTokenAuth(token)
MakeRequest(t, delReq, http.StatusNoContent)
// Attempt to delete the tag, which should be denied by the tag protection rule.
delReq = NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/tags/%s", user.Name, repoName, tags[0].Name).
AddTokenAuth(token)
MakeRequest(t, delReq, http.StatusUnprocessableEntity)
// Remove the tag protection rule.
delReq = NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/tag_protections/%d", user.Name, repoName, tagProtection.ID).
AddTokenAuth(token)
MakeRequest(t, delReq, http.StatusNoContent)
// Attempt to delete the tag again, which should now be permitted.
delReq = NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/tags/%s", user.Name, repoName, tags[0].Name).
AddTokenAuth(token)
MakeRequest(t, delReq, http.StatusNoContent)
}

View file

@ -87,6 +87,49 @@ func TestAPIPullUpdateByRebase(t *testing.T) {
})
}
func TestAPIPullUpdateBranchProtection(t *testing.T) {
onApplicationRun(t, func(t *testing.T, giteaURL *url.URL) {
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
baseRepoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4})
org26 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 26})
pr := createOutdatedPR(t, user, org26, baseRepoOwner)
// Allow edits from maintainers on the PR
pr.AllowMaintainerEdit = true
err := issues_model.UpdateAllowEdits(t.Context(), pr)
require.NoError(t, err)
session := loginUser(t, user.LoginName)
token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository)
// Set up a branch protection rule on the *head* branch such that it cannot be pushed to, which should block
// updating the PR.
pr.LoadBaseRepo(t.Context())
pr.LoadHeadRepo(t.Context())
req := NewRequestWithJSON(t, "POST",
fmt.Sprintf("/api/v1/repos/%s/%s/branch_protections", pr.HeadRepo.OwnerName, pr.HeadRepo.Name),
&api.BranchProtection{
BranchName: "*",
RuleName: "*",
EnablePush: true,
}).AddTokenAuth(token)
MakeRequest(t, req, http.StatusCreated)
// `session/token` is from the owner of the head branch, and should be allowed to do the update:
req = NewRequestf(t, "POST", "/api/v1/repos/%s/%s/pulls/%d/update", pr.BaseRepo.OwnerName, pr.BaseRepo.Name, pr.Issue.Index).
AddTokenAuth(token)
session.MakeRequest(t, req, http.StatusOK)
// Switch over to the base repo owner. Even though this PR is set to allow edits by maintainers, they shouldn't
// be allowed to update the PR because the head branch is protected by a branch protection rule.
session = loginUser(t, baseRepoOwner.LoginName)
token = getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository)
req = NewRequestf(t, "POST", "/api/v1/repos/%s/%s/pulls/%d/update", pr.BaseRepo.OwnerName, pr.BaseRepo.Name, pr.Issue.Index).
AddTokenAuth(token)
session.MakeRequest(t, req, http.StatusForbidden)
})
}
func TestAPIViewUpdateSettings(t *testing.T) {
onApplicationRun(t, func(t *testing.T, giteaURL *url.URL) {
// Create PR to test
@ -181,8 +224,13 @@ func assertViewPullUpdate(t *testing.T, pr *issues_model.PullRequest, session *T
}
}
func createOutdatedPR(t *testing.T, actor, forkOrg *user_model.User) *issues_model.PullRequest {
baseRepo, _, _ := tests.CreateDeclarativeRepo(t, actor, "repo-pr-update", nil, nil, nil)
func createOutdatedPR(t *testing.T, actor, forkOrg *user_model.User, baseRepoOwnerOption ...*user_model.User) *issues_model.PullRequest {
baseRepoOwner := actor
if len(baseRepoOwnerOption) == 1 {
baseRepoOwner = baseRepoOwnerOption[0]
}
baseRepo, _, _ := tests.CreateDeclarativeRepo(t, baseRepoOwner, "repo-pr-update", nil, nil, nil)
headRepo, err := repo_service.ForkRepositoryAndUpdates(git.DefaultContext, actor, forkOrg, repo_service.ForkRepoOptions{
BaseRepo: baseRepo,
@ -193,7 +241,7 @@ func createOutdatedPR(t *testing.T, actor, forkOrg *user_model.User) *issues_mod
assert.NotEmpty(t, headRepo)
// create a commit on base Repo
_, err = files_service.ChangeRepoFiles(git.DefaultContext, baseRepo, actor, &files_service.ChangeRepoFilesOptions{
_, err = files_service.ChangeRepoFiles(git.DefaultContext, baseRepo, baseRepoOwner, &files_service.ChangeRepoFilesOptions{
Files: []*files_service.ChangeRepoFile{
{
Operation: "create",

View file

@ -110,22 +110,50 @@ func TestDeleteRelease(t *testing.T) {
release := unittest.AssertExistsAndLoadBean(t, &repo_model.Release{TagName: "v2.0"})
assert.False(t, release.IsTag)
// Using the ID of a comment that does not belong to the repository must fail
session5 := loginUser(t, "user5")
session := loginUser(t, "user2") // owner user session
session5 := loginUser(t, "user5") // different user session; using the ID of a release that does not belong to the repository must fail
anonSession := emptyTestSession(t) // anonymous session
otherRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{OwnerName: "user5", LowerName: "repo4"})
// can't delete a release by ID from the wrong repository context (otherRepo)
req := NewRequest(t, "POST", fmt.Sprintf("%s/releases/delete?id=%d", otherRepo.Link(), release.ID))
session5.MakeRequest(t, req, http.StatusNotFound)
session := loginUser(t, "user2")
// can't delete a release that the current user isn't a writer for
req = NewRequest(t, "POST", fmt.Sprintf("%s/releases/delete?id=%d", repo.Link(), release.ID))
session5.MakeRequest(t, req, http.StatusNotFound)
// can't delete a release while anonymous
req = NewRequest(t, "POST", fmt.Sprintf("%s/releases/delete?id=%d", repo.Link(), release.ID))
anonSession.MakeRequest(t, req, http.StatusSeeOther) // login redirect
// can't delete a release by ID from the wrong repository context (otherRepo) as the correct user
req = NewRequest(t, "POST", fmt.Sprintf("%s/releases/delete?id=%d", otherRepo.Link(), release.ID))
session.MakeRequest(t, req, http.StatusNotFound)
// but when everything aligns, we can delete the release
req = NewRequest(t, "POST", fmt.Sprintf("%s/releases/delete?id=%d", repo.Link(), release.ID))
session.MakeRequest(t, req, http.StatusOK)
release = unittest.AssertExistsAndLoadBean(t, &repo_model.Release{ID: release.ID})
if assert.True(t, release.IsTag) {
// can't delete a release by ID from the wrong repository context (otherRepo)
req = NewRequest(t, "POST", fmt.Sprintf("%s/tags/delete?id=%d", otherRepo.Link(), release.ID))
session5.MakeRequest(t, req, http.StatusNotFound)
// can't delete a release that the current user isn't a writer for
req = NewRequest(t, "POST", fmt.Sprintf("%s/tags/delete?id=%d", repo.Link(), release.ID))
session5.MakeRequest(t, req, http.StatusNotFound)
// can't delete a release while anonymous
req = NewRequest(t, "POST", fmt.Sprintf("%s/tags/delete?id=%d", repo.Link(), release.ID))
anonSession.MakeRequest(t, req, http.StatusSeeOther) // login redirect
// can't delete a release by ID from the wrong repository context (otherRepo) as the correct user
req = NewRequest(t, "POST", fmt.Sprintf("%s/tags/delete?id=%d", otherRepo.Link(), release.ID))
session.MakeRequest(t, req, http.StatusNotFound)
// but when everything aligns, we can delete the tag
req = NewRequest(t, "POST", fmt.Sprintf("%s/tags/delete?id=%d", repo.Link(), release.ID))
session.MakeRequest(t, req, http.StatusOK)

View file

@ -220,7 +220,7 @@ func TestRepushTag(t *testing.T) {
_, _, err = git.NewCommand(git.DefaultContext, "push", "origin", "--delete", "v2.0").RunStdString(&git.RunOpts{Dir: dstPath})
require.NoError(t, err)
// query the release by API and it should be a draft
req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/%s", owner.Name, repo.Name, "v2.0"))
req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/%s", owner.Name, repo.Name, "v2.0")).AddTokenAuth(token)
resp := MakeRequest(t, req, http.StatusOK)
var respRelease *api.Release
DecodeJSON(t, resp, &respRelease)

View file

@ -370,6 +370,7 @@ type DeclarativeRepoOptions struct {
AutoInit optional.Option[bool]
IsTemplate optional.Option[bool]
ObjectFormat optional.Option[string]
IsPrivate optional.Option[bool]
}
func CreateDeclarativeRepoWithOptions(t *testing.T, owner *user_model.User, opts DeclarativeRepoOptions) (*repo_model.Repository, string, func()) {
@ -402,6 +403,7 @@ func CreateDeclarativeRepoWithOptions(t *testing.T, owner *user_model.User, opts
DefaultBranch: "main",
IsTemplate: opts.IsTemplate.Value(),
ObjectFormatName: opts.ObjectFormat.Value(),
IsPrivate: opts.IsPrivate.Value(),
})
require.NoError(t, err)
assert.NotEmpty(t, repo)