Skip to content

Commit

Permalink
Move push update to post-receive and protected branch check to pre-re…
Browse files Browse the repository at this point in the history
…ceive (go-gitea#1030)

* move all push update to git hook post-receive and protected branch check to git hook pre-receive

* add SSH_ORIGINAL_COMMAND check back

* remove all unused codes

* fix the import
  • Loading branch information
lunny authored Feb 25, 2017
1 parent e8e56da commit cd1821a
Show file tree
Hide file tree
Showing 9 changed files with 175 additions and 415 deletions.
135 changes: 118 additions & 17 deletions cmd/hook.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,22 @@
package cmd

import (
"bufio"
"bytes"
"crypto/tls"
"fmt"
"os"
"strconv"
"strings"

"code.gitea.io/git"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/httplib"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"

"github.com/Unknwon/com"
"github.com/urfave/cli"
)

Expand Down Expand Up @@ -57,10 +68,59 @@ func runHookPreReceive(c *cli.Context) error {
if len(os.Getenv("SSH_ORIGINAL_COMMAND")) == 0 {
return nil
}

if err := setup("hooks/pre-receive.log"); err != nil {
fail("Hook pre-receive init failed", fmt.Sprintf("setup: %v", err))
}

// the environment setted on serv command
repoID, _ := strconv.ParseInt(os.Getenv(models.ProtectedBranchRepoID), 10, 64)
isWiki := (os.Getenv(models.EnvRepoIsWiki) == "true")

buf := bytes.NewBuffer(nil)
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
buf.Write(scanner.Bytes())
buf.WriteByte('\n')

// TODO: support news feeds for wiki
if isWiki {
continue
}

fields := bytes.Fields(scanner.Bytes())
if len(fields) != 3 {
continue
}

oldCommitID := string(fields[0])
newCommitID := string(fields[1])
refFullName := string(fields[2])

branchName := strings.TrimPrefix(refFullName, git.BranchPrefix)
protectBranch, err := models.GetProtectedBranchBy(repoID, branchName)
if err != nil {
log.GitLogger.Fatal(2, "retrieve protected branches information failed")
}

if protectBranch != nil {
fail(fmt.Sprintf("protected branch %s can not be pushed to", branchName), "")
}

// check and deletion
if newCommitID == git.EmptySHA {
fail(fmt.Sprintf("Branch '%s' is protected from deletion", branchName), "")
}

// Check force push
output, err := git.NewCommand("rev-list", oldCommitID, "^"+newCommitID).Run()
if err != nil {
fail("Internal error", "Fail to detect force push: %v", err)
} else if len(output) > 0 {
fail(fmt.Sprintf("Branch '%s' is protected from force push", branchName), "")
}
}

return nil
}

Expand All @@ -73,23 +133,6 @@ func runHookUpdate(c *cli.Context) error {
fail("Hook update init failed", fmt.Sprintf("setup: %v", err))
}

args := c.Args()
if len(args) != 3 {
fail("Arguments received are not equal to three", "Arguments received are not equal to three")
} else if len(args[0]) == 0 {
fail("First argument 'refName' is empty", "First argument 'refName' is empty")
}

uuid := os.Getenv(envUpdateTaskUUID)
if err := models.AddUpdateTask(&models.UpdateTask{
UUID: uuid,
RefName: args[0],
OldCommitID: args[1],
NewCommitID: args[2],
}); err != nil {
fail("Internal error", "Fail to add update task '%s': %v", uuid, err)
}

return nil
}

Expand All @@ -102,5 +145,63 @@ func runHookPostReceive(c *cli.Context) error {
fail("Hook post-receive init failed", fmt.Sprintf("setup: %v", err))
}

// the environment setted on serv command
repoUser := os.Getenv(models.EnvRepoUsername)
repoUserSalt := os.Getenv(models.EnvRepoUserSalt)
isWiki := (os.Getenv(models.EnvRepoIsWiki) == "true")
repoName := os.Getenv(models.EnvRepoName)
pusherID, _ := strconv.ParseInt(os.Getenv(models.EnvPusherID), 10, 64)
pusherName := os.Getenv(models.EnvPusherName)

buf := bytes.NewBuffer(nil)
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
buf.Write(scanner.Bytes())
buf.WriteByte('\n')

// TODO: support news feeds for wiki
if isWiki {
continue
}

fields := bytes.Fields(scanner.Bytes())
if len(fields) != 3 {
continue
}

oldCommitID := string(fields[0])
newCommitID := string(fields[1])
refFullName := string(fields[2])

if err := models.PushUpdate(models.PushUpdateOptions{
RefFullName: refFullName,
OldCommitID: oldCommitID,
NewCommitID: newCommitID,
PusherID: pusherID,
PusherName: pusherName,
RepoUserName: repoUser,
RepoName: repoName,
}); err != nil {
log.GitLogger.Error(2, "Update: %v", err)
}

// Ask for running deliver hook and test pull request tasks.
reqURL := setting.LocalURL + repoUser + "/" + repoName + "/tasks/trigger?branch=" +
strings.TrimPrefix(refFullName, git.BranchPrefix) + "&secret=" + base.EncodeMD5(repoUserSalt) + "&pusher=" + com.ToStr(pusherID)
log.GitLogger.Trace("Trigger task: %s", reqURL)

resp, err := httplib.Head(reqURL).SetTLSClientConfig(&tls.Config{
InsecureSkipVerify: true,
}).Response()
if err == nil {
resp.Body.Close()
if resp.StatusCode/100 != 2 {
log.GitLogger.Error(2, "Failed to trigger task: not 2xx response code")
}
} else {
log.GitLogger.Error(2, "Failed to trigger task: %v", err)
}
}

return nil
}
76 changes: 13 additions & 63 deletions cmd/serv.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
package cmd

import (
"crypto/tls"
"encoding/json"
"fmt"
"os"
Expand All @@ -15,22 +14,17 @@ import (
"strings"
"time"

"code.gitea.io/git"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/httplib"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
"github.com/Unknwon/com"
"github.com/dgrijalva/jwt-go"
gouuid "github.com/satori/go.uuid"
"github.com/urfave/cli"
)

const (
accessDenied = "Repository does not exist or you do not have access"
lfsAuthenticateVerb = "git-lfs-authenticate"
envUpdateTaskUUID = "GITEA_UUID"
)

// CmdServ represents the available serv sub-command.
Expand Down Expand Up @@ -96,52 +90,6 @@ func fail(userMessage, logMessage string, args ...interface{}) {
os.Exit(1)
}

func handleUpdateTask(uuid string, user, repoUser *models.User, reponame string, isWiki bool) {
task, err := models.GetUpdateTaskByUUID(uuid)
if err != nil {
if models.IsErrUpdateTaskNotExist(err) {
log.GitLogger.Trace("No update task is presented: %s", uuid)
return
}
log.GitLogger.Fatal(2, "GetUpdateTaskByUUID: %v", err)
} else if err = models.DeleteUpdateTaskByUUID(uuid); err != nil {
log.GitLogger.Fatal(2, "DeleteUpdateTaskByUUID: %v", err)
}

if isWiki {
return
}

if err = models.PushUpdate(models.PushUpdateOptions{
RefFullName: task.RefName,
OldCommitID: task.OldCommitID,
NewCommitID: task.NewCommitID,
PusherID: user.ID,
PusherName: user.Name,
RepoUserName: repoUser.Name,
RepoName: reponame,
}); err != nil {
log.GitLogger.Error(2, "Update: %v", err)
}

// Ask for running deliver hook and test pull request tasks.
reqURL := setting.LocalURL + repoUser.Name + "/" + reponame + "/tasks/trigger?branch=" +
strings.TrimPrefix(task.RefName, git.BranchPrefix) + "&secret=" + base.EncodeMD5(repoUser.Salt) + "&pusher=" + com.ToStr(user.ID)
log.GitLogger.Trace("Trigger task: %s", reqURL)

resp, err := httplib.Head(reqURL).SetTLSClientConfig(&tls.Config{
InsecureSkipVerify: true,
}).Response()
if err == nil {
resp.Body.Close()
if resp.StatusCode/100 != 2 {
log.GitLogger.Error(2, "Failed to trigger task: not 2xx response code")
}
} else {
log.GitLogger.Error(2, "Failed to trigger task: %v", err)
}
}

func runServ(c *cli.Context) error {
if c.IsSet("config") {
setting.CustomConf = c.String("config")
Expand Down Expand Up @@ -187,6 +135,7 @@ func runServ(c *cli.Context) error {
if len(rr) != 2 {
fail("Invalid repository path", "Invalid repository path: %v", args)
}

username := strings.ToLower(rr[0])
reponame := strings.ToLower(strings.TrimSuffix(rr[1], ".git"))

Expand All @@ -196,6 +145,14 @@ func runServ(c *cli.Context) error {
reponame = reponame[:len(reponame)-5]
}

os.Setenv(models.EnvRepoUsername, username)
if isWiki {
os.Setenv(models.EnvRepoIsWiki, "true")
} else {
os.Setenv(models.EnvRepoIsWiki, "false")
}
os.Setenv(models.EnvRepoName, reponame)

repoUser, err := models.GetUserByName(username)
if err != nil {
if models.IsErrUserNotExist(err) {
Expand All @@ -204,6 +161,8 @@ func runServ(c *cli.Context) error {
fail("Internal error", "Failed to get repository owner (%s): %v", username, err)
}

os.Setenv(models.EnvRepoUserSalt, repoUser.Salt)

repo, err := models.GetRepositoryByName(repoUser.ID, reponame)
if err != nil {
if models.IsErrRepoNotExist(err) {
Expand Down Expand Up @@ -286,7 +245,8 @@ func runServ(c *cli.Context) error {
user.Name, requestedMode, repoPath)
}

os.Setenv("GITEA_PUSHER_NAME", user.Name)
os.Setenv(models.EnvPusherName, user.Name)
os.Setenv(models.EnvPusherID, fmt.Sprintf("%d", user.ID))
}
}

Expand Down Expand Up @@ -323,11 +283,6 @@ func runServ(c *cli.Context) error {
return nil
}

uuid := gouuid.NewV4().String()
os.Setenv(envUpdateTaskUUID, uuid)
// Keep the old env variable name for backward compability
os.Setenv("uuid", uuid)

// Special handle for Windows.
if setting.IsWindows {
verb = strings.Replace(verb, "-", " ", 1)
Expand All @@ -341,7 +296,6 @@ func runServ(c *cli.Context) error {
gitcmd = exec.Command(verb, repoPath)
}

os.Setenv(models.ProtectedBranchAccessMode, requestedMode.String())
os.Setenv(models.ProtectedBranchRepoID, fmt.Sprintf("%d", repo.ID))

gitcmd.Dir = setting.RepoRootPath
Expand All @@ -352,10 +306,6 @@ func runServ(c *cli.Context) error {
fail("Internal error", "Failed to execute git command: %v", err)
}

if requestedMode == models.AccessModeWrite {
handleUpdateTask(uuid, user, repoUser, reponame, isWiki)
}

// Update user key activity.
if keyID > 0 {
key, err := models.GetPublicKeyByID(keyID)
Expand Down
Loading

0 comments on commit cd1821a

Please sign in to comment.