Skip to content

Commit 94c79d6

Browse files
committed
fix(imagerepository): validate imports and bound repository sync
1 parent 2e126a3 commit 94c79d6

3 files changed

Lines changed: 330 additions & 38 deletions

File tree

‎internal/controller/imagerepository_controller.go‎

Lines changed: 135 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ package controller
1818

1919
import (
2020
"context"
21+
"errors"
2122
"fmt"
2223
"os"
2324
"path/filepath"
@@ -37,10 +38,13 @@ import (
3738
"k8s.io/apimachinery/pkg/runtime"
3839
"k8s.io/apimachinery/pkg/runtime/schema"
3940
"k8s.io/apimachinery/pkg/types"
41+
"k8s.io/apimachinery/pkg/util/wait"
4042
"k8s.io/client-go/util/retry"
4143
ctrl "sigs.k8s.io/controller-runtime"
4244
"sigs.k8s.io/controller-runtime/pkg/client"
45+
"sigs.k8s.io/controller-runtime/pkg/event"
4346
"sigs.k8s.io/controller-runtime/pkg/log"
47+
"sigs.k8s.io/controller-runtime/pkg/predicate"
4448
"sigs.k8s.io/yaml"
4549

4650
kubeworkspacesiov1alpha1 "github.com/kube-workspaces/controller/api/v1alpha1"
@@ -90,7 +94,7 @@ func (r *ImageRepositoryReconciler) Reconcile(ctx context.Context, req ctrl.Requ
9094
LastTransitionTime: metav1.Now(),
9195
})
9296
_ = r.Status().Update(ctx, &repo)
93-
return ctrl.Result{RequeueAfter: defaultSyncInterval}, nil
97+
return ctrl.Result{}, nil
9498
}
9599

96100
// Manual sync trigger via annotation
@@ -125,7 +129,8 @@ func (r *ImageRepositoryReconciler) Reconcile(ctx context.Context, req ctrl.Requ
125129
})
126130
repo.Status.ObservedGeneration = repo.Generation
127131
_ = r.Status().Update(ctx, &repo)
128-
return ctrl.Result{RequeueAfter: time.Minute}, nil
132+
// Returning the error uses controller-runtime's exponential retry backoff.
133+
return ctrl.Result{}, err
129134
}
130135

131136
// Clear sync annotation if present
@@ -149,18 +154,33 @@ func (r *ImageRepositoryReconciler) Reconcile(ctx context.Context, req ctrl.Requ
149154
Message: fmt.Sprintf("Synced %d image(s)", len(result.imported)),
150155
LastTransitionTime: metav1.Now(),
151156
})
157+
if len(result.invalid) > 0 {
158+
// Keep diagnostics bounded. Raw API errors may contain manifest values.
159+
meta.SetStatusCondition(&repo.Status.Conditions, metav1.Condition{
160+
Type: "Ready", Status: metav1.ConditionFalse, Reason: "InvalidManifests",
161+
Message: fmt.Sprintf("Skipped %d invalid manifest(s); pruning withheld. First invalid file: %.200s", len(result.invalid), result.invalid[0]),
162+
LastTransitionTime: metav1.Now(),
163+
})
164+
}
152165
if err := r.Status().Update(ctx, &repo); err != nil {
153166
return ctrl.Result{}, err
154167
}
155168

156-
return ctrl.Result{RequeueAfter: interval}, nil
169+
return ctrl.Result{RequeueAfter: wait.Jitter(interval, 0.2)}, nil
157170
}
158171

159172
type syncResult struct {
160173
commit string
161174
imported []string
175+
invalid []string
162176
}
163177

178+
// invalidImageManifest distinguishes malformed source files from cluster failures.
179+
type invalidImageManifest struct{ err error }
180+
181+
func (e *invalidImageManifest) Error() string { return e.err.Error() }
182+
func (e *invalidImageManifest) Unwrap() error { return e.err }
183+
164184
func (r *ImageRepositoryReconciler) syncRepo(ctx context.Context, repo *kubeworkspacesiov1alpha1.ImageRepository) (*syncResult, error) {
165185
tmpDir, err := os.MkdirTemp("", "imagerepo-")
166186
if err != nil {
@@ -178,40 +198,23 @@ func (r *ImageRepositoryReconciler) syncRepo(ctx context.Context, repo *kubework
178198
Depth: 1,
179199
}
180200
if repo.Spec.Ref != "" {
181-
cloneOpts.ReferenceName = plumbing.NewBranchReferenceName(repo.Spec.Ref)
182-
if strings.Contains(repo.Spec.Ref, "/") || strings.HasPrefix(repo.Spec.Ref, "refs/") {
183-
cloneOpts.ReferenceName = plumbing.ReferenceName(repo.Spec.Ref)
184-
}
201+
// Fetch history/refs when a branch, tag or commit is explicitly requested.
202+
// Never silently sync the default branch when a requested ref is absent.
203+
cloneOpts.Depth = 0
185204
}
186205

187-
var auth transport.AuthMethod
188-
if repo.Spec.Auth != nil && repo.Spec.Auth.SecretRef != nil {
189-
var secret corev1.Secret
190-
if err := r.Get(ctx, types.NamespacedName{Name: repo.Spec.Auth.SecretRef.Name, Namespace: "kube-workspaces-system"}, &secret); err != nil {
191-
// try default namespace
192-
if err2 := r.Get(ctx, types.NamespacedName{Name: repo.Spec.Auth.SecretRef.Name, Namespace: "default"}, &secret); err2 != nil {
193-
return nil, fmt.Errorf("failed to get auth secret: %w", err)
194-
}
195-
}
196-
username := string(secret.Data["username"])
197-
password := string(secret.Data["password"])
198-
if password == "" {
199-
password = string(secret.Data["token"])
200-
}
201-
if username == "" {
202-
username = "git"
203-
}
204-
auth = &http.BasicAuth{Username: username, Password: password}
205-
cloneOpts.Auth = auth
206+
cloneOpts.Auth, err = r.imageRepositoryAuth(ctx, repo)
207+
if err != nil {
208+
return nil, err
206209
}
207210

208211
repoClone, err := git.PlainCloneContext(ctx, tmpDir, false, cloneOpts)
209212
if err != nil {
210-
// try without branch ref
211-
cloneOpts.ReferenceName = ""
212-
cloneOpts.Depth = 1
213-
repoClone, err = git.PlainCloneContext(ctx, tmpDir, false, cloneOpts)
214-
if err != nil {
213+
// Git transport errors can include credentials from the remote URL.
214+
return nil, fmt.Errorf("failed to clone repository; check URL and credentials")
215+
}
216+
if repo.Spec.Ref != "" {
217+
if err := checkoutImageRepositoryRef(repoClone, repo.Spec.Ref); err != nil {
215218
return nil, err
216219
}
217220
}
@@ -232,11 +235,17 @@ func (r *ImageRepositoryReconciler) syncRepo(ctx context.Context, repo *kubework
232235
}
233236

234237
var imported []string
238+
var invalid []string
235239
desired := map[string]struct{}{}
236240

237241
for _, p := range files {
238242
name, err := r.syncImageFile(ctx, repo, commit, tmpDir, p)
239243
if err != nil {
244+
var manifestErr *invalidImageManifest
245+
if errors.As(err, &manifestErr) || apierrors.IsInvalid(err) || apierrors.IsBadRequest(err) {
246+
invalid = append(invalid, strings.TrimPrefix(p, tmpDir+"/"))
247+
continue
248+
}
240249
return nil, fmt.Errorf("sync %s: %w", strings.TrimPrefix(p, tmpDir+"/"), err)
241250
}
242251
if name != "" {
@@ -253,6 +262,9 @@ func (r *ImageRepositoryReconciler) syncRepo(ctx context.Context, repo *kubework
253262
return nil, fmt.Errorf("list images for pruning: %w", err)
254263
}
255264
for i := range list.Items {
265+
if len(invalid) > 0 {
266+
break // An incomplete inventory must never remove existing images.
267+
}
256268
image := &list.Items[i]
257269
if _, ok := desired[image.GetName()]; !ok {
258270
// A concurrent adoption/update must not be deleted using a stale list.
@@ -273,7 +285,54 @@ func (r *ImageRepositoryReconciler) syncRepo(ctx context.Context, repo *kubework
273285
}
274286
}
275287

276-
return &syncResult{commit: commit, imported: uniq}, nil
288+
return &syncResult{commit: commit, imported: uniq, invalid: invalid}, nil
289+
}
290+
291+
func (r *ImageRepositoryReconciler) imageRepositoryAuth(ctx context.Context, repo *kubeworkspacesiov1alpha1.ImageRepository) (transport.AuthMethod, error) {
292+
if repo.Spec.Auth == nil {
293+
return nil, nil
294+
}
295+
if authType := repo.Spec.Auth.Type; authType != "" && authType != "basic" && authType != "https-basic" {
296+
return nil, fmt.Errorf("unsupported authentication type; use HTTPS basic authentication")
297+
}
298+
if repo.Spec.Auth.SecretRef == nil {
299+
return nil, nil
300+
}
301+
var secret corev1.Secret
302+
if err := r.Get(ctx, types.NamespacedName{Name: repo.Spec.Auth.SecretRef.Name, Namespace: "kube-workspaces-system"}, &secret); err != nil {
303+
// Preserve the historical default-namespace fallback.
304+
if err2 := r.Get(ctx, types.NamespacedName{Name: repo.Spec.Auth.SecretRef.Name, Namespace: "default"}, &secret); err2 != nil {
305+
return nil, fmt.Errorf("failed to get auth secret: %w", err)
306+
}
307+
}
308+
username := string(secret.Data["username"])
309+
password := string(secret.Data["password"])
310+
if password == "" {
311+
password = string(secret.Data["token"])
312+
}
313+
if username == "" {
314+
username = "git"
315+
}
316+
return &http.BasicAuth{Username: username, Password: password}, nil
317+
}
318+
319+
func checkoutImageRepositoryRef(repository *git.Repository, ref string) error {
320+
hash, err := repository.ResolveRevision(plumbing.Revision(ref))
321+
if err != nil {
322+
// Non-default branches of a clone live under refs/remotes/origin.
323+
hash, err = repository.ResolveRevision(plumbing.Revision("refs/remotes/origin/" + ref))
324+
}
325+
if err != nil {
326+
return fmt.Errorf("requested git ref could not be resolved")
327+
}
328+
worktree, err := repository.Worktree()
329+
if err != nil {
330+
return fmt.Errorf("failed to open repository worktree")
331+
}
332+
if err := worktree.Checkout(&git.CheckoutOptions{Hash: *hash}); err != nil {
333+
return fmt.Errorf("failed to check out requested git ref")
334+
}
335+
return nil
277336
}
278337

279338
// syncImageFile imports one manifest and returns its name, or an empty name for
@@ -285,23 +344,26 @@ func (r *ImageRepositoryReconciler) syncImageFile(ctx context.Context, repo *kub
285344
}
286345
jsonData, err := yaml.YAMLToJSON(data)
287346
if err != nil {
288-
return "", fmt.Errorf("parse %s: %w", path, err)
347+
return "", &invalidImageManifest{err: err}
289348
}
290349
// Use Kubernetes' JSON decoder to preserve integer fields. Generic YAML/JSON
291350
// decoding turns numbers into float64 and makes unchanged specs look modified.
292351
obj := &unstructured.Unstructured{}
293352
if err := obj.UnmarshalJSON(jsonData); err != nil {
294-
return "", fmt.Errorf("parse %s: %w", path, err)
353+
return "", &invalidImageManifest{err: err}
295354
}
296-
if obj.GetKind() != "Image" || obj.GroupVersionKind().Group != "kubeworkspaces.io" {
355+
if obj.GetKind() != "Image" {
297356
return "", nil
298357
}
358+
if obj.GetAPIVersion() != "kubeworkspaces.io/v1alpha1" {
359+
return "", &invalidImageManifest{err: fmt.Errorf("unsupported Image apiVersion")}
360+
}
299361
name := obj.GetName()
300362
if name == "" {
301-
return "", nil
363+
return "", &invalidImageManifest{err: fmt.Errorf("image name is required")}
302364
}
303365
if _, ok := obj.Object["spec"].(map[string]interface{}); !ok {
304-
return "", fmt.Errorf("image %s is missing a spec object", name)
366+
return "", &invalidImageManifest{err: fmt.Errorf("image %s is missing a spec object", name)}
305367
}
306368
labels := obj.GetLabels()
307369
if labels == nil {
@@ -371,7 +433,14 @@ func imageRepositoryFiles(root string, paths []string) ([]string, error) {
371433
var files []string
372434
seen := map[string]bool{}
373435
for _, scanPath := range paths {
374-
fullPath := filepath.Join(root, strings.TrimSpace(scanPath))
436+
scanPath = strings.TrimSpace(scanPath)
437+
if scanPath == "" || filepath.IsAbs(scanPath) {
438+
return nil, fmt.Errorf("image directory must be relative to the repository")
439+
}
440+
fullPath, err := containedImageRepositoryPath(root, filepath.Join(root, scanPath))
441+
if err != nil {
442+
return nil, err
443+
}
375444
entries, err := os.ReadDir(fullPath)
376445
if err != nil {
377446
return nil, fmt.Errorf("read image directory %q: %w", scanPath, err)
@@ -381,6 +450,9 @@ func imageRepositoryFiles(root string, paths []string) ([]string, error) {
381450
continue
382451
}
383452
path := filepath.Join(fullPath, entry.Name())
453+
if _, err := containedImageRepositoryPath(root, path); err != nil {
454+
return nil, err
455+
}
384456
if !seen[path] {
385457
files = append(files, path)
386458
seen[path] = true
@@ -390,9 +462,34 @@ func imageRepositoryFiles(root string, paths []string) ([]string, error) {
390462
return files, nil
391463
}
392464

465+
func containedImageRepositoryPath(root, path string) (string, error) {
466+
resolved, err := filepath.EvalSymlinks(path)
467+
if err != nil {
468+
return "", fmt.Errorf("resolve image repository path: %w", err)
469+
}
470+
resolvedRoot, err := filepath.EvalSymlinks(root)
471+
if err != nil {
472+
return "", err
473+
}
474+
rel, err := filepath.Rel(resolvedRoot, resolved)
475+
if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
476+
return "", fmt.Errorf("image path escapes the repository")
477+
}
478+
return path, nil
479+
}
480+
481+
func imageRepositoryPredicate() predicate.Predicate {
482+
return predicate.Funcs{UpdateFunc: func(e event.UpdateEvent) bool {
483+
return e.ObjectOld.GetGeneration() != e.ObjectNew.GetGeneration() ||
484+
(e.ObjectNew.GetAnnotations()[imageRepositorySyncAnno] != "" &&
485+
e.ObjectOld.GetAnnotations()[imageRepositorySyncAnno] != e.ObjectNew.GetAnnotations()[imageRepositorySyncAnno])
486+
}}
487+
}
488+
393489
// SetupWithManager sets up the controller with the Manager.
394490
func (r *ImageRepositoryReconciler) SetupWithManager(mgr ctrl.Manager) error {
395491
return ctrl.NewControllerManagedBy(mgr).
396492
For(&kubeworkspacesiov1alpha1.ImageRepository{}).
493+
WithEventFilter(imageRepositoryPredicate()).
397494
Complete(r)
398495
}

0 commit comments

Comments
 (0)