diff --git a/cmd/cloudflared/tunnel/ingress_subcommands.go b/cmd/cloudflared/tunnel/ingress_subcommands.go index 82ef7561..35a802c5 100644 --- a/cmd/cloudflared/tunnel/ingress_subcommands.go +++ b/cmd/cloudflared/tunnel/ingress_subcommands.go @@ -3,6 +3,7 @@ package tunnel import ( "encoding/json" "fmt" + "io" "net/url" "github.com/cloudflare/cloudflared/cmd/cloudflared/cliutil" @@ -13,12 +14,12 @@ import ( "github.com/urfave/cli/v2" ) -const ingressDataJSONFlagName = "json" +const ingressDataJSONArgvFlagName = "json" -var ingressDataJSON = &cli.StringFlag{ - Name: ingressDataJSONFlagName, +var ingressDataJSONArgv = &cli.StringFlag{ + Name: ingressDataJSONArgvFlagName, Aliases: []string{"j"}, - Usage: `Accepts data in the form of json as an input rather than read from a file`, + Usage: `Accepts a config in the form of json (as a command line argument) rather than read from a file`, EnvVars: []string{"TUNNEL_INGRESS_VALIDATE_JSON"}, } @@ -59,7 +60,7 @@ func buildValidateIngressCommand() *cli.Command { Usage: "Validate the ingress configuration ", UsageText: "cloudflared tunnel [--config FILEPATH] ingress validate", Description: "Validates the configuration file, ensuring your ingress rules are OK.", - Flags: []cli.Flag{ingressDataJSON}, + Flags: []cli.Flag{ingressDataJSONArgv}, } } @@ -78,9 +79,15 @@ func buildTestURLCommand() *cli.Command { } } -// validateIngressCommand check the syntax of the ingress rules in the cloudflared config file +// validateIngressCommand check the syntax of the ingress rules in the cloudflared config func validateIngressCommand(c *cli.Context, warnings string) error { - conf, err := getConfiguration(c) + return validateIngress(c, warnings, config.GetConfiguration(), c.App.Reader) +} + +// validateIngress calls validateIngressCommand with its sources of +// configuration (the process-wide config file settings and stdin) injected. +func validateIngress(c *cli.Context, warnings string, globalConf *config.Configuration, configStdin io.Reader) error { + conf, err := getConfiguration(c, globalConf, configStdin) if err != nil { return err } @@ -100,20 +107,38 @@ func validateIngressCommand(c *cli.Context, warnings string) error { return nil } -func getConfiguration(c *cli.Context) (*config.Configuration, error) { +// Gets the cloudflared configuration from the correct source depending on CLI +// flags. This function will use: +// +// - A config provided via the CLI if invoked as "tunnel ingress validate --json " +// - The passed in globalConf, if non-nil (this is present if cloudflared is invoked with "tunnel --config subcommand") +// - A config provided via stdin otherwise +func getConfiguration(c *cli.Context, globalConf *config.Configuration, configStdin io.Reader) (*config.Configuration, error) { var conf *config.Configuration - if c.IsSet(ingressDataJSONFlagName) { - ingressJSON := c.String(ingressDataJSONFlagName) + + // Option 1) --json + if c.IsSet(ingressDataJSONArgvFlagName) { + ingressJSON := c.String(ingressDataJSONArgvFlagName) fmt.Println("Validating rules from cmdline flag --json") err := json.Unmarshal([]byte(ingressJSON), &conf) return conf, err } - conf = config.GetConfiguration() - if conf.Source() == "" { - return nil, errors.New("No configuration file was found. Please create one, or use the --config flag to specify its filepath. You can use the help command to learn more about configuration files") + + // Option 2) Global configuration (Normally injected as the --config passed to "cloudflared tunnel") + if globalConf.Source() != "" { + fmt.Println("Validating rules from ", globalConf.Source()) + return globalConf, nil } - fmt.Println("Validating rules from", conf.Source()) - return conf, nil + + // Option 3) Read from standard input + fmt.Println("Configuration not provided via a file or CLI, reading config as JSON from standard input") + ingressJSON, err := io.ReadAll(configStdin) + if err != nil { + return nil, fmt.Errorf("read stdin: %w", err) + } + + err = json.Unmarshal(ingressJSON, &conf) + return conf, err } // testURLCommand checks which ingress rule matches the given URL. diff --git a/cmd/cloudflared/tunnel/subcommand_context_test.go b/cmd/cloudflared/tunnel/subcommand_context_test.go index ca2a42b2..df34d414 100644 --- a/cmd/cloudflared/tunnel/subcommand_context_test.go +++ b/cmd/cloudflared/tunnel/subcommand_context_test.go @@ -4,8 +4,11 @@ import ( "encoding/base64" "flag" "fmt" + "io" "reflect" + "strings" "testing" + "testing/iotest" "time" "github.com/google/uuid" @@ -15,6 +18,7 @@ import ( "github.com/urfave/cli/v2" "github.com/cloudflare/cloudflared/cfapi" + "github.com/cloudflare/cloudflared/config" "github.com/cloudflare/cloudflared/connection" "github.com/cloudflare/cloudflared/credentials" ) @@ -247,7 +251,6 @@ func Test_subcommandContext_Delete(t *testing.T) { type fields struct { c *cli.Context log *zerolog.Logger - isUIEnabled bool fs fileSystem tunnelstoreClient *deleteMockTunnelStore userCredential *credentials.User @@ -325,45 +328,113 @@ func Test_subcommandContext_Delete(t *testing.T) { } func Test_subcommandContext_ValidateIngressCommand(t *testing.T) { + testValidConfig := `{ "warp-routing": {"enabled": true}, "originRequest" : {"connectTimeout": 10}, "ingress" : [ {"hostname": "test", "service": "https://localhost:8000" } , {"service": "http_status:404"} ]}` + testInvalidConfig := `{ "ingress" : [ {"hostname": "test", "service": "localhost:8000" } , {"service": "http_status:invalid_status"} ]}` + invalidConfigErr := errors.New("Validation failed: localhost:8000 is an invalid address, please make sure it has a scheme and a hostname") + + newGlobalConf := func(rules ...config.UnvalidatedIngressRule) *config.Configuration { + conf := &config.Configuration{Ingress: rules} + conf.SetSource("/etc/cloudflared/config.yml") + return conf + } + var tests = []struct { name string + stdin io.Reader + globalConf *config.Configuration c *cli.Context - wantErr bool expectedErr error }{ { - name: "read a valid configuration from data", + name: "read a valid configuration from the command line", + stdin: strings.NewReader(""), c: func() *cli.Context { - data := `{ "warp-routing": {"enabled": true}, "originRequest" : {"connectTimeout": 10}, "ingress" : [ {"hostname": "test", "service": "https://localhost:8000" } , {"service": "http_status:404"} ]}` flagSet := flag.NewFlagSet("json", flag.PanicOnError) - flagSet.String(ingressDataJSONFlagName, data, "") + flagSet.String(ingressDataJSONArgvFlagName, testValidConfig, "") c := cli.NewContext(cli.NewApp(), flagSet, nil) - _ = c.Set(ingressDataJSONFlagName, data) + _ = c.Set(ingressDataJSONArgvFlagName, testValidConfig) return c }(), }, { - name: "read an invalid configuration with multiple mistakes", + name: "read a valid configuration from stdin when no flags are provided", + stdin: strings.NewReader(testValidConfig), c: func() *cli.Context { - data := `{ "ingress" : [ {"hostname": "test", "service": "localhost:8000" } , {"service": "http_status:invalid_status"} ]}` - flagSet := flag.NewFlagSet("json", flag.PanicOnError) - flagSet.String(ingressDataJSONFlagName, data, "") + flagSet := flag.NewFlagSet("no-flags", flag.PanicOnError) c := cli.NewContext(cli.NewApp(), flagSet, nil) - _ = c.Set(ingressDataJSONFlagName, data) return c }(), - wantErr: true, - expectedErr: errors.New("Validation failed: localhost:8000 is an invalid address, please make sure it has a scheme and a hostname"), + }, + { + name: "read an invalid configuration with multiple mistakes from the command line", + stdin: strings.NewReader(""), + c: func() *cli.Context { + flagSet := flag.NewFlagSet("json", flag.PanicOnError) + flagSet.String(ingressDataJSONArgvFlagName, testInvalidConfig, "") + c := cli.NewContext(cli.NewApp(), flagSet, nil) + _ = c.Set(ingressDataJSONArgvFlagName, testInvalidConfig) + return c + }(), + expectedErr: invalidConfigErr, + }, + { + name: "read an invalid configuration with multiple mistakes from stdin when no flags are provided", + stdin: strings.NewReader(testInvalidConfig), + c: func() *cli.Context { + flagSet := flag.NewFlagSet("no-flags", flag.PanicOnError) + c := cli.NewContext(cli.NewApp(), flagSet, nil) + return c + }(), + expectedErr: invalidConfigErr, + }, + { + name: "stdin read error", + stdin: iotest.ErrReader(errors.New("stdin error")), + c: func() *cli.Context { + flagSet := flag.NewFlagSet("no-flags", flag.PanicOnError) + return cli.NewContext(cli.NewApp(), flagSet, nil) + }(), + expectedErr: errors.New("read stdin: stdin error"), + }, + { + name: "read a valid configuration from the global config without reading stdin", + stdin: iotest.ErrReader(errors.New("stdin must not be read")), + globalConf: newGlobalConf( + config.UnvalidatedIngressRule{Hostname: "test", Service: "https://localhost:8000"}, + config.UnvalidatedIngressRule{Service: "http_status:404"}, + ), + c: func() *cli.Context { + flagSet := flag.NewFlagSet("no-flags", flag.PanicOnError) + return cli.NewContext(cli.NewApp(), flagSet, nil) + }(), + }, + { + name: "read an invalid configuration from the global config without reading stdin", + stdin: iotest.ErrReader(errors.New("stdin must not be read")), + globalConf: newGlobalConf( + config.UnvalidatedIngressRule{Hostname: "test", Service: "localhost:8000"}, + config.UnvalidatedIngressRule{Service: "http_status:404"}, + ), + c: func() *cli.Context { + flagSet := flag.NewFlagSet("no-flags", flag.PanicOnError) + return cli.NewContext(cli.NewApp(), flagSet, nil) + }(), + expectedErr: invalidConfigErr, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - err := validateIngressCommand(tt.c, "") - if tt.wantErr { + globalConf := tt.globalConf + if globalConf == nil { + globalConf = &config.Configuration{} + } + + err := validateIngress(tt.c, "", globalConf, tt.stdin) + if tt.expectedErr != nil { assert.Equal(t, tt.expectedErr.Error(), err.Error()) } else { - assert.Nil(t, err) + assert.NoError(t, err) } }) } diff --git a/config/configuration.go b/config/configuration.go index fbfd1755..95419c61 100644 --- a/config/configuration.go +++ b/config/configuration.go @@ -280,6 +280,10 @@ func (c *Configuration) Source() string { return c.sourceFile } +func (c *Configuration) SetSource(file string) { + c.sourceFile = file +} + func (c *configFileSettings) Int(name string) (int, error) { if raw, ok := c.Settings[name]; ok { if v, ok := raw.(int); ok {