Skip to content

Commit 7312752

Browse files
zeripathtechknowlogick
authored andcommitted
Fix notifications on pushing with deploy keys by setting hook environment variables (#5935) (#5944)
The gitea prerecieve and postrecieve hooks and the gitea PushUpdate function require that the PusherID and PusherName are real users. Previously, these environment variables were not being set when using a deploy key - the main result being that pushing to empty repositories meant that is_empty status was not changed. I've also added an integration test to ensure that the is_empty status is updated on pushing with a deploy key. There is a slight issue in that the deploy key is now considered a proxy for the owner - we don't have a way of separating out the deploy key from the owner at present. This can be fixed in another PR. Fix #3795 Signed-off-by: Andrew Thornton [email protected]
1 parent 022634a commit 7312752

File tree

2 files changed

+166
-0
lines changed

2 files changed

+166
-0
lines changed

cmd/serv.go

+6
Original file line numberDiff line numberDiff line change
@@ -250,6 +250,12 @@ func runServ(c *cli.Context) error {
250250
if err = private.UpdateDeployKeyUpdated(key.ID, repo.ID); err != nil {
251251
fail("Internal error", "UpdateDeployKey: %v", err)
252252
}
253+
254+
// FIXME: Deploy keys aren't really the owner of the repo pushing changes
255+
// however we don't have good way of representing deploy keys in hook.go
256+
// so for now use the owner
257+
os.Setenv(models.EnvPusherName, username)
258+
os.Setenv(models.EnvPusherID, fmt.Sprintf("%d", repo.OwnerID))
253259
} else {
254260
user, err = private.GetUserByKeyID(key.ID)
255261
if err != nil {

integrations/deploy_key_push_test.go

+160
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,160 @@
1+
// Copyright 2019 The Gitea Authors. All rights reserved.
2+
// Use of this source code is governed by a MIT-style
3+
// license that can be found in the LICENSE file.
4+
5+
package integrations
6+
7+
import (
8+
"fmt"
9+
"io/ioutil"
10+
"log"
11+
"net/http"
12+
"net/url"
13+
"os"
14+
"os/exec"
15+
"path/filepath"
16+
"testing"
17+
"time"
18+
19+
"code.gitea.io/git"
20+
21+
"code.gitea.io/gitea/modules/setting"
22+
api "code.gitea.io/sdk/gitea"
23+
"github.com/stretchr/testify/assert"
24+
)
25+
26+
func createEmptyRepository(username, reponame string) func(*testing.T) {
27+
return func(t *testing.T) {
28+
session := loginUser(t, username)
29+
token := getTokenForLoggedInUser(t, session)
30+
req := NewRequestWithJSON(t, "POST", "/api/v1/user/repos?token="+token, &api.CreateRepoOption{
31+
AutoInit: false,
32+
Description: "Temporary empty repo",
33+
Name: reponame,
34+
Private: false,
35+
})
36+
session.MakeRequest(t, req, http.StatusCreated)
37+
}
38+
}
39+
40+
func createDeployKey(username, reponame, keyname, keyFile string, readOnly bool) func(*testing.T) {
41+
return func(t *testing.T) {
42+
session := loginUser(t, username)
43+
token := getTokenForLoggedInUser(t, session)
44+
urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/keys?token=%s", username, reponame, token)
45+
46+
dataPubKey, err := ioutil.ReadFile(keyFile + ".pub")
47+
assert.NoError(t, err)
48+
req := NewRequestWithJSON(t, "POST", urlStr, api.CreateKeyOption{
49+
Title: keyname,
50+
Key: string(dataPubKey),
51+
ReadOnly: readOnly,
52+
})
53+
session.MakeRequest(t, req, http.StatusCreated)
54+
}
55+
}
56+
57+
func initTestRepository(dstPath string) func(*testing.T) {
58+
return func(t *testing.T) {
59+
// Init repository in dstPath
60+
assert.NoError(t, git.InitRepository(dstPath, false))
61+
assert.NoError(t, ioutil.WriteFile(filepath.Join(dstPath, "README.md"), []byte(fmt.Sprintf("# Testing Repository\n\nOriginally created in: %s", dstPath)), 0644))
62+
assert.NoError(t, git.AddChanges(dstPath, true))
63+
signature := git.Signature{
64+
65+
Name: "test",
66+
When: time.Now(),
67+
}
68+
assert.NoError(t, git.CommitChanges(dstPath, git.CommitChangesOptions{
69+
Committer: &signature,
70+
Author: &signature,
71+
Message: "Initial Commit",
72+
}))
73+
}
74+
}
75+
76+
func pushTestRepository(dstPath, username, reponame string, u url.URL, keyFile string) func(*testing.T) {
77+
return func(t *testing.T) {
78+
//Setup remote link
79+
u.Scheme = "ssh"
80+
u.User = url.User("git")
81+
u.Host = fmt.Sprintf("%s:%d", setting.SSH.ListenHost, setting.SSH.ListenPort)
82+
83+
//Setup ssh wrapper
84+
os.Setenv("GIT_SSH_COMMAND",
85+
"ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -i "+
86+
filepath.Join(setting.AppWorkPath, keyFile))
87+
os.Setenv("GIT_SSH_VARIANT", "ssh")
88+
89+
log.Printf("Adding remote: %s\n", u.String())
90+
_, err := git.NewCommand("remote", "add", "origin", u.String()).RunInDir(dstPath)
91+
assert.NoError(t, err)
92+
93+
log.Printf("Pushing to: %s\n", u.String())
94+
_, err = git.NewCommand("push", "-u", "origin", "master").RunInDir(dstPath)
95+
assert.NoError(t, err)
96+
}
97+
}
98+
99+
func checkRepositoryEmptyStatus(username, reponame string, isEmpty bool) func(*testing.T) {
100+
return func(t *testing.T) {
101+
session := loginUser(t, username)
102+
token := getTokenForLoggedInUser(t, session)
103+
urlStr := fmt.Sprintf("/api/v1/repos/%s/%s?token=%s", username, reponame, token)
104+
105+
req := NewRequest(t, "GET", urlStr)
106+
resp := session.MakeRequest(t, req, http.StatusOK)
107+
108+
var repository api.Repository
109+
DecodeJSON(t, resp, &repository)
110+
111+
assert.Equal(t, isEmpty, repository.Empty)
112+
}
113+
}
114+
115+
func deleteRepository(username, reponame string) func(*testing.T) {
116+
return func(t *testing.T) {
117+
session := loginUser(t, username)
118+
token := getTokenForLoggedInUser(t, session)
119+
urlStr := fmt.Sprintf("/api/v1/repos/%s/%s?token=%s", username, reponame, token)
120+
121+
req := NewRequest(t, "DELETE", urlStr)
122+
session.MakeRequest(t, req, http.StatusNoContent)
123+
}
124+
}
125+
126+
func TestPushDeployKeyOnEmptyRepo(t *testing.T) {
127+
onGiteaRun(t, testPushDeployKeyOnEmptyRepo)
128+
}
129+
130+
func testPushDeployKeyOnEmptyRepo(t *testing.T, u *url.URL) {
131+
reponame := "deploy-key-empty-repo-1"
132+
username := "user2"
133+
u.Path = fmt.Sprintf("%s/%s.git", username, reponame)
134+
keyname := fmt.Sprintf("%s-push", reponame)
135+
136+
t.Run("CreateEmptyRepository", createEmptyRepository(username, reponame))
137+
t.Run("CheckIsEmpty", checkRepositoryEmptyStatus(username, reponame, true))
138+
139+
//Setup the push deploy key file
140+
keyFile := filepath.Join(setting.AppDataPath, keyname)
141+
err := exec.Command("ssh-keygen", "-f", keyFile, "-t", "rsa", "-N", "").Run()
142+
assert.NoError(t, err)
143+
defer os.RemoveAll(keyFile)
144+
defer os.RemoveAll(keyFile + ".pub")
145+
146+
t.Run("CreatePushDeployKey", createDeployKey(username, reponame, keyname, keyFile, false))
147+
148+
// Setup the testing repository
149+
dstPath, err := ioutil.TempDir("", "repo-tmp-deploy-key-empty-repo-1")
150+
assert.NoError(t, err)
151+
defer os.RemoveAll(dstPath)
152+
153+
t.Run("InitTestRepository", initTestRepository(dstPath))
154+
t.Run("SSHPushTestRepository", pushTestRepository(dstPath, username, reponame, *u, keyFile))
155+
156+
log.Println("Done Push")
157+
t.Run("CheckIsNotEmpty", checkRepositoryEmptyStatus(username, reponame, false))
158+
159+
t.Run("DeleteRepository", deleteRepository(username, reponame))
160+
}

0 commit comments

Comments
 (0)