From e976c14cbef4b920100a678e7a284c14cd844ef5 Mon Sep 17 00:00:00 2001 From: dovholuknf <46322585+dovholuknf@users.noreply.github.com> Date: Wed, 5 Jul 2023 16:58:40 -0400 Subject: [PATCH] further refinements to tests and alt server certs --- quickstart/docker/docker-compose.yml | 2 + ziti/cmd/create_config.go | 67 ++++-------- ziti/cmd/create_config_controller.go | 104 ++++++++++--------- ziti/cmd/create_config_controller_test.go | 73 +++++++------ ziti/cmd/create_config_environment.go | 2 +- ziti/cmd/create_config_router.go | 70 +++++++------ ziti/cmd/create_config_router_edge.go | 3 +- ziti/cmd/create_config_router_edge_test.go | 78 +++++++------- ziti/cmd/create_config_router_fabric.go | 2 + ziti/cmd/create_config_router_fabric_test.go | 40 ++++--- ziti/cmd/create_config_router_test.go | 34 ++---- ziti/cmd/helpers/env_helpers.go | 18 ++-- ziti/cmd/helpers/helpers_test.go | 12 +-- ziti/constants/constants.go | 2 + 14 files changed, 248 insertions(+), 259 deletions(-) diff --git a/quickstart/docker/docker-compose.yml b/quickstart/docker/docker-compose.yml index 79841cdc2..83acf6063 100644 --- a/quickstart/docker/docker-compose.yml +++ b/quickstart/docker/docker-compose.yml @@ -98,6 +98,8 @@ services: - ZITI_EDGE_ROUTER_PORT=${ZITI_EDGE_ROUTER_WSS_PORT:-3023} - ZITI_EDGE_ROUTER_LISTENER_BIND_PORT=${ZITI_EDGE_ROUTER_LISTENER_BIND_PORT:-10081} - ZITI_EDGE_ROUTER_ROLES=public + - ZITI_PKI_ALT_SERVER_CERT=${ZITI_PKI_ALT_SERVER_CERT:-} + - ZITI_PKI_ALT_SERVER_KEY=${ZITI_PKI_ALT_SERVER_KEY:-} networks: - zitiblue - zitired diff --git a/ziti/cmd/create_config.go b/ziti/cmd/create_config.go index abe80c2f6..bbcd73537 100644 --- a/ziti/cmd/create_config.go +++ b/ziti/cmd/create_config.go @@ -71,6 +71,7 @@ type CtrlValues struct { AdvertisedAddress string AdvertisedPort string BindAddress string + AltAdvertisedAddress string } type HealthChecksValues struct { @@ -190,7 +191,6 @@ type RouterListenerTemplateValues struct { } var workingDir string -var data = &ConfigTemplateValues{} func init() { workingDir, _ = cmdHelper.GetZitiHome() @@ -207,8 +207,9 @@ func NewCmdCreateConfig() *cobra.Command { }, } - cmd.AddCommand(NewCmdCreateConfigController()) - cmd.AddCommand(NewCmdCreateConfigRouter()) + opts := &CreateConfigRouterOptions{} + cmd.AddCommand(NewCmdCreateConfigController().Command) + cmd.AddCommand(NewCmdCreateConfigRouter(opts).Command) cmd.AddCommand(NewCmdCreateConfigEnvironment()) return cmd @@ -230,39 +231,6 @@ func (data *ConfigTemplateValues) populateConfigValues() { zitiHome, err := cmdHelper.GetZitiHome() handleVariableError(err, constants.ZitiHomeVarName) - // Get Ziti Controller Advertised Address - zitiCtrlAdvertisedAddress := cmdHelper.GetCtrlAdvertisedAddress() - - // Get Ziti Controller ctrl:listener address and port - ctrlBindAddress := cmdHelper.GetCtrlBindAddress() - ctrlAdvertisedPort := cmdHelper.GetCtrlAdvertisedPort() - - // Get Ziti Controller edge:api address and port - ctrlEdgeApiAddress := cmdHelper.GetCtrlEdgeAdvertisedAddress() - ctrlEdgeApiPort := cmdHelper.GetCtrlEdgeAdvertisedPort() - - // Get Ziti Controller Identity edge:enrollment duration - ctrlEdgeIdentityEnrollmentDuration, err := cmdHelper.GetCtrlEdgeIdentityEnrollmentDuration() - handleVariableError(err, constants.CtrlEdgeIdentityEnrollmentDurationVarName) - - // Get Ziti Controller Router edge:enrollment enrollment duration - ctrlEdgeRouterEnrollmentDuration, err := cmdHelper.GetCtrlEdgeRouterEnrollmentDuration() - handleVariableError(err, constants.CtrlEdgeRouterEnrollmentDurationVarName) - - // Get Ziti Controller web:bindPoints interface address and port - ctrlEdgeInterfaceAddress := cmdHelper.GetCtrlEdgeBindAddress() - ctrlEdgeInterfacePort := cmdHelper.GetCtrlEdgeAdvertisedPort() - - // Get Ziti Controller web:bindPoints address address and port - ctrlEdgeAdvertisedAddress := cmdHelper.GetCtrlEdgeAdvertisedAddress() - ctrlEdgeAdvertisedPort := cmdHelper.GetCtrlEdgeAdvertisedPort() - - // Get Ziti Edge Router Port - zitiEdgeRouterPort := cmdHelper.GetZitiEdgeRouterPort() - - zitiEdgeRouterListenerBindPort := cmdHelper.GetZitiEdgeRouterListenerBindPort() - handleVariableError(err, constants.ZitiEdgeRouterListenerBindPortVarName) - data.ZitiHome = zitiHome data.Hostname = hostname // ************* Controller Values ************ @@ -277,9 +245,10 @@ func (data *ConfigTemplateValues) populateConfigValues() { data.Controller.Ctrl.MinConnectTimeout = channel.MinConnectTimeout data.Controller.Ctrl.MaxConnectTimeout = channel.MaxConnectTimeout data.Controller.Ctrl.DefaultConnectTimeout = channel.DefaultConnectTimeout - data.Controller.Ctrl.AdvertisedAddress = zitiCtrlAdvertisedAddress - data.Controller.Ctrl.BindAddress = ctrlBindAddress - data.Controller.Ctrl.AdvertisedPort = ctrlAdvertisedPort + data.Controller.Ctrl.AdvertisedAddress = cmdHelper.GetCtrlAdvertisedAddress() + data.Controller.Ctrl.AltAdvertisedAddress = cmdHelper.GetCtrlEdgeAltAdvertisedAddress() + data.Controller.Ctrl.BindAddress = cmdHelper.GetCtrlBindAddress() + data.Controller.Ctrl.AdvertisedPort = cmdHelper.GetCtrlAdvertisedPort() // healthChecks: data.Controller.HealthChecks.Interval = fabCtrl.DefaultHealthChecksBoltCheckInterval data.Controller.HealthChecks.Timeout = fabCtrl.DefaultHealthChecksBoltCheckTimeout @@ -288,17 +257,17 @@ func (data *ConfigTemplateValues) populateConfigValues() { data.Controller.EdgeApi.APIActivityUpdateBatchSize = edge.DefaultEdgeApiActivityUpdateBatchSize data.Controller.EdgeApi.APIActivityUpdateInterval = edge.DefaultEdgeAPIActivityUpdateInterval data.Controller.EdgeApi.SessionTimeout = edge.DefaultEdgeSessionTimeout - data.Controller.EdgeApi.Address = ctrlEdgeApiAddress - data.Controller.EdgeApi.Port = ctrlEdgeApiPort - data.Controller.EdgeEnrollment.EdgeIdentityDuration = ctrlEdgeIdentityEnrollmentDuration - data.Controller.EdgeEnrollment.EdgeRouterDuration = ctrlEdgeRouterEnrollmentDuration + data.Controller.EdgeApi.Address = cmdHelper.GetCtrlEdgeAdvertisedAddress() + data.Controller.EdgeApi.Port = cmdHelper.GetCtrlEdgeAdvertisedPort() + data.Controller.EdgeEnrollment.EdgeIdentityDuration = cmdHelper.GetCtrlEdgeIdentityEnrollmentDuration() + data.Controller.EdgeEnrollment.EdgeRouterDuration = cmdHelper.GetCtrlEdgeRouterEnrollmentDuration() data.Controller.EdgeEnrollment.DefaultEdgeIdentityDuration = edge.DefaultEdgeEnrollmentDuration data.Controller.EdgeEnrollment.DefaultEdgeRouterDuration = edge.DefaultEdgeEnrollmentDuration // web: - data.Controller.Web.BindPoints.InterfaceAddress = ctrlEdgeInterfaceAddress - data.Controller.Web.BindPoints.InterfacePort = ctrlEdgeInterfacePort - data.Controller.Web.BindPoints.AddressAddress = ctrlEdgeAdvertisedAddress - data.Controller.Web.BindPoints.AddressPort = ctrlEdgeAdvertisedPort + data.Controller.Web.BindPoints.InterfaceAddress = cmdHelper.GetCtrlEdgeBindAddress() + data.Controller.Web.BindPoints.InterfacePort = cmdHelper.GetCtrlEdgeAdvertisedPort() + data.Controller.Web.BindPoints.AddressAddress = cmdHelper.GetCtrlEdgeAltAdvertisedAddress() + data.Controller.Web.BindPoints.AddressPort = cmdHelper.GetCtrlEdgeAdvertisedPort() // Web Identities are handled in create_config_controller data.Controller.Web.Options.IdleTimeout = edge.DefaultHttpIdleTimeout data.Controller.Web.Options.ReadTimeout = edge.DefaultHttpReadTimeout @@ -307,8 +276,8 @@ func (data *ConfigTemplateValues) populateConfigValues() { data.Controller.Web.Options.MaxTLSVersion = fabXweb.ReverseTlsVersionMap[fabXweb.MaxTLSVersion] // ************* Router Values ************ - data.Router.Edge.Port = zitiEdgeRouterPort - data.Router.Edge.ListenerBindPort = zitiEdgeRouterListenerBindPort + data.Router.Edge.Port = cmdHelper.GetZitiEdgeRouterPort() + data.Router.Edge.ListenerBindPort = cmdHelper.GetZitiEdgeRouterListenerBindPort() data.Router.Listener.GetSessionTimeout = constants.DefaultGetSessionTimeout data.Router.Wss.WriteTimeout = foundation.DefaultWsWriteTimeout diff --git a/ziti/cmd/create_config_controller.go b/ziti/cmd/create_config_controller.go index 8082f52af..85789975a 100644 --- a/ziti/cmd/create_config_controller.go +++ b/ziti/cmd/create_config_controller.go @@ -76,63 +76,71 @@ type CreateConfigControllerOptions struct { EdgeRouterEnrollmentDuration time.Duration } +type CreateControllerConfigCmd struct { + *cobra.Command + ConfigData *ConfigTemplateValues +} + // NewCmdCreateConfigController creates a command object for the "create" command -func NewCmdCreateConfigController() *cobra.Command { +func NewCmdCreateConfigController() *CreateControllerConfigCmd { controllerOptions := &CreateConfigControllerOptions{} - - cmd := &cobra.Command{ - Use: "controller", - Short: "Create a controller config", - Aliases: []string{"ctrl"}, - Long: createConfigControllerLong, - Example: createConfigControllerExample, - PreRun: func(cmd *cobra.Command, args []string) { - // Setup logging - var logOut *os.File - if controllerOptions.Verbose { - logrus.SetLevel(logrus.DebugLevel) - // Only print log to stdout if not printing config to stdout - if strings.ToLower(controllerOptions.Output) != "stdout" { - logOut = os.Stdout - } else { - logOut = os.Stderr + data := &ConfigTemplateValues{} + cmd := &CreateControllerConfigCmd{ + ConfigData: data, + Command: &cobra.Command{ + Use: "controller", + Short: "Create a controller config", + Aliases: []string{"ctrl"}, + Long: createConfigControllerLong, + Example: createConfigControllerExample, + PreRun: func(cmd *cobra.Command, args []string) { + // Setup logging + var logOut *os.File + if controllerOptions.Verbose { + logrus.SetLevel(logrus.DebugLevel) + // Only print log to stdout if not printing config to stdout + if strings.ToLower(controllerOptions.Output) != "stdout" { + logOut = os.Stdout + } else { + logOut = os.Stderr + } + logrus.SetOutput(logOut) } - logrus.SetOutput(logOut) - } - data.populateConfigValues() + data.populateConfigValues() - // Update controller specific values with configOptions passed in if the argument was provided or the value is currently blank - if data.Controller.Ctrl.AdvertisedPort == "" || controllerOptions.CtrlPort != constants.DefaultCtrlAdvertisedPort { - data.Controller.Ctrl.AdvertisedPort = controllerOptions.CtrlPort - } - // Update with the passed in arg if it's not the default (CLI flag should override other methods of modifying these values) - if controllerOptions.EdgeIdentityEnrollmentDuration != edge.DefaultEdgeEnrollmentDuration { - data.Controller.EdgeEnrollment.EdgeIdentityDuration = controllerOptions.EdgeIdentityEnrollmentDuration - } - if controllerOptions.EdgeRouterEnrollmentDuration != edge.DefaultEdgeEnrollmentDuration { - data.Controller.EdgeEnrollment.EdgeRouterDuration = controllerOptions.EdgeRouterEnrollmentDuration - } + // Update controller specific values with configOptions passed in if the argument was provided or the value is currently blank + if data.Controller.Ctrl.AdvertisedPort == "" || controllerOptions.CtrlPort != constants.DefaultCtrlAdvertisedPort { + data.Controller.Ctrl.AdvertisedPort = controllerOptions.CtrlPort + } + // Update with the passed in arg if it's not the default (CLI flag should override other methods of modifying these values) + if controllerOptions.EdgeIdentityEnrollmentDuration != edge.DefaultEdgeEnrollmentDuration { + data.Controller.EdgeEnrollment.EdgeIdentityDuration = controllerOptions.EdgeIdentityEnrollmentDuration + } + if controllerOptions.EdgeRouterEnrollmentDuration != edge.DefaultEdgeEnrollmentDuration { + data.Controller.EdgeEnrollment.EdgeRouterDuration = controllerOptions.EdgeRouterEnrollmentDuration + } - // process identity information - SetControllerIdentity(&data.Controller) - SetEdgeConfig(&data.Controller) - SetWebConfig(&data.Controller) + // process identity information + SetControllerIdentity(&data.Controller) + SetEdgeConfig(&data.Controller) + SetWebConfig(&data.Controller) - }, - Run: func(cmd *cobra.Command, args []string) { - controllerOptions.Cmd = cmd - controllerOptions.Args = args - err := controllerOptions.run(data) - helpers2.CheckErr(err) - }, - PostRun: func(cmd *cobra.Command, args []string) { - // Reset log output after run completes - logrus.SetOutput(os.Stdout) + }, + Run: func(cmd *cobra.Command, args []string) { + controllerOptions.Cmd = cmd + controllerOptions.Args = args + err := controllerOptions.run(data) + helpers2.CheckErr(err) + }, + PostRun: func(cmd *cobra.Command, args []string) { + // Reset log output after run completes + logrus.SetOutput(os.Stdout) + }, }, } - controllerOptions.addCreateFlags(cmd) - controllerOptions.addFlags(cmd) + controllerOptions.addCreateFlags(cmd.Command) + controllerOptions.addFlags(cmd.Command) return cmd } diff --git a/ziti/cmd/create_config_controller_test.go b/ziti/cmd/create_config_controller_test.go index fe43b4d4d..34cbfdd9f 100644 --- a/ziti/cmd/create_config_controller_test.go +++ b/ziti/cmd/create_config_controller_test.go @@ -104,8 +104,11 @@ type ApiOptions struct { } /* END Controller config template structure */ +var hostname string -var controllerOptions = CreateConfigControllerOptions{} +func init() { + hostname, _ = os.Hostname() +} func TestControllerOutputPathDoesNotExist(t *testing.T) { expectedErrorMsg := "stat /IDoNotExist: no such file or directory" @@ -123,7 +126,7 @@ func TestCreateConfigControllerTemplateValues(t *testing.T) { // Create and run the CLI command (capture output, otherwise config prints to stdout instead of test results) // This must run first, otherwise the addresses used later won't be correct; this command re-allocates the `data` struct - _ = execCreateConfigControllerCommand(nil, nil) + _, data := execCreateConfigControllerCommand(nil, nil) expectedNonEmptyStringFields := []string{ ".ZitiHome", @@ -243,10 +246,7 @@ func TestCreateConfigControllerTemplateValues(t *testing.T) { } func TestCtrlConfigDefaultsWhenUnset(t *testing.T) { - // Clears template data and unsets all env vars - clearControllerOptionsAndTemplateData() - - ctrlConfig := execCreateConfigControllerCommand(nil, nil) + ctrlConfig, data := execCreateConfigControllerCommand(nil, nil) // identity: t.Run("TestPKICert", func(t *testing.T) { @@ -446,7 +446,7 @@ func TestCtrlConfigDefaultsWhenBlank(t *testing.T) { "ZITI_HOME": "", } // run the config - ctrlConfig := execCreateConfigControllerCommand(nil, keys) + ctrlConfig, data := execCreateConfigControllerCommand(nil, keys) // identity: t.Run("TestPKICert", func(t *testing.T) { @@ -651,7 +651,7 @@ func TestZitiCtrlIdentitySection(t *testing.T) { "ZITI_PKI_CTRL_CA": caPath, } - ctrlConfig := execCreateConfigControllerCommand(nil, keys) + ctrlConfig, data := execCreateConfigControllerCommand(nil, keys) assert.Equal(t, certPath, data.Controller.Identity.Cert) assert.Equal(t, certPath, ctrlConfig.Identity.Cert) @@ -669,7 +669,7 @@ func TestCtrlBindAddress(t *testing.T) { "ZITI_CTRL_BIND_ADDRESS": customValue, } - ctrlConfig := execCreateConfigControllerCommand(nil, keys) + ctrlConfig, data := execCreateConfigControllerCommand(nil, keys) assert.Equal(t, customValue, data.Controller.Ctrl.BindAddress) assert.Equal(t, customValue, strings.Split(ctrlConfig.Ctrl.Listener, ":")[1]) @@ -681,7 +681,7 @@ func TestCtrlAdvertisedPort(t *testing.T) { "ZITI_CTRL_ADVERTISED_PORT": customValue, } - ctrlConfig := execCreateConfigControllerCommand(nil, keys) + ctrlConfig, data := execCreateConfigControllerCommand(nil, keys) assert.Equal(t, customValue, data.Controller.Ctrl.AdvertisedPort) assert.Equal(t, customValue, strings.Split(ctrlConfig.Ctrl.Listener, ":")[2]) @@ -693,7 +693,7 @@ func TestCtrlEdgeAPIAddress(t *testing.T) { "ZITI_CTRL_EDGE_ADVERTISED_ADDRESS": customValue, } - ctrlConfig := execCreateConfigControllerCommand(nil, keys) + ctrlConfig, data := execCreateConfigControllerCommand(nil, keys) assert.Equal(t, customValue, data.Controller.EdgeApi.Address) assert.Equal(t, customValue, strings.Split(ctrlConfig.Edge.Api.Address, ":")[0]) @@ -705,7 +705,7 @@ func TestCtrlEdgeAPIPort(t *testing.T) { "ZITI_CTRL_EDGE_ADVERTISED_PORT": customValue, } - ctrlConfig := execCreateConfigControllerCommand(nil, keys) + ctrlConfig, data := execCreateConfigControllerCommand(nil, keys) assert.Equal(t, customValue, data.Controller.EdgeApi.Port) assert.Equal(t, customValue, strings.Split(ctrlConfig.Edge.Api.Address, ":")[1]) @@ -719,7 +719,7 @@ func TestCtrlEdgeAPIEnrollmentSignerCert(t *testing.T) { "ZITI_PKI_SIGNER_KEY": keyPath, } - ctrlConfig := execCreateConfigControllerCommand(nil, keys) + ctrlConfig, data := execCreateConfigControllerCommand(nil, keys) assert.Equal(t, certPath, data.Controller.EdgeEnrollment.SigningCert) assert.Equal(t, certPath, ctrlConfig.Edge.Enrollment.SigningCert.Cert) @@ -735,7 +735,7 @@ func TestEdgeIdentityEnrollmentDurationEnvVar(t *testing.T) { "ZITI_EDGE_IDENTITY_ENROLLMENT_DURATION": customValue, } - ctrlConfig := execCreateConfigControllerCommand(nil, keys) + ctrlConfig, data := execCreateConfigControllerCommand(nil, keys) assert.Equal(t, customDuration, data.Controller.EdgeEnrollment.EdgeIdentityDuration) assert.Equal(t, expectedValue, ctrlConfig.Edge.Enrollment.EdgeIdentity.Duration) @@ -750,7 +750,7 @@ func TestEdgeIdentityEnrollmentDurationCLITakesPriority(t *testing.T) { } args := []string{"--identityEnrollmentDuration", cliValue} - ctrlConfig := execCreateConfigControllerCommand(args, keys) + ctrlConfig, data := execCreateConfigControllerCommand(args, keys) // Expect that the CLI value was used over the environment variable expectedValue, _ := time.ParseDuration(cliValue) @@ -765,7 +765,7 @@ func TestEdgeIdentityEnrollmentDurationCLIConvertsToMin(t *testing.T) { expectedConfigValue := "60m" // Config value representation should be in minutes args := []string{"--identityEnrollmentDuration", cliValue} - ctrlConfig := execCreateConfigControllerCommand(args, nil) + ctrlConfig, data := execCreateConfigControllerCommand(args, nil) // Expect that the CLI value was used over the environment variable expectedValue, _ := time.ParseDuration(cliValue) @@ -783,7 +783,7 @@ func TestEdgeRouterEnrollmentDurationEnvVar(t *testing.T) { "ZITI_EDGE_ROUTER_ENROLLMENT_DURATION": customValue, } - ctrlConfig := execCreateConfigControllerCommand(nil, keys) + ctrlConfig, data := execCreateConfigControllerCommand(nil, keys) assert.Equal(t, customDuration, data.Controller.EdgeEnrollment.EdgeRouterDuration) assert.Equal(t, expectedValue, ctrlConfig.Edge.Enrollment.EdgeRouter.Duration) @@ -798,7 +798,7 @@ func TestEdgeRouterEnrollmentDurationCLITakesPriority(t *testing.T) { } args := []string{"--routerEnrollmentDuration", cliValue} - ctrlConfig := execCreateConfigControllerCommand(args, keys) + ctrlConfig, data := execCreateConfigControllerCommand(args, keys) // Expect that the CLI value was used over the environment variable expectedValue, _ := time.ParseDuration(cliValue) @@ -813,7 +813,7 @@ func TestEdgeRouterEnrollmentDurationCLIConvertsToMin(t *testing.T) { expectedConfigValue := "60m" // Config value representation should be in minutes args := []string{"--routerEnrollmentDuration", cliValue} - ctrlConfig := execCreateConfigControllerCommand(args, nil) + ctrlConfig, data := execCreateConfigControllerCommand(args, nil) // Expect that the CLI value was used over the environment variable expectedValue, _ := time.ParseDuration(cliValue) @@ -831,7 +831,7 @@ func TestEdgeRouterAndIdentityEnrollmentDurationTogetherCLI(t *testing.T) { // Create and run the CLI command args := []string{"--routerEnrollmentDuration", cliRouterDurationValue, "--identityEnrollmentDuration", cliIdentityDurationValue} - configStruct := execCreateConfigControllerCommand(args, nil) + configStruct, _ := execCreateConfigControllerCommand(args, nil) // Expect that the config values are represented correctly assert.Equal(t, expectedIdentityConfigValue, configStruct.Edge.Enrollment.EdgeIdentity.Duration) @@ -849,7 +849,7 @@ func TestEdgeRouterAndIdentityEnrollmentDurationTogetherEnvVar(t *testing.T) { "ZITI_EDGE_IDENTITY_ENROLLMENT_DURATION": envVarIdentityDurationValue, "ZITI_EDGE_ROUTER_ENROLLMENT_DURATION": envVarRouterDurationValue, } - configStruct := execCreateConfigControllerCommand(nil, keys) + configStruct, _ := execCreateConfigControllerCommand(nil, keys) // Expect that the config values are represented correctly assert.Equal(t, expectedIdentityConfigValue, configStruct.Edge.Enrollment.EdgeIdentity.Duration) @@ -864,7 +864,7 @@ func TestCtrlEdgeInterfaceAddress(t *testing.T) { "ZITI_CTRL_EDGE_ADVERTISED_PORT": port, } - ctrlConfig := execCreateConfigControllerCommand(nil, keys) + ctrlConfig, data := execCreateConfigControllerCommand(nil, keys) assert.Equal(t, addy, data.Controller.Web.BindPoints.InterfaceAddress) assert.Equal(t, addy, strings.Split(ctrlConfig.Web[0].BindPoints[0].BpInterface, ":")[0]) @@ -877,7 +877,7 @@ func TestCtrlEdgeAdvertisedAddress(t *testing.T) { "ZITI_CTRL_EDGE_ADVERTISED_ADDRESS": customValue, } - ctrlConfig := execCreateConfigControllerCommand(nil, keys) + ctrlConfig, data := execCreateConfigControllerCommand(nil, keys) assert.Equal(t, customValue, data.Controller.Web.BindPoints.AddressAddress) assert.Equal(t, customValue, strings.Split(ctrlConfig.Web[0].BindPoints[0].Address, ":")[0]) @@ -889,7 +889,7 @@ func TestCtrlEdgeAdvertisedPort(t *testing.T) { "ZITI_CTRL_EDGE_ADVERTISED_PORT": customValue, } - ctrlConfig := execCreateConfigControllerCommand(nil, keys) + ctrlConfig, data := execCreateConfigControllerCommand(nil, keys) assert.Equal(t, customValue, data.Controller.Web.BindPoints.AddressPort) assert.Equal(t, customValue, strings.Split(ctrlConfig.Web[0].BindPoints[0].Address, ":")[1]) @@ -907,7 +907,7 @@ func TestCtrlEdgeIdentitySection(t *testing.T) { "ZITI_PKI_CTRL_CERT": certPath, } - ctrlConfig := execCreateConfigControllerCommand(nil, keys) + ctrlConfig, data := execCreateConfigControllerCommand(nil, keys) assert.Equal(t, certPath, data.Controller.Web.Identity.Cert) assert.Equal(t, certPath, ctrlConfig.Web[0].Identity.Cert) @@ -919,11 +919,19 @@ func TestCtrlEdgeIdentitySection(t *testing.T) { assert.Equal(t, caPath, ctrlConfig.Web[0].Identity.Ca) } -func clearControllerOptionsAndTemplateData() { - controllerOptions = CreateConfigControllerOptions{} - data = &ConfigTemplateValues{} +func TestCtrlEdgeAltAddress(t *testing.T) { + // first test when it's not set + ctrlConfig, data := execCreateConfigControllerCommand(nil, map[string]string{}) + assert.Equal(t, hostname, data.Controller.Ctrl.AltAdvertisedAddress) + assert.Equal(t, hostname+":"+testDefaultCtrlEdgeAdvertisedPort, ctrlConfig.Web[0].BindPoints[0].Address) - unsetZitiEnv() + altAddy := "alternative.address.ziti" + keys := map[string]string{ + "ZITI_CTRL_EDGE_ALT_CTRL_ADVERTISED_ADDRESS": altAddy, + } + ctrlConfig2, data2 := execCreateConfigControllerCommand(nil, keys) + assert.Equal(t, altAddy, data2.Controller.Ctrl.AltAdvertisedAddress) + assert.Equal(t, altAddy+":"+testDefaultCtrlEdgeAdvertisedPort, ctrlConfig2.Web[0].BindPoints[0].Address) } func configToStruct(config string) ControllerConfig { @@ -935,9 +943,10 @@ func configToStruct(config string) ControllerConfig { return configStruct } -func execCreateConfigControllerCommand(args []string, keys map[string]string) ControllerConfig { +func execCreateConfigControllerCommand(args []string, keys map[string]string) (ControllerConfig, *ConfigTemplateValues) { // Setup - clearControllerOptionsAndTemplateData() + clearEnvAndInitializeTestData() + controllerOptions := CreateConfigControllerOptions{} controllerOptions.Output = defaultOutput setEnvByMap(keys) @@ -948,5 +957,5 @@ func execCreateConfigControllerCommand(args []string, keys map[string]string) Co _ = cmd.Execute() }) - return configToStruct(configOutput) + return configToStruct(configOutput), cmd.ConfigData } diff --git a/ziti/cmd/create_config_environment.go b/ziti/cmd/create_config_environment.go index 021a5235c..7e223ed37 100644 --- a/ziti/cmd/create_config_environment.go +++ b/ziti/cmd/create_config_environment.go @@ -74,8 +74,8 @@ type CreateConfigEnvironmentOptions struct { // NewCmdCreateConfigEnvironment creates a command object for the "environment" command func NewCmdCreateConfigEnvironment() *cobra.Command { - environmentOptions = &CreateConfigEnvironmentOptions{} + data := &ConfigTemplateValues{} cmd := &cobra.Command{ Use: "environment", diff --git a/ziti/cmd/create_config_router.go b/ziti/cmd/create_config_router.go index 249d2dc51..90f911353 100644 --- a/ziti/cmd/create_config_router.go +++ b/ziti/cmd/create_config_router.go @@ -19,11 +19,10 @@ package cmd import ( _ "embed" cmdhelper "github.com/openziti/ziti/ziti/cmd/helpers" - "os" - "strings" - "github.com/sirupsen/logrus" "github.com/spf13/cobra" + "os" + "strings" ) const ( @@ -41,45 +40,54 @@ type CreateConfigRouterOptions struct { LanInterface string } -var routerOptions = CreateConfigRouterOptions{} +type NewCreateConfigRouterCmd struct { + *cobra.Command + RenderedValues *ConfigTemplateValues +} // NewCmdCreateConfigRouter creates a command object for the "router" command -func NewCmdCreateConfigRouter() *cobra.Command { - - cmd := &cobra.Command{ - Use: "router", - Short: "Creates a config file for specified Router name", - Aliases: []string{"rtr"}, - PersistentPreRun: func(cmd *cobra.Command, args []string) { - // Setup logging - var logOut *os.File - if routerOptions.Verbose { - logrus.SetLevel(logrus.DebugLevel) - // Only print log to stdout if not printing config to stdout - if strings.ToLower(routerOptions.Output) != "stdout" { - logOut = os.Stdout - } else { - logOut = os.Stderr +func NewCmdCreateConfigRouter(routerOptions *CreateConfigRouterOptions) *NewCreateConfigRouterCmd { + data := &ConfigTemplateValues{} + if routerOptions == nil { + routerOptions = &CreateConfigRouterOptions{} + } + cmd := &NewCreateConfigRouterCmd{ + Command: &cobra.Command{ + Use: "router", + Short: "Creates a config file for specified Router name", + Aliases: []string{"rtr"}, + PersistentPreRun: func(cmd *cobra.Command, args []string) { + // Setup logging + var logOut *os.File + if routerOptions.Verbose { + logrus.SetLevel(logrus.DebugLevel) + // Only print log to stdout if not printing config to stdout + if strings.ToLower(routerOptions.Output) != "stdout" { + logOut = os.Stdout + } else { + logOut = os.Stderr + } + logrus.SetOutput(logOut) } - logrus.SetOutput(logOut) - } - data.populateConfigValues() + data.populateConfigValues() - // Update router data with options passed in - data.Router.Name = validateRouterName(routerOptions.RouterName) - SetZitiRouterIdentity(&data.Router, data.Router.Name) - }, - Run: func(cmd *cobra.Command, args []string) { - cmdhelper.CheckErr(cmd.Help()) + // Update router data with options passed in + data.Router.Name = validateRouterName(routerOptions.RouterName) + SetZitiRouterIdentity(&data.Router, data.Router.Name) + }, + Run: func(cmd *cobra.Command, args []string) { + cmdhelper.CheckErr(cmd.Help()) + }, }, + RenderedValues: data, } cmd.AddCommand(NewCmdCreateConfigRouterEdge()) cmd.AddCommand(NewCmdCreateConfigRouterFabric()) - routerOptions.addCreateFlags(cmd) - routerOptions.addFlags(cmd) + routerOptions.addCreateFlags(cmd.Command) + routerOptions.addFlags(cmd.Command) return cmd } diff --git a/ziti/cmd/create_config_router_edge.go b/ziti/cmd/create_config_router_edge.go index ca66e5f77..e4ea190fa 100644 --- a/ziti/cmd/create_config_router_edge.go +++ b/ziti/cmd/create_config_router_edge.go @@ -64,7 +64,8 @@ var routerConfigEdgeTemplate string // NewCmdCreateConfigRouterEdge creates a command object for the "edge" command func NewCmdCreateConfigRouterEdge() *cobra.Command { - + data := &ConfigTemplateValues{} + routerOptions := &CreateConfigRouterOptions{} cmd := &cobra.Command{ Use: "edge", Short: "Create an edge router config", diff --git a/ziti/cmd/create_config_router_edge_test.go b/ziti/cmd/create_config_router_edge_test.go index 62368fc8d..d5ec38394 100644 --- a/ziti/cmd/create_config_router_edge_test.go +++ b/ziti/cmd/create_config_router_edge_test.go @@ -15,7 +15,8 @@ var defaultArgs = []string{"edge", "--routerName", "test-router"} var testHostname, _ = os.Hostname() func TestEdgeRouterAdvertisedAddress(t *testing.T) { - clearRouterOptionsAndTemplateData() + data := &ConfigTemplateValues{} + clearEnvAndInitializeTestData() routerAdvHostIp := "192.168.10.10" routerAdvHostDns := "controller01.zitinetwork.example.org" keys := map[string]string{ @@ -23,28 +24,28 @@ func TestEdgeRouterAdvertisedAddress(t *testing.T) { "ZITI_EDGE_ROUTER_PORT": "443", } // Defaults to hostname if nothing is set - execCreateConfigCommand(defaultArgs, keys) + createRouterConfig(defaultArgs, nil, keys) require.Equal(t, testHostname, data.Router.Edge.AdvertisedHost, nil) // If IP override set, uses that value over hostname keys["ZITI_EDGE_ROUTER_IP_OVERRIDE"] = routerAdvHostIp - execCreateConfigCommand(defaultArgs, keys) + createRouterConfig(defaultArgs, nil, keys) require.Equal(t, routerAdvHostIp, data.Router.Edge.AdvertisedHost, nil) // If advertised address set, uses that over IP override or hostname keys["ZITI_EDGE_ROUTER_ADVERTISED_HOST"] = routerAdvHostDns keys["ZITI_EDGE_ROUTER_IP_OVERRIDE"] = routerAdvHostIp - execCreateConfigCommand(defaultArgs, keys) + createRouterConfig(defaultArgs, nil, keys) require.Equal(t, routerAdvHostDns, data.Router.Edge.AdvertisedHost, nil) } func TestTunnelerEnabledByDefault(t *testing.T) { // Setup options - clearRouterOptionsAndTemplateData() + routerOptions := clearEnvAndInitializeTestData() routerOptions.Output = defaultOutput // Create and run the CLI command without the tunnel flag - config := createRouterConfig([]string{"edge", "--routerName", "myRouter"}) + config, _ := createRouterConfig([]string{"edge", "--routerName", "myRouter"}, routerOptions, nil) // Confirm tunneler is enabled in config output foundTunnel := false @@ -58,11 +59,10 @@ func TestTunnelerEnabledByDefault(t *testing.T) { func TestTunnelerNoneMode(t *testing.T) { // Setup options - clearRouterOptionsAndTemplateData() - routerOptions.Output = defaultOutput + routerOptions := clearEnvAndInitializeTestData() // Create and run the CLI command with the disable tunnel flag - config := createRouterConfig([]string{"edge", "--routerName", "myRouter", "--tunnelerMode", "none"}) + config, data := createRouterConfig([]string{"edge", "--routerName", "myRouter", "--tunnelerMode", "none"}, routerOptions, nil) // Expect tunneler mode to be "none" mode assert.Equal(t, noneTunMode, data.Router.TunnelerMode, "Expected tunneler mode to be %s but found %s", noneTunMode, data.Router.TunnelerMode) @@ -79,11 +79,10 @@ func TestTunnelerNoneMode(t *testing.T) { func TestTunnelerHostModeIsDefault(t *testing.T) { // Setup options - clearRouterOptionsAndTemplateData() - routerOptions.Output = defaultOutput + routerOptions := clearEnvAndInitializeTestData() // Create and run the CLI command without the tunnel flag - config := createRouterConfig([]string{"edge", "--routerName", "myRouter"}) + config, data := createRouterConfig([]string{"edge", "--routerName", "myRouter"}, routerOptions, nil) // Expect tunneler mode to be "host" mode assert.Equal(t, hostTunMode, data.Router.TunnelerMode, "Expected tunneler mode to be %s but found %s", hostTunMode, data.Router.TunnelerMode) @@ -98,11 +97,10 @@ func TestTunnelerHostModeIsDefault(t *testing.T) { func TestTunnelerTproxyMode(t *testing.T) { // Setup options - clearRouterOptionsAndTemplateData() - routerOptions.Output = defaultOutput + routerOptions := clearEnvAndInitializeTestData() // Create and run the CLI command without the tunnel flag - config := createRouterConfig([]string{"edge", "--routerName", "myRouter", "--tunnelerMode", tproxyTunMode}) + config, data := createRouterConfig([]string{"edge", "--routerName", "myRouter", "--tunnelerMode", tproxyTunMode}, routerOptions, nil) // Expect tunneler mode to be "host" mode assert.Equal(t, tproxyTunMode, data.Router.TunnelerMode, "Expected tunneler mode to be %s but found %s", tproxyTunMode, data.Router.TunnelerMode) @@ -121,8 +119,7 @@ func TestTunnelerInvalidMode(t *testing.T) { expectedErrorMsg := "Unknown tunneler mode [" + invalidMode + "] provided, should be \"" + noneTunMode + "\", \"" + hostTunMode + "\", or \"" + tproxyTunMode + "\"" // Create the options with both flags set to true - clearRouterOptionsAndTemplateData() - routerOptions.Output = defaultOutput + routerOptions := clearEnvAndInitializeTestData() routerOptions.TunnelerMode = invalidMode err := routerOptions.runEdgeRouter(&ConfigTemplateValues{}) @@ -131,10 +128,10 @@ func TestTunnelerInvalidMode(t *testing.T) { } func TestPrivateEdgeRouterNotAdvertising(t *testing.T) { - clearRouterOptionsAndTemplateData() + routerOptions := clearEnvAndInitializeTestData() // Create and run the CLI command - config := createRouterConfig([]string{"edge", "--routerName", "myRouter", "--private"}) + config, _ := createRouterConfig([]string{"edge", "--routerName", "myRouter", "--private"}, routerOptions, nil) // Expect that the config values are represented correctly assert.Equal(t, 0, len(config.Link.Listeners), "Expected zero link listeners for private edge router, found a non-zero value") @@ -145,15 +142,14 @@ func TestBlankEdgeRouterNameBecomesHostname(t *testing.T) { blank := "" // Setup options with blank router name - clearRouterOptionsAndTemplateData() - routerOptions.Output = defaultOutput + routerOptions := clearEnvAndInitializeTestData() routerOptions.RouterName = blank // Check that template values is a blank name - assert.Equal(t, blank, data.Router.Name, "Mismatch router name, expected %s but got %s", "", hostname) + //xx how does this work? assert.Equal(t, blank, data.Router.Name, "Mismatch router name, expected %s but got %s", "", hostname) // Create and run the CLI command - _ = createRouterConfig([]string{"edge", "--routerName", blank}) + _, data := createRouterConfig([]string{"edge", "--routerName", blank}, routerOptions, nil) // Check that the blank name was replaced with hostname in the template values assert.Equal(t, hostname, data.Router.Name, "Mismatch router name, expected %s but got %s", "", hostname) @@ -161,13 +157,14 @@ func TestBlankEdgeRouterNameBecomesHostname(t *testing.T) { } func TestDefaultZitiEdgeRouterListenerBindPort(t *testing.T) { + routerOptions := clearEnvAndInitializeTestData() expectedDefaultPortStr := strconv.Itoa(testDefaultRouterListenerPort) // Make sure the related env vars are unset _ = os.Unsetenv("ZITI_EDGE_ROUTER_LISTENER_BIND_PORT") // Create and run the CLI command - config := createRouterConfig([]string{"edge", "--routerName", "testRouter"}) + config, data := createRouterConfig([]string{"edge", "--routerName", "testRouter"}, routerOptions, nil) // Check that the template data has been updated as expected assert.Equal(t, expectedDefaultPortStr, data.Router.Edge.ListenerBindPort) @@ -184,13 +181,14 @@ func TestDefaultZitiEdgeRouterListenerBindPort(t *testing.T) { } func TestSetZitiEdgeRouterListenerBindPort(t *testing.T) { + routerOptions := clearEnvAndInitializeTestData() myPortValue := "1234" // Set the port manually _ = os.Setenv("ZITI_EDGE_ROUTER_LISTENER_BIND_PORT", myPortValue) // Create and run the CLI command - config := createRouterConfig([]string{"edge", "--routerName", "testRouter"}) + config, data := createRouterConfig([]string{"edge", "--routerName", "testRouter"}, routerOptions, nil) assert.Equal(t, myPortValue, data.Router.Edge.ListenerBindPort) @@ -209,8 +207,7 @@ func TestEdgeRouterCannotBeWSSAndPrivate(t *testing.T) { expectedErrorMsg := "Flags for private and wss configs are mutually exclusive. You must choose private or wss, not both" // Create the options with both flags set to true - clearRouterOptionsAndTemplateData() - routerOptions.Output = defaultOutput + routerOptions := clearEnvAndInitializeTestData() routerOptions.IsPrivate = true routerOptions.WssEnabled = true @@ -223,7 +220,7 @@ func TestEdgeRouterOutputPathDoesNotExist(t *testing.T) { expectedErrorMsg := "stat /IDoNotExist: no such file or directory" // Set the router options - clearRouterOptionsAndTemplateData() + routerOptions := clearEnvAndInitializeTestData() routerOptions.TunnelerMode = defaultTunnelerMode routerOptions.RouterName = "MyEdgeRouter" routerOptions.Output = "/IDoNotExist/MyEdgeRouter.yaml" @@ -234,7 +231,13 @@ func TestEdgeRouterOutputPathDoesNotExist(t *testing.T) { } func TestExecuteCreateConfigRouterEdgeHasNonBlankTemplateValues(t *testing.T) { + routerOptions := clearEnvAndInitializeTestData() + routerName := "MyEdgeRouter" + + // Create and run the CLI command + _, data := createRouterConfig([]string{"edge", "--routerName", routerName}, routerOptions, nil) + expectedNonEmptyStringFields := []string{".Router.Edge.ListenerBindPort", ".ZitiHome", ".Hostname", ".Router.Name", ".Router.IdentityCert", ".Router.IdentityServerCert", ".Router.IdentityKey", ".Router.IdentityCA", ".Router.Edge.Port"} expectedNonEmptyStringValues := []*string{&data.Router.Edge.ListenerBindPort, &data.ZitiHome, &data.Hostname, &data.Router.Name, &data.Router.IdentityCert, &data.Router.IdentityServerCert, &data.Router.IdentityKey, &data.Router.IdentityCA, &data.Router.Edge.Port} expectedNonEmptyIntFields := []string{".Router.Listener.OutQueueSize", ".Router.Wss.ReadBufferSize", ".Router.Wss.WriteBufferSize", ".Router.Forwarder.XgressDialQueueLength", ".Router.Forwarder.XgressDialWorkerCount", ".Router.Forwarder.LinkDialQueueLength", ".Router.Forwarder.LinkDialWorkerCount"} @@ -242,9 +245,6 @@ func TestExecuteCreateConfigRouterEdgeHasNonBlankTemplateValues(t *testing.T) { expectedNonEmptyTimeFields := []string{".Router.Listener.ConnectTimeout", "Router.Listener.GetSessionTimeout", ".Router.Wss.WriteTimeout", ".Router.Wss.ReadTimeout", ".Router.Wss.IdleTimeout", ".Router.Wss.PongTimeout", ".Router.Wss.PingInterval", ".Router.Wss.HandshakeTimeout", ".Router.Forwarder.LatencyProbeInterval"} expectedNonEmptyTimeValues := []*time.Duration{&data.Router.Listener.ConnectTimeout, &data.Router.Listener.GetSessionTimeout, &data.Router.Wss.WriteTimeout, &data.Router.Wss.ReadTimeout, &data.Router.Wss.IdleTimeout, &data.Router.Wss.PongTimeout, &data.Router.Wss.PingInterval, &data.Router.Wss.HandshakeTimeout, &data.Router.Forwarder.LatencyProbeInterval} - // Create and run the CLI command - _ = createRouterConfig([]string{"edge", "--routerName", routerName}) - // Check that the expected string template values are not blank for field, value := range expectedNonEmptyStringValues { assert.NotEqualf(t, "", *value, expectedNonEmptyStringFields[field]+" should be a non-blank value") @@ -262,22 +262,20 @@ func TestExecuteCreateConfigRouterEdgeHasNonBlankTemplateValues(t *testing.T) { } func TestEdgeRouterIPOverrideIsConsumed(t *testing.T) { - routerName := "MyFabricRouter" - blank := "" - externalIP := "123.456.78.9" + routerOptions := clearEnvAndInitializeTestData() - // Setup options - clearRouterOptionsAndTemplateData() - routerOptions.Output = defaultOutput + routerName := "MyFabricRouter" + //useful? blank := "" + externalIP := "123.456.78.9" // Set the env variable to non-empty value _ = os.Setenv(constants.ZitiEdgeRouterIPOverrideVarName, externalIP) - // Check that template value is currently blank - assert.Equal(t, blank, data.Router.Edge.IPOverride, "Mismatch router IP override, expected %s but got %s", blank, data.Router.Edge.IPOverride) + //useful? // Check that template value is currently blank + //useful? assert.Equal(t, blank, data.Router.Edge.IPOverride, "Mismatch router IP override, expected %s but got %s", blank, data.Router.Edge.IPOverride) // Create and run the CLI command (capture output, otherwise config prints to stdout instead of test results) - config := createRouterConfig([]string{"edge", "--routerName", routerName}) + config, data := createRouterConfig([]string{"edge", "--routerName", routerName}, routerOptions, nil) // Check that the template values now contains the custom external IP override value assert.Equal(t, externalIP, data.Router.Edge.IPOverride, "Mismatch router IP override, expected %s but got %s", externalIP, data.Router.Edge.IPOverride) diff --git a/ziti/cmd/create_config_router_fabric.go b/ziti/cmd/create_config_router_fabric.go index de642a534..82aaf6722 100644 --- a/ziti/cmd/create_config_router_fabric.go +++ b/ziti/cmd/create_config_router_fabric.go @@ -45,6 +45,8 @@ var routerConfigFabricTemplate string // NewCmdCreateConfigRouterFabric creates a command object for the "fabric" command func NewCmdCreateConfigRouterFabric() *cobra.Command { + data := &ConfigTemplateValues{} + routerOptions := &CreateConfigRouterOptions{} cmd := &cobra.Command{ Use: "fabric", diff --git a/ziti/cmd/create_config_router_fabric_test.go b/ziti/cmd/create_config_router_fabric_test.go index 7c4a005bb..6e58c9f8f 100644 --- a/ziti/cmd/create_config_router_fabric_test.go +++ b/ziti/cmd/create_config_router_fabric_test.go @@ -11,7 +11,12 @@ import ( ) func TestExecuteCreateConfigRouterFabricHasNonBlankTemplateValues(t *testing.T) { + routerOptions := clearEnvAndInitializeTestData() routerName := "MyFabricRouter" + + // Create and run the CLI command (capture output, otherwise config prints to stdout instead of test results) + _, data := createRouterConfig([]string{"fabric", "--routerName", routerName}, routerOptions, nil) + expectedNonEmptyStringFields := []string{".Router.Listener.BindPort", ".ZitiHome", ".Hostname", ".Router.Name", ".Router.IdentityCert", ".Router.IdentityServerCert", ".Router.IdentityKey", ".Router.IdentityCA", ".Router.Edge.Port"} expectedNonEmptyStringValues := []*string{&data.Router.Edge.ListenerBindPort, &data.ZitiHome, &data.Hostname, &data.Router.Name, &data.Router.IdentityCert, &data.Router.IdentityServerCert, &data.Router.IdentityKey, &data.Router.IdentityCA, &data.Router.Edge.Port} expectedNonEmptyIntFields := []string{".Router.Listener.OutQueueSize", ".Router.Wss.ReadBufferSize", ".Router.Wss.WriteBufferSize", ".Router.Forwarder.XgressDialQueueLength", ".Router.Forwarder.XgressDialWorkerCount", ".Router.Forwarder.LinkDialQueueLength", ".Router.Forwarder.LinkDialWorkerCount"} @@ -19,9 +24,6 @@ func TestExecuteCreateConfigRouterFabricHasNonBlankTemplateValues(t *testing.T) expectedNonEmptyTimeFields := []string{".Router.Listener.ConnectTimeout", "Router.Listener.GetSessionTimeout", ".Router.Wss.WriteTimeout", ".Router.Wss.ReadTimeout", ".Router.Wss.IdleTimeout", ".Router.Wss.PongTimeout", ".Router.Wss.PingInterval", ".Router.Wss.HandshakeTimeout", ".Router.Forwarder.LatencyProbeInterval"} expectedNonEmptyTimeValues := []*time.Duration{&data.Router.Listener.ConnectTimeout, &data.Router.Listener.GetSessionTimeout, &data.Router.Wss.WriteTimeout, &data.Router.Wss.ReadTimeout, &data.Router.Wss.IdleTimeout, &data.Router.Wss.PongTimeout, &data.Router.Wss.PingInterval, &data.Router.Wss.HandshakeTimeout, &data.Router.Forwarder.LatencyProbeInterval} - // Create and run the CLI command (capture output, otherwise config prints to stdout instead of test results) - _ = createRouterConfig([]string{"fabric", "--routerName", routerName}) - // Check that the expected string template values are not blank for field, value := range expectedNonEmptyStringValues { assert.NotEqualf(t, "", *value, expectedNonEmptyStringFields[field]+" should be a non-blank value") @@ -39,22 +41,15 @@ func TestExecuteCreateConfigRouterFabricHasNonBlankTemplateValues(t *testing.T) } func TestFabricRouterIPOverrideIsConsumed(t *testing.T) { + routerOptions := clearEnvAndInitializeTestData() routerName := "MyFabricRouter" - blank := "" externalIP := "123.456.78.9" - // Setup options - clearRouterOptionsAndTemplateData() - routerOptions.Output = defaultOutput - // Set the env variable to non-empty value _ = os.Setenv(constants.ZitiEdgeRouterIPOverrideVarName, externalIP) - // Check that template value is currently blank - assert.Equal(t, blank, data.Router.Edge.IPOverride, "Mismatch router IP override, expected %s but got %s", blank, data.Router.Edge.IPOverride) - // Create and run the CLI command (capture output, otherwise config prints to stdout instead of test results) - config := createRouterConfig([]string{"fabric", "--routerName", routerName}) + config, data := createRouterConfig([]string{"fabric", "--routerName", routerName}, routerOptions, nil) // Check that the template values now contains the custom external IP override value assert.Equal(t, externalIP, data.Router.Edge.IPOverride, "Mismatch router IP override, expected %s but got %s", externalIP, data.Router.Edge.IPOverride) @@ -70,29 +65,27 @@ func TestFabricRouterIPOverrideIsConsumed(t *testing.T) { } func TestFabricRouterHasNoListeners(t *testing.T) { - clearRouterOptionsAndTemplateData() + routerOptions := clearEnvAndInitializeTestData() // Create and run the CLI command - config := createRouterConfig([]string{"fabric", "--routerName", "myRouter"}) + config, _ := createRouterConfig([]string{"fabric", "--routerName", "myRouter"}, routerOptions, nil) // Expect that the config values are represented correctly assert.Equal(t, 0, len(config.Listeners), "Expected zero listeners for fabric router, found a non-zero value") } func TestBlankFabricRouterNameBecomesHostname(t *testing.T) { + routerOptions := clearEnvAndInitializeTestData() hostname, _ := os.Hostname() blank := "" // Create the options with empty router name - clearRouterOptionsAndTemplateData() + clearEnvAndInitializeTestData() routerOptions.Output = defaultOutput routerOptions.RouterName = blank - // Check that template values is a blank name - assert.Equal(t, blank, data.Router.Name, "Mismatch router name, expected %s but got %s", "", hostname) - // Create and run the CLI command - _ = createRouterConfig([]string{"fabric", "--routerName", blank}) + _, data := createRouterConfig([]string{"fabric", "--routerName", blank}, routerOptions, nil) // Check that the blank name was replaced with hostname in the template values assert.Equal(t, hostname, data.Router.Name, "Mismatch router name, expected %s but got %s", "", hostname) @@ -100,10 +93,11 @@ func TestBlankFabricRouterNameBecomesHostname(t *testing.T) { } func TestFabricRouterOutputPathDoesNotExist(t *testing.T) { + routerOptions := clearEnvAndInitializeTestData() expectedErrorMsg := "stat /IDoNotExist: no such file or directory" // Set the router options - clearRouterOptionsAndTemplateData() + clearEnvAndInitializeTestData() routerOptions.RouterName = "MyFabricRouter" routerOptions.Output = "/IDoNotExist/MyFabricRouter.yaml" @@ -113,13 +107,14 @@ func TestFabricRouterOutputPathDoesNotExist(t *testing.T) { } func TestDefaultZitiFabricRouterListenerBindPort(t *testing.T) { + routerOptions := clearEnvAndInitializeTestData() expectedDefaultPortStr := strconv.Itoa(testDefaultRouterListenerPort) // Make sure the related env vars are unset _ = os.Unsetenv("ZITI_EDGE_ROUTER_LISTENER_BIND_PORT") // Create and run the CLI command - config := createRouterConfig([]string{"fabric", "--routerName", "testRouter"}) + config, data := createRouterConfig([]string{"fabric", "--routerName", "testRouter"}, routerOptions, nil) // Check that the template data has been updated as expected assert.Equal(t, expectedDefaultPortStr, data.Router.Edge.ListenerBindPort) @@ -136,13 +131,14 @@ func TestDefaultZitiFabricRouterListenerBindPort(t *testing.T) { } func TestSetZitiFabricRouterListenerBindPort(t *testing.T) { + routerOptions := clearEnvAndInitializeTestData() myPortValue := "1234" // Set the port manually _ = os.Setenv("ZITI_EDGE_ROUTER_LISTENER_BIND_PORT", myPortValue) // Create and run the CLI command - config := createRouterConfig([]string{"fabric", "--routerName", "testRouter"}) + config, data := createRouterConfig([]string{"fabric", "--routerName", "testRouter"}, routerOptions, nil) assert.Equal(t, myPortValue, data.Router.Edge.ListenerBindPort) diff --git a/ziti/cmd/create_config_router_test.go b/ziti/cmd/create_config_router_test.go index e0acf695c..dbc7ec1e4 100644 --- a/ziti/cmd/create_config_router_test.go +++ b/ziti/cmd/create_config_router_test.go @@ -105,9 +105,10 @@ type Forwarder struct { /* END Controller config template structure */ -func createRouterConfig(args []string) RouterConfig { +func createRouterConfig(args []string, routerOptions *CreateConfigRouterOptions, keys map[string]string) (RouterConfig, *ConfigTemplateValues) { // Create and run the CLI command - cmd := NewCmdCreateConfigRouter() + setEnvByMap(keys) + cmd := NewCmdCreateConfigRouter(routerOptions) cmd.SetArgs(args) // captureOutput is used to consume output, otherwise config prints to stdout along with test results output := captureOutput(func() { @@ -120,28 +121,15 @@ func createRouterConfig(args []string) RouterConfig { if err2 != nil { fmt.Println(err2) } - return configStruct + return configStruct, cmd.RenderedValues } -func execCreateConfigCommand(args []string, keys map[string]string) { - // Setup options - clearRouterOptionsAndTemplateData() +func clearEnvAndInitializeTestData() *CreateConfigRouterOptions { + unsetZitiEnv() + routerOptions := &CreateConfigRouterOptions{} routerOptions.Output = defaultOutput - setEnvByMap(keys) - // Create and run the CLI command (capture output, otherwise config prints to stdout instead of test results) - cmd := NewCmdCreateConfigRouter() - cmd.SetArgs(args) - _ = captureOutput(func() { - _ = cmd.Execute() - }) -} - -func clearRouterOptionsAndTemplateData() { - routerOptions = CreateConfigRouterOptions{} - data = &ConfigTemplateValues{} - - unsetZitiEnv() + return &CreateConfigRouterOptions{} } func TestSetZitiRouterIdentityCertDefault(t *testing.T) { @@ -246,7 +234,7 @@ func TestSetZitiRouterIdentityCACustom(t *testing.T) { func TestSetZitiRouterIdentitySetsAllIdentitiesAndRouterName(t *testing.T) { // Setup - clearRouterOptionsAndTemplateData() + clearEnvAndInitializeTestData() expectedName := "MyRouterName" blank := "" rtv := &RouterTemplateValues{} @@ -273,7 +261,7 @@ func TestSetZitiRouterIdentitySetsAllIdentitiesAndRouterName(t *testing.T) { func TestSetZitiRouterIdentitySetsAllIdentitiesAndRouterNameToHostWhenBlank(t *testing.T) { // Setup - clearRouterOptionsAndTemplateData() + clearEnvAndInitializeTestData() expectedName, _ := os.Hostname() blank := "" rtv := &RouterTemplateValues{} @@ -299,7 +287,7 @@ func TestSetZitiRouterIdentitySetsAllIdentitiesAndRouterNameToHostWhenBlank(t *t } func TestAltServerCerts(t *testing.T) { - clearRouterOptionsAndTemplateData() + clearEnvAndInitializeTestData() certPath := "/path/to/cert" keyPath := "/path/to/key" _ = os.Setenv("ZITI_PKI_ALT_SERVER_CERT", certPath) diff --git a/ziti/cmd/helpers/env_helpers.go b/ziti/cmd/helpers/env_helpers.go index 3d40eab95..cf2de5541 100644 --- a/ziti/cmd/helpers/env_helpers.go +++ b/ziti/cmd/helpers/env_helpers.go @@ -107,9 +107,15 @@ func GetCtrlAdvertisedPort() string { func GetCtrlEdgeBindAddress() string { return getFromEnv(constants.CtrlEdgeBindAddressVarName, defaultValue(constants.DefaultCtrlEdgeBindAddress)) } + func GetCtrlEdgeAdvertisedAddress() string { return getFromEnv(constants.CtrlEdgeAdvertisedAddressVarName, HostnameOrNetworkName) } + +func GetCtrlEdgeAltAdvertisedAddress() string { + return getFromEnv(constants.CtrlEdgeAltAdvertisedAddressVarName, GetCtrlEdgeAdvertisedAddress) +} + func GetCtrlEdgeAdvertisedPort() string { return getFromEnv(constants.CtrlEdgeAdvertisedPortVarName, defaultValue(constants.DefaultCtrlEdgeAdvertisedPort)) } @@ -122,30 +128,30 @@ func GetZitiEdgeRouterListenerBindPort() string { return getFromEnv(constants.ZitiEdgeRouterListenerBindPortVarName, defaultValue(constants.DefaultZitiEdgeRouterListenerBindPort)) } -func GetCtrlEdgeIdentityEnrollmentDuration() (time.Duration, error) { +func GetCtrlEdgeIdentityEnrollmentDuration() time.Duration { retVal := getFromEnv(constants.CtrlEdgeIdentityEnrollmentDurationVarName, defaultIntValue(int64(edge.DefaultEdgeEnrollmentDuration.Minutes()))) retValInt, err := strconv.Atoi(retVal) if err != nil { err := errors.Wrap(err, "Unable to get "+constants.CtrlEdgeIdentityEnrollmentDurationVarDescription) if err != nil { - return edge.DefaultEdgeEnrollmentDuration, err + return edge.DefaultEdgeEnrollmentDuration } } - return time.Duration(retValInt) * time.Minute, nil + return time.Duration(retValInt) * time.Minute } -func GetCtrlEdgeRouterEnrollmentDuration() (time.Duration, error) { +func GetCtrlEdgeRouterEnrollmentDuration() time.Duration { retVal := getFromEnv(constants.CtrlEdgeRouterEnrollmentDurationVarName, defaultIntValue(int64(edge.DefaultEdgeEnrollmentDuration.Minutes()))) retValInt, err := strconv.Atoi(retVal) if err != nil { err := errors.Wrap(err, "Unable to get "+constants.CtrlEdgeRouterEnrollmentDurationVarDescription) if err != nil { - return edge.DefaultEdgeEnrollmentDuration, err + return edge.DefaultEdgeEnrollmentDuration } } - return time.Duration(retValInt) * time.Minute, nil + return time.Duration(retValInt) * time.Minute } type envVarNotFound func() string diff --git a/ziti/cmd/helpers/helpers_test.go b/ziti/cmd/helpers/helpers_test.go index 5e0ec1989..de94b37df 100644 --- a/ziti/cmd/helpers/helpers_test.go +++ b/ziti/cmd/helpers/helpers_test.go @@ -205,7 +205,7 @@ func TestGetEdgeIdentityEnrollmentDurationWhenSet(t *testing.T) { _ = os.Setenv(varName, fmt.Sprintf("%.0f", expectedValue.Minutes())) // Check that the value matches - actualValue, _ := GetCtrlEdgeIdentityEnrollmentDuration() + actualValue := GetCtrlEdgeIdentityEnrollmentDuration() assert.Equal(t, expectedValue, actualValue) } @@ -220,7 +220,7 @@ func TestGetEdgeIdentityEnrollmentDurationWhenSetToBlank(t *testing.T) { _ = os.Setenv(varName, "") // Check that the value matches - actualValue, _ := GetCtrlEdgeIdentityEnrollmentDuration() + actualValue := GetCtrlEdgeIdentityEnrollmentDuration() assert.Equal(t, expectedValue, actualValue) } @@ -234,7 +234,7 @@ func TestGetEdgeIdentityEnrollmentDurationWhenNotSet(t *testing.T) { _ = os.Setenv(varName, fmt.Sprintf("%.0f", expectedValue.Minutes())) // Check that the value matches - actualValue, _ := GetCtrlEdgeIdentityEnrollmentDuration() + actualValue := GetCtrlEdgeIdentityEnrollmentDuration() assert.Equal(t, expectedValue, actualValue) } @@ -247,7 +247,7 @@ func TestGetEdgeRouterEnrollmentDurationWhenSet(t *testing.T) { _ = os.Setenv(varName, fmt.Sprintf("%.0f", expectedValue.Minutes())) // Check that the value matches - actualValue, _ := GetCtrlEdgeRouterEnrollmentDuration() + actualValue := GetCtrlEdgeRouterEnrollmentDuration() assert.Equal(t, expectedValue, actualValue) } @@ -262,7 +262,7 @@ func TestGetEdgeRouterEnrollmentDurationWhenSetToBlank(t *testing.T) { _ = os.Setenv(varName, "") // Check that the value matches - actualValue, _ := GetCtrlEdgeRouterEnrollmentDuration() + actualValue := GetCtrlEdgeRouterEnrollmentDuration() assert.Equal(t, expectedValue, actualValue) } @@ -276,6 +276,6 @@ func TestGetEdgeRouterEnrollmentDurationWhenNotSet(t *testing.T) { _ = os.Setenv(varName, fmt.Sprintf("%.0f", expectedValue.Minutes())) // Check that the value matches - actualValue, _ := GetCtrlEdgeRouterEnrollmentDuration() + actualValue := GetCtrlEdgeRouterEnrollmentDuration() assert.Equal(t, expectedValue, actualValue) } diff --git a/ziti/constants/constants.go b/ziti/constants/constants.go index 9c866307b..2d4856e1b 100644 --- a/ziti/constants/constants.go +++ b/ziti/constants/constants.go @@ -71,6 +71,8 @@ const ( CtrlEdgeBindAddressVarDescription = "The address on which the edge controller will listen on for API connections." CtrlEdgeAdvertisedAddressVarName = "ZITI_CTRL_EDGE_ADVERTISED_ADDRESS" CtrlEdgeAdvertisedAddressVarDescription = "The publicly addressable controller address value" + CtrlEdgeAltAdvertisedAddressVarName = "ZITI_CTRL_EDGE_ALT_CTRL_ADVERTISED_ADDRESS" + CtrlEdgeAltAdvertisedAddressVarDescription = "The publicly addressable, alternative controller address value" CtrlEdgeAdvertisedPortVarName = "ZITI_CTRL_EDGE_ADVERTISED_PORT" CtrlEdgeAdvertisedPortVarDescription = "The publicly addressable controller port value" PkiSignerCertVarName = "ZITI_PKI_SIGNER_CERT"