* Move hook functionality internally * Internalise serv logic * Remove old internal paths * finally remove the gitlogger * Disallow push on archived repositories * fix lint error * Update modules/private/key.go * Update routers/private/hook.go * Update routers/private/hook.go * Update routers/private/hook.go * Updated routers/private/serv.go * Fix LFS Locks over SSH * rev-list needs to be run by the hook process * fixup * Improve git test * Ensure that the lfs files are created with a different prefix * Reduce the replication in git_test.go * slight refactor * Remove unnecessary "/" * Restore ensureAnonymousClone * Restore ensureAnonymousClone * Run rev-list on server side * Try passing in the alternative directories instead * Mark test as skipped * Improve git test * Ensure that the lfs files are created with a different prefix * Reduce the replication in git_test.go * Remove unnecessary "/"for-closed-social
@ -1,44 +0,0 @@ | |||
// Copyright 2017 The Gitea Authors. All rights reserved. | |||
// Use of this source code is governed by a MIT-style | |||
// license that can be found in the LICENSE file. | |||
package integrations | |||
import ( | |||
"encoding/json" | |||
"fmt" | |||
"net/http" | |||
"testing" | |||
"code.gitea.io/gitea/models" | |||
"code.gitea.io/gitea/modules/setting" | |||
"code.gitea.io/gitea/modules/util" | |||
"github.com/stretchr/testify/assert" | |||
) | |||
func assertProtectedBranch(t *testing.T, repoID int64, branchName string, isErr, canPush bool) { | |||
reqURL := fmt.Sprintf("/api/internal/branch/%d/%s", repoID, util.PathEscapeSegments(branchName)) | |||
req := NewRequest(t, "GET", reqURL) | |||
t.Log(reqURL) | |||
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", setting.InternalToken)) | |||
resp := MakeRequest(t, req, NoExpectedStatus) | |||
if isErr { | |||
assert.EqualValues(t, http.StatusInternalServerError, resp.Code) | |||
} else { | |||
assert.EqualValues(t, http.StatusOK, resp.Code) | |||
var branch models.ProtectedBranch | |||
t.Log(resp.Body.String()) | |||
assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), &branch)) | |||
assert.Equal(t, canPush, !branch.IsProtected()) | |||
} | |||
} | |||
func TestInternal_GetProtectedBranch(t *testing.T) { | |||
prepareTestEnv(t) | |||
assertProtectedBranch(t, 1, "master", false, true) | |||
assertProtectedBranch(t, 1, "dev", false, true) | |||
assertProtectedBranch(t, 1, "lunny/dev", false, true) | |||
} |
@ -1,67 +0,0 @@ | |||
// Copyright 2017 The Gitea Authors. All rights reserved. | |||
// Use of this source code is governed by a MIT-style | |||
// license that can be found in the LICENSE file. | |||
package private | |||
import ( | |||
"encoding/json" | |||
"fmt" | |||
"code.gitea.io/gitea/models" | |||
"code.gitea.io/gitea/modules/log" | |||
"code.gitea.io/gitea/modules/setting" | |||
"code.gitea.io/gitea/modules/util" | |||
) | |||
// GetProtectedBranchBy get protected branch information | |||
func GetProtectedBranchBy(repoID int64, branchName string) (*models.ProtectedBranch, error) { | |||
// Ask for running deliver hook and test pull request tasks. | |||
reqURL := setting.LocalURL + fmt.Sprintf("api/internal/branch/%d/%s", repoID, util.PathEscapeSegments(branchName)) | |||
log.GitLogger.Trace("GetProtectedBranchBy: %s", reqURL) | |||
resp, err := newInternalRequest(reqURL, "GET").Response() | |||
if err != nil { | |||
return nil, err | |||
} | |||
var branch models.ProtectedBranch | |||
if err := json.NewDecoder(resp.Body).Decode(&branch); err != nil { | |||
return nil, err | |||
} | |||
defer resp.Body.Close() | |||
// All 2XX status codes are accepted and others will return an error | |||
if resp.StatusCode/100 != 2 { | |||
return nil, fmt.Errorf("Failed to get protected branch: %s", decodeJSONError(resp).Err) | |||
} | |||
return &branch, nil | |||
} | |||
// CanUserPush returns if user can push | |||
func CanUserPush(protectedBranchID, userID int64) (bool, error) { | |||
// Ask for running deliver hook and test pull request tasks. | |||
reqURL := setting.LocalURL + fmt.Sprintf("api/internal/protectedbranch/%d/%d", protectedBranchID, userID) | |||
log.GitLogger.Trace("CanUserPush: %s", reqURL) | |||
resp, err := newInternalRequest(reqURL, "GET").Response() | |||
if err != nil { | |||
return false, err | |||
} | |||
var canPush = make(map[string]interface{}) | |||
if err := json.NewDecoder(resp.Body).Decode(&canPush); err != nil { | |||
return false, err | |||
} | |||
defer resp.Body.Close() | |||
// All 2XX status codes are accepted and others will return an error | |||
if resp.StatusCode/100 != 2 { | |||
return false, fmt.Errorf("Failed to retrieve push user: %s", decodeJSONError(resp).Err) | |||
} | |||
return canPush["can_push"].(bool), nil | |||
} |
@ -0,0 +1,84 @@ | |||
// Copyright 2019 The Gitea Authors. All rights reserved. | |||
// Use of this source code is governed by a MIT-style | |||
// license that can be found in the LICENSE file. | |||
package private | |||
import ( | |||
"encoding/json" | |||
"fmt" | |||
"net/http" | |||
"net/url" | |||
"code.gitea.io/gitea/modules/setting" | |||
) | |||
// Git environment variables | |||
const ( | |||
GitAlternativeObjectDirectories = "GIT_ALTERNATE_OBJECT_DIRECTORIES" | |||
GitObjectDirectory = "GIT_OBJECT_DIRECTORY" | |||
GitQuarantinePath = "GIT_QUARANTINE_PATH" | |||
) | |||
// HookOptions represents the options for the Hook calls | |||
type HookOptions struct { | |||
OldCommitID string | |||
NewCommitID string | |||
RefFullName string | |||
UserID int64 | |||
UserName string | |||
GitObjectDirectory string | |||
GitAlternativeObjectDirectories string | |||
} | |||
// HookPreReceive check whether the provided commits are allowed | |||
func HookPreReceive(ownerName, repoName string, opts HookOptions) (int, string) { | |||
reqURL := setting.LocalURL + fmt.Sprintf("api/internal/hook/pre-receive/%s/%s?old=%s&new=%s&ref=%s&userID=%d&gitObjectDirectory=%s&gitAlternativeObjectDirectories=%s", | |||
url.PathEscape(ownerName), | |||
url.PathEscape(repoName), | |||
url.QueryEscape(opts.OldCommitID), | |||
url.QueryEscape(opts.NewCommitID), | |||
url.QueryEscape(opts.RefFullName), | |||
opts.UserID, | |||
url.QueryEscape(opts.GitObjectDirectory), | |||
url.QueryEscape(opts.GitAlternativeObjectDirectories), | |||
) | |||
resp, err := newInternalRequest(reqURL, "GET").Response() | |||
if err != nil { | |||
return http.StatusInternalServerError, fmt.Sprintf("Unable to contact gitea: %v", err.Error()) | |||
} | |||
defer resp.Body.Close() | |||
if resp.StatusCode != http.StatusOK { | |||
return resp.StatusCode, decodeJSONError(resp).Err | |||
} | |||
return http.StatusOK, "" | |||
} | |||
// HookPostReceive updates services and users | |||
func HookPostReceive(ownerName, repoName string, opts HookOptions) (map[string]interface{}, string) { | |||
reqURL := setting.LocalURL + fmt.Sprintf("api/internal/hook/post-receive/%s/%s?old=%s&new=%s&ref=%s&userID=%d&username=%s", | |||
url.PathEscape(ownerName), | |||
url.PathEscape(repoName), | |||
url.QueryEscape(opts.OldCommitID), | |||
url.QueryEscape(opts.NewCommitID), | |||
url.QueryEscape(opts.RefFullName), | |||
opts.UserID, | |||
url.QueryEscape(opts.UserName)) | |||
resp, err := newInternalRequest(reqURL, "GET").Response() | |||
if err != nil { | |||
return nil, fmt.Sprintf("Unable to contact gitea: %v", err.Error()) | |||
} | |||
defer resp.Body.Close() | |||
if resp.StatusCode != http.StatusOK { | |||
return nil, decodeJSONError(resp).Err | |||
} | |||
res := map[string]interface{}{} | |||
_ = json.NewDecoder(resp.Body).Decode(&res) | |||
return res, "" | |||
} |
@ -1,40 +0,0 @@ | |||
// Copyright 2017 The Gitea Authors. All rights reserved. | |||
// Use of this source code is governed by a MIT-style | |||
// license that can be found in the LICENSE file. | |||
package private | |||
import ( | |||
"encoding/json" | |||
"fmt" | |||
"code.gitea.io/gitea/models" | |||
"code.gitea.io/gitea/modules/log" | |||
"code.gitea.io/gitea/modules/setting" | |||
) | |||
// PushUpdate update publick key updates | |||
func PushUpdate(opt models.PushUpdateOptions) error { | |||
// Ask for running deliver hook and test pull request tasks. | |||
reqURL := setting.LocalURL + "api/internal/push/update" | |||
log.GitLogger.Trace("PushUpdate: %s", reqURL) | |||
body, err := json.Marshal(&opt) | |||
if err != nil { | |||
return err | |||
} | |||
resp, err := newInternalRequest(reqURL, "POST").Body(body).Response() | |||
if err != nil { | |||
return err | |||
} | |||
defer resp.Body.Close() | |||
// All 2XX status codes are accepted and others will return an error | |||
if resp.StatusCode/100 != 2 { | |||
return fmt.Errorf("Failed to update public key: %s", decodeJSONError(resp).Err) | |||
} | |||
return nil | |||
} |
@ -1,68 +0,0 @@ | |||
// Copyright 2018 The Gitea Authors. All rights reserved. | |||
// Use of this source code is governed by a MIT-style | |||
// license that can be found in the LICENSE file. | |||
package private | |||
import ( | |||
"encoding/json" | |||
"fmt" | |||
"net/url" | |||
"code.gitea.io/gitea/models" | |||
"code.gitea.io/gitea/modules/log" | |||
"code.gitea.io/gitea/modules/setting" | |||
) | |||
// GetRepository return the repository by its ID and a bool about if it's allowed to have PR | |||
func GetRepository(repoID int64) (*models.Repository, bool, error) { | |||
reqURL := setting.LocalURL + fmt.Sprintf("api/internal/repository/%d", repoID) | |||
log.GitLogger.Trace("GetRepository: %s", reqURL) | |||
resp, err := newInternalRequest(reqURL, "GET").Response() | |||
if err != nil { | |||
return nil, false, err | |||
} | |||
var repoInfo struct { | |||
Repository *models.Repository | |||
AllowPullRequest bool | |||
} | |||
if err := json.NewDecoder(resp.Body).Decode(&repoInfo); err != nil { | |||
return nil, false, err | |||
} | |||
defer resp.Body.Close() | |||
// All 2XX status codes are accepted and others will return an error | |||
if resp.StatusCode/100 != 2 { | |||
return nil, false, fmt.Errorf("failed to retrieve repository: %s", decodeJSONError(resp).Err) | |||
} | |||
return repoInfo.Repository, repoInfo.AllowPullRequest, nil | |||
} | |||
// ActivePullRequest returns an active pull request if it exists | |||
func ActivePullRequest(baseRepoID int64, headRepoID int64, baseBranch, headBranch string) (*models.PullRequest, error) { | |||
reqURL := setting.LocalURL + fmt.Sprintf("api/internal/active-pull-request?baseRepoID=%d&headRepoID=%d&baseBranch=%s&headBranch=%s", baseRepoID, headRepoID, url.QueryEscape(baseBranch), url.QueryEscape(headBranch)) | |||
log.GitLogger.Trace("ActivePullRequest: %s", reqURL) | |||
resp, err := newInternalRequest(reqURL, "GET").Response() | |||
if err != nil { | |||
return nil, err | |||
} | |||
var pr *models.PullRequest | |||
if err := json.NewDecoder(resp.Body).Decode(&pr); err != nil { | |||
return nil, err | |||
} | |||
defer resp.Body.Close() | |||
// All 2XX status codes are accepted and others will return an error | |||
if resp.StatusCode/100 != 2 { | |||
return nil, fmt.Errorf("failed to retrieve pull request: %s", decodeJSONError(resp).Err) | |||
} | |||
return pr, nil | |||
} |
@ -0,0 +1,106 @@ | |||
// Copyright 2019 The Gitea Authors. All rights reserved. | |||
// Use of this source code is governed by a MIT-style | |||
// license that can be found in the LICENSE file. | |||
package private | |||
import ( | |||
"encoding/json" | |||
"fmt" | |||
"net/http" | |||
"net/url" | |||
"code.gitea.io/gitea/models" | |||
"code.gitea.io/gitea/modules/setting" | |||
) | |||
// KeyAndOwner is the response from ServNoCommand | |||
type KeyAndOwner struct { | |||
Key *models.PublicKey `json:"key"` | |||
Owner *models.User `json:"user"` | |||
} | |||
// ServNoCommand returns information about the provided key | |||
func ServNoCommand(keyID int64) (*models.PublicKey, *models.User, error) { | |||
reqURL := setting.LocalURL + fmt.Sprintf("api/internal/serv/none/%d", | |||
keyID) | |||
resp, err := newInternalRequest(reqURL, "GET").Response() | |||
if err != nil { | |||
return nil, nil, err | |||
} | |||
defer resp.Body.Close() | |||
if resp.StatusCode != http.StatusOK { | |||
return nil, nil, fmt.Errorf("%s", decodeJSONError(resp).Err) | |||
} | |||
var keyAndOwner KeyAndOwner | |||
if err := json.NewDecoder(resp.Body).Decode(&keyAndOwner); err != nil { | |||
return nil, nil, err | |||
} | |||
return keyAndOwner.Key, keyAndOwner.Owner, nil | |||
} | |||
// ServCommandResults are the results of a call to the private route serv | |||
type ServCommandResults struct { | |||
IsWiki bool | |||
IsDeployKey bool | |||
KeyID int64 | |||
KeyName string | |||
UserName string | |||
UserID int64 | |||
OwnerName string | |||
RepoName string | |||
RepoID int64 | |||
} | |||
// ErrServCommand is an error returned from ServCommmand. | |||
type ErrServCommand struct { | |||
Results ServCommandResults | |||
Type string | |||
Err string | |||
StatusCode int | |||
} | |||
func (err ErrServCommand) Error() string { | |||
return err.Err | |||
} | |||
// IsErrServCommand checks if an error is a ErrServCommand. | |||
func IsErrServCommand(err error) bool { | |||
_, ok := err.(ErrServCommand) | |||
return ok | |||
} | |||
// ServCommand preps for a serv call | |||
func ServCommand(keyID int64, ownerName, repoName string, mode models.AccessMode, verbs ...string) (*ServCommandResults, error) { | |||
reqURL := setting.LocalURL + fmt.Sprintf("api/internal/serv/command/%d/%s/%s?mode=%d", | |||
keyID, | |||
url.PathEscape(ownerName), | |||
url.PathEscape(repoName), | |||
mode) | |||
for _, verb := range verbs { | |||
if verb != "" { | |||
reqURL += fmt.Sprintf("&verb=%s", url.QueryEscape(verb)) | |||
} | |||
} | |||
resp, err := newInternalRequest(reqURL, "GET").Response() | |||
if err != nil { | |||
return nil, err | |||
} | |||
defer resp.Body.Close() | |||
if resp.StatusCode != http.StatusOK { | |||
var errServCommand ErrServCommand | |||
if err := json.NewDecoder(resp.Body).Decode(&errServCommand); err != nil { | |||
return nil, err | |||
} | |||
errServCommand.StatusCode = resp.StatusCode | |||
return nil, errServCommand | |||
} | |||
var results ServCommandResults | |||
if err := json.NewDecoder(resp.Body).Decode(&results); err != nil { | |||
return nil, err | |||
} | |||
return &results, nil | |||
} |
@ -1,33 +0,0 @@ | |||
// Copyright 2018 The Gitea Authors. All rights reserved. | |||
// Use of this source code is governed by a MIT-style | |||
// license that can be found in the LICENSE file. | |||
package private | |||
import ( | |||
"fmt" | |||
"code.gitea.io/gitea/modules/log" | |||
"code.gitea.io/gitea/modules/setting" | |||
) | |||
// InitWiki initwiki via repo id | |||
func InitWiki(repoID int64) error { | |||
// Ask for running deliver hook and test pull request tasks. | |||
reqURL := setting.LocalURL + fmt.Sprintf("api/internal/repositories/%d/wiki/init", repoID) | |||
log.GitLogger.Trace("InitWiki: %s", reqURL) | |||
resp, err := newInternalRequest(reqURL, "GET").Response() | |||
if err != nil { | |||
return err | |||
} | |||
defer resp.Body.Close() | |||
// All 2XX status codes are accepted and others will return an error | |||
if resp.StatusCode/100 != 2 { | |||
return fmt.Errorf("Failed to init wiki: %s", decodeJSONError(resp).Err) | |||
} | |||
return nil | |||
} |
@ -1,52 +0,0 @@ | |||
// Copyright 2017 The Gitea Authors. All rights reserved. | |||
// Use of this source code is governed by a MIT-style | |||
// license that can be found in the LICENSE file. | |||
package private | |||
import ( | |||
"code.gitea.io/gitea/models" | |||
macaron "gopkg.in/macaron.v1" | |||
) | |||
// GetProtectedBranchBy get protected branch information | |||
func GetProtectedBranchBy(ctx *macaron.Context) { | |||
repoID := ctx.ParamsInt64(":id") | |||
branchName := ctx.Params("*") | |||
protectBranch, err := models.GetProtectedBranchBy(repoID, branchName) | |||
if err != nil { | |||
ctx.JSON(500, map[string]interface{}{ | |||
"err": err.Error(), | |||
}) | |||
return | |||
} else if protectBranch != nil { | |||
ctx.JSON(200, protectBranch) | |||
} else { | |||
ctx.JSON(200, &models.ProtectedBranch{ | |||
ID: 0, | |||
}) | |||
} | |||
} | |||
// CanUserPush returns if user push | |||
func CanUserPush(ctx *macaron.Context) { | |||
pbID := ctx.ParamsInt64(":pbid") | |||
userID := ctx.ParamsInt64(":userid") | |||
protectBranch, err := models.GetProtectedBranchByID(pbID) | |||
if err != nil { | |||
ctx.JSON(500, map[string]interface{}{ | |||
"err": err.Error(), | |||
}) | |||
return | |||
} else if protectBranch != nil { | |||
ctx.JSON(200, map[string]interface{}{ | |||
"can_push": protectBranch.CanUserPush(userID), | |||
}) | |||
} else { | |||
ctx.JSON(200, map[string]interface{}{ | |||
"can_push": false, | |||
}) | |||
} | |||
} |
@ -0,0 +1,209 @@ | |||
// Copyright 2019 The Gitea Authors. All rights reserved. | |||
// Use of this source code is governed by a MIT-style | |||
// license that can be found in the LICENSE file. | |||
// Package private includes all internal routes. The package name internal is ideal but Golang is not allowed, so we use private as package name instead. | |||
package private | |||
import ( | |||
"fmt" | |||
"net/http" | |||
"os" | |||
"strings" | |||
"code.gitea.io/gitea/models" | |||
"code.gitea.io/gitea/modules/git" | |||
"code.gitea.io/gitea/modules/log" | |||
"code.gitea.io/gitea/modules/private" | |||
"code.gitea.io/gitea/modules/util" | |||
macaron "gopkg.in/macaron.v1" | |||
) | |||
// HookPreReceive checks whether a individual commit is acceptable | |||
func HookPreReceive(ctx *macaron.Context) { | |||
ownerName := ctx.Params(":owner") | |||
repoName := ctx.Params(":repo") | |||
oldCommitID := ctx.QueryTrim("old") | |||
newCommitID := ctx.QueryTrim("new") | |||
refFullName := ctx.QueryTrim("ref") | |||
userID := ctx.QueryInt64("userID") | |||
gitObjectDirectory := ctx.QueryTrim("gitObjectDirectory") | |||
gitAlternativeObjectDirectories := ctx.QueryTrim("gitAlternativeObjectDirectories") | |||
branchName := strings.TrimPrefix(refFullName, git.BranchPrefix) | |||
repo, err := models.GetRepositoryByOwnerAndName(ownerName, repoName) | |||
if err != nil { | |||
log.Error("Unable to get repository: %s/%s Error: %v", ownerName, repoName, err) | |||
ctx.JSON(http.StatusInternalServerError, map[string]interface{}{ | |||
"err": err.Error(), | |||
}) | |||
return | |||
} | |||
repo.OwnerName = ownerName | |||
protectBranch, err := models.GetProtectedBranchBy(repo.ID, branchName) | |||
if err != nil { | |||
log.Error("Unable to get protected branch: %s in %-v Error: %v", branchName, repo, err) | |||
ctx.JSON(500, map[string]interface{}{ | |||
"err": err.Error(), | |||
}) | |||
return | |||
} | |||
if protectBranch != nil && protectBranch.IsProtected() { | |||
// check and deletion | |||
if newCommitID == git.EmptySHA { | |||
log.Warn("Forbidden: Branch: %s in %-v is protected from deletion", branchName, repo) | |||
ctx.JSON(http.StatusForbidden, map[string]interface{}{ | |||
"err": fmt.Sprintf("branch %s is protected from deletion", branchName), | |||
}) | |||
return | |||
} | |||
// detect force push | |||
if git.EmptySHA != oldCommitID { | |||
env := append(os.Environ(), | |||
private.GitAlternativeObjectDirectories+"="+gitAlternativeObjectDirectories, | |||
private.GitObjectDirectory+"="+gitObjectDirectory, | |||
private.GitQuarantinePath+"="+gitObjectDirectory, | |||
) | |||
output, err := git.NewCommand("rev-list", "--max-count=1", oldCommitID, "^"+newCommitID).RunInDirWithEnv(repo.RepoPath(), 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, map[string]interface{}{ | |||
"err": fmt.Sprintf("Fail to detect force push: %v", err), | |||
}) | |||
return | |||
} else if len(output) > 0 { | |||
log.Warn("Forbidden: Branch: %s in %-v is protected from force push", branchName, repo) | |||
ctx.JSON(http.StatusForbidden, map[string]interface{}{ | |||
"err": fmt.Sprintf("branch %s is protected from force push", branchName), | |||
}) | |||
return | |||
} | |||
} | |||
if !protectBranch.CanUserPush(userID) { | |||
log.Warn("Forbidden: User %d cannot push to protected branch: %s in %-v", userID, branchName, repo) | |||
ctx.JSON(http.StatusForbidden, map[string]interface{}{ | |||
"err": fmt.Sprintf("protected branch %s can not be pushed to", branchName), | |||
}) | |||
return | |||
} | |||
} | |||
ctx.PlainText(http.StatusOK, []byte("ok")) | |||
} | |||
// HookPostReceive updates services and users | |||
func HookPostReceive(ctx *macaron.Context) { | |||
ownerName := ctx.Params(":owner") | |||
repoName := ctx.Params(":repo") | |||
oldCommitID := ctx.Query("old") | |||
newCommitID := ctx.Query("new") | |||
refFullName := ctx.Query("ref") | |||
userID := ctx.QueryInt64("userID") | |||
userName := ctx.Query("username") | |||
branch := refFullName | |||
if strings.HasPrefix(refFullName, git.BranchPrefix) { | |||
branch = strings.TrimPrefix(refFullName, git.BranchPrefix) | |||
} else if strings.HasPrefix(refFullName, git.TagPrefix) { | |||
branch = strings.TrimPrefix(refFullName, git.TagPrefix) | |||
} | |||
// Only trigger activity updates for changes to branches or | |||
// tags. Updates to other refs (eg, refs/notes, refs/changes, | |||
// or other less-standard refs spaces are ignored since there | |||
// may be a very large number of them). | |||
if strings.HasPrefix(refFullName, git.BranchPrefix) || strings.HasPrefix(refFullName, git.TagPrefix) { | |||
if err := models.PushUpdate(branch, models.PushUpdateOptions{ | |||
RefFullName: refFullName, | |||
OldCommitID: oldCommitID, | |||
NewCommitID: newCommitID, | |||
PusherID: userID, | |||
PusherName: userName, | |||
RepoUserName: ownerName, | |||
RepoName: repoName, | |||
}); err != nil { | |||
log.Error("Failed to Update: %s/%s Branch: %s Error: %v", ownerName, repoName, branch, err) | |||
ctx.JSON(http.StatusInternalServerError, map[string]interface{}{ | |||
"err": fmt.Sprintf("Failed to Update: %s/%s Branch: %s Error: %v", ownerName, repoName, branch, err), | |||
}) | |||
return | |||
} | |||
} | |||
if newCommitID != git.EmptySHA && strings.HasPrefix(refFullName, git.BranchPrefix) { | |||
repo, err := models.GetRepositoryByOwnerAndName(ownerName, repoName) | |||
if err != nil { | |||
log.Error("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err) | |||
ctx.JSON(http.StatusInternalServerError, map[string]interface{}{ | |||
"err": fmt.Sprintf("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err), | |||
}) | |||
return | |||
} | |||
repo.OwnerName = ownerName | |||
pullRequestAllowed := repo.AllowsPulls() | |||
if !pullRequestAllowed { | |||
ctx.JSON(http.StatusOK, map[string]interface{}{ | |||
"message": false, | |||
}) | |||
return | |||
} | |||
baseRepo := repo | |||
if repo.IsFork { | |||
if err := repo.GetBaseRepo(); err != nil { | |||
log.Error("Failed to get Base Repository of Forked repository: %-v Error: %v", repo, err) | |||
ctx.JSON(http.StatusInternalServerError, map[string]interface{}{ | |||
"err": fmt.Sprintf("Failed to get Base Repository of Forked repository: %-v Error: %v", repo, err), | |||
}) | |||
return | |||
} | |||
baseRepo = repo.BaseRepo | |||
} | |||
if !repo.IsFork && branch == baseRepo.DefaultBranch { | |||
ctx.JSON(http.StatusOK, map[string]interface{}{ | |||
"message": false, | |||
}) | |||
return | |||
} | |||
pr, err := models.GetUnmergedPullRequest(repo.ID, baseRepo.ID, branch, baseRepo.DefaultBranch) | |||
if err != nil && !models.IsErrPullRequestNotExist(err) { | |||
log.Error("Failed to get active PR in: %-v Branch: %s to: %-v Branch: %s Error: %v", repo, branch, baseRepo, baseRepo.DefaultBranch, err) | |||
ctx.JSON(http.StatusInternalServerError, map[string]interface{}{ | |||
"err": fmt.Sprintf( | |||
"Failed to get active PR in: %-v Branch: %s to: %-v Branch: %s Error: %v", repo, branch, baseRepo, baseRepo.DefaultBranch, err), | |||
}) | |||
return | |||
} | |||
if pr == nil { | |||
if repo.IsFork { | |||
branch = fmt.Sprintf("%s:%s", repo.OwnerName, branch) | |||
} | |||
ctx.JSON(http.StatusOK, map[string]interface{}{ | |||
"message": true, | |||
"create": true, | |||
"branch": branch, | |||
"url": fmt.Sprintf("%s/compare/%s...%s", baseRepo.HTMLURL(), util.PathEscapeSegments(baseRepo.DefaultBranch), util.PathEscapeSegments(branch)), | |||
}) | |||
} else { | |||
ctx.JSON(http.StatusOK, map[string]interface{}{ | |||
"message": true, | |||
"create": false, | |||
"branch": branch, | |||
"url": fmt.Sprintf("%s/pulls/%d", baseRepo.HTMLURL(), pr.Index), | |||
}) | |||
} | |||
return | |||
} | |||
ctx.JSON(http.StatusOK, map[string]interface{}{ | |||
"message": false, | |||
}) | |||
return | |||
} |
@ -1,47 +0,0 @@ | |||
// Copyright 2017 The Gitea Authors. All rights reserved. | |||
// Use of this source code is governed by a MIT-style | |||
// license that can be found in the LICENSE file. | |||
package private | |||
import ( | |||
"encoding/json" | |||
"strings" | |||
"code.gitea.io/gitea/models" | |||
"code.gitea.io/gitea/modules/git" | |||
"code.gitea.io/gitea/modules/log" | |||
macaron "gopkg.in/macaron.v1" | |||
) | |||
// PushUpdate update public key updates | |||
func PushUpdate(ctx *macaron.Context) { | |||
var opt models.PushUpdateOptions | |||
if err := json.NewDecoder(ctx.Req.Request.Body).Decode(&opt); err != nil { | |||
ctx.JSON(500, map[string]interface{}{ | |||
"err": err.Error(), | |||
}) | |||
return | |||
} | |||
branch := strings.TrimPrefix(opt.RefFullName, git.BranchPrefix) | |||
if len(branch) == 0 || opt.PusherID <= 0 { | |||
ctx.Error(404) | |||
log.Trace("PushUpdate: branch or secret is empty, or pusher ID is not valid") | |||
return | |||
} | |||
err := models.PushUpdate(branch, opt) | |||
if err != nil { | |||
if models.IsErrUserNotExist(err) { | |||
ctx.Error(404) | |||
} else { | |||
ctx.JSON(500, map[string]interface{}{ | |||
"err": err.Error(), | |||
}) | |||
} | |||
return | |||
} | |||
ctx.Status(202) | |||
} |
@ -1,83 +0,0 @@ | |||
// Copyright 2018 The Gitea Authors. All rights reserved. | |||
// Use of this source code is governed by a MIT-style | |||
// license that can be found in the LICENSE file. | |||
package private | |||
import ( | |||
"net/http" | |||
"code.gitea.io/gitea/models" | |||
macaron "gopkg.in/macaron.v1" | |||
) | |||
// GetRepository return the default branch of a repository | |||
func GetRepository(ctx *macaron.Context) { | |||
repoID := ctx.ParamsInt64(":rid") | |||
repository, err := models.GetRepositoryByID(repoID) | |||
repository.MustOwnerName() | |||
allowPulls := repository.AllowsPulls() | |||
// put it back to nil because json unmarshal can't unmarshal it | |||
repository.Units = nil | |||
if err != nil { | |||
ctx.JSON(http.StatusInternalServerError, map[string]interface{}{ | |||
"err": err.Error(), | |||
}) | |||
return | |||
} | |||
if repository.IsFork { | |||
repository.GetBaseRepo() | |||
if err != nil { | |||
ctx.JSON(http.StatusInternalServerError, map[string]interface{}{ | |||
"err": err.Error(), | |||
}) | |||
return | |||
} | |||
repository.BaseRepo.MustOwnerName() | |||
allowPulls = repository.BaseRepo.AllowsPulls() | |||
// put it back to nil because json unmarshal can't unmarshal it | |||
repository.BaseRepo.Units = nil | |||
} | |||
ctx.JSON(http.StatusOK, struct { | |||
Repository *models.Repository | |||
AllowPullRequest bool | |||
}{ | |||
Repository: repository, | |||
AllowPullRequest: allowPulls, | |||
}) | |||
} | |||
// GetActivePullRequest return an active pull request when it exists or an empty object | |||
func GetActivePullRequest(ctx *macaron.Context) { | |||
baseRepoID := ctx.QueryInt64("baseRepoID") | |||
headRepoID := ctx.QueryInt64("headRepoID") | |||
baseBranch := ctx.QueryTrim("baseBranch") | |||
if len(baseBranch) == 0 { | |||
ctx.JSON(http.StatusInternalServerError, map[string]interface{}{ | |||
"err": "QueryTrim failed", | |||
}) | |||
return | |||
} | |||
headBranch := ctx.QueryTrim("headBranch") | |||
if len(headBranch) == 0 { | |||
ctx.JSON(http.StatusInternalServerError, map[string]interface{}{ | |||
"err": "QueryTrim failed", | |||
}) | |||
return | |||
} | |||
pr, err := models.GetUnmergedPullRequest(headRepoID, baseRepoID, headBranch, baseBranch) | |||
if err != nil && !models.IsErrPullRequestNotExist(err) { | |||
ctx.JSON(http.StatusInternalServerError, map[string]interface{}{ | |||
"err": err.Error(), | |||
}) | |||
return | |||
} | |||
ctx.JSON(http.StatusOK, pr) | |||
} |
@ -0,0 +1,286 @@ | |||
// Copyright 2019 The Gitea Authors. All rights reserved. | |||
// Use of this source code is governed by a MIT-style | |||
// license that can be found in the LICENSE file. | |||
// Package private includes all internal routes. The package name internal is ideal but Golang is not allowed, so we use private as package name instead. | |||
package private | |||
import ( | |||
"fmt" | |||
"net/http" | |||
"strings" | |||
"code.gitea.io/gitea/models" | |||
"code.gitea.io/gitea/modules/log" | |||
"code.gitea.io/gitea/modules/private" | |||
"code.gitea.io/gitea/modules/setting" | |||
macaron "gopkg.in/macaron.v1" | |||
) | |||
// ServNoCommand returns information about the provided keyid | |||
func ServNoCommand(ctx *macaron.Context) { | |||
keyID := ctx.ParamsInt64(":keyid") | |||
if keyID <= 0 { | |||
ctx.JSON(http.StatusBadRequest, map[string]interface{}{ | |||
"err": fmt.Sprintf("Bad key id: %d", keyID), | |||
}) | |||
} | |||
results := private.KeyAndOwner{} | |||
key, err := models.GetPublicKeyByID(keyID) | |||
if err != nil { | |||
if models.IsErrKeyNotExist(err) { | |||
ctx.JSON(http.StatusUnauthorized, map[string]interface{}{ | |||
"err": fmt.Sprintf("Cannot find key: %d", keyID), | |||
}) | |||
return | |||
} | |||
log.Error("Unable to get public key: %d Error: %v", keyID, err) | |||
ctx.JSON(http.StatusInternalServerError, map[string]interface{}{ | |||
"err": err.Error(), | |||
}) | |||
return | |||
} | |||
results.Key = key | |||
if key.Type == models.KeyTypeUser { | |||
user, err := models.GetUserByID(key.OwnerID) | |||
if err != nil { | |||
if models.IsErrUserNotExist(err) { | |||
ctx.JSON(http.StatusUnauthorized, map[string]interface{}{ | |||
"err": fmt.Sprintf("Cannot find owner with id: %d for key: %d", key.OwnerID, keyID), | |||
}) | |||
return | |||
} | |||
log.Error("Unable to get owner with id: %d for public key: %d Error: %v", key.OwnerID, keyID, err) | |||
ctx.JSON(http.StatusInternalServerError, map[string]interface{}{ | |||
"err": err.Error(), | |||
}) | |||
return | |||
} | |||
results.Owner = user | |||
} | |||
ctx.JSON(http.StatusOK, &results) | |||
return | |||
} | |||
// ServCommand returns information about the provided keyid | |||
func ServCommand(ctx *macaron.Context) { | |||
// Although we provide the verbs we don't need them at present they're just for logging purposes | |||
keyID := ctx.ParamsInt64(":keyid") | |||
ownerName := ctx.Params(":owner") | |||
repoName := ctx.Params(":repo") | |||
mode := models.AccessMode(ctx.QueryInt("mode")) | |||
// Set the basic parts of the results to return | |||
results := private.ServCommandResults{ | |||
RepoName: repoName, | |||
OwnerName: ownerName, | |||
KeyID: keyID, | |||
} | |||
// Now because we're not translating things properly let's just default some Engish strings here | |||
modeString := "read" | |||
if mode > models.AccessModeRead { | |||
modeString = "write to" | |||
} | |||
// The default unit we're trying to look at is code | |||
unitType := models.UnitTypeCode | |||
// Unless we're a wiki... | |||
if strings.HasSuffix(repoName, ".wiki") { | |||
// in which case we need to look at the wiki | |||
unitType = models.UnitTypeWiki | |||
// And we'd better munge the reponame and tell downstream we're looking at a wiki | |||
results.IsWiki = true | |||
results.RepoName = repoName[:len(repoName)-5] | |||
} | |||
// Now get the Repository and set the results section | |||
repo, err := models.GetRepositoryByOwnerAndName(results.OwnerName, results.RepoName) | |||
if err != nil { | |||
if models.IsErrRepoNotExist(err) { | |||
ctx.JSON(http.StatusNotFound, map[string]interface{}{ | |||
"results": results, | |||
"type": "ErrRepoNotExist", | |||
"err": fmt.Sprintf("Cannot find repository %s/%s", results.OwnerName, results.RepoName), | |||
}) | |||
return | |||
} | |||
log.Error("Unable to get repository: %s/%s Error: %v", results.OwnerName, results.RepoName, err) | |||
ctx.JSON(http.StatusInternalServerError, map[string]interface{}{ | |||
"results": results, | |||
"type": "InternalServerError", | |||
"err": fmt.Sprintf("Unable to get repository: %s/%s %v", results.OwnerName, results.RepoName, err), | |||
}) | |||
return | |||
} | |||
repo.OwnerName = ownerName | |||
results.RepoID = repo.ID | |||
// We can shortcut at this point if the repo is a mirror | |||
if mode > models.AccessModeRead && repo.IsMirror { | |||
ctx.JSON(http.StatusUnauthorized, map[string]interface{}{ | |||
"results": results, | |||
"type": "ErrMirrorReadOnly", | |||
"err": fmt.Sprintf("Mirror Repository %s/%s is read-only", results.OwnerName, results.RepoName), | |||
}) | |||
return | |||
} | |||
// Get the Public Key represented by the keyID | |||
key, err := models.GetPublicKeyByID(keyID) | |||
if err != nil { | |||
if models.IsErrKeyNotExist(err) { | |||
ctx.JSON(http.StatusUnauthorized, map[string]interface{}{ | |||
"results": results, | |||
"type": "ErrKeyNotExist", | |||
"err": fmt.Sprintf("Cannot find key: %d", keyID), | |||
}) | |||
return | |||
} | |||
log.Error("Unable to get public key: %d Error: %v", keyID, err) | |||
ctx.JSON(http.StatusInternalServerError, map[string]interface{}{ | |||
"results": results, | |||
"type": "InternalServerError", | |||
"err": fmt.Sprintf("Unable to get key: %d Error: %v", keyID, err), | |||
}) | |||
return | |||
} | |||
results.KeyName = key.Name | |||
results.KeyID = key.ID | |||
results.UserID = key.OwnerID | |||
// Deploy Keys have ownerID set to 0 therefore we can't use the owner | |||
// So now we need to check if the key is a deploy key | |||
// We'll keep hold of the deploy key here for permissions checking | |||
var deployKey *models.DeployKey | |||
var user *models.User | |||
if key.Type == models.KeyTypeDeploy { | |||
results.IsDeployKey = true | |||
var err error | |||
deployKey, err = models.GetDeployKeyByRepo(key.ID, repo.ID) | |||
if err != nil { | |||
if models.IsErrDeployKeyNotExist(err) { | |||
ctx.JSON(http.StatusUnauthorized, map[string]interface{}{ | |||
"results": results, | |||
"type": "ErrDeployKeyNotExist", | |||
"err": fmt.Sprintf("Public (Deploy) Key: %d:%s is not authorized to %s %s/%s.", key.ID, key.Name, modeString, results.OwnerName, results.RepoName), | |||
}) | |||
return | |||
} | |||
log.Error("Unable to get deploy for public (deploy) key: %d in %-v Error: %v", key.ID, repo, err) | |||
ctx.JSON(http.StatusInternalServerError, map[string]interface{}{ | |||
"results": results, | |||
"type": "InternalServerError", | |||
"err": fmt.Sprintf("Unable to get Deploy Key for Public Key: %d:%s in %s/%s.", key.ID, key.Name, results.OwnerName, results.RepoName), | |||
}) | |||
return | |||
} | |||
results.KeyName = deployKey.Name | |||
// FIXME: Deploy keys aren't really the owner of the repo pushing changes | |||
// however we don't have good way of representing deploy keys in hook.go | |||
// so for now use the owner of the repository | |||
results.UserName = results.OwnerName | |||
results.UserID = repo.OwnerID | |||
} else { | |||
// Get the user represented by the Key | |||
var err error | |||
user, err = models.GetUserByID(key.OwnerID) | |||
if err != nil { | |||
if models.IsErrUserNotExist(err) { | |||
ctx.JSON(http.StatusUnauthorized, map[string]interface{}{ | |||
"results": results, | |||
"type": "ErrUserNotExist", | |||
"err": fmt.Sprintf("Public Key: %d:%s owner %d does not exist.", key.ID, key.Name, key.OwnerID), | |||
}) | |||
return | |||
} | |||
log.Error("Unable to get owner: %d for public key: %d:%s Error: %v", key.OwnerID, key.ID, key.Name, err) | |||
ctx.JSON(http.StatusInternalServerError, map[string]interface{}{ | |||
"results": results, | |||
"type": "InternalServerError", | |||
"err": fmt.Sprintf("Unable to get Owner: %d for Deploy Key: %d:%s in %s/%s.", key.OwnerID, key.ID, key.Name, ownerName, repoName), | |||
}) | |||
return | |||
} | |||
results.UserName = user.Name | |||
} | |||
// Don't allow pushing if the repo is archived | |||
if mode > models.AccessModeRead && repo.IsArchived { | |||
ctx.JSON(http.StatusUnauthorized, map[string]interface{}{ | |||
"results": results, | |||
"type": "ErrRepoIsArchived", | |||
"err": fmt.Sprintf("Repo: %s/%s is archived.", results.OwnerName, results.RepoName), | |||
}) | |||
return | |||
} | |||
// Permissions checking: | |||
if mode > models.AccessModeRead || repo.IsPrivate || setting.Service.RequireSignInView { | |||
if key.Type == models.KeyTypeDeploy { | |||
if deployKey.Mode < mode { | |||
ctx.JSON(http.StatusUnauthorized, map[string]interface{}{ | |||
"results": results, | |||
"type": "ErrUnauthorized", | |||
"err": fmt.Sprintf("Deploy Key: %d:%s is not authorized to %s %s/%s.", key.ID, key.Name, modeString, results.OwnerName, results.RepoName), | |||
}) | |||
return | |||
} | |||
} else { | |||
perm, err := models.GetUserRepoPermission(repo, user) | |||
if err != nil { | |||
log.Error("Unable to get permissions for %-v with key %d in %-v Error: %v", user, key.ID, repo, err) | |||
ctx.JSON(http.StatusInternalServerError, map[string]interface{}{ | |||
"results": results, | |||
"type": "InternalServerError", | |||
"err": fmt.Sprintf("Unable to get permissions for user %d:%s with key %d in %s/%s Error: %v", user.ID, user.Name, key.ID, results.OwnerName, results.RepoName, err), | |||
}) | |||
return | |||
} | |||
userMode := perm.UnitAccessMode(unitType) | |||
if userMode < mode { | |||
ctx.JSON(http.StatusUnauthorized, map[string]interface{}{ | |||
"results": results, | |||
"type": "ErrUnauthorized", | |||
"err": fmt.Sprintf("User: %d:%s with Key: %d:%s is not authorized to %s %s/%s.", user.ID, user.Name, key.ID, key.Name, modeString, ownerName, repoName), | |||
}) | |||
return | |||
} | |||
} | |||
} | |||
// Finally if we're trying to touch the wiki we should init it | |||
if results.IsWiki { | |||
if err = repo.InitWiki(); err != nil { | |||
log.Error("Failed to initialize the wiki in %-v Error: %v", repo, err) | |||
ctx.JSON(http.StatusInternalServerError, map[string]interface{}{ | |||
"results": results, | |||
"type": "InternalServerError", | |||
"err": fmt.Sprintf("Failed to initialize the wiki in %s/%s Error: %v", ownerName, repoName, err), | |||
}) | |||
return | |||
} | |||
} | |||
log.Debug("Serv Results:\nIsWiki: %t\nIsDeployKey: %t\nKeyID: %d\tKeyName: %s\nUserName: %s\nUserID: %d\nOwnerName: %s\nRepoName: %s\nRepoID: %d", | |||
results.IsWiki, | |||
results.IsDeployKey, | |||
results.KeyID, | |||
results.KeyName, | |||
results.UserName, | |||
results.UserID, | |||
results.OwnerName, | |||
results.RepoName, | |||
results.RepoID) | |||
ctx.JSON(http.StatusOK, results) | |||
// We will update the keys in a different call. | |||
return | |||
} |
@ -1,34 +0,0 @@ | |||
// Copyright 2017 The Gitea Authors. All rights reserved. | |||
// Use of this source code is governed by a MIT-style | |||
// license that can be found in the LICENSE file. | |||
package private | |||
import ( | |||
"code.gitea.io/gitea/models" | |||
macaron "gopkg.in/macaron.v1" | |||
) | |||
// InitWiki initilizes wiki via repo id | |||
func InitWiki(ctx *macaron.Context) { | |||
repoID := ctx.ParamsInt64("repoid") | |||
repo, err := models.GetRepositoryByID(repoID) | |||
if err != nil { | |||
ctx.JSON(500, map[string]interface{}{ | |||
"err": err.Error(), | |||
}) | |||
return | |||
} | |||
err = repo.InitWiki() | |||
if err != nil { | |||
ctx.JSON(500, map[string]interface{}{ | |||
"err": err.Error(), | |||
}) | |||
return | |||
} | |||
ctx.Status(202) | |||
} |