mirror of
https://github.com/go-gitea/gitea.git
synced 2026-04-30 01:14:41 +02:00
## Overview This PR introduces granular permission controls for Gitea Actions tokens (`GITEA_TOKEN`), aligning Gitea's security model with GitHub Actions standards while maintaining compatibility with Gitea's unique repository unit system. It addresses the need for finer access control by allowing administrators and repository owners to define default token permissions, set maximum permission ceilings, and control cross-repository access within organizations. ## Key Features ### 1. Granular Token Permissions - **Standard Keyword Support**: Implements support for the `permissions:` keyword in workflow and job YAML files (e.g., `contents: read`, `issues: write`). - **Permission Modes**: - **Permissive**: Default write access for most units (backwards compatible). - **Restricted**: Default read-only access for `contents` and `packages`, with no access to other units. - ~~**Custom**: Allows defining specific default levels for each unit type (Code, Issues, PRs, Packages, etc.).~~**EDIT removed UI was confusing** - **Clamping Logic**: Workflow-defined permissions are automatically "clamped" by repository or organization-level maximum settings. Workflows cannot escalate their own permissions beyond these limits. ### 2. Organization & Repository Settings - **Settings UI**: Added new settings pages at both Organization and Repository levels to manage Actions token defaults and maximums. - **Inheritance**: Repositories can be configured to "Follow organization-level configuration," simplifying management across large organizations. - **Cross-Repository Access**: Added a policy to control whether Actions workflows can access other repositories or packages within the same organization. This can be set to "None," "All," or restricted to a "Selected" list of repositories. ### 3. Security Hardening - **Fork Pull Request Protection**: Tokens for workflows triggered by pull requests from forks are strictly enforced as read-only, regardless of repository settings. - ~~**Package Access**: Actions tokens can now only access packages explicitly linked to a repository, with cross-repo access governed by the organization's security policy.~~ **EDIT removed https://github.com/go-gitea/gitea/pull/36173#issuecomment-3873675346** - **Git Hook Integration**: Propagates Actions Task IDs to git hooks to ensure that pushes performed by Actions tokens respect the specific permissions granted at runtime. ### 4. Technical Implementation - **Permission Persistence**: Parsed permissions are calculated at job creation and stored in the `action_run_job` table. This ensures the token's authority is deterministic throughout the job's lifecycle. - **Parsing Priority**: Implemented a priority system in the YAML parser where the broad `contents` scope is applied first, allowing granular scopes like `code` or `releases` to override it for precise control. - **Re-runs**: Permissions are re-evaluated during a job re-run to incorporate any changes made to repository settings in the interim. ### How to Test 1. **Unit Tests**: Run `go test ./services/actions/...` and `go test ./models/repo/...` to verify parsing logic and permission clamping. 2. **Integration Tests**: Comprehensive tests have been added to `tests/integration/actions_job_token_test.go` covering: - Permissive vs. Restricted mode behavior. - YAML `permissions:` keyword evaluation. - Organization cross-repo access policies. - Resource access (Git, API, and Packages) under various permission configs. 3. **Manual Verification**: - Navigate to **Site/Org/Repo Settings -> Actions -> General**. - Change "Default Token Permissions" and verify that newly triggered workflows reflect these changes in their `GITEA_TOKEN` capabilities. - Attempt a cross-repo API call from an Action and verify the Org policy is enforced. ## Documentation Added a PR in gitea's docs for this : https://gitea.com/gitea/docs/pulls/318 ## UI: <img width="1366" height="619" alt="Screenshot 2026-01-24 174112" src="https://github.com/user-attachments/assets/bfa29c9a-4ea5-4346-9410-16d491ef3d44" /> <img width="1360" height="621" alt="Screenshot 2026-01-24 174048" src="https://github.com/user-attachments/assets/d5ec46c8-9a13-4874-a6a4-fb379936cef5" /> /fixes #24635 /claim #24635 --------- Signed-off-by: Excellencedev <ademiluyisuccessandexcellence@gmail.com> Signed-off-by: ChristopherHX <christopher.homberger@web.de> Signed-off-by: silverwind <me@silverwind.io> Signed-off-by: wxiaoguang <wxiaoguang@gmail.com> Co-authored-by: ChristopherHX <christopher.homberger@web.de> Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> Co-authored-by: silverwind <me@silverwind.io> Co-authored-by: Zettat123 <zettat123@gmail.com> Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
554 lines
19 KiB
Go
554 lines
19 KiB
Go
// Copyright 2019 The Gitea Authors. All rights reserved.
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
package private
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"os"
|
|
|
|
asymkey_model "code.gitea.io/gitea/models/asymkey"
|
|
git_model "code.gitea.io/gitea/models/git"
|
|
issues_model "code.gitea.io/gitea/models/issues"
|
|
perm_model "code.gitea.io/gitea/models/perm"
|
|
access_model "code.gitea.io/gitea/models/perm/access"
|
|
"code.gitea.io/gitea/models/unit"
|
|
user_model "code.gitea.io/gitea/models/user"
|
|
"code.gitea.io/gitea/modules/git"
|
|
"code.gitea.io/gitea/modules/git/gitcmd"
|
|
"code.gitea.io/gitea/modules/gitrepo"
|
|
"code.gitea.io/gitea/modules/log"
|
|
"code.gitea.io/gitea/modules/private"
|
|
"code.gitea.io/gitea/modules/util"
|
|
"code.gitea.io/gitea/modules/web"
|
|
"code.gitea.io/gitea/services/agit"
|
|
gitea_context "code.gitea.io/gitea/services/context"
|
|
pull_service "code.gitea.io/gitea/services/pull"
|
|
)
|
|
|
|
type preReceiveContext struct {
|
|
*gitea_context.PrivateContext
|
|
|
|
// loadedPusher indicates that where the following information are loaded
|
|
loadedPusher bool
|
|
user *user_model.User // it's the org user if a DeployKey is used
|
|
userPerm access_model.Permission
|
|
deployKeyAccessMode perm_model.AccessMode
|
|
|
|
canCreatePullRequest bool
|
|
checkedCanCreatePullRequest bool
|
|
|
|
canWriteCode bool
|
|
checkedCanWriteCode bool
|
|
|
|
protectedTags []*git_model.ProtectedTag
|
|
gotProtectedTags bool
|
|
|
|
env []string
|
|
|
|
opts *private.HookOptions
|
|
|
|
branchName string
|
|
}
|
|
|
|
// CanWriteCode returns true if pusher can write code
|
|
func (ctx *preReceiveContext) CanWriteCode() bool {
|
|
if !ctx.checkedCanWriteCode {
|
|
if !ctx.loadPusherAndPermission() {
|
|
return false
|
|
}
|
|
ctx.canWriteCode = issues_model.CanMaintainerWriteToBranch(ctx, ctx.userPerm, ctx.branchName, ctx.user) || ctx.deployKeyAccessMode >= perm_model.AccessModeWrite
|
|
ctx.checkedCanWriteCode = true
|
|
}
|
|
return ctx.canWriteCode
|
|
}
|
|
|
|
// AssertCanWriteCode returns true if pusher can write code
|
|
func (ctx *preReceiveContext) AssertCanWriteCode() bool {
|
|
if !ctx.CanWriteCode() {
|
|
if ctx.Written() {
|
|
return false
|
|
}
|
|
ctx.JSON(http.StatusForbidden, private.Response{
|
|
UserMsg: "User permission denied for writing.",
|
|
})
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
// CanCreatePullRequest returns true if pusher can create pull requests
|
|
func (ctx *preReceiveContext) CanCreatePullRequest() bool {
|
|
if !ctx.checkedCanCreatePullRequest {
|
|
if !ctx.loadPusherAndPermission() {
|
|
return false
|
|
}
|
|
ctx.canCreatePullRequest = ctx.userPerm.CanRead(unit.TypePullRequests)
|
|
ctx.checkedCanCreatePullRequest = true
|
|
}
|
|
return ctx.canCreatePullRequest
|
|
}
|
|
|
|
// AssertCreatePullRequest returns true if can create pull requests
|
|
func (ctx *preReceiveContext) AssertCreatePullRequest() bool {
|
|
if !ctx.CanCreatePullRequest() {
|
|
if ctx.Written() {
|
|
return false
|
|
}
|
|
ctx.JSON(http.StatusForbidden, private.Response{
|
|
UserMsg: "User permission denied for creating pull-request.",
|
|
})
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
// HookPreReceive checks whether a individual commit is acceptable
|
|
func HookPreReceive(ctx *gitea_context.PrivateContext) {
|
|
opts := web.GetForm(ctx).(*private.HookOptions)
|
|
|
|
ourCtx := &preReceiveContext{
|
|
PrivateContext: ctx,
|
|
env: generateGitEnv(opts), // Generate git environment for checking commits
|
|
opts: opts,
|
|
}
|
|
|
|
// Iterate across the provided old commit IDs
|
|
for i := range opts.OldCommitIDs {
|
|
oldCommitID := opts.OldCommitIDs[i]
|
|
newCommitID := opts.NewCommitIDs[i]
|
|
refFullName := opts.RefFullNames[i]
|
|
|
|
switch {
|
|
case refFullName.IsBranch():
|
|
preReceiveBranch(ourCtx, oldCommitID, newCommitID, refFullName)
|
|
case refFullName.IsTag():
|
|
preReceiveTag(ourCtx, refFullName)
|
|
case git.DefaultFeatures().SupportProcReceive && refFullName.IsFor():
|
|
preReceiveFor(ourCtx, refFullName)
|
|
default:
|
|
ourCtx.AssertCanWriteCode()
|
|
}
|
|
if ctx.Written() {
|
|
return
|
|
}
|
|
}
|
|
|
|
ctx.PlainText(http.StatusOK, "ok")
|
|
}
|
|
|
|
func preReceiveBranch(ctx *preReceiveContext, oldCommitID, newCommitID string, refFullName git.RefName) {
|
|
branchName := refFullName.BranchName()
|
|
ctx.branchName = branchName
|
|
|
|
if !ctx.AssertCanWriteCode() {
|
|
return
|
|
}
|
|
|
|
repo := ctx.Repo.Repository
|
|
gitRepo := ctx.Repo.GitRepo
|
|
objectFormat := ctx.Repo.GetObjectFormat()
|
|
|
|
defaultBranch := repo.DefaultBranch
|
|
if ctx.opts.IsWiki && repo.DefaultWikiBranch != "" {
|
|
defaultBranch = repo.DefaultWikiBranch
|
|
}
|
|
if branchName == defaultBranch && newCommitID == objectFormat.EmptyObjectID().String() {
|
|
log.Warn("Forbidden: Branch: %s is the default branch in %-v and cannot be deleted", branchName, repo)
|
|
ctx.JSON(http.StatusForbidden, private.Response{
|
|
UserMsg: fmt.Sprintf("branch %s is the default branch and cannot be deleted", branchName),
|
|
})
|
|
return
|
|
}
|
|
|
|
protectBranch, err := git_model.GetFirstMatchProtectedBranchRule(ctx, repo.ID, branchName)
|
|
if err != nil {
|
|
log.Error("Unable to get protected branch: %s in %-v Error: %v", branchName, repo, err)
|
|
ctx.JSON(http.StatusInternalServerError, private.Response{
|
|
Err: err.Error(),
|
|
})
|
|
return
|
|
}
|
|
|
|
// Allow pushes to non-protected branches
|
|
if protectBranch == nil {
|
|
return
|
|
}
|
|
protectBranch.Repo = repo
|
|
|
|
// This ref is a protected branch.
|
|
//
|
|
// First of all we need to enforce absolutely:
|
|
//
|
|
// 1. Detect and prevent deletion of the branch
|
|
if newCommitID == objectFormat.EmptyObjectID().String() {
|
|
log.Warn("Forbidden: Branch: %s in %-v is protected from deletion", branchName, repo)
|
|
ctx.JSON(http.StatusForbidden, private.Response{
|
|
UserMsg: fmt.Sprintf("branch %s is protected from deletion", branchName),
|
|
})
|
|
return
|
|
}
|
|
|
|
isForcePush := false
|
|
|
|
// 2. Disallow force pushes to protected branches
|
|
if oldCommitID != objectFormat.EmptyObjectID().String() {
|
|
output, _, err := gitrepo.RunCmdString(ctx,
|
|
repo,
|
|
gitcmd.NewCommand("rev-list", "--max-count=1").
|
|
AddDynamicArguments(oldCommitID, "^"+newCommitID).
|
|
WithEnv(ctx.env),
|
|
)
|
|
if err != nil {
|
|
log.Error("Unable to detect force push between: %s and %s in %-v Error: %v", oldCommitID, newCommitID, repo, err)
|
|
ctx.JSON(http.StatusInternalServerError, private.Response{
|
|
Err: fmt.Sprintf("Fail to detect force push: %v", err),
|
|
})
|
|
return
|
|
} else if len(output) > 0 {
|
|
if protectBranch.CanForcePush {
|
|
isForcePush = true
|
|
} else {
|
|
log.Warn("Forbidden: Branch: %s in %-v is protected from force push", branchName, repo)
|
|
ctx.JSON(http.StatusForbidden, private.Response{
|
|
UserMsg: fmt.Sprintf("branch %s is protected from force push", branchName),
|
|
})
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
// 3. Enforce require signed commits
|
|
if protectBranch.RequireSignedCommits {
|
|
err := verifyCommits(oldCommitID, newCommitID, gitRepo, ctx.env)
|
|
if err != nil {
|
|
if !isErrUnverifiedCommit(err) {
|
|
log.Error("Unable to check commits from %s to %s in %-v: %v", oldCommitID, newCommitID, repo, err)
|
|
ctx.JSON(http.StatusInternalServerError, private.Response{
|
|
Err: fmt.Sprintf("Unable to check commits from %s to %s: %v", oldCommitID, newCommitID, err),
|
|
})
|
|
return
|
|
}
|
|
unverifiedCommit := err.(*errUnverifiedCommit).sha
|
|
log.Warn("Forbidden: Branch: %s in %-v is protected from unverified commit %s", branchName, repo, unverifiedCommit)
|
|
ctx.JSON(http.StatusForbidden, private.Response{
|
|
UserMsg: fmt.Sprintf("branch %s is protected from unverified commit %s", branchName, unverifiedCommit),
|
|
})
|
|
return
|
|
}
|
|
}
|
|
|
|
// Now there are several tests which can be overridden:
|
|
//
|
|
// 4. Check protected file patterns - this is overridable from the UI
|
|
changedProtectedfiles := false
|
|
protectedFilePath := ""
|
|
|
|
globs := protectBranch.GetProtectedFilePatterns()
|
|
if len(globs) > 0 {
|
|
_, err := pull_service.CheckFileProtection(gitRepo, branchName, oldCommitID, newCommitID, globs, 1, ctx.env)
|
|
if err != nil {
|
|
if !pull_service.IsErrFilePathProtected(err) {
|
|
log.Error("Unable to check file protection for commits from %s to %s in %-v: %v", oldCommitID, newCommitID, repo, err)
|
|
ctx.JSON(http.StatusInternalServerError, private.Response{
|
|
Err: fmt.Sprintf("Unable to check file protection for commits from %s to %s: %v", oldCommitID, newCommitID, err),
|
|
})
|
|
return
|
|
}
|
|
|
|
changedProtectedfiles = true
|
|
protectedFilePath = err.(pull_service.ErrFilePathProtected).Path
|
|
}
|
|
}
|
|
|
|
// 5. Check if the doer is allowed to push (and force-push if the incoming push is a force-push)
|
|
var canPush bool
|
|
if ctx.opts.DeployKeyID != 0 {
|
|
// This flag is only ever true if protectBranch.CanForcePush is true
|
|
if isForcePush {
|
|
canPush = !changedProtectedfiles && protectBranch.CanPush && (!protectBranch.EnableForcePushAllowlist || protectBranch.ForcePushAllowlistDeployKeys)
|
|
} else {
|
|
canPush = !changedProtectedfiles && protectBranch.CanPush && (!protectBranch.EnableWhitelist || protectBranch.WhitelistDeployKeys)
|
|
}
|
|
} else {
|
|
user, err := user_model.GetUserByID(ctx, ctx.opts.UserID)
|
|
if err != nil {
|
|
log.Error("Unable to GetUserByID for commits from %s to %s in %-v: %v", oldCommitID, newCommitID, repo, err)
|
|
ctx.JSON(http.StatusInternalServerError, private.Response{
|
|
Err: fmt.Sprintf("Unable to GetUserByID for commits from %s to %s: %v", oldCommitID, newCommitID, err),
|
|
})
|
|
return
|
|
}
|
|
if isForcePush {
|
|
canPush = !changedProtectedfiles && protectBranch.CanUserForcePush(ctx, user)
|
|
} else {
|
|
canPush = !changedProtectedfiles && protectBranch.CanUserPush(ctx, user)
|
|
}
|
|
}
|
|
|
|
// 6. If we're not allowed to push directly
|
|
if !canPush {
|
|
// Is this is a merge from the UI/API?
|
|
if ctx.opts.PullRequestID == 0 {
|
|
// 6a. If we're not merging from the UI/API then there are two ways we got here:
|
|
//
|
|
// We are changing a protected file and we're not allowed to do that
|
|
if changedProtectedfiles {
|
|
log.Warn("Forbidden: Branch: %s in %-v is protected from changing file %s", branchName, repo, protectedFilePath)
|
|
ctx.JSON(http.StatusForbidden, private.Response{
|
|
UserMsg: fmt.Sprintf("branch %s is protected from changing file %s", branchName, protectedFilePath),
|
|
})
|
|
return
|
|
}
|
|
|
|
// Allow commits that only touch unprotected files
|
|
globs := protectBranch.GetUnprotectedFilePatterns()
|
|
if len(globs) > 0 {
|
|
unprotectedFilesOnly, err := pull_service.CheckUnprotectedFiles(gitRepo, branchName, oldCommitID, newCommitID, globs, ctx.env)
|
|
if err != nil {
|
|
log.Error("Unable to check file protection for commits from %s to %s in %-v: %v", oldCommitID, newCommitID, repo, err)
|
|
ctx.JSON(http.StatusInternalServerError, private.Response{
|
|
Err: fmt.Sprintf("Unable to check file protection for commits from %s to %s: %v", oldCommitID, newCommitID, err),
|
|
})
|
|
return
|
|
}
|
|
if unprotectedFilesOnly {
|
|
// Commit only touches unprotected files, this is allowed
|
|
return
|
|
}
|
|
}
|
|
|
|
// Or we're simply not able to push to this protected branch
|
|
if isForcePush {
|
|
log.Warn("Forbidden: User %d is not allowed to force-push to protected branch: %s in %-v", ctx.opts.UserID, branchName, repo)
|
|
ctx.JSON(http.StatusForbidden, private.Response{
|
|
UserMsg: "Not allowed to force-push to protected branch " + branchName,
|
|
})
|
|
return
|
|
}
|
|
log.Warn("Forbidden: User %d is not allowed to push to protected branch: %s in %-v", ctx.opts.UserID, branchName, repo)
|
|
ctx.JSON(http.StatusForbidden, private.Response{
|
|
UserMsg: "Not allowed to push to protected branch " + branchName,
|
|
})
|
|
return
|
|
}
|
|
// 6b. Merge (from UI or API)
|
|
|
|
// Get the PR, user and permissions for the user in the repository
|
|
pr, err := issues_model.GetPullRequestByID(ctx, ctx.opts.PullRequestID)
|
|
if err != nil {
|
|
log.Error("Unable to get PullRequest %d Error: %v", ctx.opts.PullRequestID, err)
|
|
ctx.JSON(http.StatusInternalServerError, private.Response{
|
|
Err: fmt.Sprintf("Unable to get PullRequest %d Error: %v", ctx.opts.PullRequestID, err),
|
|
})
|
|
return
|
|
}
|
|
|
|
// although we should have called `loadPusherAndPermission` before, here we call it explicitly again because we need to access ctx.user below
|
|
if !ctx.loadPusherAndPermission() {
|
|
// if error occurs, loadPusherAndPermission had written the error response
|
|
return
|
|
}
|
|
|
|
// Now check if the user is allowed to merge PRs for this repository
|
|
// Note: we can use ctx.perm and ctx.user directly as they will have been loaded above
|
|
allowedMerge, err := pull_service.IsUserAllowedToMerge(ctx, pr, ctx.userPerm, ctx.user)
|
|
if err != nil {
|
|
log.Error("Error calculating if allowed to merge: %v", err)
|
|
ctx.JSON(http.StatusInternalServerError, private.Response{
|
|
Err: fmt.Sprintf("Error calculating if allowed to merge: %v", err),
|
|
})
|
|
return
|
|
}
|
|
|
|
if !allowedMerge {
|
|
log.Warn("Forbidden: User %d is not allowed to push to protected branch: %s in %-v and is not allowed to merge pr #%d", ctx.opts.UserID, branchName, repo, pr.Index)
|
|
ctx.JSON(http.StatusForbidden, private.Response{
|
|
UserMsg: "Not allowed to push to protected branch " + branchName,
|
|
})
|
|
return
|
|
}
|
|
|
|
// If we're an admin for the repository we can ignore status checks, reviews and override protected files
|
|
if ctx.userPerm.IsAdmin() {
|
|
return
|
|
}
|
|
|
|
// Now if we're not an admin - we can't overwrite protected files so fail now
|
|
if changedProtectedfiles {
|
|
log.Warn("Forbidden: Branch: %s in %-v is protected from changing file %s", branchName, repo, protectedFilePath)
|
|
ctx.JSON(http.StatusForbidden, private.Response{
|
|
UserMsg: fmt.Sprintf("branch %s is protected from changing file %s", branchName, protectedFilePath),
|
|
})
|
|
return
|
|
}
|
|
|
|
// Check all status checks and reviews are ok
|
|
if err := pull_service.CheckPullBranchProtections(ctx, pr, true); err != nil {
|
|
if errors.Is(err, pull_service.ErrNotReadyToMerge) {
|
|
log.Warn("Forbidden: User %d is not allowed push to protected branch %s in %-v and pr #%d is not ready to be merged: %s", ctx.opts.UserID, branchName, repo, pr.Index, err.Error())
|
|
ctx.JSON(http.StatusForbidden, private.Response{
|
|
UserMsg: fmt.Sprintf("Not allowed to push to protected branch %s and pr #%d is not ready to be merged: %s", branchName, ctx.opts.PullRequestID, err.Error()),
|
|
})
|
|
return
|
|
}
|
|
log.Error("Unable to check if mergeable: protected branch %s in %-v and pr #%d. Error: %v", ctx.opts.UserID, branchName, repo, pr.Index, err)
|
|
ctx.JSON(http.StatusInternalServerError, private.Response{
|
|
Err: fmt.Sprintf("Unable to get status of pull request %d. Error: %v", ctx.opts.PullRequestID, err),
|
|
})
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
func preReceiveTag(ctx *preReceiveContext, refFullName git.RefName) {
|
|
if !ctx.AssertCanWriteCode() {
|
|
return
|
|
}
|
|
|
|
tagName := refFullName.TagName()
|
|
|
|
if !ctx.gotProtectedTags {
|
|
var err error
|
|
ctx.protectedTags, err = git_model.GetProtectedTags(ctx, ctx.Repo.Repository.ID)
|
|
if err != nil {
|
|
log.Error("Unable to get protected tags for %-v Error: %v", ctx.Repo.Repository, err)
|
|
ctx.JSON(http.StatusInternalServerError, private.Response{
|
|
Err: err.Error(),
|
|
})
|
|
return
|
|
}
|
|
ctx.gotProtectedTags = true
|
|
}
|
|
|
|
isAllowed, err := git_model.IsUserAllowedToControlTag(ctx, ctx.protectedTags, tagName, ctx.opts.UserID)
|
|
if err != nil {
|
|
ctx.JSON(http.StatusInternalServerError, private.Response{
|
|
Err: err.Error(),
|
|
})
|
|
return
|
|
}
|
|
if !isAllowed {
|
|
log.Warn("Forbidden: Tag %s in %-v is protected", tagName, ctx.Repo.Repository)
|
|
ctx.JSON(http.StatusForbidden, private.Response{
|
|
UserMsg: fmt.Sprintf("Tag %s is protected", tagName),
|
|
})
|
|
return
|
|
}
|
|
}
|
|
|
|
func preReceiveFor(ctx *preReceiveContext, refFullName git.RefName) {
|
|
if !ctx.AssertCreatePullRequest() {
|
|
return
|
|
}
|
|
|
|
if ctx.Repo.Repository.IsEmpty {
|
|
ctx.JSON(http.StatusForbidden, private.Response{
|
|
UserMsg: "Can't create pull request for an empty repository.",
|
|
})
|
|
return
|
|
}
|
|
|
|
if ctx.opts.IsWiki {
|
|
ctx.JSON(http.StatusForbidden, private.Response{
|
|
UserMsg: "Pull requests are not supported on the wiki.",
|
|
})
|
|
return
|
|
}
|
|
|
|
_, _, err := agit.GetAgitBranchInfo(ctx, ctx.Repo.Repository.ID, refFullName.ForBranchName())
|
|
if err != nil {
|
|
if !errors.Is(err, util.ErrNotExist) {
|
|
ctx.JSON(http.StatusForbidden, private.Response{
|
|
UserMsg: fmt.Sprintf("Unexpected ref: %s", refFullName),
|
|
})
|
|
} else {
|
|
ctx.JSON(http.StatusInternalServerError, private.Response{
|
|
Err: err.Error(),
|
|
})
|
|
}
|
|
}
|
|
}
|
|
|
|
func generateGitEnv(opts *private.HookOptions) (env []string) {
|
|
env = os.Environ()
|
|
if opts.GitAlternativeObjectDirectories != "" {
|
|
env = append(env,
|
|
private.GitAlternativeObjectDirectories+"="+opts.GitAlternativeObjectDirectories)
|
|
}
|
|
if opts.GitObjectDirectory != "" {
|
|
env = append(env,
|
|
private.GitObjectDirectory+"="+opts.GitObjectDirectory)
|
|
}
|
|
if opts.GitQuarantinePath != "" {
|
|
env = append(env,
|
|
private.GitQuarantinePath+"="+opts.GitQuarantinePath)
|
|
}
|
|
return env
|
|
}
|
|
|
|
// loadPusherAndPermission returns false if an error occurs, and it writes the error response
|
|
func (ctx *preReceiveContext) loadPusherAndPermission() bool {
|
|
if ctx.loadedPusher {
|
|
return true
|
|
}
|
|
|
|
if ctx.opts.UserID == user_model.ActionsUserID {
|
|
taskID := ctx.opts.ActionsTaskID
|
|
ctx.user = user_model.NewActionsUserWithTaskID(taskID)
|
|
if taskID == 0 {
|
|
log.Error("HookPreReceive: ActionsUser with task ID 0")
|
|
ctx.JSON(http.StatusInternalServerError, private.Response{
|
|
Err: "ActionsUser with task ID 0",
|
|
})
|
|
return false
|
|
}
|
|
|
|
userPerm, err := access_model.GetActionsUserRepoPermission(ctx, ctx.Repo.Repository, ctx.user, taskID)
|
|
if err != nil {
|
|
log.Error("Unable to get Actions user repo permission for task %d Error: %v", taskID, err)
|
|
ctx.JSON(http.StatusInternalServerError, private.Response{
|
|
Err: fmt.Sprintf("Unable to get Actions user repo permission for task %d Error: %v", taskID, err),
|
|
})
|
|
return false
|
|
}
|
|
ctx.userPerm = userPerm
|
|
} else {
|
|
user, err := user_model.GetUserByID(ctx, ctx.opts.UserID)
|
|
if err != nil {
|
|
log.Error("Unable to get User id %d Error: %v", ctx.opts.UserID, err)
|
|
ctx.JSON(http.StatusInternalServerError, private.Response{
|
|
Err: fmt.Sprintf("Unable to get User id %d Error: %v", ctx.opts.UserID, err),
|
|
})
|
|
return false
|
|
}
|
|
ctx.user = user
|
|
userPerm, err := access_model.GetUserRepoPermission(ctx, ctx.Repo.Repository, user)
|
|
if err != nil {
|
|
log.Error("Unable to get Repo permission of repo %s/%s of User %s: %v", ctx.Repo.Repository.OwnerName, ctx.Repo.Repository.Name, user.Name, err)
|
|
ctx.JSON(http.StatusInternalServerError, private.Response{
|
|
Err: fmt.Sprintf("Unable to get Repo permission of repo %s/%s of User %s: %v", ctx.Repo.Repository.OwnerName, ctx.Repo.Repository.Name, user.Name, err),
|
|
})
|
|
return false
|
|
}
|
|
ctx.userPerm = userPerm
|
|
}
|
|
|
|
if ctx.opts.DeployKeyID != 0 {
|
|
deployKey, err := asymkey_model.GetDeployKeyByID(ctx, ctx.opts.DeployKeyID)
|
|
if err != nil {
|
|
log.Error("Unable to get DeployKey id %d Error: %v", ctx.opts.DeployKeyID, err)
|
|
ctx.JSON(http.StatusInternalServerError, private.Response{
|
|
Err: fmt.Sprintf("Unable to get DeployKey id %d Error: %v", ctx.opts.DeployKeyID, err),
|
|
})
|
|
return false
|
|
}
|
|
ctx.deployKeyAccessMode = deployKey.Mode
|
|
}
|
|
|
|
ctx.loadedPusher = true
|
|
return true
|
|
}
|