diff --git a/pkg/registry/sdn/securitygroup/rest_test.go b/pkg/registry/sdn/securitygroup/rest_test.go index f3ad68fc3..764f05197 100644 --- a/pkg/registry/sdn/securitygroup/rest_test.go +++ b/pkg/registry/sdn/securitygroup/rest_test.go @@ -1517,6 +1517,97 @@ func TestCreateRejectsEmptyFQDNSelector(t *testing.T) { } } +func sgWithEgress(name string, eg sdnv1alpha1.EgressRule) *sdnv1alpha1.SecurityGroup { + return &sdnv1alpha1.SecurityGroup{ + ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: testNamespace}, + Spec: sdnv1alpha1.SecurityGroupSpec{ + Attachments: []sdnv1alpha1.ApplicationReference{{Kind: "Postgres", Name: "db"}}, + Egress: []sdnv1alpha1.EgressRule{eg}, + }, + } +} + +// TestCreateRejectsInvalidPortOrFQDN pins the field and the reason of each +// rejection. A port range used to be reported as a malformed port name, and a +// malformed FQDN reached the backing write, where the CiliumNetworkPolicy CRD +// rejected it with an error about an object the tenant never wrote. +func TestCreateRejectsInvalidPortOrFQDN(t *testing.T) { + fqdn := func(sel sdnv1alpha1.FQDNSelector) sdnv1alpha1.EgressRule { + return sdnv1alpha1.EgressRule{ToFQDNs: []sdnv1alpha1.FQDNSelector{sel}} + } + port := func(p string) sdnv1alpha1.EgressRule { + return sdnv1alpha1.EgressRule{ToPorts: []sdnv1alpha1.PortRule{{Ports: []sdnv1alpha1.PortProtocol{{Port: p}}}}} + } + cases := map[string]struct { + rule sdnv1alpha1.EgressRule + field string + detail string + }{ + "port range": {port("80-90"), "spec.egress[0].toPorts[0].ports[0].port", "port ranges are not supported"}, + "full port range": {port("1-65535"), "spec.egress[0].toPorts[0].ports[0].port", "port ranges are not supported"}, + "matchName with space": {fqdn(sdnv1alpha1.FQDNSelector{MatchName: "bad name.example.org"}), "spec.egress[0].toFQDNs[0].matchName", "must be a DNS name"}, + "matchName with wildcard": {fqdn(sdnv1alpha1.FQDNSelector{MatchName: "*.example.org"}), "spec.egress[0].toFQDNs[0].matchName", "must be a DNS name"}, + "matchName with leading dot": {fqdn(sdnv1alpha1.FQDNSelector{MatchName: ".example.org"}), "spec.egress[0].toFQDNs[0].matchName", "must be a DNS name"}, + "matchName with empty label": {fqdn(sdnv1alpha1.FQDNSelector{MatchName: "example..org"}), "spec.egress[0].toFQDNs[0].matchName", "must be a DNS name"}, + "matchName with scheme": {fqdn(sdnv1alpha1.FQDNSelector{MatchName: "https://example.org"}), "spec.egress[0].toFQDNs[0].matchName", "must be a DNS name"}, + "matchName too long": {fqdn(sdnv1alpha1.FQDNSelector{MatchName: strings.Repeat("a", 256)}), "spec.egress[0].toFQDNs[0].matchName", "may not be more than 255"}, + "matchPattern with slash": {fqdn(sdnv1alpha1.FQDNSelector{MatchPattern: "*.example.org/path"}), "spec.egress[0].toFQDNs[0].matchPattern", "must be a DNS name"}, + "matchPattern with question": {fqdn(sdnv1alpha1.FQDNSelector{MatchPattern: "?.example.org"}), "spec.egress[0].toFQDNs[0].matchPattern", "must be a DNS name"}, + "matchPattern with empty label": {fqdn(sdnv1alpha1.FQDNSelector{MatchPattern: "*..example.org"}), "spec.egress[0].toFQDNs[0].matchPattern", "must be a DNS name"}, + "matchPattern too long": {fqdn(sdnv1alpha1.FQDNSelector{MatchPattern: "*." + strings.Repeat("a", 254)}), "spec.egress[0].toFQDNs[0].matchPattern", "may not be more than 255"}, + "both matchName and pattern": {fqdn(sdnv1alpha1.FQDNSelector{MatchName: "example.org", MatchPattern: "*.example.org"}), "spec.egress[0].toFQDNs[0]", "only one of matchName or matchPattern"}, + } + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + r := newTestREST(t) + _, err := r.Create(ctxNS(), sgWithEgress("sg-bad", tc.rule), nil, &metav1.CreateOptions{}) + var status apierrors.APIStatus + if !apierrors.IsInvalid(err) || !errors.As(err, &status) { + t.Fatalf("Create with %s: got err %v, want Invalid", name, err) + } + causes := status.Status().Details.Causes + if len(causes) != 1 || causes[0].Field != tc.field || !strings.Contains(causes[0].Message, tc.detail) { + t.Fatalf("Create with %s: causes = %+v, want one on %s containing %q", name, causes, tc.field, tc.detail) + } + np := &CiliumNetworkPolicy{} + if err := r.c.Get(context.Background(), types.NamespacedName{Namespace: testNamespace, Name: "sg-bad"}, np); !apierrors.IsNotFound(err) { + t.Fatalf("invalid SecurityGroup was persisted: err=%v", err) + } + }) + } +} + +func TestCreateAcceptsValidPortOrFQDN(t *testing.T) { + cases := map[string]sdnv1alpha1.EgressRule{ + "single port": {ToPorts: []sdnv1alpha1.PortRule{{Ports: []sdnv1alpha1.PortProtocol{{Port: "8080"}}}}}, + "named port with digits": {ToPorts: []sdnv1alpha1.PortRule{{Ports: []sdnv1alpha1.PortProtocol{{Port: "http-8080"}}}}}, + "matchName": {ToFQDNs: []sdnv1alpha1.FQDNSelector{{MatchName: "api.example.org"}}}, + "matchName with trailing dot": {ToFQDNs: []sdnv1alpha1.FQDNSelector{{MatchName: "api.example.org."}}}, + "matchName with underscore": {ToFQDNs: []sdnv1alpha1.FQDNSelector{{MatchName: "_sip._tcp.example.org"}}}, + "matchName single label": {ToFQDNs: []sdnv1alpha1.FQDNSelector{{MatchName: "localhost"}}}, + "matchName at max length": {ToFQDNs: []sdnv1alpha1.FQDNSelector{{MatchName: strings.Repeat("a", 255)}}}, + "matchPattern subdomain": {ToFQDNs: []sdnv1alpha1.FQDNSelector{{MatchPattern: "*.example.org"}}}, + "matchPattern multilevel": {ToFQDNs: []sdnv1alpha1.FQDNSelector{{MatchPattern: "**.example.org"}}}, + "matchPattern infix": {ToFQDNs: []sdnv1alpha1.FQDNSelector{{MatchPattern: "sub*.example.org"}}}, + "matchPattern match all": {ToFQDNs: []sdnv1alpha1.FQDNSelector{{MatchPattern: "*"}}}, + } + for name, rule := range cases { + t.Run(name, func(t *testing.T) { + r := newTestREST(t) + if _, err := r.Create(ctxNS(), sgWithEgress("sg-ok", rule), nil, &metav1.CreateOptions{}); err != nil { + t.Fatalf("Create with %s returned error: %v", name, err) + } + np := &CiliumNetworkPolicy{} + if err := r.c.Get(context.Background(), types.NamespacedName{Namespace: testNamespace, Name: "sg-ok"}, np); err != nil { + t.Fatalf("backing policy not found: %v", err) + } + if got := np.Spec.Egress[0]; !reflect.DeepEqual(got.ToFQDNs, rule.ToFQDNs) || !reflect.DeepEqual(got.ToPorts, rule.ToPorts) { + t.Fatalf("egress rule not projected 1:1: got %+v, want %+v", got, rule) + } + }) + } +} + // TestCreateRejectsNamespaceMismatch asserts Create rejects a SecurityGroup // whose metadata.namespace differs from the request namespace, so a caller // cannot post to one namespace and persist into another. The aggregated diff --git a/pkg/registry/sdn/securitygroup/validate.go b/pkg/registry/sdn/securitygroup/validate.go index 4aa37f765..172a21887 100644 --- a/pkg/registry/sdn/securitygroup/validate.go +++ b/pkg/registry/sdn/securitygroup/validate.go @@ -5,6 +5,7 @@ package securitygroup import ( "net/netip" + "regexp" "strconv" "strings" @@ -19,6 +20,21 @@ import ( // An empty protocol defaults to ANY and is allowed. var validProtocols = map[string]struct{}{"TCP": {}, "UDP": {}, "SCTP": {}, "ANY": {}} +// The FQDN rules of the cilium.io/v2 CiliumNetworkPolicy CRD +// (spec.egress[].toFQDNs[]). The API server enforces them on the backing +// write, so a value they reject must be caught here to fail on the +// SecurityGroup path rather than with a CiliumNetworkPolicy schema error. +var ( + fqdnMatchNameRE = regexp.MustCompile(`^([-a-zA-Z0-9_]+[.]?)+$`) + fqdnMatchPatternRE = regexp.MustCompile(`^([-a-zA-Z0-9_*]+[.]?)+$`) +) + +const fqdnMaxLength = 255 + +// portRangeRE matches a "first-last" port range, which PortProtocol cannot +// express: it carries a single port, and Cilium's endPort is not exposed. +var portRangeRE = regexp.MustCompile(`^[0-9]+-[0-9]+$`) + // reservedEntities are Cilium's built-in entity names. They stay // platform-managed and are deliberately not tenant-expressible — a SecurityGroup // reaches external destinations through CIDR/FQDN, not entities — so the API @@ -158,13 +174,33 @@ func validateCIDRs(path *field.Path, cidrs []string) field.ErrorList { func validateFQDNs(path *field.Path, fqdns []sdnv1alpha1.FQDNSelector) field.ErrorList { var errs field.ErrorList for i := range fqdns { - if fqdns[i].MatchName == "" && fqdns[i].MatchPattern == "" { + name, pattern := fqdns[i].MatchName, fqdns[i].MatchPattern + switch { + case name == "" && pattern == "": errs = append(errs, field.Required(path.Index(i), "must set matchName or matchPattern")) + case name != "" && pattern != "": + errs = append(errs, field.Forbidden(path.Index(i), "must set only one of matchName or matchPattern")) + case name != "": + errs = append(errs, validateFQDNValue(path.Index(i).Child("matchName"), name, fqdnMatchNameRE, + "must be a DNS name made of letters, digits, '-', '_' and single '.' separators")...) + default: + errs = append(errs, validateFQDNValue(path.Index(i).Child("matchPattern"), pattern, fqdnMatchPatternRE, + "must be a DNS name made of letters, digits, '-', '_', '*' and single '.' separators")...) } } return errs } +func validateFQDNValue(path *field.Path, value string, re *regexp.Regexp, msg string) field.ErrorList { + if len(value) > fqdnMaxLength { + return field.ErrorList{field.TooLong(path, value, fqdnMaxLength)} + } + if !re.MatchString(value) { + return field.ErrorList{field.Invalid(path, value, msg)} + } + return nil +} + func validatePortRules(path *field.Path, rules []sdnv1alpha1.PortRule) field.ErrorList { var errs field.ErrorList for i := range rules { @@ -177,6 +213,8 @@ func validatePortRules(path *field.Path, rules []sdnv1alpha1.PortRule) field.Err if n < 1 || n > 65535 { errs = append(errs, field.Invalid(pPath.Child("port"), pp.Port, "port number must be between 1 and 65535")) } + } else if portRangeRE.MatchString(pp.Port) { + errs = append(errs, field.Invalid(pPath.Child("port"), pp.Port, "port ranges are not supported; list each port as its own entry")) } else { for _, msg := range validation.IsValidPortName(pp.Port) { errs = append(errs, field.Invalid(pPath.Child("port"), pp.Port, msg))