Debian Codegraph @

api/krusty/remoteloader_test.go

raw
1 // Copyright 2022 The Kubernetes Authors.
2 // SPDX-License-Identifier: Apache-2.0
3
4 package krusty_test
5
6 import (
7 "bytes"
8 "encoding/base64"
9 "fmt"
10 "io"
11 "os"
12 "os/exec"
13 "path/filepath"
14 "strings"
15 "testing"
16
17 "github.com/stretchr/testify/assert"
18 "github.com/stretchr/testify/require"
19 "sigs.k8s.io/kustomize/api/internal/loader"
20 "sigs.k8s.io/kustomize/api/krusty"
21 "sigs.k8s.io/kustomize/api/resmap"
22 kusttest_test "sigs.k8s.io/kustomize/api/testutils/kusttest"
23 "sigs.k8s.io/kustomize/kyaml/yaml"
24 )
25
26 func TestRemoteLoad_LocalProtocol(t *testing.T) {
27 type testRepos struct {
28 root string
29 simple string
30 noSuffix string
31 hash string
32 multiBaseDev string
33 withSubmodule string
34 }
35
36 // creates git repos under a root temporary directory with the following structure
37 // root/
38 // simple.git/ - base with just a pod
39 // nosuffix/ - same as simple.git/ without the .git suffix
40 // hash-xx/ - same as simple.git/ with random hash at xx
41 // multibase.git/ - base with a dev overlay
42 // with-submodule.git/ - includes `simple` as a submodule
43 // submodule/ - the submodule referencing `simple`
44 createGitRepos := func(t *testing.T) testRepos {
45 t.Helper()
46
47 bash := func(script string) {
48 cmd := exec.Command("sh", "-c", script)
49 o, err := cmd.CombinedOutput()
50 if err != nil {
51 t.Fatalf("error running %v\nerr: %v\n%s", script, err, string(o))
52 }
53 }
54 root := t.TempDir()
55
56 hashPath, err := os.MkdirTemp(root, "hash-")
57 require.NoError(t, err)
58 hashDir := filepath.Base(hashPath)
59
60 bash(fmt.Sprintf(`
61 set -eux
62
63 export ROOT="%s"
64 export HASH_DIR="%s"
65 export [email protected]
66 export GIT_AUTHOR_NAME=Nobody
67 export [email protected]
68 export GIT_COMMITTER_NAME=Nobody
69
70 cp -r testdata/remoteload/simple $ROOT/simple.git
71 (
72 cd $ROOT/simple.git
73 git config --global protocol.file.allow always
74 git init --initial-branch=main
75 git add .
76 git commit -m "import"
77 git checkout -b change-image
78 cat >>kustomization.yaml <<EOF
79
80 images:
81 - name: nginx
82 newName: nginx
83 newTag: "2"
84 EOF
85 git commit -am "image change"
86 git checkout main
87 )
88 cp -r $ROOT/simple.git $ROOT/nosuffix
89 cp -r testdata/remoteload/multibase $ROOT/multibase.git
90 (
91 cd $ROOT/multibase.git
92 git init --initial-branch=main
93 git add .
94 git commit -m "import"
95 )
96 cp -r testdata/remoteload/with-submodule $ROOT/with-submodule.git # see README
97 cp -r $ROOT/simple.git/. $ROOT/$HASH_DIR
98 (
99 cd $ROOT/with-submodule.git
100 git init --initial-branch=main
101 git add .
102 git commit -m "import"
103 git checkout -b relative-submodule
104 git submodule add ../$HASH_DIR submodule
105 git commit -m "relative submodule"
106 git checkout main
107 git submodule add $ROOT/simple.git submodule
108 git commit -m "submodule"
109 )
110 `, root, hashDir))
111 return testRepos{
112 root: root,
113 // The strings below aren't currently used, and more serve as documentation.
114 simple: "simple.git",
115 noSuffix: "nosuffix",
116 hash: hashDir,
117 multiBaseDev: "multibase.git",
118 withSubmodule: "with-submodule.git",
119 }
120 }
121
122 const simpleBuild = `apiVersion: v1
123 kind: Pod
124 metadata:
125 labels:
126 app: myapp
127 name: myapp-pod
128 spec:
129 containers:
130 - image: nginx:1.7.9
131 name: nginx
132 `
133 var simpleBuildWithNginx2 = strings.ReplaceAll(simpleBuild, "nginx:1.7.9", "nginx:2")
134 var multibaseDevExampleBuild = strings.ReplaceAll(simpleBuild, "myapp-pod", "dev-myapp-pod")
135
136 repos := createGitRepos(t)
137 tests := []struct {
138 name string
139 kustomization string
140 expected string
141 err string
142 skip bool
143 }{
144 {
145 name: "simple",
146 kustomization: `
147 resources:
148 - file://$ROOT/simple.git
149 `,
150 expected: simpleBuild,
151 },
152 {
153 name: "without git suffix",
154 kustomization: `
155 resources:
156 - file://$ROOT/nosuffix
157 `,
158 expected: simpleBuild,
159 },
160 {
161 name: "has path",
162 kustomization: `
163 resources:
164 - file://$ROOT/multibase.git/dev
165 `,
166 expected: multibaseDevExampleBuild,
167 },
168 {
169 name: "has path without git suffix",
170 kustomization: `
171 resources:
172 - file://$ROOT/multibase//dev
173 `,
174 expected: multibaseDevExampleBuild,
175 },
176 {
177 name: "has ref",
178 kustomization: `
179 resources:
180 - "file://$ROOT/simple.git?ref=change-image"
181 `,
182
183 expected: simpleBuildWithNginx2,
184 },
185 {
186 // Version is the same as ref
187 name: "has version",
188 kustomization: `
189 resources:
190 - file://$ROOT/simple.git?version=change-image
191 `,
192 expected: simpleBuildWithNginx2,
193 },
194 {
195 name: "has submodule",
196 kustomization: `
197 resources:
198 - file://$ROOT/with-submodule.git/submodule
199 `,
200 expected: simpleBuild,
201 },
202 {
203 name: "has relative submodule",
204 kustomization: `
205 resources:
206 - file://$ROOT/with-submodule.git/submodule?ref=relative-submodule
207 `,
208
209 expected: simpleBuild,
210 },
211 {
212 name: "has timeout",
213 kustomization: `
214 resources:
215 - file://$ROOT/simple.git?timeout=500
216 `,
217 expected: simpleBuild,
218 },
219 {
220 name: "has submodule but not initialized",
221 kustomization: `
222 resources:
223 - file://$ROOT/with-submodule.git/submodule?submodules=0
224 `,
225 err: "unable to find one of 'kustomization.yaml', 'kustomization.yml' or 'Kustomization' in directory",
226 },
227 {
228 name: "has origin annotation",
229 skip: true, // The annotated path should be "pod.yaml" but is "notCloned/pod.yaml"
230 kustomization: `
231 resources:
232 - file://$ROOT/simple.git
233 buildMetadata: [originAnnotations]
234 `,
235 expected: `apiVersion: v1
236 kind: Pod
237 metadata:
238 annotations:
239 config.kubernetes.io/origin: |
240 path: pod.yaml
241 repo: file://$ROOT/simple.git
242 labels:
243 app: myapp
244 name: myapp-pod
245 spec:
246 containers:
247 - image: nginx:1.7.9
248 name: nginx
249 `,
250 },
251 {
252 name: "has ref path timeout and origin annotation",
253 kustomization: `
254 resources:
255 - file://$ROOT/multibase.git/dev?version=main&timeout=500
256 buildMetadata: [originAnnotations]
257 `,
258 expected: `apiVersion: v1
259 kind: Pod
260 metadata:
261 annotations:
262 config.kubernetes.io/origin: |
263 path: base/pod.yaml
264 repo: file://$ROOT/multibase.git
265 ref: main
266 labels:
267 app: myapp
268 name: dev-myapp-pod
269 spec:
270 containers:
271 - image: nginx:1.7.9
272 name: nginx
273 `,
274 },
275 {
276 name: "repo does not exist ",
277 kustomization: `
278 resources:
279 - file:///not/a/real/repo
280 `,
281 err: "fatal: '/not/a/real/repo' does not appear to be a git repository",
282 },
283 }
284
285 t.Setenv("LC_ALL", "C")
286
287 for _, test := range tests {
288 t.Run(test.name, func(t *testing.T) {
289 if test.skip {
290 t.SkipNow()
291 }
292
293 kust := strings.ReplaceAll(test.kustomization, "$ROOT", repos.root)
294 fSys, tmpDir := kusttest_test.CreateKustDir(t, kust)
295
296 b := krusty.MakeKustomizer(krusty.MakeDefaultOptions())
297 m, err := b.Run(
298 fSys,
299 tmpDir.String())
300
301 if test.err != "" {
302 require.Error(t, err)
303 require.Regexp(t, test.err, err.Error())
304 } else {
305 require.NoError(t, err)
306 checkYaml(t, m, strings.ReplaceAll(test.expected, "$ROOT", repos.root))
307 }
308 })
309 }
310 }
311
312 func TestRemoteLoad_RemoteProtocols(t *testing.T) {
313 // Slow remote tests with long timeouts.
314 // TODO: If these end up flaking, they should retry. If not, remove this TODO.
315 tests := []struct {
316 name string
317 kustomization string
318 err string
319 errT error
320 beforeTest func(t *testing.T)
321 }{
322 {
323 name: "https",
324 kustomization: `
325 resources:
326 - https://github.com/kubernetes-sigs/kustomize//examples/multibases/dev/?submodules=0&ref=kustomize%2Fv4.5.7&timeout=300
327 `,
328 },
329 {
330 name: "https with explicit .git suffix",
331 kustomization: `
332 resources:
333 - https://github.com/kubernetes-sigs/kustomize.git//examples/multibases/dev/?submodules=0&ref=kustomize%2Fv4.5.7&timeout=300
334 `,
335 },
336 {
337 name: "git double-colon https",
338 kustomization: `
339 resources:
340 - git::https://github.com/kubernetes-sigs/kustomize//examples/multibases/dev/?submodules=0&ref=kustomize%2Fv4.5.7&timeout=300
341 `,
342 },
343 {
344 name: "https raw remote file",
345 kustomization: `
346 resources:
347 - https://raw.githubusercontent.com/kubernetes-sigs/kustomize/v3.1.0/examples/multibases/base/pod.yaml?timeout=300
348 namePrefix: dev-
349 `,
350 },
351 {
352 name: "https without scheme",
353 kustomization: `
354 resources:
355 - github.com/kubernetes-sigs/kustomize/examples/multibases/dev?submodules=0&ref=kustomize%2Fv4.5.7&timeout=300
356 `,
357 },
358 {
359 name: "ssh",
360 beforeTest: configureGitSSHCommand,
361 kustomization: `
362 resources:
363 - [email protected]/kubernetes-sigs/kustomize/examples/multibases/dev?submodules=0&ref=kustomize%2Fv4.5.7&timeout=300
364 `,
365 },
366 {
367 name: "ssh with colon",
368 beforeTest: configureGitSSHCommand,
369 kustomization: `
370 resources:
371 - [email protected]:kubernetes-sigs/kustomize/examples/multibases/dev?submodules=0&ref=kustomize%2Fv4.5.7&timeout=300
372 `,
373 },
374 {
375 name: "ssh scheme",
376 beforeTest: configureGitSSHCommand,
377 kustomization: `
378 resources:
379 - ssh://[email protected]/kubernetes-sigs/kustomize/examples/multibases/dev?submodules=0&ref=kustomize%2Fv4.5.7&timeout=300
380 `,
381 },
382 {
383 name: "http error",
384 kustomization: `
385 resources:
386 - https://github.com/thisisa404.yaml
387 `,
388 err: "accumulating resources: accumulating resources from 'https://github.com/thisisa404.yaml': HTTP Error: status code 404 (Not Found)",
389 errT: loader.ErrHTTP,
390 },
391 }
392
393 for _, test := range tests {
394 t.Run(test.name, func(t *testing.T) {
395 if test.beforeTest != nil {
396 test.beforeTest(t)
397 }
398 fSys, tmpDir := kusttest_test.CreateKustDir(t, test.kustomization)
399
400 b := krusty.MakeKustomizer(krusty.MakeDefaultOptions())
401 m, err := b.Run(
402 fSys,
403 tmpDir.String())
404
405 if test.err != "" {
406 require.Error(t, err)
407 assert.Contains(t, err.Error(), test.err)
408 if test.errT != nil {
409 require.ErrorIs(t, err, test.errT)
410 }
411 } else {
412 require.NoError(t, err)
413 const multibaseDevExampleBuild = `apiVersion: v1
414 kind: Pod
415 metadata:
416 labels:
417 app: myapp
418 name: dev-myapp-pod
419 spec:
420 containers:
421 - image: nginx:1.7.9
422 name: nginx
423 `
424 checkYaml(t, m, multibaseDevExampleBuild)
425 }
426 })
427 }
428 }
429
430 func configureGitSSHCommand(t *testing.T) {
431 t.Helper()
432
433 // This contains a read-only Deploy Key for the kustomize repo.
434 node, err := yaml.ReadFile("testdata/repo_read_only_ssh_key.yaml")
435 require.NoError(t, err)
436 keyB64, err := node.GetString("key")
437 require.NoError(t, err)
438 key, err := base64.StdEncoding.DecodeString(keyB64)
439 require.NoError(t, err)
440
441 // Write the key to a temp file and use it in SSH
442 f, err := os.CreateTemp("", "kustomize_ssh")
443 require.NoError(t, err)
444 _, err = io.Copy(f, bytes.NewReader(key))
445 require.NoError(t, err)
446 cmd := fmt.Sprintf("ssh -i %s -o IdentitiesOnly=yes", f.Name())
447 const SSHCommandKey = "GIT_SSH_COMMAND"
448 t.Setenv(SSHCommandKey, cmd)
449 t.Cleanup(func() {
450 _ = os.Remove(f.Name())
451 })
452 }
453
454 func checkYaml(t *testing.T, actual resmap.ResMap, expected string) {
455 t.Helper()
456
457 yml, err := actual.AsYaml()
458 require.NoError(t, err)
459 assert.Equal(t, expected, string(yml))
460 }