Move middleware context handler logic to service (#29605)

* middleware: Move context handler to own service

Signed-off-by: Arve Knudsen <arve.knudsen@gmail.com>

Co-authored-by: Emil Tullsted <sakjur@users.noreply.github.com>
Co-authored-by: Will Browne <wbrowne@users.noreply.github.com>
This commit is contained in:
Arve Knudsen
2020-12-11 11:44:44 +01:00
committed by GitHub
co-authored by Emil Tullsted Will Browne
parent d0f52d5334
commit 12661e8a9d
51 changed files with 1321 additions and 1079 deletions
+94 -70
View File
@@ -47,7 +47,7 @@ var (
// This constant corresponds to the default value for ldap_sync_ttl in .ini files
// it is used for comparison and has to be kept in sync
const (
AuthProxySyncTTL = 60
authProxySyncTTL = 60
)
var (
@@ -75,12 +75,8 @@ var (
CustomInitPath = "conf/custom.ini"
// HTTP server options
Protocol Scheme
Domain string
HttpAddr, HttpPort string
CertFile, KeyFile string
SocketPath string
RouterLogging bool
DataProxyLogging bool
DataProxyTimeout int
DataProxyTLSHandshakeTimeout int
@@ -93,28 +89,19 @@ var (
EnforceDomain bool
// Security settings.
SecretKey string
DisableGravatar bool
EmailCodeValidMinutes int
DataProxyWhiteList map[string]bool
DisableBruteForceLoginProtection bool
CookieSecure bool
CookieSameSiteDisabled bool
CookieSameSiteMode http.SameSite
AllowEmbedding bool
XSSProtectionHeader bool
ContentTypeProtectionHeader bool
StrictTransportSecurity bool
StrictTransportSecurityMaxAge int
StrictTransportSecurityPreload bool
StrictTransportSecuritySubDomains bool
SecretKey string
DisableGravatar bool
EmailCodeValidMinutes int
DataProxyWhiteList map[string]bool
CookieSecure bool
CookieSameSiteDisabled bool
CookieSameSiteMode http.SameSite
// Snapshots
ExternalSnapshotUrl string
ExternalSnapshotName string
ExternalEnabled bool
SnapShotRemoveExpired bool
SnapshotPublicMode bool
// Dashboard history
DashboardVersionsToKeep int
@@ -129,7 +116,6 @@ var (
VerifyEmailEnabled bool
LoginHint string
PasswordHint string
DefaultTheme string
DisableLoginForm bool
DisableSignoutMenu bool
SignoutRedirectUrl string
@@ -139,7 +125,7 @@ var (
OAuthAutoLogin bool
ViewersCanEdit bool
// Http auth
// HTTP auth
AdminUser string
AdminPassword string
LoginCookieName string
@@ -147,18 +133,10 @@ var (
SigV4AuthEnabled bool
AnonymousEnabled bool
AnonymousOrgName string
AnonymousOrgRole string
// Auth proxy settings
AuthProxyEnabled bool
AuthProxyHeaderName string
AuthProxyHeaderProperty string
AuthProxyAutoSignUp bool
AuthProxyEnableLoginToken bool
AuthProxySyncTtl int
AuthProxyWhitelist string
AuthProxyHeaders map[string]string
AuthProxyEnabled bool
AuthProxyHeaderProperty string
// Basic Auth
BasicAuthEnabled bool
@@ -224,6 +202,9 @@ type Cfg struct {
ServeFromSubPath bool
StaticRootPath string
Protocol Scheme
SocketPath string
RouterLogging bool
Domain string
// build
BuildVersion string
@@ -251,11 +232,18 @@ type Cfg struct {
RendererConcurrentRequestLimit int
// Security
DisableInitAdminCreation bool
DisableBruteForceLoginProtection bool
CookieSecure bool
CookieSameSiteDisabled bool
CookieSameSiteMode http.SameSite
DisableInitAdminCreation bool
DisableBruteForceLoginProtection bool
CookieSecure bool
CookieSameSiteDisabled bool
CookieSameSiteMode http.SameSite
AllowEmbedding bool
XSSProtectionHeader bool
ContentTypeProtectionHeader bool
StrictTransportSecurity bool
StrictTransportSecurityMaxAge int
StrictTransportSecurityPreload bool
StrictTransportSecuritySubDomains bool
TempDataLifetime time.Duration
PluginsEnableAlpha bool
@@ -282,6 +270,17 @@ type Cfg struct {
LoginMaxLifetime time.Duration
TokenRotationIntervalMinutes int
SigV4AuthEnabled bool
BasicAuthEnabled bool
// Auth proxy settings
AuthProxyEnabled bool
AuthProxyHeaderName string
AuthProxyHeaderProperty string
AuthProxyAutoSignUp bool
AuthProxyEnableLoginToken bool
AuthProxyWhitelist string
AuthProxyHeaders map[string]string
AuthProxySyncTTL int
// OAuth
OAuthCookieMaxAge int
@@ -302,6 +301,9 @@ type Cfg struct {
// Use to enable new features which may still be in alpha/beta stage.
FeatureToggles map[string]bool
AnonymousEnabled bool
AnonymousOrgName string
AnonymousOrgRole string
AnonymousHideVersion bool
DateFormats DateFormats
@@ -317,6 +319,21 @@ type Cfg struct {
// Sentry config
Sentry Sentry
// Snapshots
SnapshotPublicMode bool
ErrTemplateName string
Env string
// LDAP
LDAPEnabled bool
LDAPAllowSignup bool
Quota QuotaSettings
DefaultTheme string
}
// IsExpressionsEnabled returns whether the expressions feature is enabled.
@@ -707,9 +724,12 @@ func (cfg *Cfg) Load(args *CommandLineArgs) error {
cfg.IsEnterprise = IsEnterprise
cfg.Packaging = Packaging
cfg.ErrTemplateName = ErrTemplateName
ApplicationName = "Grafana"
Env = valueAsString(iniFile.Section(""), "app_mode", "development")
cfg.Env = Env
InstanceName = valueAsString(iniFile.Section(""), "instance_name", "unknown_instance_name")
plugins := valueAsString(iniFile.Section("paths"), "plugins", "")
PluginsPath = makeAbsolute(plugins, HomePath)
@@ -736,7 +756,7 @@ func (cfg *Cfg) Load(args *CommandLineArgs) error {
return err
}
if err := readSnapshotsSettings(iniFile); err != nil {
if err := readSnapshotsSettings(cfg, iniFile); err != nil {
return err
}
@@ -789,7 +809,6 @@ func (cfg *Cfg) Load(args *CommandLineArgs) error {
cfg.PluginsAllowUnsigned = append(cfg.PluginsAllowUnsigned, plug)
}
cfg.MarketplaceURL = pluginsSection.Key("marketplace_url").MustString("https://grafana.com/grafana/plugins/")
cfg.Protocol = Protocol
// Read and populate feature toggles list
featureTogglesSection := iniFile.Section("feature_toggles")
@@ -858,8 +877,10 @@ func (cfg *Cfg) readLDAPConfig() {
LDAPConfigFile = ldapSec.Key("config_file").String()
LDAPSyncCron = ldapSec.Key("sync_cron").String()
LDAPEnabled = ldapSec.Key("enabled").MustBool(false)
cfg.LDAPEnabled = LDAPEnabled
LDAPActiveSyncEnabled = ldapSec.Key("active_sync_enabled").MustBool(false)
LDAPAllowSignup = ldapSec.Key("allow_sign_up").MustBool(true)
cfg.LDAPAllowSignup = LDAPAllowSignup
}
func (cfg *Cfg) readSessionConfig() {
@@ -910,7 +931,7 @@ func (cfg *Cfg) LogConfigSources() {
cfg.Logger.Info("Path Logs", "path", cfg.LogsPath)
cfg.Logger.Info("Path Plugins", "path", PluginsPath)
cfg.Logger.Info("Path Provisioning", "path", cfg.ProvisioningPath)
cfg.Logger.Info("App mode " + Env)
cfg.Logger.Info("App mode " + cfg.Env)
}
type DynamicSection struct {
@@ -949,7 +970,6 @@ func readSecuritySettings(iniFile *ini.File, cfg *Cfg) error {
SecretKey = valueAsString(security, "secret_key", "")
DisableGravatar = security.Key("disable_gravatar").MustBool(true)
cfg.DisableBruteForceLoginProtection = security.Key("disable_brute_force_login_protection").MustBool(false)
DisableBruteForceLoginProtection = cfg.DisableBruteForceLoginProtection
CookieSecure = security.Key("cookie_secure").MustBool(false)
cfg.CookieSecure = CookieSecure
@@ -974,14 +994,14 @@ func readSecuritySettings(iniFile *ini.File, cfg *Cfg) error {
cfg.CookieSameSiteMode = CookieSameSiteMode
}
}
AllowEmbedding = security.Key("allow_embedding").MustBool(false)
cfg.AllowEmbedding = security.Key("allow_embedding").MustBool(false)
ContentTypeProtectionHeader = security.Key("x_content_type_options").MustBool(true)
XSSProtectionHeader = security.Key("x_xss_protection").MustBool(true)
StrictTransportSecurity = security.Key("strict_transport_security").MustBool(false)
StrictTransportSecurityMaxAge = security.Key("strict_transport_security_max_age_seconds").MustInt(86400)
StrictTransportSecurityPreload = security.Key("strict_transport_security_preload").MustBool(false)
StrictTransportSecuritySubDomains = security.Key("strict_transport_security_subdomains").MustBool(false)
cfg.ContentTypeProtectionHeader = security.Key("x_content_type_options").MustBool(true)
cfg.XSSProtectionHeader = security.Key("x_xss_protection").MustBool(true)
cfg.StrictTransportSecurity = security.Key("strict_transport_security").MustBool(false)
cfg.StrictTransportSecurityMaxAge = security.Key("strict_transport_security_max_age_seconds").MustInt(86400)
cfg.StrictTransportSecurityPreload = security.Key("strict_transport_security_preload").MustBool(false)
cfg.StrictTransportSecuritySubDomains = security.Key("strict_transport_security_subdomains").MustBool(false)
// read data source proxy whitelist
DataProxyWhiteList = make(map[string]bool)
@@ -1054,41 +1074,45 @@ func readAuthSettings(iniFile *ini.File, cfg *Cfg) (err error) {
// anonymous access
AnonymousEnabled = iniFile.Section("auth.anonymous").Key("enabled").MustBool(false)
AnonymousOrgName = valueAsString(iniFile.Section("auth.anonymous"), "org_name", "")
AnonymousOrgRole = valueAsString(iniFile.Section("auth.anonymous"), "org_role", "")
cfg.AnonymousEnabled = AnonymousEnabled
cfg.AnonymousOrgName = valueAsString(iniFile.Section("auth.anonymous"), "org_name", "")
cfg.AnonymousOrgRole = valueAsString(iniFile.Section("auth.anonymous"), "org_role", "")
cfg.AnonymousHideVersion = iniFile.Section("auth.anonymous").Key("hide_version").MustBool(false)
// basic auth
authBasic := iniFile.Section("auth.basic")
BasicAuthEnabled = authBasic.Key("enabled").MustBool(true)
cfg.BasicAuthEnabled = BasicAuthEnabled
authProxy := iniFile.Section("auth.proxy")
AuthProxyEnabled = authProxy.Key("enabled").MustBool(false)
cfg.AuthProxyEnabled = AuthProxyEnabled
AuthProxyHeaderName = valueAsString(authProxy, "header_name", "")
cfg.AuthProxyHeaderName = valueAsString(authProxy, "header_name", "")
AuthProxyHeaderProperty = valueAsString(authProxy, "header_property", "")
AuthProxyAutoSignUp = authProxy.Key("auto_sign_up").MustBool(true)
AuthProxyEnableLoginToken = authProxy.Key("enable_login_token").MustBool(false)
cfg.AuthProxyHeaderProperty = AuthProxyHeaderProperty
cfg.AuthProxyAutoSignUp = authProxy.Key("auto_sign_up").MustBool(true)
cfg.AuthProxyEnableLoginToken = authProxy.Key("enable_login_token").MustBool(false)
ldapSyncVal := authProxy.Key("ldap_sync_ttl").MustInt()
syncVal := authProxy.Key("sync_ttl").MustInt()
if ldapSyncVal != AuthProxySyncTTL {
AuthProxySyncTtl = ldapSyncVal
if ldapSyncVal != authProxySyncTTL {
cfg.AuthProxySyncTTL = ldapSyncVal
cfg.Logger.Warn("[Deprecated] the configuration setting 'ldap_sync_ttl' is deprecated, please use 'sync_ttl' instead")
} else {
AuthProxySyncTtl = syncVal
cfg.AuthProxySyncTTL = syncVal
}
AuthProxyWhitelist = valueAsString(authProxy, "whitelist", "")
cfg.AuthProxyWhitelist = valueAsString(authProxy, "whitelist", "")
AuthProxyHeaders = make(map[string]string)
cfg.AuthProxyHeaders = make(map[string]string)
headers := valueAsString(authProxy, "headers", "")
for _, propertyAndHeader := range util.SplitString(headers) {
split := strings.SplitN(propertyAndHeader, ":", 2)
if len(split) == 2 {
AuthProxyHeaders[split[0]] = split[1]
cfg.AuthProxyHeaders[split[0]] = split[1]
}
}
@@ -1106,7 +1130,7 @@ func readUserSettings(iniFile *ini.File, cfg *Cfg) error {
LoginHint = valueAsString(users, "login_hint", "")
PasswordHint = valueAsString(users, "password_hint", "")
DefaultTheme = valueAsString(users, "default_theme", "")
cfg.DefaultTheme = valueAsString(users, "default_theme", "")
ExternalUserMngLinkUrl = valueAsString(users, "external_manage_link_url", "")
ExternalUserMngLinkName = valueAsString(users, "external_manage_link_name", "")
ExternalUserMngInfo = valueAsString(users, "external_manage_info", "")
@@ -1178,7 +1202,7 @@ func readAlertingSettings(iniFile *ini.File) error {
return nil
}
func readSnapshotsSettings(iniFile *ini.File) error {
func readSnapshotsSettings(cfg *Cfg, iniFile *ini.File) error {
snapshots := iniFile.Section("snapshots")
ExternalSnapshotUrl = valueAsString(snapshots, "external_snapshot_url", "")
@@ -1186,7 +1210,7 @@ func readSnapshotsSettings(iniFile *ini.File) error {
ExternalEnabled = snapshots.Key("external_enabled").MustBool(true)
SnapShotRemoveExpired = snapshots.Key("snapshot_remove_expired").MustBool(true)
SnapshotPublicMode = snapshots.Key("public_mode").MustBool(false)
cfg.SnapshotPublicMode = snapshots.Key("public_mode").MustBool(false)
return nil
}
@@ -1204,28 +1228,28 @@ func readServerSettings(iniFile *ini.File, cfg *Cfg) error {
cfg.AppSubURL = AppSubUrl
cfg.ServeFromSubPath = ServeFromSubPath
Protocol = HTTPScheme
cfg.Protocol = HTTPScheme
protocolStr := valueAsString(server, "protocol", "http")
if protocolStr == "https" {
Protocol = HTTPSScheme
cfg.Protocol = HTTPSScheme
CertFile = server.Key("cert_file").String()
KeyFile = server.Key("cert_key").String()
}
if protocolStr == "h2" {
Protocol = HTTP2Scheme
cfg.Protocol = HTTP2Scheme
CertFile = server.Key("cert_file").String()
KeyFile = server.Key("cert_key").String()
}
if protocolStr == "socket" {
Protocol = SocketScheme
SocketPath = server.Key("socket").String()
cfg.Protocol = SocketScheme
cfg.SocketPath = server.Key("socket").String()
}
Domain = valueAsString(server, "domain", "localhost")
cfg.Domain = valueAsString(server, "domain", "localhost")
HttpAddr = valueAsString(server, "http_addr", DefaultHTTPAddr)
HttpPort = valueAsString(server, "http_port", "3000")
RouterLogging = server.Key("router_logging").MustBool(false)
cfg.RouterLogging = server.Key("router_logging").MustBool(false)
EnableGzip = server.Key("enable_gzip").MustBool(false)
EnforceDomain = server.Key("enforce_domain").MustBool(false)
+2
View File
@@ -86,4 +86,6 @@ func (cfg *Cfg) readQuotaSettings() {
ApiKey: quota.Key("global_api_key").MustInt64(-1),
Session: quota.Key("global_session").MustInt64(-1),
}
cfg.Quota = Quota
}
+5 -5
View File
@@ -133,7 +133,7 @@ func TestLoadingSettings(t *testing.T) {
})
So(err, ShouldBeNil)
So(Domain, ShouldEqual, "test2")
So(cfg.Domain, ShouldEqual, "test2")
})
Convey("Defaults can be overridden in specified config file", func() {
@@ -239,7 +239,7 @@ func TestLoadingSettings(t *testing.T) {
})
So(err, ShouldBeNil)
So(AuthProxySyncTtl, ShouldEqual, 2)
So(cfg.AuthProxySyncTTL, ShouldEqual, 2)
})
Convey("Only ldap_sync_ttl should return the value ldap_sync_ttl", func() {
@@ -250,7 +250,7 @@ func TestLoadingSettings(t *testing.T) {
})
So(err, ShouldBeNil)
So(AuthProxySyncTtl, ShouldEqual, 5)
So(cfg.AuthProxySyncTTL, ShouldEqual, 5)
})
Convey("ldap_sync should override ldap_sync_ttl that is default value", func() {
@@ -261,7 +261,7 @@ func TestLoadingSettings(t *testing.T) {
})
So(err, ShouldBeNil)
So(AuthProxySyncTtl, ShouldEqual, 5)
So(cfg.AuthProxySyncTTL, ShouldEqual, 5)
})
Convey("ldap_sync should not override ldap_sync_ttl that is different from default value", func() {
@@ -272,7 +272,7 @@ func TestLoadingSettings(t *testing.T) {
})
So(err, ShouldBeNil)
So(AuthProxySyncTtl, ShouldEqual, 12)
So(cfg.AuthProxySyncTTL, ShouldEqual, 12)
})
})