diff --git a/cmd/minikube/cmd/start.go b/cmd/minikube/cmd/start.go index d51fec280a..a5546e0aae 100644 --- a/cmd/minikube/cmd/start.go +++ b/cmd/minikube/cmd/start.go @@ -1118,6 +1118,14 @@ func validateFlags(cmd *cobra.Command, drvName string) { viper.Set(imageRepository, validateImageRepository(viper.GetString(imageRepository))) } + if cmd.Flags().Changed(ports) { + err := validatePorts(viper.GetStringSlice(ports)) + if err != nil { + exit.Message(reason.Usage, "{{.err}}", out.V{"err": err}) + } + + } + if cmd.Flags().Changed(containerRuntime) { runtime := strings.ToLower(viper.GetString(containerRuntime)) @@ -1314,6 +1322,25 @@ func validateListenAddress(listenAddr string) { } } +// 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 +} + // This function validates that the --insecure-registry follows one of the following formats: // "[:]" "[:]" "/" func validateInsecureRegistry() { diff --git a/cmd/minikube/cmd/start_test.go b/cmd/minikube/cmd/start_test.go index 30b91b5a30..8ed305cdfe 100644 --- a/cmd/minikube/cmd/start_test.go +++ b/cmd/minikube/cmd/start_test.go @@ -363,3 +363,39 @@ func TestValidateImageRepository(t *testing.T) { } } + +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) + } + }) + } +}