mirror of
https://github.com/cozystack/cozystack.git
synced 2026-11-30 04:06:34 +09:00
fix(securitygroups): reject port ranges and malformed FQDNs on the SecurityGroup path (#5134)
<!-- Thank you for making a contribution! Here are some tips for you: - Use Conventional Commits for the PR title: `type(scope): description` - Types: feat, fix, docs, style, refactor, perf, test, build, ci, chore - Scopes are not an exhaustive list — pick the most specific scope for the change and extend the list when a genuinely new area appears. Examples: - System components: dashboard, platform, operator, cilium, kube-ovn, linstor, fluxcd, cluster-api - Managed apps: postgres, mariadb, redis, kafka, clickhouse, virtual-machine, kubernetes - Development and maintenance: api, hack, tests, ci, docs, maintenance - Breaking changes: append `!` after type/scope (`feat(api)!: ...`) or add a `BREAKING CHANGE:` footer - If it's a work in progress, consider creating this PR as a draft. - Don't hesistate to ask for opinion and review in the community chats, even if it's still a draft. - Add the label `kind/backport` if it's a bugfix that needs to be backported to a previous version. --> ## What this PR does Fixes #5130. `validatePortRules` sent any non-numeric port to `IsValidPortName`, so `"80-90"` came back as "must contain at least one letter (a-z)". A `first-last` value now gets "port ranges are not supported; list each port as its own entry" on the same field. `PortProtocol` carries a single port and Cilium's `endPort` is not exposed, so the limit itself is unchanged. `validateFQDNs` only checked that a selector was not empty. A malformed `matchName` or `matchPattern` passed, and the backing write then failed on the CiliumNetworkPolicy CRD, which surfaced as an error about a `cilium.io` object. The validator now applies the CRD's own rules for `spec.egress[].toFQDNs[]`, with a field error on the SecurityGroup path: `^([-a-zA-Z0-9_]+[.]?)+$` for `matchName`, `^([-a-zA-Z0-9_*]+[.]?)+$` for `matchPattern`, `maxLength: 255` for both, and the `oneOf` that allows only one of the two per selector. These are copied from the CRD served by Cilium 1.19.5 and match the agent's `FQDNSelector.sanitize`, which also refuses a selector that sets both fields. `TestCreateRejectsInvalidPortOrFQDN` lists each rejected value and checks that the error carries a single cause, on the expected field, with the expected reason. All 13 cases fail on `main`. `TestCreateAcceptsValidPortOrFQDN` lists accepted values (named port `http-8080`, trailing dot, underscore labels, `**.` prefix, infix and lone `*` patterns, 255 characters) and checks they project 1:1. `go test ./pkg/registry/sdn/...` passes. As a cross-check, every FQDN value in both tables was also sent to the CiliumNetworkPolicy CRD of a lab running Cilium 1.19.5, with `kubectl create --dry-run=server`. The CRD rejects exactly the values the validator rejects and accepts exactly the ones it accepts. ### Screenshots <!-- REQUIRED for UI changes: attach screenshots or screen recordings demonstrating the visual impact of your changes. PRs with UI changes without screenshots will not be merged. --> ### Downstream repositories The diff touches `pkg/registry/sdn/securitygroup/validate.go` and its tests only: the SecurityGroup schema does not change, and no package, chart, CRD, `hack/` or convention is touched. Neither the website nor the Terraform provider documents or models SecurityGroup fields. <!-- Cozystack is upstream for repositories that are NOT kept in sync with it automatically, and nothing in CI compares the two sides, so a change here can break them silently. Which change forces what, and which file to touch, is the trigger map in docs/agents/contributing.md under "Downstream Repositories". Walk it before you tick anything. IF YOU ARE AN AI AGENT OR AN LLM, THIS IS PART OF THE TASK, NOT A FORM TO FILL IN: 1. Walk the trigger map against the actual diff of this PR, file by file. Do not decide from the PR title or from your memory of what you changed. 2. For every repository you tick, open the follow-up PR there and link it on the same line. A ticked box with no link claims work that does not exist, which is worse than an empty box. Search that repository for an open PR or issue covering it first, and link that instead of filing a duplicate. 3. When the follow-up is out of scope, or needs a decision that is not yours to make, open an issue in that repository instead, link that, and say so in the PR body. Do not push a speculative PR into another repository just to fill a line here. 4. Do not tick "No downstream repository is affected" to make the checklist go away. If you are unsure, leave every box empty and say so in the PR body, so a human decides. --> - [x] No downstream repository is affected by this change - [ ] [cozystack/website](https://github.com/cozystack/website) - follow-up: - [ ] [cozystack/terraform-provider-cozystack](https://github.com/cozystack/terraform-provider-cozystack) - follow-up: - [ ] [cozystack/ansible-cozystack](https://github.com/cozystack/ansible-cozystack) - follow-up: - [ ] [cozystack/ccp](https://github.com/cozystack/ccp) - follow-up: - [ ] [cozystack/talm](https://github.com/cozystack/talm) - follow-up: - [ ] [cozystack/cozyhr](https://github.com/cozystack/cozyhr) - follow-up: - [ ] [cozystack/cozy-proxy](https://github.com/cozystack/cozy-proxy) - follow-up: - [ ] [cozystack/cozystack-telemetry-server](https://github.com/cozystack/cozystack-telemetry-server) - follow-up: - [ ] [cozystack/external-apps-example](https://github.com/cozystack/external-apps-example) - follow-up: - [ ] [cozystack/examples](https://github.com/cozystack/examples) - follow-up: - [ ] [cozystack/community](https://github.com/cozystack/community) - follow-up: ### Release note <!-- Write a release note: - Explain what has changed internally and for users. - Start with the same `type(scope):` prefix as in the PR title - Follow the guidelines at https://github.com/kubernetes/community/blob/master/contributors/guide/release-notes.md. --> ```release-note fix(securitygroups): a port range now gets a clear "port ranges are not supported" error, and a malformed toFQDNs matchName or matchPattern is rejected on the SecurityGroup field instead of failing on the backing CiliumNetworkPolicy. ``` <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Security group egress rules now reject port ranges with a clear validation error; list each port separately. * FQDN selectors are checked for supported name or pattern formats, required selector fields, and a maximum length of 255 characters. * Invalid egress settings are rejected without creating a policy, while valid ports and FQDN selectors can be saved. * **Documentation** * Updated guidance to reflect egress port and FQDN validation rules. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
This commit is contained in:
3 files changed
+131
-2
No files matched your search
@@ -184,4 +184,4 @@ The aggregated-API + controller model is intentionally minimal. The following ca
|
||||
- **Cluster-scope** SecurityGroups projecting to CiliumClusterwideNetworkPolicy.
|
||||
- Reusable **CIDR/FQDN groups**, and exposing more of the CiliumNetworkPolicy rule surface (ICMP, `toServices`, CIDR-set exceptions) as demand appears.
|
||||
- An optional **existence/authorization check** on attachments and SG peers (SubjectAccessReview) to fail fast on a typo instead of silently matching zero pods.
|
||||
- **Richer spec validation.** Create and update already validate the highest-risk fields synchronously — CIDR syntax, port range, the protocol enum, attachment/peer label validity, reserved-entity names — and reject a bad value with `Invalid` instead of writing a policy Cilium would silently discard. Still deferred: FQDN `matchName`/`matchPattern` syntax and cross-rule consistency, which pass through to Cilium.
|
||||
- **Richer spec validation.** Create and update already validate the highest-risk fields synchronously — CIDR syntax, port number bounds (a `first-last` port range is rejected, since a port entry carries a single port and Cilium's `endPort` is not exposed), the protocol enum, attachment/peer label validity, reserved-entity names, and FQDN selectors against the CiliumNetworkPolicy CRD's own rules (exactly one of `matchName`/`matchPattern`, the CRD's patterns, at most 255 characters) — and reject a bad value with a field error on the SecurityGroup path instead of writing a policy that Cilium would silently discard or that the CiliumNetworkPolicy schema would refuse on the backing write. Still deferred: cross-rule consistency, which passes through to Cilium.
|
||||
@@ -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
|
||||
|
||||
@@ -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))
|
||||
|
||||
Reference in new issue
Block a user