-
Notifications
You must be signed in to change notification settings - Fork 0
/
end_to_end_test.go
405 lines (362 loc) · 9.26 KB
/
end_to_end_test.go
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
package vignet_test
import (
"context"
"io"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"time"
"github.com/go-git/go-billy/v5"
"github.com/go-git/go-billy/v5/memfs"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing/cache"
"github.com/go-git/go-git/v5/plumbing/object"
gitHttp "github.com/go-git/go-git/v5/plumbing/transport/http"
"github.com/go-git/go-git/v5/storage/filesystem"
"github.com/stretchr/testify/require"
"github.com/networkteam/vignet"
"github.com/networkteam/vignet/policy"
)
func TestEndToEnd(t *testing.T) {
tt := []struct {
name string
patchPayload string
expectedError string
expectedStatus int
expectedGitContent map[string]fileExpectation
multipartFiles map[string]string
}{
{
name: "valid setField with new key and create",
patchPayload: `
{
"commands": [
{
"path": "my-group/my-project/release.yml",
"setField": {
"field": "spec.values.image.tag",
"value": "1.2.3",
"create": true
}
}
]
}
`,
expectedGitContent: map[string]fileExpectation{
"my-group/my-project/release.yml": content{`foo: bar
spec:
values:
image:
tag: 1.2.3
`},
},
},
{
name: "valid multiple setField with JSONPath",
patchPayload: `
{
"commands": [
{
"path": "my-group/my-project/deployment.yml",
"setField": {
"field": "spec.template.spec.containers[0].image",
"value": "test.example.com:0.2.0"
}
},
{
"path": "my-group/my-project/deployment.yml",
"setField": {
"field": "spec.template.spec.containers[0].env[?(@.name == 'BUILD_ID')].value",
"value": "42"
}
}
]
}
`,
expectedGitContent: map[string]fileExpectation{
"my-group/my-project/deployment.yml": content{`spec:
template:
spec:
containers:
- name: test
image: test.example.com:0.2.0
env:
- name: BUILD_ID
value: '42'
`},
},
},
{
name: "invalid setField with new key and no create",
patchPayload: `
{
"commands": [
{
"path": "my-group/my-project/release.yml",
"setField": {
"field": "spec.values.image.tag",
"value": "1.2.3"
}
}
]
}
`,
expectedStatus: 422,
expectedError: `no nodes matched path`,
},
{
name: "invalid setField with non-existing file",
patchPayload: `
{
"commands": [
{
"path": "my-group/my-project/unknown.yml",
"setField": {
"field": "spec.values.image.tag",
"value": "1.2.3"
}
}
]
}
`,
expectedStatus: 422,
expectedError: `file does not exist`,
},
{
name: "valid create",
patchPayload: `
{
"commands": [
{
"path": "my-group/my-project/new.yml",
"createFile": {
"content": "---\nfoo: bar #Test\n"
}
}
]
}
`,
expectedGitContent: map[string]fileExpectation{
"my-group/my-project/release.yml": content{`foo: bar`},
"my-group/my-project/new.yml": content{"---\nfoo: bar #Test\n"},
},
},
{
name: "invalid create with existing file",
patchPayload: `
{
"commands": [
{
"path": "my-group/my-project/release.yml",
"createFile": {
"content": "---\nfoo: bar #Test\n"
}
}
]
}
`,
expectedStatus: 422,
expectedError: "file already exists",
},
{
name: "valid delete",
patchPayload: `
{
"commands": [
{
"path": "my-group/my-project/release.yml",
"deleteFile": {}
}
]
}
`,
expectedGitContent: map[string]fileExpectation{
"my-group/my-project/release.yml": deleted{},
},
},
{
name: "invalid delete with non-existing file",
patchPayload: `
{
"commands": [
{
"path": "my-group/my-project/unknown.yml",
"deleteFile": {}
}
]
}
`,
expectedStatus: 422,
expectedError: "file does not exist",
},
}
// - Generate JWK key set
ks := generateJwkSet(t)
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
// --- Start mock server for JWKs
// - Start mock server to serve JWKs for authorizer
jwksSrv := httptest.NewServer(jwksHandler(t, ks))
defer jwksSrv.Close()
// --- Start mock Git HTTP server
// - Initialize Git repository with some content
fs := memfs.New()
initGitRepo(t, fs, map[string]string{
"my-group/my-project/release.yml": "foo: bar",
"other/file.yml": "version: 123",
"my-group/my-project/deployment.yml": `spec:
template:
spec:
containers:
- name: test
image: test.example.com:0.1.0
env:
- name: BUILD_ID
value: '1'
`,
})
// - Start mock HTTP Git server with basic auth
gitSrv := httptest.NewServer(newMockHttpGitServer(fs, mockHttpGitServerOpts{basicAuth: &gitHttp.BasicAuth{
Username: "j.doe",
Password: "not-a-secret",
}}))
defer gitSrv.Close()
// --- Setup HTTP handler
// - Initialize GitLab authentication provider using the JWKs server
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
authProvider, err := vignet.NewGitLabAuthenticationProvider(ctx, jwksSrv.URL)
require.NoError(t, err)
// - Initialize authorizer with default policy
defaultBundle, err := policy.LoadDefaultBundle()
require.NoError(t, err)
authorizer, err := vignet.NewRegoAuthorizer(ctx, defaultBundle)
require.NoError(t, err)
// - Create handler
handler := vignet.NewHandler(authProvider, authorizer, vignet.Config{
Repositories: vignet.RepositoriesConfig{
"e2e-test": {
URL: gitSrv.URL,
BasicAuth: &vignet.BasicAuthConfig{
Username: "j.doe",
Password: "not-a-secret",
},
},
},
Commit: vignet.CommitConfig{
DefaultMessage: "Bumped release",
},
})
// --- Build patch request
// - Build a simulated JWT coming from GitLab Job (CI_JOB_JWT)
serializedJWT := buildJWT(t, ks)
req, _ := http.NewRequest("POST", "/patch/e2e-test", strings.NewReader(tc.patchPayload))
req.Header.Set("Authorization", "Bearer "+string(serializedJWT))
// --- Perform request
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
// --- Assert response
if tc.expectedStatus == 0 {
require.Equal(t, http.StatusOK, rec.Code)
} else {
require.Equal(t, tc.expectedStatus, rec.Code)
}
if tc.expectedError != "" {
require.Contains(t, rec.Body.String(), tc.expectedError)
return
}
// --- Assert Git repository contains change
assertGitRepoHeadCommit(t, fs, "Bumped release")
assertGitRepoContains(t, fs, tc.expectedGitContent)
})
}
}
// --- Helper types to have a nicer API to build the test cases
type content struct{ string }
func (c content) content() string { return c.string }
func (content) isDeleted() bool { return false }
type deleted struct{}
func (deleted) content() string { return "" }
func (deleted) isDeleted() bool { return true }
type fileExpectation interface {
content() string
isDeleted() bool
}
func assertGitRepoHeadCommit(t *testing.T, fs billy.Filesystem, expectedMessage string) {
t.Helper()
storer := filesystem.NewStorage(fs, cache.NewObjectLRUDefault())
defer storer.Close()
repo, err := git.Open(storer, nil)
require.NoError(t, err)
head, err := repo.Head()
require.NoError(t, err)
commit, err := repo.CommitObject(head.Hash())
require.NoError(t, err)
require.Equal(t, expectedMessage, commit.Message)
}
func assertGitRepoContains(t *testing.T, fs billy.Filesystem, expectedFiles map[string]fileExpectation) {
t.Helper()
storer := filesystem.NewStorage(fs, cache.NewObjectLRUDefault())
defer storer.Close()
workdirFS := memfs.New()
repo, err := git.Open(storer, workdirFS)
require.NoError(t, err)
w, err := repo.Worktree()
require.NoError(t, err)
// The trick part: reset will apply the Git repo storage to the in-memory workdir filesystem
err = w.Reset(&git.ResetOptions{
Mode: git.HardReset,
})
require.NoError(t, err)
// Check files
for path, expectation := range expectedFiles {
switch v := (expectation).(type) {
case content:
f, err := workdirFS.Open(path)
require.NoError(t, err)
b, _ := io.ReadAll(f)
require.NoError(t, err)
f.Close()
// Assert content
require.Equal(t, v.string, string(b))
case deleted:
_, err := workdirFS.Stat(path)
require.ErrorIs(t, err, os.ErrNotExist)
}
}
}
func initGitRepo(t *testing.T, fs billy.Filesystem, initialFiles map[string]string) {
t.Helper()
storer := filesystem.NewStorage(fs, cache.NewObjectLRUDefault())
defer storer.Close()
workdirFS := memfs.New()
repo, err := git.Init(storer, workdirFS)
require.NoError(t, err)
// Create initial files
for path, content := range initialFiles {
(func() {
f, err := workdirFS.Create(path)
require.NoError(t, err)
defer f.Close()
_, err = f.Write([]byte(content))
require.NoError(t, err)
})()
}
// Add files
w, err := repo.Worktree()
require.NoError(t, err)
for path := range initialFiles {
_, err := w.Add(path)
require.NoError(t, err)
}
_, err = w.Commit("Initial commit", &git.CommitOptions{
Author: &object.Signature{
Name: "vignet",
Email: "test@vignet",
When: time.Now(),
},
})
require.NoError(t, err)
}