Skip to content

Commit

Permalink
Merge pull request #12233 from kadern0/issue-10495
Browse files Browse the repository at this point in the history
Added port validation
  • Loading branch information
spowelljr committed Sep 27, 2021
2 parents 9bca7cd + 4e1bcc0 commit f85e7db
Show file tree
Hide file tree
Showing 10 changed files with 179 additions and 41 deletions.
96 changes: 68 additions & 28 deletions cmd/minikube/cmd/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -1088,13 +1088,9 @@ func validateCPUCount(drvName string) {
// validateFlags validates the supplied flags against known bad combinations
func validateFlags(cmd *cobra.Command, drvName string) {
if cmd.Flags().Changed(humanReadableDiskSize) {
diskSizeMB, err := util.CalculateSizeInMB(viper.GetString(humanReadableDiskSize))
err := validateDiskSize(viper.GetString(humanReadableDiskSize))
if err != nil {
exitIfNotForced(reason.Usage, "Validation unable to parse disk size '{{.diskSize}}': {{.error}}", out.V{"diskSize": viper.GetString(humanReadableDiskSize), "error": err})
}

if diskSizeMB < minimumDiskSize {
exitIfNotForced(reason.RsrcInsufficientStorage, "Requested disk size {{.requested_size}} is less than minimum of {{.minimum_size}}", out.V{"requested_size": diskSizeMB, "minimum_size": minimumDiskSize})
exitIfNotForced(reason.Usage, "{{.err}}", out.V{"err": err})
}
}

Expand All @@ -1117,31 +1113,20 @@ func validateFlags(cmd *cobra.Command, drvName string) {
if cmd.Flags().Changed(imageRepository) {
viper.Set(imageRepository, validateImageRepository(viper.GetString(imageRepository)))
}

if cmd.Flags().Changed(containerRuntime) {
runtime := strings.ToLower(viper.GetString(containerRuntime))

validOptions := cruntime.ValidRuntimes()
// `crio` is accepted as an alternative spelling to `cri-o`
validOptions = append(validOptions, constants.CRIO)

var validRuntime bool
for _, option := range validOptions {
if runtime == option {
validRuntime = true
}

// Convert `cri-o` to `crio` as the K8s config uses the `crio` spelling
if runtime == "cri-o" {
viper.Set(containerRuntime, constants.CRIO)
}
if cmd.Flags().Changed(ports) {
err := validatePorts(viper.GetStringSlice(ports))
if err != nil {
exit.Message(reason.Usage, "{{.err}}", out.V{"err": err})
}

if !validRuntime {
exit.Message(reason.Usage, `Invalid Container Runtime: "{{.runtime}}". Valid runtimes are: {{.validOptions}}`, out.V{"runtime": runtime, "validOptions": strings.Join(cruntime.ValidRuntimes(), ", ")})
}
}

validateCNI(cmd, runtime)
if cmd.Flags().Changed(containerRuntime) {
err := validateRuntime(viper.GetString(containerRuntime))
if err != nil {
exit.Message(reason.Usage, "{{.err}}", out.V{"err": err})
}
validateCNI(cmd, viper.GetString(containerRuntime))
}

if driver.BareMetal(drvName) {
Expand Down Expand Up @@ -1206,6 +1191,61 @@ func validateFlags(cmd *cobra.Command, drvName string) {
validateInsecureRegistry()
}

// This function validates that the --ports are not below 1024 for the host and not outside range
func validatePorts(ports []string) error {
for _, portDuplet := range ports {
for i, port := range strings.Split(portDuplet, ":") {
p, err := strconv.Atoi(port)
if err != nil {
return errors.Errorf("Sorry, one of the ports provided with --ports flag is not valid %s", ports)
}
if p > 65535 || p < 1 {
return errors.Errorf("Sorry, one of the ports provided with --ports flag is outside range %s", ports)
}
if p < 1024 && i == 0 {
return errors.Errorf("Sorry, you cannot use privileged ports on the host (below 1024) %s", ports)
}
}
}
return nil
}

// validateDiskSize validates the supplied disk size
func validateDiskSize(diskSize string) error {
diskSizeMB, err := util.CalculateSizeInMB(diskSize)
if err != nil {
return errors.Errorf("Validation unable to parse disk size %v: %v", diskSize, err)
}
if diskSizeMB < minimumDiskSize {
return errors.Errorf("Requested disk size %v is less than minimum of %v", diskSizeMB, minimumDiskSize)
}
return nil
}

// validateRuntime validates the supplied runtime
func validateRuntime(runtime string) error {
validOptions := cruntime.ValidRuntimes()
// `crio` is accepted as an alternative spelling to `cri-o`
validOptions = append(validOptions, constants.CRIO)

var validRuntime bool
for _, option := range validOptions {
if runtime == option {
validRuntime = true
}

// Convert `cri-o` to `crio` as the K8s config uses the `crio` spelling
if runtime == "cri-o" {
viper.Set(containerRuntime, constants.CRIO)
}
}

if !validRuntime {
return errors.Errorf("Invalid Container Runtime: %s. Valid runtimes are: %s", runtime, cruntime.ValidRuntimes())
}
return nil
}

// if container runtime is not docker, check that cni is not disabled
func validateCNI(cmd *cobra.Command, runtime string) {
if runtime == "docker" {
Expand Down
103 changes: 103 additions & 0 deletions cmd/minikube/cmd/start_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ limitations under the License.
package cmd

import (
"fmt"
"os"
"strings"
"testing"
Expand All @@ -27,6 +28,7 @@ import (

cfg "k8s.io/minikube/pkg/minikube/config"
"k8s.io/minikube/pkg/minikube/constants"
"k8s.io/minikube/pkg/minikube/cruntime"
"k8s.io/minikube/pkg/minikube/driver"
"k8s.io/minikube/pkg/minikube/proxy"
)
Expand Down Expand Up @@ -363,3 +365,104 @@ func TestValidateImageRepository(t *testing.T) {
}

}

func TestValidateDiskSize(t *testing.T) {
var tests = []struct {
diskSize string
errorMsg string
}{
{
diskSize: "2G",
errorMsg: "",
},
{
diskSize: "test",
errorMsg: "Validation unable to parse disk size test: FromHumanSize: invalid size: 'test'",
},
{
diskSize: "6M",
errorMsg: fmt.Sprintf("Requested disk size 6 is less than minimum of %v", minimumDiskSize),
},
}
for _, test := range tests {
t.Run(test.diskSize, func(t *testing.T) {
got := validateDiskSize(test.diskSize)
gotError := ""
if got != nil {
gotError = got.Error()
}
if gotError != test.errorMsg {
t.Errorf("validateDiskSize(diskSize=%v): got %v, expected %v", test.diskSize, got, test.errorMsg)
}
})
}
}

func TestValidateRuntime(t *testing.T) {
var tests = []struct {
runtime string
errorMsg string
}{
{
runtime: "cri-o",
errorMsg: "",
},
{
runtime: "docker",
errorMsg: "",
},

{
runtime: "test",
errorMsg: fmt.Sprintf("Invalid Container Runtime: test. Valid runtimes are: %v", cruntime.ValidRuntimes()),
},
}
for _, test := range tests {
t.Run(test.runtime, func(t *testing.T) {
got := validateRuntime(test.runtime)
gotError := ""
if got != nil {
gotError = got.Error()
}
if gotError != test.errorMsg {
t.Errorf("ValidateRuntime(runtime=%v): got %v, expected %v", test.runtime, got, test.errorMsg)
}
})
}
}

func TestValidatePorts(t *testing.T) {
var tests = []struct {
ports []string
errorMsg string
}{
{
ports: []string{"test:80"},
errorMsg: "Sorry, one of the ports provided with --ports flag is not valid [test:80]",
},
{
ports: []string{"0:80"},
errorMsg: "Sorry, one of the ports provided with --ports flag is outside range [0:80]",
},
{
ports: []string{"80:80"},
errorMsg: "Sorry, you cannot use privileged ports on the host (below 1024) [80:80]",
},
{
ports: []string{"8080:80", "6443:443"},
errorMsg: "",
},
}
for _, test := range tests {
t.Run(strings.Join(test.ports, ","), func(t *testing.T) {
gotError := ""
got := validatePorts(test.ports)
if got != nil {
gotError = got.Error()
}
if gotError != test.errorMsg {
t.Errorf("validatePorts(ports=%v): got %v, expected %v", test.ports, got, test.errorMsg)
}
})
}
}
3 changes: 1 addition & 2 deletions translations/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -347,7 +347,6 @@
"Insecure Docker registries to pass to the Docker daemon. The default service CIDR range will automatically be added.": "Unsichere Docker-Registrys, die an den Docker-Daemon übergeben werden. Der CIDR-Bereich des Standarddienstes wird automatisch hinzugefügt.",
"Install VirtualBox and ensure it is in the path, or select an alternative value for --driver": "",
"Install the latest hyperkit binary, and run 'minikube delete'": "",
"Invalid Container Runtime: \"{{.runtime}}\". Valid runtimes are: {{.validOptions}}": "",
"Invalid port": "",
"Istio needs {{.minCPUs}} CPUs -- your configuration only allocates {{.cpus}} CPUs": "",
"Istio needs {{.minMem}}MB of memory -- your configuration only allocates {{.memory}}MB": "",
Expand Down Expand Up @@ -798,7 +797,6 @@
"VM driver is one of: %v": "VM-Treiber ist einer von: %v",
"Valid components are: {{.valid_extra_opts}}": "",
"Validate your KVM networks. Run: virt-host-validate and then virsh net-list --all": "",
"Validation unable to parse disk size '{{.diskSize}}': {{.error}}": "",
"Verify that your HTTP_PROXY and HTTPS_PROXY environment variables are set correctly.": "",
"Verifying Kubernetes components...": "",
"Verifying dashboard health ...": "",
Expand Down Expand Up @@ -961,6 +959,7 @@
"{{.driver_name}} has less than 2 CPUs available, but Kubernetes requires at least 2 to be available": "",
"{{.driver_name}} has only {{.container_limit}}MB memory but you specified {{.specified_memory}}MB": "",
"{{.driver}} only has {{.size}}MiB available, less than the required {{.req}}MiB for Kubernetes": "",
"{{.err}}": "",
"{{.extra_option_component_name}}.{{.key}}={{.value}}": "",
"{{.name}} doesn't have images.": "",
"{{.name}} has following images:": "",
Expand Down
3 changes: 1 addition & 2 deletions translations/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,6 @@
"Insecure Docker registries to pass to the Docker daemon. The default service CIDR range will automatically be added.": "Registros de Docker que no son seguros y que se transferirán al daemon de Docker. Se añadirá automáticamente el intervalo CIDR de servicio predeterminado.",
"Install VirtualBox and ensure it is in the path, or select an alternative value for --driver": "",
"Install the latest hyperkit binary, and run 'minikube delete'": "",
"Invalid Container Runtime: \"{{.runtime}}\". Valid runtimes are: {{.validOptions}}": "",
"Invalid port": "",
"Istio needs {{.minCPUs}} CPUs -- your configuration only allocates {{.cpus}} CPUs": "",
"Istio needs {{.minMem}}MB of memory -- your configuration only allocates {{.memory}}MB": "",
Expand Down Expand Up @@ -804,7 +803,6 @@
"VM driver is one of: %v": "El controlador de la VM es uno de los siguientes: %v",
"Valid components are: {{.valid_extra_opts}}": "",
"Validate your KVM networks. Run: virt-host-validate and then virsh net-list --all": "",
"Validation unable to parse disk size '{{.diskSize}}': {{.error}}": "",
"Verify that your HTTP_PROXY and HTTPS_PROXY environment variables are set correctly.": "",
"Verifying Kubernetes components...": "",
"Verifying dashboard health ...": "",
Expand Down Expand Up @@ -967,6 +965,7 @@
"{{.driver_name}} has less than 2 CPUs available, but Kubernetes requires at least 2 to be available": "",
"{{.driver_name}} has only {{.container_limit}}MB memory but you specified {{.specified_memory}}MB": "",
"{{.driver}} only has {{.size}}MiB available, less than the required {{.req}}MiB for Kubernetes": "",
"{{.err}}": "",
"{{.extra_option_component_name}}.{{.key}}={{.value}}": "",
"{{.name}} doesn't have images.": "",
"{{.name}} has following images:": "",
Expand Down
1 change: 1 addition & 0 deletions translations/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -978,6 +978,7 @@
"{{.driver_name}} has less than 2 CPUs available, but Kubernetes requires at least 2 to be available": "{{.driver_name}} dispose de moins de 2 processeurs disponibles, mais Kubernetes nécessite au moins 2 procésseurs pour fonctionner",
"{{.driver_name}} has only {{.container_limit}}MB memory but you specified {{.specified_memory}}MB": "{{.driver_name}} ne dispose que de {{.container_limit}}Mo de mémoire, mais vous avez spécifié {{.specified_memory}}Mo",
"{{.driver}} only has {{.size}}MiB available, less than the required {{.req}}MiB for Kubernetes": "{{.driver}} ne dispose que de {{.size}}Mio disponible, moins que les {{.req}}Mio requis pour Kubernetes",
"{{.err}}": "",
"{{.extra_option_component_name}}.{{.key}}={{.value}}": "{{.extra_option_component_name}}.{{.key}}={{.value}}",
"{{.name}} doesn't have images.": "{{.name}} n'a pas d'images.",
"{{.name}} has following images:": "{{.name}} a les images suivantes :",
Expand Down
2 changes: 1 addition & 1 deletion translations/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -338,7 +338,6 @@
"Insecure Docker registries to pass to the Docker daemon. The default service CIDR range will automatically be added.": "Docker デーモンに渡す Docker レジストリが安全ではありません。デフォルトのサービス CIDR 範囲が自動的に追加されます",
"Install VirtualBox and ensure it is in the path, or select an alternative value for --driver": "",
"Install the latest hyperkit binary, and run 'minikube delete'": "",
"Invalid Container Runtime: \"{{.runtime}}\". Valid runtimes are: {{.validOptions}}": "",
"Invalid port": "",
"Istio needs {{.minCPUs}} CPUs -- your configuration only allocates {{.cpus}} CPUs": "",
"Istio needs {{.minMem}}MB of memory -- your configuration only allocates {{.memory}}MB": "",
Expand Down Expand Up @@ -983,6 +982,7 @@
"{{.driver}} does not appear to be installed": "{{.driver}} がインストールされていないようです",
"{{.driver}} does not appear to be installed, but is specified by an existing profile. Please run 'minikube delete' or install {{.driver}}": "{{.driver}} がインストールされていないようですが、既存のプロフィールから指定されています。「 minikube delete 」を実行、あるいは {{.driver}} をインストールしてください",
"{{.driver}} only has {{.size}}MiB available, less than the required {{.req}}MiB for Kubernetes": "",
"{{.err}}": "",
"{{.extra_option_component_name}}.{{.key}}={{.value}}": "{{.extra_option_component_name}}.{{.key}}={{.value}}",
"{{.name}} doesn't have images.": "",
"{{.name}} has following images:": "",
Expand Down
3 changes: 1 addition & 2 deletions translations/ko.json
Original file line number Diff line number Diff line change
Expand Up @@ -369,7 +369,6 @@
"Insecure Docker registries to pass to the Docker daemon. The default service CIDR range will automatically be added.": "",
"Install VirtualBox and ensure it is in the path, or select an alternative value for --driver": "",
"Install the latest hyperkit binary, and run 'minikube delete'": "",
"Invalid Container Runtime: \"{{.runtime}}\". Valid runtimes are: {{.validOptions}}": "",
"Invalid port": "",
"Istio needs {{.minCPUs}} CPUs -- your configuration only allocates {{.cpus}} CPUs": "",
"Istio needs {{.minMem}}MB of memory -- your configuration only allocates {{.memory}}MB": "",
Expand Down Expand Up @@ -804,7 +803,6 @@
"Using the {{.driver}} driver based on user configuration": "유저 환경 설정 정보에 기반하여 {{.driver}} 드라이버를 사용하는 중",
"Valid components are: {{.valid_extra_opts}}": "",
"Validate your KVM networks. Run: virt-host-validate and then virsh net-list --all": "",
"Validation unable to parse disk size '{{.diskSize}}': {{.error}}": "",
"Verify that your HTTP_PROXY and HTTPS_PROXY environment variables are set correctly.": "",
"Verifying Kubernetes components...": "Kubernetes 구성 요소를 확인...",
"Verifying dashboard health ...": "",
Expand Down Expand Up @@ -978,6 +976,7 @@
"{{.driver_name}} has only {{.container_limit}}MB memory but you specified {{.specified_memory}}MB": "",
"{{.driver}} does not appear to be installed": "{{.driver}} 가 설치되지 않았습니다",
"{{.driver}} only has {{.size}}MiB available, less than the required {{.req}}MiB for Kubernetes": "",
"{{.err}}": "",
"{{.extra_option_component_name}}.{{.key}}={{.value}}": "",
"{{.name}} cluster does not exist": "{{.name}} 클러스터가 존재하지 않습니다",
"{{.name}} doesn't have images.": "{{.name}} 이미지가 없습니다.",
Expand Down
3 changes: 1 addition & 2 deletions translations/pl.json
Original file line number Diff line number Diff line change
Expand Up @@ -356,7 +356,6 @@
"Insecure Docker registries to pass to the Docker daemon. The default service CIDR range will automatically be added.": "",
"Install VirtualBox and ensure it is in the path, or select an alternative value for --driver": "",
"Install the latest hyperkit binary, and run 'minikube delete'": "",
"Invalid Container Runtime: \"{{.runtime}}\". Valid runtimes are: {{.validOptions}}": "",
"Invalid port": "",
"Invalid size passed in argument: {{.error}}": "Nieprawidłowy rozmiar przekazany w argumencie: {{.error}}",
"Istio needs {{.minCPUs}} CPUs -- your configuration only allocates {{.cpus}} CPUs": "",
Expand Down Expand Up @@ -813,7 +812,6 @@
"VM driver is one of: %v": "Sterownik wirtualnej maszyny to jeden z: %v",
"Valid components are: {{.valid_extra_opts}}": "",
"Validate your KVM networks. Run: virt-host-validate and then virsh net-list --all": "",
"Validation unable to parse disk size '{{.diskSize}}': {{.error}}": "",
"Verify that your HTTP_PROXY and HTTPS_PROXY environment variables are set correctly.": "Zweryfikuj czy zmienne HTTP_PROXY i HTTPS_PROXY są ustawione poprawnie",
"Verify the IP address of the running cluster in kubeconfig.": "Weryfikacja adresu IP działającego klastra w kubeconfig",
"Verifying Kubernetes components...": "",
Expand Down Expand Up @@ -981,6 +979,7 @@
"{{.driver_name}} has less than 2 CPUs available, but Kubernetes requires at least 2 to be available": "",
"{{.driver_name}} has only {{.container_limit}}MB memory but you specified {{.specified_memory}}MB": "",
"{{.driver}} only has {{.size}}MiB available, less than the required {{.req}}MiB for Kubernetes": "sterownik {{.driver}} ma tylko {{.size}}MiB dostępnej przestrzeni dyskowej, to mniej niż wymagane {{.req}}MiB dla Kubernetesa",
"{{.err}}": "",
"{{.extra_option_component_name}}.{{.key}}={{.value}}": "",
"{{.name}} cluster does not exist": "Klaster {{.name}} nie istnieje",
"{{.name}} doesn't have images.": "{{.name}} nie ma obrazów.",
Expand Down
3 changes: 1 addition & 2 deletions translations/strings.txt
Original file line number Diff line number Diff line change
Expand Up @@ -326,7 +326,6 @@
"Insecure Docker registries to pass to the Docker daemon. The default service CIDR range will automatically be added.": "",
"Install VirtualBox and ensure it is in the path, or select an alternative value for --driver": "",
"Install the latest hyperkit binary, and run 'minikube delete'": "",
"Invalid Container Runtime: \"{{.runtime}}\". Valid runtimes are: {{.validOptions}}": "",
"Invalid port": "",
"Istio needs {{.minCPUs}} CPUs -- your configuration only allocates {{.cpus}} CPUs": "",
"Istio needs {{.minMem}}MB of memory -- your configuration only allocates {{.memory}}MB": "",
Expand Down Expand Up @@ -745,7 +744,6 @@
"Using the {{.driver}} driver based on user configuration": "",
"Valid components are: {{.valid_extra_opts}}": "",
"Validate your KVM networks. Run: virt-host-validate and then virsh net-list --all": "",
"Validation unable to parse disk size '{{.diskSize}}': {{.error}}": "",
"Verify that your HTTP_PROXY and HTTPS_PROXY environment variables are set correctly.": "",
"Verifying Kubernetes components...": "",
"Verifying dashboard health ...": "",
Expand Down Expand Up @@ -906,6 +904,7 @@
"{{.driver_name}} has less than 2 CPUs available, but Kubernetes requires at least 2 to be available": "",
"{{.driver_name}} has only {{.container_limit}}MB memory but you specified {{.specified_memory}}MB": "",
"{{.driver}} only has {{.size}}MiB available, less than the required {{.req}}MiB for Kubernetes": "",
"{{.err}}": "",
"{{.extra_option_component_name}}.{{.key}}={{.value}}": "",
"{{.name}} doesn't have images.": "",
"{{.name}} has following images:": "",
Expand Down
Loading

0 comments on commit f85e7db

Please sign in to comment.