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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
|
package updateref_test
import (
"context"
"errors"
"fmt"
"io"
"strings"
"testing"
"github.com/stretchr/testify/require"
"gitlab.com/gitlab-org/gitaly/v16/internal/featureflag"
"gitlab.com/gitlab-org/gitaly/v16/internal/git"
"gitlab.com/gitlab-org/gitaly/v16/internal/git/gittest"
"gitlab.com/gitlab-org/gitaly/v16/internal/git/localrepo"
"gitlab.com/gitlab-org/gitaly/v16/internal/git/quarantine"
"gitlab.com/gitlab-org/gitaly/v16/internal/git/updateref"
"gitlab.com/gitlab-org/gitaly/v16/internal/gitaly/config"
"gitlab.com/gitlab-org/gitaly/v16/internal/gitaly/hook"
"gitlab.com/gitlab-org/gitaly/v16/internal/gitaly/service"
hookservice "gitlab.com/gitlab-org/gitaly/v16/internal/gitaly/service/hook"
"gitlab.com/gitlab-org/gitaly/v16/internal/testhelper"
"gitlab.com/gitlab-org/gitaly/v16/internal/testhelper/testcfg"
"gitlab.com/gitlab-org/gitaly/v16/internal/testhelper/testserver"
"gitlab.com/gitlab-org/gitaly/v16/proto/go/gitalypb"
"google.golang.org/grpc"
)
func TestUpdaterWithHooks_UpdateReference_invalidParameters(t *testing.T) {
t.Parallel()
ctx := testhelper.Context(t)
cfg := testcfg.Build(t)
gitCmdFactory := gittest.NewCommandFactory(t, cfg)
repo, _ := gittest.CreateRepository(t, ctx, cfg, gittest.CreateRepositoryConfig{
SkipCreationViaService: true,
})
revA := git.ObjectID(strings.Repeat("a", gittest.DefaultObjectHash.EncodedLen()))
revB := git.ObjectID(strings.Repeat("b", gittest.DefaultObjectHash.EncodedLen()))
updater := updateref.NewUpdaterWithHooks(cfg, nil, &hook.MockManager{}, gitCmdFactory, nil)
testCases := []struct {
desc string
ref git.ReferenceName
newRev, oldRev git.ObjectID
expectedErr error
}{
{
desc: "missing reference",
oldRev: revA,
newRev: revB,
expectedErr: fmt.Errorf("reference cannot be empty"),
},
{
desc: "missing old rev",
ref: "refs/heads/master",
newRev: revB,
expectedErr: fmt.Errorf("validating old value: %w", git.InvalidObjectIDLengthError{OID: "", CorrectLength: gittest.DefaultObjectHash.EncodedLen(), Length: 0}),
},
{
desc: "missing new rev",
ref: "refs/heads/master",
oldRev: revB,
expectedErr: fmt.Errorf("validating new value: %w", git.InvalidObjectIDLengthError{OID: "", CorrectLength: gittest.DefaultObjectHash.EncodedLen(), Length: 0}),
},
{
desc: "invalid old rev",
ref: "refs/heads/master",
newRev: revA,
oldRev: "foobar",
expectedErr: fmt.Errorf("validating old value: %w", git.InvalidObjectIDLengthError{OID: "foobar", CorrectLength: gittest.DefaultObjectHash.EncodedLen(), Length: 6}),
},
{
desc: "invalid new rev",
ref: "refs/heads/master",
newRev: "foobar",
oldRev: revB,
expectedErr: fmt.Errorf("validating new value: %w", git.InvalidObjectIDLengthError{OID: "foobar", CorrectLength: gittest.DefaultObjectHash.EncodedLen(), Length: 6}),
},
}
for _, tc := range testCases {
t.Run(tc.desc, func(t *testing.T) {
err := updater.UpdateReference(ctx, repo, gittest.TestUser, nil, tc.ref, tc.newRev, tc.oldRev)
require.Equal(t, tc.expectedErr, err)
})
}
}
func TestUpdaterWithHooks_UpdateReference(t *testing.T) {
t.Parallel()
ctx := testhelper.Context(t)
cfg := testcfg.Build(t)
// We need to set up a separate "real" hook service here, as it will be used in
// git-update-ref(1) spawned by `updateRefWithHooks()`
testserver.RunGitalyServer(t, cfg, func(srv *grpc.Server, deps *service.Dependencies) {
gitalypb.RegisterHookServiceServer(srv, hookservice.NewServer(deps.GetHookManager(), deps.GetGitCmdFactory(), deps.GetPackObjectsCache(), deps.GetPackObjectsConcurrencyTracker(), deps.GetPackObjectsLimiter()))
})
repo, repoPath := gittest.CreateRepository(t, ctx, cfg, gittest.CreateRepositoryConfig{
SkipCreationViaService: true,
})
commitID := gittest.WriteCommit(t, cfg, repoPath, gittest.WithBranch("main"))
requirePayload := func(t *testing.T, env []string) {
require.Len(t, env, 1)
expectedPayload := git.NewHooksPayload(
cfg,
repo,
gittest.DefaultObjectHash,
nil,
&git.UserDetails{
UserID: gittest.TestUser.GlId,
Username: gittest.TestUser.GlUsername,
Protocol: "web",
}, git.ReceivePackHooks, featureflag.FromContext(ctx))
actualPayload, err := git.HooksPayloadFromEnv(env)
require.NoError(t, err)
// Flags aren't sorted, so we just verify they contain the same elements.
require.ElementsMatch(t, expectedPayload.FeatureFlagsWithValue, actualPayload.FeatureFlagsWithValue)
expectedPayload.FeatureFlagsWithValue = nil
actualPayload.FeatureFlagsWithValue = nil
require.Equal(t, expectedPayload, actualPayload)
}
referenceTransactionCalls := 0
testCases := []struct {
desc string
preReceive func(t *testing.T, ctx context.Context, repo *gitalypb.Repository, pushOptions, env []string, stdin io.Reader, stdout, stderr io.Writer) error
postReceive func(t *testing.T, ctx context.Context, repo *gitalypb.Repository, pushOptions, env []string, stdin io.Reader, stdout, stderr io.Writer) error
update func(t *testing.T, ctx context.Context, repo *gitalypb.Repository, ref, oldValue, newValue string, env []string, stdout, stderr io.Writer) error
referenceTransaction func(t *testing.T, ctx context.Context, state hook.ReferenceTransactionState, env []string, stdin io.Reader) error
expectedErr string
expectedRefDeletion bool
}{
{
desc: "successful update",
preReceive: func(t *testing.T, ctx context.Context, repo *gitalypb.Repository, pushOptions, env []string, stdin io.Reader, stdout, stderr io.Writer) error {
changes, err := io.ReadAll(stdin)
require.NoError(t, err)
require.Equal(t, fmt.Sprintf("%s %s refs/heads/main\n", commitID, gittest.DefaultObjectHash.ZeroOID.String()), string(changes))
require.Empty(t, pushOptions)
requirePayload(t, env)
return nil
},
update: func(t *testing.T, ctx context.Context, repo *gitalypb.Repository, ref, oldValue, newValue string, env []string, stdout, stderr io.Writer) error {
require.Equal(t, "refs/heads/main", ref)
require.Equal(t, commitID.String(), oldValue)
require.Equal(t, newValue, gittest.DefaultObjectHash.ZeroOID.String())
requirePayload(t, env)
return nil
},
postReceive: func(t *testing.T, ctx context.Context, repo *gitalypb.Repository, pushOptions, env []string, stdin io.Reader, stdout, stderr io.Writer) error {
changes, err := io.ReadAll(stdin)
require.NoError(t, err)
require.Equal(t, fmt.Sprintf("%s %s refs/heads/main\n", commitID.String(), gittest.DefaultObjectHash.ZeroOID.String()), string(changes))
requirePayload(t, env)
require.Empty(t, pushOptions)
return nil
},
referenceTransaction: func(t *testing.T, ctx context.Context, state hook.ReferenceTransactionState, env []string, stdin io.Reader) error {
changes, err := io.ReadAll(stdin)
require.NoError(t, err)
require.Equal(t, fmt.Sprintf("%s %s refs/heads/main\n", commitID.String(), gittest.DefaultObjectHash.ZeroOID.String()), string(changes))
require.Less(t, referenceTransactionCalls, 2)
if referenceTransactionCalls == 0 {
require.Equal(t, state, hook.ReferenceTransactionPrepared)
} else {
require.Equal(t, state, hook.ReferenceTransactionCommitted)
}
referenceTransactionCalls++
requirePayload(t, env)
return nil
},
expectedRefDeletion: true,
},
{
desc: "prereceive error",
preReceive: func(t *testing.T, ctx context.Context, repo *gitalypb.Repository, pushOptions, env []string, stdin io.Reader, stdout, stderr io.Writer) error {
_, err := io.Copy(stderr, strings.NewReader("prereceive failure"))
require.NoError(t, err)
return errors.New("ignored")
},
expectedErr: "prereceive failure",
},
{
desc: "prereceive error from GitLab API response",
preReceive: func(t *testing.T, ctx context.Context, repo *gitalypb.Repository, pushOptions, env []string, stdin io.Reader, stdout, stderr io.Writer) error {
return hook.NotAllowedError{Message: "GitLab: file is locked"}
},
expectedErr: "GitLab: file is locked",
},
{
desc: "update error",
preReceive: func(t *testing.T, ctx context.Context, repo *gitalypb.Repository, pushOptions, env []string, stdin io.Reader, stdout, stderr io.Writer) error {
return nil
},
update: func(t *testing.T, ctx context.Context, repo *gitalypb.Repository, ref, oldValue, newValue string, env []string, stdout, stderr io.Writer) error {
_, err := io.Copy(stderr, strings.NewReader("update failure"))
require.NoError(t, err)
return errors.New("ignored")
},
expectedErr: "update failure",
},
{
desc: "reference-transaction error",
preReceive: func(t *testing.T, ctx context.Context, repo *gitalypb.Repository, pushOptions, env []string, stdin io.Reader, stdout, stderr io.Writer) error {
return nil
},
update: func(t *testing.T, ctx context.Context, repo *gitalypb.Repository, ref, oldValue, newValue string, env []string, stdout, stderr io.Writer) error {
return nil
},
referenceTransaction: func(t *testing.T, ctx context.Context, state hook.ReferenceTransactionState, env []string, stdin io.Reader) error {
// The reference-transaction hook doesn't execute any custom hooks,
// which is why it currently doesn't have any stdout/stderr.
// Instead, errors are directly returned.
return errors.New("reference-transaction failure")
},
expectedErr: "reference-transaction failure",
},
{
desc: "post-receive custom hooks error is ignored",
preReceive: func(t *testing.T, ctx context.Context, repo *gitalypb.Repository, pushOptions, env []string, stdin io.Reader, stdout, stderr io.Writer) error {
return nil
},
update: func(t *testing.T, ctx context.Context, repo *gitalypb.Repository, ref, oldValue, newValue string, env []string, stdout, stderr io.Writer) error {
return nil
},
referenceTransaction: func(t *testing.T, ctx context.Context, state hook.ReferenceTransactionState, env []string, stdin io.Reader) error {
return nil
},
postReceive: func(t *testing.T, ctx context.Context, repo *gitalypb.Repository, pushOptions, env []string, stdin io.Reader, stdout, stderr io.Writer) error {
_, err := io.Copy(stderr, strings.NewReader("post-receive failure"))
require.NoError(t, err)
return hook.NewCustomHookError(errors.New("ignored"))
},
expectedRefDeletion: true,
},
{
desc: "post-receive non-custom hooks error returned",
preReceive: func(t *testing.T, ctx context.Context, repo *gitalypb.Repository, pushOptions, env []string, stdin io.Reader, stdout, stderr io.Writer) error {
return nil
},
update: func(t *testing.T, ctx context.Context, repo *gitalypb.Repository, ref, oldValue, newValue string, env []string, stdout, stderr io.Writer) error {
return nil
},
referenceTransaction: func(t *testing.T, ctx context.Context, state hook.ReferenceTransactionState, env []string, stdin io.Reader) error {
return nil
},
postReceive: func(t *testing.T, ctx context.Context, repo *gitalypb.Repository, pushOptions, env []string, stdin io.Reader, stdout, stderr io.Writer) error {
_, err := io.Copy(stderr, strings.NewReader("post-receive failure"))
require.NoError(t, err)
return errors.New("uh oh")
},
expectedRefDeletion: true,
expectedErr: "running post-receive hooks: uh oh",
},
}
for _, tc := range testCases {
referenceTransactionCalls = 0
t.Run(tc.desc, func(t *testing.T) {
hookManager := hook.NewMockManager(t, tc.preReceive, tc.postReceive, tc.update, tc.referenceTransaction)
gitCmdFactory := gittest.NewCommandFactory(t, cfg)
updater := updateref.NewUpdaterWithHooks(cfg, config.NewLocator(cfg), hookManager, gitCmdFactory, nil)
err := updater.UpdateReference(ctx, repo, gittest.TestUser, nil, git.ReferenceName("refs/heads/main"), gittest.DefaultObjectHash.ZeroOID, commitID)
if tc.expectedErr == "" {
require.NoError(t, err)
} else {
require.Contains(t, err.Error(), tc.expectedErr)
}
if tc.expectedRefDeletion {
contained, err := localrepo.NewTestRepo(t, cfg, repo).HasRevision(ctx, git.Revision("refs/heads/main"))
require.NoError(t, err)
require.False(t, contained, "branch should have been deleted")
gittest.Exec(t, cfg, "-C", repoPath, "branch", "main", commitID.String())
} else {
ref, err := localrepo.NewTestRepo(t, cfg, repo).GetReference(ctx, "refs/heads/main")
require.NoError(t, err)
require.Equal(t, ref.Target, commitID.String())
}
})
}
}
func TestUpdaterWithHooks_quarantine(t *testing.T) {
t.Parallel()
ctx := testhelper.Context(t)
cfg := testcfg.Build(t)
gitCmdFactory := gittest.NewCommandFactory(t, cfg)
locator := config.NewLocator(cfg)
repoProto, repoPath := gittest.CreateRepository(t, ctx, cfg, gittest.CreateRepositoryConfig{
SkipCreationViaService: true,
})
commitID := gittest.WriteCommit(t, cfg, repoPath, gittest.WithBranch("main"))
unquarantinedRepo := localrepo.NewTestRepo(t, cfg, repoProto)
quarantine, err := quarantine.New(ctx, repoProto, locator)
require.NoError(t, err)
quarantinedRepo := localrepo.NewTestRepo(t, cfg, quarantine.QuarantinedRepo())
blobID, err := quarantinedRepo.WriteBlob(ctx, "", strings.NewReader("1834298812398123"))
require.NoError(t, err)
expectQuarantined := func(t *testing.T, env []string, quarantined bool) {
t.Helper()
if env != nil {
payload, err := git.HooksPayloadFromEnv(env)
require.NoError(t, err)
if quarantined {
testhelper.ProtoEqual(t, quarantine.QuarantinedRepo(), payload.Repo)
} else {
testhelper.ProtoEqual(t, repoProto, payload.Repo)
}
}
exists, err := quarantinedRepo.HasRevision(ctx, blobID.Revision()+"^{blob}")
require.NoError(t, err)
require.Equal(t, quarantined, exists)
exists, err = unquarantinedRepo.HasRevision(ctx, blobID.Revision()+"^{blob}")
require.NoError(t, err)
require.Equal(t, !quarantined, exists)
}
hookExecutions := make(map[string]int)
hookManager := hook.NewMockManager(t,
// The pre-receive hook is not expected to have the object in the normal repo.
func(t *testing.T, ctx context.Context, repo *gitalypb.Repository, pushOptions, env []string, stdin io.Reader, stdout, stderr io.Writer) error {
expectQuarantined(t, env, true)
testhelper.ProtoEqual(t, quarantine.QuarantinedRepo(), repo)
hookExecutions["prereceive"]++
return nil
},
// But the post-receive hook shall get the unquarantined repository as input, with
// objects already having been migrated into the target repo.
func(t *testing.T, ctx context.Context, repo *gitalypb.Repository, pushOptions, env []string, stdin io.Reader, stdout, stderr io.Writer) error {
expectQuarantined(t, env, false)
testhelper.ProtoEqual(t, repoProto, repo)
hookExecutions["postreceive"]++
return nil
},
// The update hook gets executed after the pre-receive hook and will be executed for
// each reference that we're updating. As it is called immediately before the ref
// gets queued for update, objects must have already been migrated or otherwise
// updating the refs will fail due to missing objects.
func(t *testing.T, ctx context.Context, repo *gitalypb.Repository, ref, oldValue, newValue string, env []string, stdout, stderr io.Writer) error {
expectQuarantined(t, env, false)
testhelper.ProtoEqual(t, quarantine.QuarantinedRepo(), repo)
hookExecutions["update"]++
return nil
},
// The reference-transaction hook is called as we're queueing refs for update, so
// the objects must be part of the main object database or otherwise the update will
// fail due to missing objects.
func(t *testing.T, ctx context.Context, state hook.ReferenceTransactionState, env []string, stdin io.Reader) error {
expectQuarantined(t, env, false)
switch state {
case hook.ReferenceTransactionPrepared:
hookExecutions["prepare"]++
case hook.ReferenceTransactionCommitted:
hookExecutions["commit"]++
}
return nil
},
)
require.NoError(t, updateref.NewUpdaterWithHooks(cfg, locator, hookManager, gitCmdFactory, nil).UpdateReference(
ctx,
repoProto,
&gitalypb.User{
GlId: "1234",
GlUsername: "Username",
Name: []byte("Name"),
Email: []byte("mail@example.com"),
},
quarantine,
git.ReferenceName("refs/heads/main"),
gittest.DefaultObjectHash.ZeroOID,
commitID,
))
require.Equal(t, map[string]int{
"prereceive": 1,
"postreceive": 1,
"update": 1,
"prepare": 1,
"commit": 1,
}, hookExecutions)
contained, err := unquarantinedRepo.HasRevision(ctx, git.Revision("refs/heads/main"))
require.NoError(t, err)
require.False(t, contained, "branch should have been deleted")
}
|