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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
|
package smarthttp
import (
"bytes"
"context"
"fmt"
"io"
"io/ioutil"
"os"
"path"
"strings"
"testing"
"time"
"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"
"gitlab.com/gitlab-org/gitaly/streamio"
"google.golang.org/grpc/codes"
)
func TestSuccessfulReceivePackRequest(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 := runSmartHTTPServer(t)
defer server.Stop()
repo, repoPath, cleanup := testhelper.NewTestRepo(t)
defer cleanup()
client, conn := newSmartHTTPClient(t, serverSocketPath)
defer conn.Close()
ctx, cancel := testhelper.Context()
defer cancel()
stream, err := client.PostReceivePack(ctx)
require.NoError(t, err)
push := newTestPush(t, nil)
firstRequest := &gitalypb.PostReceivePackRequest{Repository: repo, GlId: "user-123", GlRepository: "project-456"}
response := doPush(t, stream, firstRequest, push.body)
expectedResponse := "0030\x01000eunpack ok\n0019ok refs/heads/master\n00000000"
require.Equal(t, expectedResponse, string(response), "Expected response to be %q, got %q", expectedResponse, response)
// The fact that this command succeeds means that we got the commit correctly, no further checks should be needed.
testhelper.MustRunCommand(t, nil, "git", "-C", repoPath, "show", push.newHead)
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=http",
"GITLAB_SHELL_DIR=" + "/foo/bar/gitlab-shell",
} {
require.Contains(t, strings.Split(string(envData), "\n"), env)
}
}
func TestSuccessfulReceivePackRequestWithGitProtocol(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 := runSmartHTTPServer(t)
defer server.Stop()
repo, repoPath, cleanup := testhelper.NewTestRepo(t)
defer cleanup()
client, conn := newSmartHTTPClient(t, serverSocketPath)
defer conn.Close()
ctx, cancel := testhelper.Context()
defer cancel()
stream, err := client.PostReceivePack(ctx)
require.NoError(t, err)
push := newTestPush(t, nil)
firstRequest := &gitalypb.PostReceivePackRequest{Repository: repo, GlId: "user-123", GlRepository: "project-123", GitProtocol: git.ProtocolV2}
doPush(t, stream, firstRequest, push.body)
envData, err := testhelper.GetGitEnvData()
require.NoError(t, err)
require.Equal(t, fmt.Sprintf("GIT_PROTOCOL=%s\n", git.ProtocolV2), envData)
// The fact that this command succeeds means that we got the commit correctly, no further checks should be needed.
testhelper.MustRunCommand(t, nil, "git", "-C", repoPath, "show", push.newHead)
}
func TestFailedReceivePackRequestWithGitOpts(t *testing.T) {
server, serverSocketPath := runSmartHTTPServer(t)
defer server.Stop()
repo, _, cleanup := testhelper.NewTestRepo(t)
defer cleanup()
client, conn := newSmartHTTPClient(t, serverSocketPath)
defer conn.Close()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
stream, err := client.PostReceivePack(ctx)
require.NoError(t, err)
push := newTestPush(t, nil)
firstRequest := &gitalypb.PostReceivePackRequest{Repository: repo, GlId: "user-123", GlRepository: "project-123", GitConfigOptions: []string{"receive.MaxInputSize=1"}}
response := doPush(t, stream, firstRequest, push.body)
expectedResponse := "002e\x02fatal: pack exceeds maximum allowed size\n0059\x010028unpack unpack-objects abnormal exit\n0028ng refs/heads/master unpacker error\n00000000"
require.Equal(t, expectedResponse, string(response), "Expected response to be %q, got %q", expectedResponse, response)
}
func TestFailedReceivePackRequestDueToHooksFailure(t *testing.T) {
hookDir, err := ioutil.TempDir("", "gitaly-tmp-hooks")
require.NoError(t, err)
defer os.RemoveAll(hookDir)
defer func(oldDir string) {
config.Config.GitlabShell.Dir = hookDir
}(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)
server, serverSocketPath := runSmartHTTPServer(t)
defer server.Stop()
repo, _, cleanup := testhelper.NewTestRepo(t)
defer cleanup()
client, conn := newSmartHTTPClient(t, serverSocketPath)
defer conn.Close()
ctx, cancel := testhelper.Context()
defer cancel()
stream, err := client.PostReceivePack(ctx)
require.NoError(t, err)
push := newTestPush(t, nil)
firstRequest := &gitalypb.PostReceivePackRequest{Repository: repo, GlId: "user-123", GlRepository: "project-123"}
response := doPush(t, stream, firstRequest, push.body)
expectedResponse := "004a\x01000eunpack ok\n0033ng refs/heads/master pre-receive hook declined\n00000000"
require.Equal(t, expectedResponse, string(response), "Expected response to be %q, got %q", expectedResponse, response)
}
func doPush(t *testing.T, stream gitalypb.SmartHTTPService_PostReceivePackClient, firstRequest *gitalypb.PostReceivePackRequest, body io.Reader) []byte {
require.NoError(t, stream.Send(firstRequest))
sw := streamio.NewWriter(func(p []byte) error {
return stream.Send(&gitalypb.PostReceivePackRequest{Data: p})
})
_, err := io.Copy(sw, body)
require.NoError(t, err)
require.NoError(t, stream.CloseSend())
responseBuffer := bytes.Buffer{}
rr := streamio.NewReader(func() ([]byte, error) {
resp, err := stream.Recv()
return resp.GetData(), err
})
_, err = io.Copy(&responseBuffer, rr)
require.NoError(t, err)
return responseBuffer.Bytes()
}
type pushData struct {
newHead string
body io.Reader
}
func newTestPush(t *testing.T, fileContents []byte) *pushData {
_, repoPath, localCleanup := testhelper.NewTestRepoWithWorktree(t)
defer localCleanup()
oldHead, newHead := createCommit(t, repoPath, fileContents)
// ReceivePack request is a packet line followed by a packet flush, then the pack file of the objects we want to push.
// This is explained a bit in https://git-scm.com/book/en/v2/Git-Internals-Transfer-Protocols#_uploading_data
// We form the packet line the same way git executable does: https://github.com/git/git/blob/d1a13d3fcb252631361a961cb5e2bf10ed467cba/send-pack.c#L524-L527
clientCapabilities := "report-status side-band-64k agent=git/2.12.0"
pkt := fmt.Sprintf("%s %s refs/heads/master\x00 %s", oldHead, newHead, clientCapabilities)
// We need to get a pack file containing the objects we want to push, so we use git pack-objects
// which expects a list of revisions passed through standard input. The list format means
// pack the objects needed if I have oldHead but not newHead (think of it from the perspective of the remote repo).
// For more info, check the man pages of both `git-pack-objects` and `git-rev-list --objects`.
stdin := strings.NewReader(fmt.Sprintf("^%s\n%s\n", oldHead, newHead))
// The options passed are the same ones used when doing an actual push.
pack := testhelper.MustRunCommand(t, stdin, "git", "-C", repoPath, "pack-objects", "--stdout", "--revs", "--thin", "--delta-base-offset", "-q")
// We chop the request into multiple small pieces to exercise the server code that handles
// the stream sent by the client, so we use a buffer to read chunks of data in a nice way.
requestBuffer := &bytes.Buffer{}
fmt.Fprintf(requestBuffer, "%04x%s%s", len(pkt)+4, pkt, pktFlushStr)
requestBuffer.Write(pack)
return &pushData{newHead: newHead, body: requestBuffer}
}
// createCommit creates a commit on HEAD with a file containing the
// specified contents.
func createCommit(t *testing.T, repoPath string, fileContents []byte) (oldHead string, newHead string) {
commitMsg := fmt.Sprintf("Testing ReceivePack RPC around %d", time.Now().Unix())
committerName := "Scrooge McDuck"
committerEmail := "scrooge@mcduck.com"
// The latest commit ID on the remote repo
oldHead = strings.TrimSpace(string(testhelper.MustRunCommand(t, nil, "git", "-C", repoPath, "rev-parse", "master")))
changedFile := "README.md"
require.NoError(t, ioutil.WriteFile(path.Join(repoPath, changedFile), fileContents, 0644))
testhelper.MustRunCommand(t, nil, "git", "-C", repoPath, "add", changedFile)
testhelper.MustRunCommand(t, nil, "git", "-C", repoPath,
"-c", fmt.Sprintf("user.name=%s", committerName),
"-c", fmt.Sprintf("user.email=%s", committerEmail),
"commit", "-m", commitMsg)
// The commit ID we want to push to the remote repo
newHead = strings.TrimSpace(string(testhelper.MustRunCommand(t, nil, "git", "-C", repoPath, "rev-parse", "master")))
return oldHead, newHead
}
func TestFailedReceivePackRequestDueToValidationError(t *testing.T) {
server, serverSocketPath := runSmartHTTPServer(t)
defer server.Stop()
client, conn := newSmartHTTPClient(t, serverSocketPath)
defer conn.Close()
rpcRequests := []gitalypb.PostReceivePackRequest{
{Repository: &gitalypb.Repository{StorageName: "fake", RelativePath: "path"}, GlId: "user-123"}, // Repository doesn't exist
{Repository: nil, GlId: "user-123"}, // Repository is nil
{Repository: &gitalypb.Repository{StorageName: "default", RelativePath: "path/to/repo"}, GlId: ""}, // Empty GlId
{Repository: &gitalypb.Repository{StorageName: "default", RelativePath: "path/to/repo"}, GlId: "user-123", Data: []byte("Fail")}, // Data exists on first request
}
for _, rpcRequest := range rpcRequests {
t.Run(fmt.Sprintf("%v", rpcRequest), func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
stream, err := client.PostReceivePack(ctx)
require.NoError(t, err)
require.NoError(t, stream.Send(&rpcRequest))
stream.CloseSend()
err = drainPostReceivePackResponse(stream)
testhelper.RequireGrpcError(t, err, codes.InvalidArgument)
})
}
}
func drainPostReceivePackResponse(stream gitalypb.SmartHTTPService_PostReceivePackClient) error {
var err error
for err == nil {
_, err = stream.Recv()
}
return err
}
|