update the err of hostPorts in psp

pull/6/head
xilabao 2017-06-16 16:22:50 +08:00
parent 4a8c245e6e
commit c9b772e9a9
2 changed files with 20 additions and 3 deletions

View File

@ -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
}

View File

@ -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)
}
}
}