1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
|
package ssh
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path"
"strings"
"testing"
"time"
"github.com/golang/protobuf/jsonpb"
"github.com/stretchr/testify/require"
"gitlab.com/gitlab-org/gitaly-proto/go/gitalypb"
"gitlab.com/gitlab-org/gitaly/internal/config"
"gitlab.com/gitlab-org/gitaly/internal/git"
"gitlab.com/gitlab-org/gitaly/internal/git/hooks"
"gitlab.com/gitlab-org/gitaly/internal/testhelper"
"golang.org/x/net/context"
"google.golang.org/grpc/codes"
)
func TestFailedReceivePackRequestDueToValidationError(t *testing.T) {
server, serverSocketPath := runSSHServer(t)
defer server.Stop()
client, conn := newSSHClient(t, serverSocketPath)
defer conn.Close()
tests := []struct {
Desc string
Req *gitalypb.SSHReceivePackRequest
Code codes.Code
}{
{
Desc: "Repository.RelativePath is empty",
Req: &gitalypb.SSHReceivePackRequest{Repository: &gitalypb.Repository{StorageName: "default", RelativePath: ""}, GlId: "user-123"},
Code: codes.InvalidArgument,
},
{
Desc: "Repository is nil",
Req: &gitalypb.SSHReceivePackRequest{Repository: nil, GlId: "user-123"},
Code: codes.InvalidArgument,
},
{
Desc: "Empty GlId",
Req: &gitalypb.SSHReceivePackRequest{Repository: &gitalypb.Repository{StorageName: "default", RelativePath: testRepo.GetRelativePath()}, GlId: ""},
Code: codes.InvalidArgument,
},
{
Desc: "Data exists on first request",
Req: &gitalypb.SSHReceivePackRequest{Repository: &gitalypb.Repository{StorageName: "default", RelativePath: testRepo.GetRelativePath()}, GlId: "user-123", Stdin: []byte("Fail")},
Code: codes.InvalidArgument,
},
}
for _, test := range tests {
t.Run(test.Desc, func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
stream, err := client.SSHReceivePack(ctx)
if err != nil {
t.Fatal(err)
}
if err = stream.Send(test.Req); err != nil {
t.Fatal(err)
}
stream.CloseSend()
err = drainPostReceivePackResponse(stream)
testhelper.RequireGrpcError(t, err, test.Code)
})
}
}
func TestReceivePackPushSuccess(t *testing.T) {
defer func(dir string) { config.Config.GitlabShell.Dir = dir }(config.Config.GitlabShell.Dir)
config.Config.GitlabShell.Dir = "/foo/bar/gitlab-shell"
hookOutputFile, cleanup := testhelper.CaptureHookEnv(t)
defer cleanup()
server, serverSocketPath := runSSHServer(t)
defer server.Stop()
lHead, rHead, err := testCloneAndPush(t, serverSocketPath, pushParams{storageName: testRepo.GetStorageName(), glID: "user-123"})
if err != nil {
t.Fatal(err)
}
require.Equal(t, lHead, rHead, "local and remote head not equal. push failed")
envData, err := ioutil.ReadFile(hookOutputFile)
require.NoError(t, err, "get git env data")
for _, env := range []string{
"GL_ID=user-123",
"GL_REPOSITORY=project-456",
"GL_PROTOCOL=ssh",
"GITLAB_SHELL_DIR=" + "/foo/bar/gitlab-shell",
} {
require.Contains(t, strings.Split(string(envData), "\n"), env)
}
}
func TestReceivePackPushSuccessWithGitProtocol(t *testing.T) {
defer func(old string) {
config.Config.Git.BinPath = old
}(config.Config.Git.BinPath)
config.Config.Git.BinPath = "../../testhelper/env_git"
server, serverSocketPath := runSSHServer(t)
defer server.Stop()
lHead, rHead, err := testCloneAndPush(t, serverSocketPath, pushParams{storageName: testRepo.GetStorageName(), glID: "1", gitProtocol: git.ProtocolV2})
if err != nil {
t.Fatal(err)
}
require.Equal(t, lHead, rHead, "local and remote head not equal. push failed")
envData, err := testhelper.GetGitEnvData()
require.NoError(t, err)
require.Equal(t, fmt.Sprintf("GIT_PROTOCOL=%s\n", git.ProtocolV2), envData)
}
func TestReceivePackPushFailure(t *testing.T) {
server, serverSocketPath := runSSHServer(t)
defer server.Stop()
_, _, err := testCloneAndPush(t, serverSocketPath, pushParams{storageName: "foobar", glID: "1"})
if err == nil {
t.Errorf("local and remote head equal. push did not fail")
}
_, _, err = testCloneAndPush(t, serverSocketPath, pushParams{storageName: testRepo.GetStorageName(), glID: ""})
if err == nil {
t.Errorf("local and remote head equal. push did not fail")
}
}
func TestReceivePackPushHookFailure(t *testing.T) {
server, serverSocketPath := runSSHServer(t)
defer server.Stop()
hookDir, err := ioutil.TempDir("", "gitaly-tmp-hooks")
require.NoError(t, err)
defer os.RemoveAll(hookDir)
defer func(oldDir string) {
config.Config.GitlabShell.Dir = oldDir
}(config.Config.GitlabShell.Dir)
config.Config.GitlabShell.Dir = hookDir
require.NoError(t, os.MkdirAll(hooks.Path(), 0755))
hookContent := []byte("#!/bin/sh\nexit 1")
ioutil.WriteFile(path.Join(hooks.Path(), "pre-receive"), hookContent, 0755)
_, _, err = testCloneAndPush(t, serverSocketPath, pushParams{storageName: testRepo.GetStorageName(), glID: "1"})
require.Error(t, err)
require.Contains(t, err.Error(), "(pre-receive hook declined)")
}
func testCloneAndPush(t *testing.T, serverSocketPath string, params pushParams) (string, string, error) {
storagePath := testhelper.GitlabTestStoragePath()
tempRepo := "gitlab-test-ssh-receive-pack.git"
testRepoPath := path.Join(storagePath, testRepo.GetRelativePath())
remoteRepoPath := path.Join(storagePath, tempRepo)
localRepoPath := path.Join(storagePath, "gitlab-test-ssh-receive-pack-local")
// Make a bare clone of the test repo to act as a remote one and to leave the original repo intact for other tests
if err := os.RemoveAll(remoteRepoPath); err != nil && !os.IsNotExist(err) {
t.Fatal(err)
}
testhelper.MustRunCommand(t, nil, "git", "clone", "--bare", testRepoPath, remoteRepoPath)
// Make a non-bare clone of the test repo to act as a local one
if err := os.RemoveAll(localRepoPath); err != nil && !os.IsNotExist(err) {
t.Fatal(err)
}
testhelper.MustRunCommand(t, nil, "git", "clone", remoteRepoPath, localRepoPath)
// We need git thinking we're pushing over SSH...
defer os.RemoveAll(remoteRepoPath)
defer os.RemoveAll(localRepoPath)
makeCommit(t, localRepoPath)
pbTempRepo := &gitalypb.Repository{StorageName: params.storageName, RelativePath: tempRepo}
pbMarshaler := &jsonpb.Marshaler{}
payload, err := pbMarshaler.MarshalToString(&gitalypb.SSHReceivePackRequest{
Repository: pbTempRepo,
GlRepository: "project-456",
GlId: params.glID,
GitConfigOptions: params.gitConfigOptions,
GitProtocol: params.gitProtocol,
})
require.NoError(t, err)
cmd := exec.Command("git", "-C", localRepoPath, "push", "-v", "git@localhost:test/test.git", "master")
cmd.Env = []string{
fmt.Sprintf("GITALY_PAYLOAD=%s", payload),
fmt.Sprintf("GITALY_ADDRESS=%s", serverSocketPath),
fmt.Sprintf("PATH=%s", ".:"+os.Getenv("PATH")),
fmt.Sprintf(`GIT_SSH_COMMAND=%s receive-pack`, gitalySSHPath),
}
out, err := cmd.CombinedOutput()
if err != nil {
return "", "", fmt.Errorf("Error pushing: %v: %q", err, out)
}
if !cmd.ProcessState.Success() {
return "", "", fmt.Errorf("Failed to run `git push`: %q", out)
}
localHead := bytes.TrimSpace(testhelper.MustRunCommand(t, nil, "git", "-C", localRepoPath, "rev-parse", "master"))
remoteHead := bytes.TrimSpace(testhelper.MustRunCommand(t, nil, "git", "-C", remoteRepoPath, "rev-parse", "master"))
return string(localHead), string(remoteHead), nil
}
// makeCommit creates a new commit and returns oldHead, newHead, success
func makeCommit(t *testing.T, localRepoPath string) ([]byte, []byte, bool) {
commitMsg := fmt.Sprintf("Testing ReceivePack RPC around %d", time.Now().Unix())
committerName := "Scrooge McDuck"
committerEmail := "scrooge@mcduck.com"
newFilePath := localRepoPath + "/foo.txt"
// Create a tiny file and add it to the index
require.NoError(t, ioutil.WriteFile(newFilePath, []byte("foo bar"), 0644))
testhelper.MustRunCommand(t, nil, "git", "-C", localRepoPath, "add", ".")
// The latest commit ID on the remote repo
oldHead := bytes.TrimSpace(testhelper.MustRunCommand(t, nil, "git", "-C", localRepoPath, "rev-parse", "master"))
testhelper.MustRunCommand(t, nil, "git", "-C", localRepoPath,
"-c", fmt.Sprintf("user.name=%s", committerName),
"-c", fmt.Sprintf("user.email=%s", committerEmail),
"commit", "-m", commitMsg)
if t.Failed() {
return nil, nil, false
}
// The commit ID we want to push to the remote repo
newHead := bytes.TrimSpace(testhelper.MustRunCommand(t, nil, "git", "-C", localRepoPath, "rev-parse", "master"))
return oldHead, newHead, t.Failed()
}
func drainPostReceivePackResponse(stream gitalypb.SSHService_SSHReceivePackClient) error {
var err error
for err == nil {
_, err = stream.Recv()
}
return err
}
type pushParams struct {
storageName string
glID string
gitConfigOptions []string
gitProtocol string
}
|