-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathclient_test.go
More file actions
404 lines (361 loc) · 13.1 KB
/
Copy pathclient_test.go
File metadata and controls
404 lines (361 loc) · 13.1 KB
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
package gitsync
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"testing"
git "github.com/go-git/go-git/v6"
"github.com/go-git/go-git/v6/plumbing"
"github.com/go-git/go-git/v6/plumbing/protocol"
"github.com/go-git/go-git/v6/plumbing/protocol/packp"
"github.com/go-git/go-git/v6/plumbing/transport"
"entire.io/entire/git-sync/internal/syncertest"
)
func TestMain(m *testing.M) {
syncertest.IsolateGitConfig()
os.Exit(m.Run())
}
type errAuthProvider struct{}
func (errAuthProvider) AuthFor(_ context.Context, _ Endpoint, _ EndpointRole) (EndpointAuth, error) {
return EndpointAuth{}, errors.New("boom")
}
func TestValidateRequests(t *testing.T) {
if err := (ProbeRequest{}).Validate(); err == nil {
t.Fatalf("expected probe validation error")
}
if err := (PlanRequest{}).Validate(); err == nil {
t.Fatalf("expected plan validation error")
}
if err := (SyncRequest{}).Validate(); err == nil {
t.Fatalf("expected sync validation error")
}
if err := (ProbeRequest{
Source: Endpoint{URL: "https://source.example/repo.git"},
Protocol: "bogus",
}).Validate(); err == nil {
t.Fatalf("expected invalid probe protocol validation error")
}
if err := (SyncRequest{
Source: Endpoint{URL: "https://source.example/repo.git"},
Target: Endpoint{URL: "https://target.example/repo.git"},
Policy: SyncPolicy{Protocol: "bogus"},
}).Validate(); err == nil {
t.Fatalf("expected invalid sync protocol validation error")
}
if err := (PlanRequest{
Source: Endpoint{URL: "https://source.example/repo.git"},
Target: Endpoint{URL: "https://target.example/repo.git"},
Scope: RefScope{
Mappings: []RefMapping{
{Source: "main", Target: "stable"},
{Source: "release", Target: "stable"},
},
},
}).Validate(); err == nil {
t.Fatalf("expected duplicate mapping validation error")
}
if err := (SyncRequest{
Source: Endpoint{URL: "https://source.example/repo.git"},
Target: Endpoint{URL: "https://target.example/repo.git"},
Policy: SyncPolicy{ForceWithLease: true, ForceBlind: true},
}).Validate(); err == nil {
t.Fatalf("expected force-with-lease + force-blind to be rejected at the request edge")
}
if err := (SyncRequest{
Source: Endpoint{URL: "https://source.example/repo.git"},
Target: Endpoint{URL: "https://target.example/repo.git"},
Policy: SyncPolicy{Mode: ModeReplicate, ForceWithLease: true},
}).Validate(); err == nil {
t.Fatalf("expected replicate + force to be rejected at the request edge")
}
}
func TestClientReturnsAuthProviderErrors(t *testing.T) {
_, err := New(Options{Auth: errAuthProvider{}}).buildProbeConfig(context.Background(), ProbeRequest{
Source: Endpoint{URL: "https://source.example/repo.git"},
})
if err == nil {
t.Fatalf("expected auth provider error")
}
}
func TestClientSyncEndToEndWithLocalRepos(t *testing.T) {
sourceRepo, sourceFS := syncertest.NewMemoryRepo(t)
syncertest.MakeCommits(t, sourceRepo, sourceFS, 1)
targetRepo, _ := syncertest.NewMemoryRepo(t)
sourceServer := newSmartHTTPRepoServer(t, sourceRepo)
targetServer := newSmartHTTPRepoServer(t, targetRepo)
defer sourceServer.Close()
defer targetServer.Close()
client := New(Options{})
result, err := client.Sync(context.Background(), SyncRequest{
Source: Endpoint{URL: sourceServer.RepoURL()},
Target: Endpoint{URL: targetServer.RepoURL()},
Scope: RefScope{Branches: []string{"master"}},
Policy: SyncPolicy{Protocol: ProtocolV1},
})
if err != nil {
t.Fatalf("client sync: %v", err)
}
if len(result.Refs) != 1 || result.Refs[0].Action != ActionCreate {
t.Fatalf("unexpected ref results: %+v", result.Refs)
}
if result.Counts.Applied != 1 {
t.Fatalf("applied = %d, want 1", result.Counts.Applied)
}
targetRef, err := targetRepo.Reference(plumbing.NewBranchReferenceName("master"), true)
if err != nil {
t.Fatalf("resolve target ref: %v", err)
}
sourceRef, err := sourceRepo.Reference(plumbing.NewBranchReferenceName("master"), true)
if err != nil {
t.Fatalf("resolve source ref: %v", err)
}
if targetRef.Hash() != sourceRef.Hash() {
t.Fatalf("target hash = %s, want %s", targetRef.Hash(), sourceRef.Hash())
}
}
func TestClientReplicateRejectsUnsupportedMode(t *testing.T) {
err := (SyncRequest{
Source: Endpoint{URL: "https://source.example/repo.git"},
Target: Endpoint{URL: "https://target.example/repo.git"},
Policy: SyncPolicy{Mode: "bogus"},
}).Validate()
if err == nil {
t.Fatalf("expected invalid operation mode validation error")
}
}
type smartHTTPRepoServer struct {
tb testing.TB
repo *git.Repository
repoPath string
server *httptest.Server
}
func newSmartHTTPRepoServer(tb testing.TB, repo *git.Repository) *smartHTTPRepoServer {
tb.Helper()
s := &smartHTTPRepoServer{
tb: tb,
repo: repo,
repoPath: "/repo.git",
}
s.server = httptest.NewServer(http.HandlerFunc(s.handle))
return s
}
func (s *smartHTTPRepoServer) Close() {
s.server.Close()
}
func (s *smartHTTPRepoServer) RepoURL() string {
return s.server.URL + s.repoPath
}
func (s *smartHTTPRepoServer) handle(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == http.MethodGet && r.URL.Path == s.repoPath+"/info/refs":
s.handleInfoRefs(w, r)
case r.Method == http.MethodPost && r.URL.Path == s.repoPath+"/git-upload-pack":
s.handleUploadPack(w, r)
case r.Method == http.MethodPost && r.URL.Path == s.repoPath+"/git-receive-pack":
s.handleReceivePack(w, r)
default:
http.NotFound(w, r)
}
}
func (s *smartHTTPRepoServer) handleInfoRefs(w http.ResponseWriter, r *http.Request) {
service := r.URL.Query().Get("service")
if service != "git-upload-pack" && service != "git-receive-pack" {
http.Error(w, "missing service", http.StatusBadRequest)
return
}
var buf bytes.Buffer
if err := transport.AdvertiseRefs(r.Context(), s.repo.Storer, &buf, service, false, protocol.V0); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", fmt.Sprintf("application/x-%s-advertisement", service))
if _, err := w.Write(buf.Bytes()); err != nil {
s.tb.Errorf("write advertised refs: %v", err)
}
}
func (s *smartHTTPRepoServer) handleUploadPack(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer r.Body.Close()
var buf bytes.Buffer
reader := io.NopCloser(bytes.NewReader(body))
writer := nopWriteCloser{&buf}
if err := transport.UploadPack(r.Context(), s.repo.Storer, reader, writer, &transport.UploadPackRequest{
StatelessRPC: true,
}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/x-git-upload-pack-result")
if _, err := w.Write(buf.Bytes()); err != nil {
s.tb.Errorf("write upload-pack response: %v", err)
}
}
func (s *smartHTTPRepoServer) handleReceivePack(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer r.Body.Close()
if !bytes.Contains(body, []byte("PACK")) {
req := &packp.UpdateRequests{}
if err := req.Decode(bytes.NewReader(body)); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
report := &packp.ReportStatus{}
report.UnpackStatus = "ok"
for _, cmd := range req.Commands {
status := "ok"
if cmd.New.IsZero() {
if err := s.repo.Storer.RemoveReference(cmd.Name); err != nil {
status = err.Error()
}
} else {
if err := s.repo.Storer.SetReference(plumbing.NewHashReference(cmd.Name, cmd.New)); err != nil {
status = err.Error()
}
}
report.CommandStatuses = append(report.CommandStatuses, &packp.CommandStatus{
ReferenceName: cmd.Name,
Status: status,
})
}
s.writeReceivePackReport(w, report)
return
}
var buf bytes.Buffer
reader := io.NopCloser(bytes.NewReader(body))
writer := nopWriteCloser{&buf}
if err := transport.ReceivePack(r.Context(), s.repo.Storer, reader, writer, &transport.ReceivePackRequest{
StatelessRPC: true,
}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/x-git-receive-pack-result")
if _, err := w.Write(buf.Bytes()); err != nil {
s.tb.Errorf("write receive-pack response: %v", err)
}
}
func (s *smartHTTPRepoServer) writeReceivePackReport(w http.ResponseWriter, report *packp.ReportStatus) {
var buf bytes.Buffer
if err := report.Encode(nopWriteCloser{&buf}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/x-git-receive-pack-result")
if _, err := w.Write(buf.Bytes()); err != nil {
s.tb.Errorf("write receive-pack report: %v", err)
}
}
type nopWriteCloser struct{ io.Writer }
func (nopWriteCloser) Close() error { return nil }
// The stable Client's config builder gets the same reflection guard as
// unstable's, for the same reason: an enumerated list of fields only covers
// what someone remembered to add, so a newly declared policy bool can be
// accepted by the API and silently ignored with every test still green. See
// unstable's TestBuildSyncConfigThreadsEveryPolicyBool — that is where this
// class of omission was actually found. Both call one shared implementation so
// the two copies cannot drift.
func TestBuildSyncConfigThreadsEveryPolicyBool(t *testing.T) {
syncertest.AssertFieldsThreaded(t, nil, func(t *testing.T, policy SyncPolicy) any {
cfg, err := New(Options{}).buildSyncConfig(context.Background(), SyncRequest{
Source: Endpoint{URL: "https://source.example/repo.git"},
Target: Endpoint{URL: "https://target.example/repo.git"},
Policy: policy,
}, false)
if err != nil {
t.Fatalf("buildSyncConfig: %v", err)
}
return cfg
})
}
func TestBuildSyncConfigThreadsEveryScopeField(t *testing.T) {
syncertest.AssertFieldsThreaded(t, nil, func(t *testing.T, scope RefScope) any {
cfg, err := New(Options{}).buildSyncConfig(context.Background(), SyncRequest{
Source: Endpoint{URL: "https://source.example/repo.git"},
Target: Endpoint{URL: "https://target.example/repo.git"},
Scope: scope,
}, false)
if err != nil {
t.Fatalf("buildSyncConfig: %v", err)
}
return cfg
})
}
// AllowEmptySource has two requirements that no path would otherwise report:
// the policy is replicate-only, and it needs an unscoped request. Both were
// accepted at the edge, threaded into the syncer, and then discarded — the
// caller got the historical "no source refs matched" with no hint that their
// safety policy had been ignored.
func TestValidateRejectsUnusableAllowEmptySource(t *testing.T) {
base := SyncRequest{
Source: Endpoint{URL: "https://source.example/repo.git"},
Target: Endpoint{URL: "https://target.example/repo.git"},
}
replicateUnscoped := base
replicateUnscoped.Policy = SyncPolicy{Mode: ModeReplicate, AllowEmptySource: true}
if err := replicateUnscoped.Validate(); err == nil {
t.Error("expected a scoped AllowEmptySource replicate to be rejected")
}
syncMode := base
syncMode.Scope = RefScope{AllRefs: true}
syncMode.Policy = SyncPolicy{Mode: ModeSync, AllowEmptySource: true}
if err := syncMode.Validate(); err == nil {
t.Error("expected AllowEmptySource outside replicate to be rejected")
}
// Mode unset defaults to sync, so it must be rejected the same way rather
// than slipping through on the zero value.
modeUnset := base
modeUnset.Scope = RefScope{AllRefs: true}
modeUnset.Policy = SyncPolicy{AllowEmptySource: true}
if err := modeUnset.Validate(); err == nil {
t.Error("expected AllowEmptySource with an unset mode to be rejected")
}
ok := base
ok.Scope = RefScope{AllRefs: true}
ok.Policy = SyncPolicy{Mode: ModeReplicate, AllowEmptySource: true, SourceAssertedEmpty: true, TargetAssertedEmpty: true}
if err := ok.Validate(); err != nil {
t.Errorf("an unscoped replicate with the policy set must validate, got %v", err)
}
}
// buildProbeConfig is the one request-edge builder the guard above does not
// cover, because ProbeRequest carries flat fields rather than a RefScope. It
// drops nothing today — ProbeRequest has no ExcludeRefs — but it is exactly
// where the bug class the guard exists for could recur unseen, so it gets the
// same treatment.
func TestBuildProbeConfigThreadsEveryField(t *testing.T) {
syncertest.AssertFieldsThreaded(t, map[string]string{
"CollectStats": "deliberately renamed: reaches syncer.Config as ShowStats",
}, func(t *testing.T, req ProbeRequest) any {
req.Source = Endpoint{URL: "https://source.example/repo.git"}
cfg, err := New(Options{}).buildProbeConfig(context.Background(), req)
if err != nil {
t.Fatalf("buildProbeConfig: %v", err)
}
return cfg
})
}
// The renamed field still has to arrive, it just cannot be checked by name.
func TestBuildProbeConfigThreadsCollectStats(t *testing.T) {
cfg, err := New(Options{}).buildProbeConfig(context.Background(), ProbeRequest{
Source: Endpoint{URL: "https://source.example/repo.git"},
CollectStats: true,
})
if err != nil {
t.Fatalf("buildProbeConfig: %v", err)
}
if !cfg.ShowStats {
t.Error("ProbeRequest.CollectStats = true was dropped by buildProbeConfig")
}
}