From 74bba64f0b07fa73cd4248d305dbc8ae451407ed Mon Sep 17 00:00:00 2001 From: Philipp Sauter Date: Mon, 27 Nov 2023 19:09:07 +0100 Subject: [PATCH] add tests --- .../ingress/annotations/parser/validators.go | 2 + .../annotations/parser/validators_test.go | 56 +++++++++++++++++++ 2 files changed, 58 insertions(+) diff --git a/internal/ingress/annotations/parser/validators.go b/internal/ingress/annotations/parser/validators.go index af09d601e..64a9d133d 100644 --- a/internal/ingress/annotations/parser/validators.go +++ b/internal/ingress/annotations/parser/validators.go @@ -117,6 +117,8 @@ func ValidateRegex(regex *regexp.Regexp, removeSpace bool) AnnotationValidator { } } +// CommonNameAnnotationValidator checks whether the annotation value starts with +// 'CN=' and is followed by a valid regex. func CommonNameAnnotationValidator(s string) error { if !strings.HasPrefix(s, "CN=") { return fmt.Errorf("value %s is not a valid Common Name annotation: missing prefix 'CN='", s) diff --git a/internal/ingress/annotations/parser/validators_test.go b/internal/ingress/annotations/parser/validators_test.go index e7aeb15ca..8523232a2 100644 --- a/internal/ingress/annotations/parser/validators_test.go +++ b/internal/ingress/annotations/parser/validators_test.go @@ -307,3 +307,59 @@ func TestCheckAnnotationRisk(t *testing.T) { }) } } + +func TestCommonNameAnnotationValidator(t *testing.T) { + tests := []struct { + name string + annotation string + wantErr bool + }{ + { + name: "correct example", + annotation: `CN=(my\.common\.name)`, + wantErr: false, + }, + { + name: "no CN= prefix", + annotation: `(my\.common\.name)`, + wantErr: true, + }, + { + name: "invalid prefix", + annotation: `CN(my\.common\.name)`, + wantErr: true, + }, + { + name: "invalid regex", + annotation: `CN=(my\.common\.name]`, + wantErr: true, + }, + { + name: "wildcard regex", + annotation: `CN=(my\..*\.name)`, + wantErr: false, + }, + { + name: "somewhat complex regex", + annotation: "CN=(my\\.app\\.dev|.*\\.bbb\\.aaaa\\.tld)", + wantErr: false, + }, + { + name: "another somewhat complex regex", + annotation: `CN=(my-app.*\.c\.defg\.net|other.app.com)`, + wantErr: false, + }, + { + name: "nested parenthesis regex", + annotation: `CN=(api-one\.(asdf)?qwer\.webpage\.organization\.org)`, + wantErr: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if err := CommonNameAnnotationValidator(tt.annotation); (err != nil) != tt.wantErr { + t.Errorf("CommonNameAnnotationValidator() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +}