Skip to content

Commit

Permalink
Validate the subscription name
Browse files Browse the repository at this point in the history
Signed-off-by: mprahl <mprahl@users.noreply.github.com>
  • Loading branch information
mprahl authored and openshift-merge-bot[bot] committed Apr 10, 2024
1 parent 1711136 commit be8927f
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
11 changes: 11 additions & 0 deletions controllers/operatorpolicy_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,17 @@ func buildSubscription(
return nil, fmt.Errorf("the policy spec.subscription is invalid: %w", err)
}

name, ok := sub["name"].(string)
if !ok || name == "" {
return nil, fmt.Errorf("name is required in spec.subscription")
}

if validationErrs := validation.IsDNS1123Label(name); len(validationErrs) != 0 {
return nil, fmt.Errorf(
"the name '%v' used for the subscription is invalid: %s", name, strings.Join(validationErrs, ", "),
)
}

ns, ok := sub["namespace"].(string)
if !ok {
if defaultNS == "" {
Expand Down
59 changes: 59 additions & 0 deletions controllers/operatorpolicy_controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,65 @@ func TestBuildSubscription(t *testing.T) {
assert.Equal(t, ret.ObjectMeta.Namespace, "default")
}

func TestBuildSubscriptionInvalidNames(t *testing.T) {
t.Parallel()

testCases := []struct {
name string
expected string
}{
{
name: "",
expected: "name is required in spec.subscription",
},
{
name: "wrong$s",
expected: "the name 'wrong$s' used for the subscription is invalid: a lowercase RFC 1123 label must " +
"consist of lower case alphanumeric characters or '-', and must start and end with an alphanumeric " +
"character (e.g. 'my-name', or '123-abc', regex used for validation is " +
"'[a-z0-9]([-a-z0-9]*[a-z0-9])?')",
},
}

for _, test := range testCases {
test := test

t.Run(
"name="+test.name,
func(t *testing.T) {
t.Parallel()

testPolicy := &policyv1beta1.OperatorPolicy{
ObjectMeta: metav1.ObjectMeta{
Name: "my-policy",
Namespace: "default",
},
Spec: policyv1beta1.OperatorPolicySpec{
Severity: "low",
RemediationAction: "enforce",
ComplianceType: "musthave",
Subscription: runtime.RawExtension{
Raw: []byte(`{
"namespace": "default",
"source": "my-catalog",
"sourceNamespace": "my-ns",
"name": "` + test.name + `",
"channel": "stable",
"startingCSV": "my-operator-v1",
"installPlanApproval": "Automatic"
}`),
},
},
}

// Check values are correctly bootstrapped to the Subscription
_, err := buildSubscription(testPolicy, "my-operators")
assert.Equal(t, err.Error(), test.expected)
},
)
}
}

func TestBuildOperatorGroup(t *testing.T) {
testPolicy := &policyv1beta1.OperatorPolicy{
ObjectMeta: metav1.ObjectMeta{
Expand Down

0 comments on commit be8927f

Please sign in to comment.