Skip to content

Commit

Permalink
Add validation for EventPolicy sub suffix matching
Browse files Browse the repository at this point in the history
Signed-off-by: Pierangelo Di Pilato <[email protected]>
  • Loading branch information
pierDipi committed Jun 17, 2024
1 parent 0eee301 commit 39511cb
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
16 changes: 16 additions & 0 deletions pkg/apis/eventing/v1alpha1/eventpolicy_validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package v1alpha1

import (
"context"
"strings"

"knative.dev/pkg/apis"
)
Expand All @@ -36,6 +37,7 @@ func (ets *EventPolicySpec) Validate(ctx context.Context) *apis.FieldError {
err = err.Also(apis.ErrMultipleOneOf("ref", "sub").ViaFieldIndex("from", i))
}
err = err.Also(f.Ref.Validate().ViaField("ref").ViaFieldIndex("from", i))
err = err.Also(validateSub(f.Sub).ViaField("sub").ViaFieldIndex("from", i))
}

for i, t := range ets.To {
Expand All @@ -53,6 +55,20 @@ func (ets *EventPolicySpec) Validate(ctx context.Context) *apis.FieldError {
return err
}

func validateSub(sub *string) *apis.FieldError {
if sub == nil || len(*sub) <= 1 {
return nil
}

lastInvalidIdx := len(*sub) - 2
firstInvalidIdx := 0
if idx := strings.IndexRune(*sub, '*'); idx >= firstInvalidIdx && idx <= lastInvalidIdx {
return apis.ErrInvalidValue(*sub, "", "'*' is only allowed as suffix")
}

return nil
}

func (r *EventPolicyFromReference) Validate() *apis.FieldError {
if r == nil {
return nil
Expand Down
39 changes: 39 additions & 0 deletions pkg/apis/eventing/v1alpha1/eventpolicy_validation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,45 @@ func TestEventPolicySpecValidation(t *testing.T) {
return apis.ErrMissingField("apiVersion").ViaField("ref").ViaFieldIndex("to", 0).ViaField("spec")
}(),
},
{
name: "invalid, from.sub '*' set as infix",
ep: &EventPolicy{
Spec: EventPolicySpec{
From: []EventPolicySpecFrom{{
Sub: ptr.String("a*c"),
}},
},
},
want: func() *apis.FieldError {
return apis.ErrInvalidValue("a*c", "sub", "'*' is only allowed as suffix").ViaFieldIndex("from", 0).ViaField("spec")
}(),
},
{
name: "valid, from.sub '*' set as infix",
ep: &EventPolicy{
Spec: EventPolicySpec{
From: []EventPolicySpecFrom{{
Sub: ptr.String("a*"),
}},
},
},
want: func() *apis.FieldError {
return nil
}(),
},
{
name: "valid, from.sub exactly '*'",
ep: &EventPolicy{
Spec: EventPolicySpec{
From: []EventPolicySpecFrom{{
Sub: ptr.String("*"),
}},
},
},
want: func() *apis.FieldError {
return nil
}(),
},
}

for _, test := range tests {
Expand Down

0 comments on commit 39511cb

Please sign in to comment.