From c9b772e9a9bd02a00647dbb37d5fab6a17e051a9 Mon Sep 17 00:00:00 2001 From: xilabao Date: Fri, 16 Jun 2017 16:22:50 +0800 Subject: [PATCH] update the err of hostPorts in psp --- pkg/security/podsecuritypolicy/provider.go | 19 ++++++++++++++++++- .../podsecuritypolicy/provider_test.go | 4 ++-- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/pkg/security/podsecuritypolicy/provider.go b/pkg/security/podsecuritypolicy/provider.go index e92c6419fc..2431e0ba5e 100644 --- a/pkg/security/podsecuritypolicy/provider.go +++ b/pkg/security/podsecuritypolicy/provider.go @@ -18,6 +18,7 @@ package podsecuritypolicy import ( "fmt" + "strings" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/validation/field" @@ -318,7 +319,7 @@ func (s *simpleProvider) hasInvalidHostPort(container *api.Container, fldPath *f allErrs := field.ErrorList{} for _, cp := range container.Ports { if cp.HostPort > 0 && !s.isValidHostPort(int(cp.HostPort)) { - detail := fmt.Sprintf("Host port %d is not allowed to be used. Allowed ports: %v", cp.HostPort, s.psp.Spec.HostPorts) + detail := fmt.Sprintf("Host port %d is not allowed to be used. Allowed ports: [%s]", cp.HostPort, hostPortRangesToString(s.psp.Spec.HostPorts)) allErrs = append(allErrs, field.Invalid(fldPath.Child("hostPort"), cp.HostPort, detail)) } } @@ -339,3 +340,19 @@ func (s *simpleProvider) isValidHostPort(port int) bool { func (s *simpleProvider) GetPSPName() string { return s.psp.Name } + +func hostPortRangesToString(ranges []extensions.HostPortRange) string { + formattedString := "" + if ranges != nil { + strRanges := []string{} + for _, r := range ranges { + if r.Min == r.Max { + strRanges = append(strRanges, fmt.Sprintf("%d", r.Min)) + } else { + strRanges = append(strRanges, fmt.Sprintf("%d-%d", r.Min, r.Max)) + } + } + formattedString = strings.Join(strRanges, ",") + } + return formattedString +} diff --git a/pkg/security/podsecuritypolicy/provider_test.go b/pkg/security/podsecuritypolicy/provider_test.go index 8cdfd65f07..714cb4a2a5 100644 --- a/pkg/security/podsecuritypolicy/provider_test.go +++ b/pkg/security/podsecuritypolicy/provider_test.go @@ -473,7 +473,7 @@ func TestValidateContainerSecurityContextFailures(t *testing.T) { "failHostPortPSP": { pod: failHostPortPod, psp: defaultPSP(), - expectedError: "Host port 1 is not allowed to be used. Allowed ports: []", + expectedError: "Host port 1 is not allowed to be used. Allowed ports: []", }, "failReadOnlyRootFS - nil": { pod: defaultPod(), @@ -508,7 +508,7 @@ func TestValidateContainerSecurityContextFailures(t *testing.T) { continue } if !strings.Contains(errs[0].Error(), v.expectedError) { - t.Errorf("%s received unexpected error %v", k, errs) + t.Errorf("%s received unexpected error %v\nexpected: %s", k, errs, v.expectedError) } } }