-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathrender_scope_test.go
More file actions
575 lines (512 loc) · 25 KB
/
Copy pathrender_scope_test.go
File metadata and controls
575 lines (512 loc) · 25 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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
// SPDX-License-Identifier: Apache-2.0
package git
import (
"context"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
gogit "github.com/go-git/go-git/v6"
v1alpha3 "github.com/ConfigButler/gitops-reverser/api/v1alpha3"
"github.com/ConfigButler/gitops-reverser/internal/manifestanalyzer"
"github.com/ConfigButler/gitops-reverser/internal/types"
"github.com/ConfigButler/gitops-reverser/internal/typeset"
)
// Render-root scoping (docs/design/support-boundary/render-root-scoping.md §4): a GitTarget
// whose spec.path is a kustomize overlay reads a base OUTSIDE its subtree through `../../base`
// as read-only context, while writes stay inside spec.path. The scan re-roots at the common
// ancestor (renderBase) so the whole store runs in one coordinate system; the write jail
// (writeSubdir) keeps a planned write inside the overlay.
const overlayBaseDeploymentYAML = `apiVersion: apps/v1
kind: Deployment
metadata:
name: web
spec:
selector:
matchLabels:
app: web
template:
metadata:
labels:
app: web
spec:
containers:
- name: podinfo
image: ghcr.io/example/podinfo:6.3.0 # base tag, shadowed by the overlay
`
const overlayBaseServiceYAML = `apiVersion: v1
kind: Service
metadata:
name: web
spec:
selector:
app: web
ports:
- port: 80
`
const overlayBaseKustomizationYAML = `apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- deployment.yaml
- service.yaml
`
const overlayKustomizationYAML = `apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
namespace: production
resources:
- ../../base
images:
- name: ghcr.io/example/podinfo
newTag: "6.4.0"
`
// overlayGitPath is the GitTarget subtree: a pure overlay whose only content is a
// kustomization that reads ../../base. Everything it deploys comes from the base.
const overlayGitPath = "apps/frontend/overlays/production"
// seedOverlayWorktree writes the base/ + overlays/production/ layout and returns the base
// deployment and overlay kustomization absolute paths (deployment first).
func seedOverlayWorktree(t *testing.T, root string) (string, string) {
t.Helper()
write := func(rel, content string) string {
full := filepath.Join(root, filepath.FromSlash(rel))
require.NoError(t, os.MkdirAll(filepath.Dir(full), 0o750))
require.NoError(t, os.WriteFile(full, []byte(content), 0o600))
return full
}
baseDeployPath := write("apps/frontend/base/deployment.yaml", overlayBaseDeploymentYAML)
write("apps/frontend/base/service.yaml", overlayBaseServiceYAML)
write("apps/frontend/base/kustomization.yaml", overlayBaseKustomizationYAML)
overlayKustPath := write(overlayGitPath+"/kustomization.yaml", overlayKustomizationYAML)
return baseDeployPath, overlayKustPath
}
// overlayDeploymentEvent is the rendered Deployment as the cluster runs it: namespace from
// the overlay's transformer, image from the overlay's images: entry.
func overlayDeploymentEvent(image string) Event {
return Event{
Object: &unstructured.Unstructured{Object: map[string]interface{}{
"apiVersion": "apps/v1",
"kind": "Deployment",
"metadata": map[string]interface{}{"name": "web", "namespace": "production"},
"spec": map[string]interface{}{
"selector": map[string]interface{}{"matchLabels": map[string]interface{}{"app": "web"}},
"template": map[string]interface{}{
"metadata": map[string]interface{}{"labels": map[string]interface{}{"app": "web"}},
"spec": map[string]interface{}{
"containers": []interface{}{
map[string]interface{}{"name": "podinfo", "image": image},
},
},
},
},
}},
Identifier: types.ResourceIdentifier{
Group: "apps", Version: "v1", Resource: "deployments", Namespace: "production", Name: "web",
},
Operation: "UPDATE",
}
}
func flushAtBase(
t *testing.T,
writer *contentWriter,
worktree *gogit.Worktree,
mapper typeset.Lookup,
base string,
events ...Event,
) (bool, error) {
t.Helper()
w := &BranchWorker{contentWriter: writer, mapper: mapper}
return w.flushEventsToWorktree(context.Background(), worktree, base, events, nil, v1alpha3.PruneOnEvent)
}
// The read scope of a pure overlay re-roots at the base's parent, keeps every scanned path
// under the common ancestor, and reports the overlay itself as the write jail.
func TestScanRenderScope_ResolvesOverlayBase(t *testing.T) {
worktree := newWorktreeForTest(t)
root := worktree.Filesystem().Root()
seedOverlayWorktree(t, root)
scoped, err := scanRenderScope(root, overlayGitPath)
require.NoError(t, err)
assert.Equal(t, "apps/frontend", scoped.renderBase, "renderBase is the common ancestor of the overlay and its base")
assert.Equal(t, "overlays/production", scoped.writeSubdir, "the overlay is the write jail relative to renderBase")
got := map[string]bool{}
for _, f := range scoped.scan.YAMLFiles {
got[f.Path] = true
}
for _, want := range []string{
"overlays/production/kustomization.yaml",
"base/deployment.yaml",
"base/service.yaml",
"base/kustomization.yaml",
} {
assert.True(t, got[want], "expected %q in the re-rooted scan", want)
}
}
// A self-contained subtree (no out-of-scope base) resolves to the identity: renderBase equals
// spec.path and writeSubdir is empty, so nothing downstream changes.
func TestScanRenderScope_SelfContainedIsIdentity(t *testing.T) {
worktree := newWorktreeForTest(t)
root := worktree.Filesystem().Root()
seedOverridesWorktree(t, root) // kustomization + apps/deployment.yaml, all in-subtree
scoped, err := scanRenderScope(root, "")
require.NoError(t, err)
assert.Empty(t, scoped.renderBase)
assert.Empty(t, scoped.writeSubdir)
}
// The launch capability: an image tag bump on a base object the overlay renders lands on the
// OVERLAY's images: entry — inside spec.path — and the base file, which is read-only context
// outside spec.path, keeps its bytes.
func TestPlanFlush_Overlay_RoutesImageTagToOverlayEntry(t *testing.T) {
writer := newContentWriter(types.SensitiveResourcePolicy{})
worktree := newWorktreeForTest(t)
baseDeployPath, overlayKustPath := seedOverlayWorktree(t, worktree.Filesystem().Root())
changed, err := flushAtBase(t, writer, worktree, deploymentMapper(), overlayGitPath,
overlayDeploymentEvent("ghcr.io/example/podinfo:6.5.0"))
require.NoError(t, err)
require.True(t, changed, "the tag bump must land on the overlay entry")
assertFileBytes(t, baseDeployPath, overlayBaseDeploymentYAML,
"the base is read-only context; its bytes must not change")
kust, err := os.ReadFile(overlayKustPath)
require.NoError(t, err)
assert.Contains(t, string(kust), `newTag: "6.5.0"`, "the overlay entry absorbs the live tag")
assert.NotContains(t, string(kust), `newTag: "6.4.0"`)
}
// Live state equal to the overlay's render is a full no-op across both files.
func TestPlanFlush_Overlay_InSyncIsNoOp(t *testing.T) {
writer := newContentWriter(types.SensitiveResourcePolicy{})
worktree := newWorktreeForTest(t)
baseDeployPath, overlayKustPath := seedOverlayWorktree(t, worktree.Filesystem().Root())
changed, err := flushAtBase(t, writer, worktree, deploymentMapper(), overlayGitPath,
overlayDeploymentEvent("ghcr.io/example/podinfo:6.4.0"))
require.NoError(t, err)
assert.False(t, changed, "live == render must write nothing")
assertFileBytes(t, baseDeployPath, overlayBaseDeploymentYAML, "base untouched")
assertFileBytes(t, overlayKustPath, overlayKustomizationYAML, "overlay untouched")
}
// An edit to a base-owned field the overlay cannot express (here a new pod-template label)
// would have to be written into the base — outside the write jail. The whole flush is refused
// rather than writing through into shared context. This is the deferred patch-authoring case
// surfacing as an honest refusal, not a silent base write.
func TestPlanFlush_Overlay_BaseFieldEditRefused(t *testing.T) {
writer := newContentWriter(types.SensitiveResourcePolicy{})
worktree := newWorktreeForTest(t)
baseDeployPath, overlayKustPath := seedOverlayWorktree(t, worktree.Filesystem().Root())
event := overlayDeploymentEvent("ghcr.io/example/podinfo:6.4.0")
// Add a base-owned field the images/replicas entries do not govern.
spec := event.Object.Object["spec"].(map[string]interface{})
tmpl := spec["template"].(map[string]interface{})
meta := tmpl["metadata"].(map[string]interface{})
meta["labels"].(map[string]interface{})["tier"] = "backend"
_, err := flushAtBase(t, writer, worktree, deploymentMapper(), overlayGitPath, event)
require.Error(t, err, "an edit that would write the read-only base must be refused")
var refused *manifestanalyzer.AcceptanceRefusedError
require.ErrorAs(t, err, &refused)
assertFileBytes(t, baseDeployPath, overlayBaseDeploymentYAML, "the base must be left untouched on refusal")
assertFileBytes(t, overlayKustPath, overlayKustomizationYAML, "nothing is committed on refusal")
}
// A base reference that climbs above the repository root is refused: the operator never reads
// outside the repository it manages.
func TestScanRenderScope_RefusesBaseEscapingRepoRoot(t *testing.T) {
worktree := newWorktreeForTest(t)
root := worktree.Filesystem().Root()
// spec.path is a single-level directory; ../../base climbs to ../base, above the root.
kust := "apiVersion: kustomize.config.k8s.io/v1beta1\nkind: Kustomization\nresources:\n - ../../base\n"
full := filepath.Join(root, "app", "kustomization.yaml")
require.NoError(t, os.MkdirAll(filepath.Dir(full), 0o750))
require.NoError(t, os.WriteFile(full, []byte(kust), 0o600))
_, err := scanRenderScope(root, "app")
require.Error(t, err, "a base escaping the repository root must be refused")
assert.Contains(t, err.Error(), "escapes the repository root")
}
func deploymentAndConfigMapMapper() typeset.Lookup {
return typeset.NewSnapshotRegistry(typeset.Snapshot{
Entries: []typeset.Entry{
{
GVK: schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "Deployment"},
GVR: schema.GroupVersionResource{Group: "apps", Version: "v1", Resource: "deployments"},
Namespaced: true, Allowed: true,
},
{
GVK: schema.GroupVersionKind{Version: "v1", Kind: "ConfigMap"},
GVR: schema.GroupVersionResource{Version: "v1", Resource: "configmaps"},
Namespaced: true, Allowed: true,
},
},
})
}
// A brand-new object in an overlay lands beside the overlay's own kustomization, is added to
// its resources: list, and renders — verified by the oracle. It must NOT be committed to a file
// no kustomization includes (which would never render, with the oracle skipped) — the silent
// divergence P1 flagged.
func TestPlanFlush_Overlay_NewObjectLandsInOverlayAndRenders(t *testing.T) {
writer := newContentWriter(types.SensitiveResourcePolicy{})
worktree := newWorktreeForTest(t)
root := worktree.Filesystem().Root()
_, overlayKustPath := seedOverlayWorktree(t, root)
cm := &unstructured.Unstructured{Object: map[string]interface{}{
"apiVersion": "v1", "kind": "ConfigMap",
"metadata": map[string]interface{}{"name": "features", "namespace": "production"},
"data": map[string]interface{}{"flag": "on"},
}}
event := Event{
Object: cm,
Identifier: types.ResourceIdentifier{
Group: "", Version: "v1", Resource: "configmaps", Namespace: "production", Name: "features",
},
Operation: "UPDATE",
}
changed, err := flushAtBase(t, writer, worktree, deploymentAndConfigMapMapper(), overlayGitPath, event)
require.NoError(t, err, "a new object in an overlay must not be silently dropped")
require.True(t, changed)
written := filepath.Join(root, filepath.FromSlash(overlayGitPath), "features.yaml")
_, statErr := os.Stat(written)
require.NoError(t, statErr, "the new object must be written inside the overlay (the write jail)")
kust, err := os.ReadFile(overlayKustPath)
require.NoError(t, err)
assert.Contains(t, string(kust), "features.yaml",
"the overlay's kustomization must gain a resources: entry so the new object renders")
}
// A base directory holding BOTH kustomization.yaml and kustomization.yml is imported whole, so
// the render reaches kustomize's own "multiple kustomization files" refusal instead of masking
// it by reading only the first.
func TestScanRenderScope_DualKustomizationFilesImportedBoth(t *testing.T) {
worktree := newWorktreeForTest(t)
root := worktree.Filesystem().Root()
write := func(rel, content string) {
full := filepath.Join(root, filepath.FromSlash(rel))
require.NoError(t, os.MkdirAll(filepath.Dir(full), 0o750))
require.NoError(t, os.WriteFile(full, []byte(content), 0o600))
}
write("apps/frontend/overlays/production/kustomization.yaml",
"apiVersion: kustomize.config.k8s.io/v1beta1\nkind: Kustomization\n"+
"namespace: production\nresources:\n - ../../base\n")
k := "apiVersion: kustomize.config.k8s.io/v1beta1\nkind: Kustomization\nresources:\n - deployment.yaml\n"
write("apps/frontend/base/kustomization.yaml", k)
write("apps/frontend/base/kustomization.yml", k)
write("apps/frontend/base/deployment.yaml", overlayBaseDeploymentYAML)
scoped, err := scanRenderScope(root, "apps/frontend/overlays/production")
require.NoError(t, err)
got := map[string]bool{}
for _, f := range scoped.scan.YAMLFiles {
got[f.Path] = true
}
assert.True(t, got["base/kustomization.yaml"] && got["base/kustomization.yml"],
"both kustomization files must be imported so the render refuses the ambiguous base")
}
// External-base discovery never follows a symlinked kustomization file, so the controller does
// not read outside the worktree during scope resolution.
func TestScanRenderScope_DoesNotFollowKustomizationSymlink(t *testing.T) {
worktree := newWorktreeForTest(t)
root := worktree.Filesystem().Root()
write := func(rel, content string) {
full := filepath.Join(root, filepath.FromSlash(rel))
require.NoError(t, os.MkdirAll(filepath.Dir(full), 0o750))
require.NoError(t, os.WriteFile(full, []byte(content), 0o600))
}
// A secret file OUTSIDE the worktree that a symlink would expose.
outside := filepath.Join(t.TempDir(), "outside-kustomization.yaml")
require.NoError(t, os.WriteFile(outside,
[]byte("apiVersion: kustomize.config.k8s.io/v1beta1\nkind: Kustomization\n# SECRET-OUTSIDE-WORKTREE\n"), 0o600))
write("apps/frontend/overlays/production/kustomization.yaml",
"apiVersion: kustomize.config.k8s.io/v1beta1\nkind: Kustomization\n"+
"namespace: production\nresources:\n - ../../base\n")
require.NoError(t, os.MkdirAll(filepath.Join(root, "apps/frontend/base"), 0o750))
require.NoError(t, os.Symlink(outside, filepath.Join(root, "apps/frontend/base/kustomization.yaml")))
scoped, err := scanRenderScope(root, "apps/frontend/overlays/production")
require.NoError(t, err)
for _, f := range scoped.scan.YAMLFiles {
assert.NotContains(t, string(f.Content), "SECRET-OUTSIDE-WORKTREE",
"a symlinked kustomization must never be read from outside the worktree")
assert.NotEqual(t, "base/kustomization.yaml", f.Path,
"the symlinked base kustomization must not be imported")
}
}
// A base that itself reads another out-of-scope base is followed transitively, and renderBase
// climbs to the common ancestor of the overlay and every base in the chain. Foreign content in
// the overlay is carried through re-keyed, and a non-manifest file in a base is skipped (a base
// contributes only its manifests to the render).
func TestScanRenderScope_TransitiveBaseAndForeignRekey(t *testing.T) {
worktree := newWorktreeForTest(t)
root := worktree.Filesystem().Root()
write := func(rel, content string) {
full := filepath.Join(root, filepath.FromSlash(rel))
require.NoError(t, os.MkdirAll(filepath.Dir(full), 0o750))
require.NoError(t, os.WriteFile(full, []byte(content), 0o600))
}
// overlay -> ../../base -> ../shared: two hops, both out of spec.path.
write("apps/frontend/overlays/production/kustomization.yaml",
"apiVersion: kustomize.config.k8s.io/v1beta1\nkind: Kustomization\n"+
"namespace: production\nresources:\n - ../../base\n")
write("apps/frontend/overlays/production/notes.txt", "operator note, not a manifest\n")
// A .yml (not .yaml) base kustomization, so readKustomization's fallback name is exercised.
write("apps/frontend/base/kustomization.yml",
"apiVersion: kustomize.config.k8s.io/v1beta1\nkind: Kustomization\n"+
"resources:\n - deployment.yaml\n - ../shared\n")
write("apps/frontend/base/deployment.yaml", overlayBaseDeploymentYAML)
write("apps/frontend/base/README.txt", "a base may carry non-manifest files; they are skipped\n")
write("apps/frontend/shared/kustomization.yaml",
"apiVersion: kustomize.config.k8s.io/v1beta1\nkind: Kustomization\nresources:\n - configmap.yaml\n")
write("apps/frontend/shared/configmap.yaml",
"apiVersion: v1\nkind: ConfigMap\nmetadata:\n name: shared\ndata:\n k: v\n")
scoped, err := scanRenderScope(root, "apps/frontend/overlays/production")
require.NoError(t, err)
assert.Equal(t, "apps/frontend", scoped.renderBase, "renderBase climbs to the ancestor of both bases")
assert.Equal(t, "overlays/production", scoped.writeSubdir)
got := map[string]bool{}
for _, f := range scoped.scan.YAMLFiles {
got[f.Path] = true
}
for _, want := range []string{
"overlays/production/kustomization.yaml",
"base/kustomization.yml", "base/deployment.yaml",
"shared/kustomization.yaml", "shared/configmap.yaml",
} {
assert.True(t, got[want], "expected %q in the re-rooted scan", want)
}
assert.False(t, got["base/README.txt"], "a base's non-manifest file is not scanned as a manifest")
foreign := map[string]bool{}
for _, fe := range scoped.scan.Foreign {
foreign[fe.Path] = true
}
assert.True(t, foreign["overlays/production/notes.txt"],
"foreign content in the overlay is carried through re-keyed to render coordinates")
}
// An external resource that is a FILE (not a directory base) — resources: [../../shared/x.yaml]
// — is pulled into the render scope. Before, only directory targets were kept, so the build
// could not load the file and the target was refused.
func TestScanRenderScope_ExternalResourceFile(t *testing.T) {
worktree := newWorktreeForTest(t)
root := worktree.Filesystem().Root()
write := func(rel, content string) {
full := filepath.Join(root, filepath.FromSlash(rel))
require.NoError(t, os.MkdirAll(filepath.Dir(full), 0o750))
require.NoError(t, os.WriteFile(full, []byte(content), 0o600))
}
write("apps/frontend/overlays/production/kustomization.yaml",
"apiVersion: kustomize.config.k8s.io/v1beta1\nkind: Kustomization\n"+
"namespace: production\nresources:\n - ../../base\n - ../../shared/extra.yaml\n")
write("apps/frontend/base/kustomization.yaml",
"apiVersion: kustomize.config.k8s.io/v1beta1\nkind: Kustomization\nresources:\n - deployment.yaml\n")
write("apps/frontend/base/deployment.yaml", overlayBaseDeploymentYAML)
write("apps/frontend/shared/extra.yaml",
"apiVersion: v1\nkind: ConfigMap\nmetadata:\n name: extra\ndata:\n k: v\n")
scoped, err := scanRenderScope(root, "apps/frontend/overlays/production")
require.NoError(t, err)
assert.Equal(t, "apps/frontend", scoped.renderBase)
got := map[string]bool{}
for _, f := range scoped.scan.YAMLFiles {
got[f.Path] = true
}
assert.True(t, got["shared/extra.yaml"], "an external resource file must be in the render scope")
assert.True(t, got["base/deployment.yaml"], "the directory base is still followed")
}
// Only the files the resources graph actually references are pulled into the render scope —
// not the whole base directory. An unrelated (even unsupported) sibling the base does not
// reference is left out, so it cannot wrongly refuse the target.
func TestScanRenderScope_UnrelatedBaseContentNotPulled(t *testing.T) {
worktree := newWorktreeForTest(t)
root := worktree.Filesystem().Root()
write := func(rel, content string) {
full := filepath.Join(root, filepath.FromSlash(rel))
require.NoError(t, os.MkdirAll(filepath.Dir(full), 0o750))
require.NoError(t, os.WriteFile(full, []byte(content), 0o600))
}
write("apps/frontend/overlays/production/kustomization.yaml",
"apiVersion: kustomize.config.k8s.io/v1beta1\nkind: Kustomization\n"+
"namespace: production\nresources:\n - ../../base\n")
write("apps/frontend/base/kustomization.yaml",
"apiVersion: kustomize.config.k8s.io/v1beta1\nkind: Kustomization\nresources:\n - deployment.yaml\n")
write("apps/frontend/base/deployment.yaml", overlayBaseDeploymentYAML)
// An unrelated, unsupported kustomization the base does NOT reference. kustomize never loads
// it, so the render scope must not either.
write("apps/frontend/base/experimental/kustomization.yaml",
"apiVersion: kustomize.config.k8s.io/v1beta1\nkind: Kustomization\n"+
"namePrefix: exp-\nresources:\n - cm.yaml\n")
write("apps/frontend/base/experimental/cm.yaml",
"apiVersion: v1\nkind: ConfigMap\nmetadata:\n name: exp\ndata:\n k: v\n")
scoped, err := scanRenderScope(root, "apps/frontend/overlays/production")
require.NoError(t, err)
for _, f := range scoped.scan.YAMLFiles {
assert.NotContains(t, f.Path, "experimental",
"an unreferenced base sibling must not be pulled into the render scope")
}
}
// A remote base is skipped when resolving read scope — it is refused before any build, never a
// directory to scan — while a local base beside it is still followed.
func TestScanRenderScope_SkipsRemoteBase(t *testing.T) {
worktree := newWorktreeForTest(t)
root := worktree.Filesystem().Root()
write := func(rel, content string) {
full := filepath.Join(root, filepath.FromSlash(rel))
require.NoError(t, os.MkdirAll(filepath.Dir(full), 0o750))
require.NoError(t, os.WriteFile(full, []byte(content), 0o600))
}
write("apps/frontend/overlays/production/kustomization.yaml",
"apiVersion: kustomize.config.k8s.io/v1beta1\nkind: Kustomization\n"+
"namespace: production\nresources:\n - ../../base\n"+
" - github.com/example-org/gitops//apps/remote?ref=v1.0.0\n")
write("apps/frontend/base/kustomization.yaml",
"apiVersion: kustomize.config.k8s.io/v1beta1\nkind: Kustomization\nresources:\n - deployment.yaml\n")
write("apps/frontend/base/deployment.yaml", overlayBaseDeploymentYAML)
scoped, err := scanRenderScope(root, "apps/frontend/overlays/production")
require.NoError(t, err, "a remote base is skipped, not an error")
assert.Equal(t, "apps/frontend", scoped.renderBase)
assert.Equal(t, "overlays/production", scoped.writeSubdir)
}
// The path helpers underpinning the re-root: common-ancestor, relative-under, and the
// minimal-directory collapse, at their boundary cases.
func TestRenderScopePathHelpers(t *testing.T) {
ancestor := []struct {
in []string
want string
}{
{[]string{"a/b/c", "a/b/d"}, "a/b"},
{[]string{"a/b/c"}, "a/b/c"},
{[]string{"a/b", "c/d"}, ""}, // no common prefix -> repo root
{[]string{"a/b/c", "a/b"}, "a/b"}, // one contains the other
{[]string{}, ""},
}
for _, c := range ancestor {
assert.Equalf(t, c.want, commonAncestor(c.in), "commonAncestor(%v)", c.in)
}
assert.Equal(t, "overlays/prod", relUnder("apps", "apps/overlays/prod"))
assert.Empty(t, relUnder("apps/x", "apps/x"), "a path relative to itself is empty")
assert.Equal(t, "apps/x", relUnder("", "apps/x"), "an empty ancestor (repo root) returns the child")
assert.ElementsMatch(t, []string{"a/b", "c"}, dirsOf([]string{"a/b/x.yaml", "c/y.yaml"}),
"dirsOf returns each file's containing directory")
}
// The generalised write-fan-in guard: a base reached by more than one render root — with NO
// override entries at stake anywhere — is refused for in-place editing. The former check only
// fired on override ambiguity, so this shared-base field write-through is exactly the hole
// render-root scoping closes. spec.path is the common parent, so the shared base is in scope
// and only ReachedByMultipleRenderRoots (not OverridesAmbiguousAt) can catch it.
func TestFanInPrecondition_RefusesSharedBaseWriteThroughWithoutOverrides(t *testing.T) {
writer := newContentWriter(types.SensitiveResourcePolicy{})
worktree := newWorktreeForTest(t)
root := worktree.Filesystem().Root()
plainOverlay := "apiVersion: kustomize.config.k8s.io/v1beta1\nkind: Kustomization\n" +
"namespace: shared\nresources:\n - ../base\n"
files := map[string]string{
"a/kustomization.yaml": plainOverlay,
"b/kustomization.yaml": plainOverlay,
"base/kustomization.yaml": "resources:\n - deployment.yaml\n",
"base/deployment.yaml": overlayBaseDeploymentYAML,
}
for rel, content := range files {
full := filepath.Join(root, filepath.FromSlash(rel))
require.NoError(t, os.MkdirAll(filepath.Dir(full), 0o750))
require.NoError(t, os.WriteFile(full, []byte(content), 0o600))
}
// A live image change on the shared Deployment has no images: entry to route to, so it
// would fall back to a source-form write into base/deployment.yaml — the file both a and b
// render.
event := overlayDeploymentEvent("ghcr.io/example/podinfo:9.9.9")
event.Identifier.Namespace = "shared"
event.Object.SetNamespace("shared")
_, err := flushAtBase(t, writer, worktree, deploymentMapper(), "", event)
require.Error(t, err)
assert.Contains(t, refusalIssueKinds(t, err), manifestanalyzer.IssueWriteFanIn,
"a write into a base reached by two render roots must be refused even with no overrides")
assertFileBytes(t, filepath.Join(root, "base", "deployment.yaml"), overlayBaseDeploymentYAML,
"the shared base must keep its bytes")
}