diff --git a/web/tls_config.go b/web/tls_config.go index 7245f741..b077ccff 100644 --- a/web/tls_config.go +++ b/web/tls_config.go @@ -90,6 +90,18 @@ func (c *FlagConfig) checkFlags() error { return nil } +// IsEnabled reports whether the TLSConfig configures TLS, i.e. whether at least +// one TLS-related field is set. It does not validate that the configuration is +// complete or that the referenced files exist; use ConfigToTLSConfig for that. +// This is useful for callers that need to know whether the server will serve +// HTTPS, for example to infer the scheme of an external URL. +func (t *TLSConfig) IsEnabled() bool { + return t.TLSCertPath != "" || t.TLSCert != "" || + t.TLSKeyPath != "" || t.TLSKey != "" || + t.ClientCAs != "" || t.ClientCAsText != "" || + t.ClientAuth != "" +} + // SetDirectory joins any relative file paths with dir. func (t *TLSConfig) SetDirectory(dir string) { t.TLSCertPath = config_util.JoinDir(dir, t.TLSCertPath) @@ -165,10 +177,7 @@ func getTLSConfig(configPath string) (*tls.Config, error) { } func validateTLSPaths(c *TLSConfig) error { - if c.TLSCertPath == "" && c.TLSCert == "" && - c.TLSKeyPath == "" && c.TLSKey == "" && - c.ClientCAs == "" && c.ClientCAsText == "" && - c.ClientAuth == "" { + if !c.IsEnabled() { return errNoTLSConfig } diff --git a/web/tls_config_test.go b/web/tls_config_test.go index a0dd1d41..289a5d23 100644 --- a/web/tls_config_test.go +++ b/web/tls_config_test.go @@ -712,3 +712,48 @@ func TestUsers(t *testing.T) { t.Run(testInputs.Name, testInputs.Test) } } + +func TestTLSConfigIsEnabled(t *testing.T) { + for _, tc := range []struct { + name string + config TLSConfig + expected bool + }{ + { + name: "empty config", + config: TLSConfig{}, + expected: false, + }, + { + name: "only non-enabling fields set", + config: TLSConfig{MinVersion: tls.VersionTLS12, PreferServerCipherSuites: true}, + expected: false, + }, + { + name: "cert_file and key_file set", + config: TLSConfig{TLSCertPath: "server.crt", TLSKeyPath: "server.key"}, + expected: true, + }, + { + name: "inline cert and key set", + config: TLSConfig{TLSCert: "cert", TLSKey: "key"}, + expected: true, + }, + { + name: "only client CA file set", + config: TLSConfig{ClientCAs: "client_ca.crt"}, + expected: true, + }, + { + name: "only client auth type set", + config: TLSConfig{ClientAuth: "RequireAndVerifyClientCert"}, + expected: true, + }, + } { + t.Run(tc.name, func(t *testing.T) { + if got := tc.config.IsEnabled(); got != tc.expected { + t.Errorf("IsEnabled() = %v, expected %v", got, tc.expected) + } + }) + } +}