From 62d26b4a6814284e4f527acf649ad367412b9aa8 Mon Sep 17 00:00:00 2001 From: Harsh Thakur Date: Sat, 9 Sep 2023 13:55:59 +0530 Subject: [PATCH] add validation for registry/repo/image being passed Signed-off-by: Harsh Thakur --- pkg/patch/patch.go | 11 +++++++++-- pkg/patch/patch_test.go | 17 +++++++++++++---- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/pkg/patch/patch.go b/pkg/patch/patch.go index d253ef33..2fbef7eb 100644 --- a/pkg/patch/patch.go +++ b/pkg/patch/patch.go @@ -173,8 +173,15 @@ func patchedImageTarget(image, patchedTag string) (*string, error) { patchedTag = fmt.Sprintf("%s-%s", tag, defaultPatchedTagSuffix) } } - // this implies user has passed a destination image name, not just a tag - if strings.Contains(patchedTag, "/") { + + slashCount := strings.Count(patchedTag, "/") + if slashCount > 0 { + if slashCount < 2 { + err := fmt.Errorf("invalid tag %s, must be in the form /:", patchedTag) + log.Error(err) + return nil, err + } + // this implies user has passed a destination image name, not just a tag patchedImageName = patchedTag } else { patchedImageName = fmt.Sprintf("%s:%s", imageName.Name(), patchedTag) diff --git a/pkg/patch/patch_test.go b/pkg/patch/patch_test.go index 7e745bf1..00f99c19 100644 --- a/pkg/patch/patch_test.go +++ b/pkg/patch/patch_test.go @@ -74,10 +74,17 @@ func TestPatchedImageTarget(t *testing.T) { wantErr: false, }, { - name: "tag passed and contains a slash(indicating registry)", + name: "tag passed but without registry or repo", image: "docker.io/library/nginx:1.21.3", patchedTag: "my.registry/nginx:1.21.3-patched", - want: "my.registry/nginx:1.21.3-patched", + want: "", + wantErr: true, + }, + { + name: "tag passed contains registry, repo and image", + image: "docker.io/library/nginx:1.21.3", + patchedTag: "my.registry.io/myrepo/nginx:1.21.3-patched", + want: "my.registry.io/myrepo/nginx:1.21.3-patched", wantErr: false, }, } @@ -89,8 +96,10 @@ func TestPatchedImageTarget(t *testing.T) { t.Errorf("patchedImageTarget() error = %v, wantErr %v", err, tt.wantErr) return } - if *got != tt.want { - t.Errorf("patchedImageTarget() = %v, want %v", *got, tt.want) + if got != nil { + if *got != tt.want { + t.Errorf("patchedImageTarget() = %v, want %v", *got, tt.want) + } } }) }