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:
co-authored by
Emil Tullsted
Will Browne
parent
d0f52d5334
commit
12661e8a9d
@@ -22,7 +22,7 @@ const (
|
||||
func TestAdminAPIEndpoint(t *testing.T) {
|
||||
const role = models.ROLE_ADMIN
|
||||
|
||||
t.Run("Given a server admin attempts to remove themself as an admin", func(t *testing.T) {
|
||||
t.Run("Given a server admin attempts to remove themselves as an admin", func(t *testing.T) {
|
||||
updateCmd := dtos.AdminUpdateUserPermissionsForm{
|
||||
IsGrafanaAdmin: false,
|
||||
}
|
||||
|
||||
+1
-1
@@ -18,7 +18,7 @@ func (hs *HTTPServer) registerRoutes() {
|
||||
reqEditorRole := middleware.ReqEditorRole
|
||||
reqOrgAdmin := middleware.ReqOrgAdmin
|
||||
reqCanAccessTeams := middleware.AdminOrFeatureEnabled(hs.Cfg.EditorsCanAdmin)
|
||||
reqSnapshotPublicModeOrSignedIn := middleware.SnapshotPublicModeOrSignedIn()
|
||||
reqSnapshotPublicModeOrSignedIn := middleware.SnapshotPublicModeOrSignedIn(hs.Cfg)
|
||||
redirectFromLegacyDashboardURL := middleware.RedirectFromLegacyDashboardURL()
|
||||
redirectFromLegacyDashboardSoloURL := middleware.RedirectFromLegacyDashboardSoloURL()
|
||||
redirectFromLegacyPanelEditURL := middleware.RedirectFromLegacyPanelEditURL()
|
||||
|
||||
+1
-1
@@ -85,7 +85,7 @@ func Success(message string) *NormalResponse {
|
||||
return JSON(200, resp)
|
||||
}
|
||||
|
||||
// Error create a erroneous response
|
||||
// Error creates an error response.
|
||||
func Error(status int, message string, err error) *NormalResponse {
|
||||
data := make(map[string]interface{})
|
||||
|
||||
|
||||
+57
-4
@@ -8,9 +8,14 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/grafana/grafana/pkg/bus"
|
||||
"github.com/grafana/grafana/pkg/middleware"
|
||||
"github.com/grafana/grafana/pkg/infra/remotecache"
|
||||
"github.com/grafana/grafana/pkg/models"
|
||||
"github.com/grafana/grafana/pkg/registry"
|
||||
"github.com/grafana/grafana/pkg/services/auth"
|
||||
"github.com/grafana/grafana/pkg/services/contexthandler"
|
||||
"github.com/grafana/grafana/pkg/services/rendering"
|
||||
"github.com/grafana/grafana/pkg/services/sqlstore"
|
||||
"github.com/grafana/grafana/pkg/setting"
|
||||
"github.com/stretchr/testify/require"
|
||||
"gopkg.in/macaron.v1"
|
||||
)
|
||||
@@ -141,20 +146,68 @@ func (sc *scenarioContext) exec() {
|
||||
type scenarioFunc func(c *scenarioContext)
|
||||
type handlerFunc func(c *models.ReqContext) Response
|
||||
|
||||
func getContextHandler(t *testing.T) *contexthandler.ContextHandler {
|
||||
t.Helper()
|
||||
|
||||
sqlStore := sqlstore.InitTestDB(t)
|
||||
remoteCacheSvc := &remotecache.RemoteCache{}
|
||||
cfg := setting.NewCfg()
|
||||
cfg.RemoteCacheOptions = &setting.RemoteCacheOptions{
|
||||
Name: "database",
|
||||
}
|
||||
userAuthTokenSvc := auth.NewFakeUserAuthTokenService()
|
||||
renderSvc := &fakeRenderService{}
|
||||
ctxHdlr := &contexthandler.ContextHandler{}
|
||||
|
||||
err := registry.BuildServiceGraph([]interface{}{cfg}, []*registry.Descriptor{
|
||||
{
|
||||
Name: sqlstore.ServiceName,
|
||||
Instance: sqlStore,
|
||||
},
|
||||
{
|
||||
Name: remotecache.ServiceName,
|
||||
Instance: remoteCacheSvc,
|
||||
},
|
||||
{
|
||||
Name: auth.ServiceName,
|
||||
Instance: userAuthTokenSvc,
|
||||
},
|
||||
{
|
||||
Name: rendering.ServiceName,
|
||||
Instance: renderSvc,
|
||||
},
|
||||
{
|
||||
Name: contexthandler.ServiceName,
|
||||
Instance: ctxHdlr,
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
return ctxHdlr
|
||||
}
|
||||
|
||||
func setupScenarioContext(t *testing.T, url string) *scenarioContext {
|
||||
sc := &scenarioContext{
|
||||
url: url,
|
||||
t: t,
|
||||
}
|
||||
viewsPath, _ := filepath.Abs("../../public/views")
|
||||
viewsPath, err := filepath.Abs("../../public/views")
|
||||
require.NoError(t, err)
|
||||
|
||||
sc.m = macaron.New()
|
||||
sc.m.Use(macaron.Renderer(macaron.RenderOptions{
|
||||
Directory: viewsPath,
|
||||
Delims: macaron.Delims{Left: "[[", Right: "]]"},
|
||||
}))
|
||||
|
||||
sc.m.Use(middleware.GetContextHandler(nil, nil, nil))
|
||||
sc.m.Use(getContextHandler(t).Middleware)
|
||||
|
||||
return sc
|
||||
}
|
||||
|
||||
type fakeRenderService struct {
|
||||
rendering.Service
|
||||
}
|
||||
|
||||
func (s *fakeRenderService) Init() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -193,11 +193,11 @@ func (hs *HTTPServer) getFrontendSettingsMap(c *models.ReqContext) (map[string]i
|
||||
"datasources": dataSources,
|
||||
"minRefreshInterval": setting.MinRefreshInterval,
|
||||
"panels": panels,
|
||||
"appUrl": setting.AppUrl,
|
||||
"appSubUrl": setting.AppSubUrl,
|
||||
"appUrl": hs.Cfg.AppURL,
|
||||
"appSubUrl": hs.Cfg.AppSubURL,
|
||||
"allowOrgCreate": (setting.AllowUserOrgCreate && c.IsSignedIn) || c.IsGrafanaAdmin,
|
||||
"authProxyEnabled": setting.AuthProxyEnabled,
|
||||
"ldapEnabled": setting.LDAPEnabled,
|
||||
"ldapEnabled": hs.Cfg.LDAPEnabled,
|
||||
"alertingEnabled": setting.AlertingEnabled,
|
||||
"alertingErrorOrTimeout": setting.AlertingErrorOrTimeout,
|
||||
"alertingNoDataOrNullValues": setting.AlertingNoDataOrNullValues,
|
||||
|
||||
@@ -18,7 +18,6 @@ import (
|
||||
"github.com/grafana/grafana/pkg/bus"
|
||||
"github.com/grafana/grafana/pkg/services/sqlstore"
|
||||
|
||||
"github.com/grafana/grafana/pkg/middleware"
|
||||
"gopkg.in/macaron.v1"
|
||||
|
||||
"github.com/grafana/grafana/pkg/setting"
|
||||
@@ -53,7 +52,7 @@ func setupTestEnvironment(t *testing.T, cfg *setting.Cfg) (*macaron.Macaron, *HT
|
||||
}
|
||||
|
||||
m := macaron.New()
|
||||
m.Use(middleware.GetContextHandler(nil, nil, nil))
|
||||
m.Use(getContextHandler(t).Middleware)
|
||||
m.Use(macaron.Renderer(macaron.RenderOptions{
|
||||
Directory: filepath.Join(setting.StaticRootPath, "views"),
|
||||
IndentJSON: true,
|
||||
@@ -84,10 +83,12 @@ func TestHTTPServer_GetFrontendSettings_hideVersionAnonyomus(t *testing.T) {
|
||||
setting.Env = "testing"
|
||||
|
||||
tests := []struct {
|
||||
desc string
|
||||
hideVersion bool
|
||||
expected settings
|
||||
}{
|
||||
{
|
||||
desc: "Not hiding version",
|
||||
hideVersion: false,
|
||||
expected: settings{
|
||||
BuildInfo: buildInfo{
|
||||
@@ -98,6 +99,7 @@ func TestHTTPServer_GetFrontendSettings_hideVersionAnonyomus(t *testing.T) {
|
||||
},
|
||||
},
|
||||
{
|
||||
desc: "Hiding version",
|
||||
hideVersion: true,
|
||||
expected: settings{
|
||||
BuildInfo: buildInfo{
|
||||
@@ -110,16 +112,18 @@ func TestHTTPServer_GetFrontendSettings_hideVersionAnonyomus(t *testing.T) {
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
hs.Cfg.AnonymousHideVersion = test.hideVersion
|
||||
expected := test.expected
|
||||
t.Run(test.desc, func(t *testing.T) {
|
||||
hs.Cfg.AnonymousHideVersion = test.hideVersion
|
||||
expected := test.expected
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
m.ServeHTTP(recorder, req)
|
||||
got := settings{}
|
||||
err := json.Unmarshal(recorder.Body.Bytes(), &got)
|
||||
require.NoError(t, err)
|
||||
require.GreaterOrEqual(t, 400, recorder.Code, "status codes higher than 400 indicates a failure")
|
||||
recorder := httptest.NewRecorder()
|
||||
m.ServeHTTP(recorder, req)
|
||||
got := settings{}
|
||||
err := json.Unmarshal(recorder.Body.Bytes(), &got)
|
||||
require.NoError(t, err)
|
||||
require.GreaterOrEqual(t, 400, recorder.Code, "status codes higher than 400 indicate a failure")
|
||||
|
||||
assert.EqualValues(t, expected, got)
|
||||
assert.EqualValues(t, expected, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
+19
-21
@@ -29,6 +29,7 @@ import (
|
||||
"github.com/grafana/grafana/pkg/models"
|
||||
"github.com/grafana/grafana/pkg/plugins"
|
||||
"github.com/grafana/grafana/pkg/registry"
|
||||
"github.com/grafana/grafana/pkg/services/contexthandler"
|
||||
"github.com/grafana/grafana/pkg/services/datasources"
|
||||
"github.com/grafana/grafana/pkg/services/hooks"
|
||||
"github.com/grafana/grafana/pkg/services/login"
|
||||
@@ -75,6 +76,7 @@ type HTTPServer struct {
|
||||
SearchService *search.SearchService `inject:""`
|
||||
ShortURLService *shorturls.ShortURLService `inject:""`
|
||||
Live *live.GrafanaLive `inject:""`
|
||||
ContextHandler *contexthandler.ContextHandler `inject:""`
|
||||
Listener net.Listener
|
||||
}
|
||||
|
||||
@@ -100,7 +102,7 @@ func (hs *HTTPServer) Run(ctx context.Context) error {
|
||||
Addr: net.JoinHostPort(setting.HttpAddr, setting.HttpPort),
|
||||
Handler: hs.macaron,
|
||||
}
|
||||
switch setting.Protocol {
|
||||
switch hs.Cfg.Protocol {
|
||||
case setting.HTTP2Scheme:
|
||||
if err := hs.configureHttp2(); err != nil {
|
||||
return err
|
||||
@@ -118,7 +120,7 @@ func (hs *HTTPServer) Run(ctx context.Context) error {
|
||||
}
|
||||
|
||||
hs.log.Info("HTTP Server Listen", "address", listener.Addr().String(), "protocol",
|
||||
setting.Protocol, "subUrl", setting.AppSubUrl, "socket", setting.SocketPath)
|
||||
hs.Cfg.Protocol, "subUrl", hs.Cfg.AppSubURL, "socket", hs.Cfg.SocketPath)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
@@ -133,7 +135,7 @@ func (hs *HTTPServer) Run(ctx context.Context) error {
|
||||
}
|
||||
}()
|
||||
|
||||
switch setting.Protocol {
|
||||
switch hs.Cfg.Protocol {
|
||||
case setting.HTTPScheme, setting.SocketScheme:
|
||||
if err := hs.httpSrv.Serve(listener); err != nil {
|
||||
if errors.Is(err, http.ErrServerClosed) {
|
||||
@@ -151,7 +153,7 @@ func (hs *HTTPServer) Run(ctx context.Context) error {
|
||||
return err
|
||||
}
|
||||
default:
|
||||
panic(fmt.Sprintf("Unhandled protocol %q", setting.Protocol))
|
||||
panic(fmt.Sprintf("Unhandled protocol %q", hs.Cfg.Protocol))
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
@@ -164,7 +166,7 @@ func (hs *HTTPServer) getListener() (net.Listener, error) {
|
||||
return hs.Listener, nil
|
||||
}
|
||||
|
||||
switch setting.Protocol {
|
||||
switch hs.Cfg.Protocol {
|
||||
case setting.HTTPScheme, setting.HTTPSScheme, setting.HTTP2Scheme:
|
||||
listener, err := net.Listen("tcp", hs.httpSrv.Addr)
|
||||
if err != nil {
|
||||
@@ -172,21 +174,21 @@ func (hs *HTTPServer) getListener() (net.Listener, error) {
|
||||
}
|
||||
return listener, nil
|
||||
case setting.SocketScheme:
|
||||
listener, err := net.ListenUnix("unix", &net.UnixAddr{Name: setting.SocketPath, Net: "unix"})
|
||||
listener, err := net.ListenUnix("unix", &net.UnixAddr{Name: hs.Cfg.SocketPath, Net: "unix"})
|
||||
if err != nil {
|
||||
return nil, errutil.Wrapf(err, "failed to open listener for socket %s", setting.SocketPath)
|
||||
return nil, errutil.Wrapf(err, "failed to open listener for socket %s", hs.Cfg.SocketPath)
|
||||
}
|
||||
|
||||
// Make socket writable by group
|
||||
// nolint:gosec
|
||||
if err := os.Chmod(setting.SocketPath, 0660); err != nil {
|
||||
if err := os.Chmod(hs.Cfg.SocketPath, 0660); err != nil {
|
||||
return nil, errutil.Wrapf(err, "failed to change socket permissions")
|
||||
}
|
||||
|
||||
return listener, nil
|
||||
default:
|
||||
hs.log.Error("Invalid protocol", "protocol", setting.Protocol)
|
||||
return nil, fmt.Errorf("invalid protocol %q", setting.Protocol)
|
||||
hs.log.Error("Invalid protocol", "protocol", hs.Cfg.Protocol)
|
||||
return nil, fmt.Errorf("invalid protocol %q", hs.Cfg.Protocol)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -271,7 +273,7 @@ func (hs *HTTPServer) configureHttp2() error {
|
||||
}
|
||||
|
||||
func (hs *HTTPServer) newMacaron() *macaron.Macaron {
|
||||
macaron.Env = setting.Env
|
||||
macaron.Env = hs.Cfg.Env
|
||||
m := macaron.New()
|
||||
|
||||
// automatically set HEAD for every GET
|
||||
@@ -294,13 +296,13 @@ func (hs *HTTPServer) applyRoutes() {
|
||||
func (hs *HTTPServer) addMiddlewaresAndStaticRoutes() {
|
||||
m := hs.macaron
|
||||
|
||||
m.Use(middleware.Logger())
|
||||
m.Use(middleware.Logger(hs.Cfg))
|
||||
|
||||
if setting.EnableGzip {
|
||||
m.Use(middleware.Gziper())
|
||||
}
|
||||
|
||||
m.Use(middleware.Recovery())
|
||||
m.Use(middleware.Recovery(hs.Cfg))
|
||||
|
||||
for _, route := range plugins.StaticRoutes {
|
||||
pluginRoute := path.Join("/public/plugins/", route.PluginId)
|
||||
@@ -316,7 +318,7 @@ func (hs *HTTPServer) addMiddlewaresAndStaticRoutes() {
|
||||
hs.mapStatic(m, hs.Cfg.ImagesDir, "", "/public/img/attachments")
|
||||
}
|
||||
|
||||
m.Use(middleware.AddDefaultResponseHeaders())
|
||||
m.Use(middleware.AddDefaultResponseHeaders(hs.Cfg))
|
||||
|
||||
if setting.ServeFromSubPath && setting.AppSubUrl != "" {
|
||||
m.SetURLPrefix(setting.AppSubUrl)
|
||||
@@ -334,16 +336,12 @@ func (hs *HTTPServer) addMiddlewaresAndStaticRoutes() {
|
||||
m.Use(hs.apiHealthHandler)
|
||||
m.Use(hs.metricsEndpoint)
|
||||
|
||||
m.Use(middleware.GetContextHandler(
|
||||
hs.AuthTokenService,
|
||||
hs.RemoteCacheService,
|
||||
hs.RenderService,
|
||||
))
|
||||
m.Use(hs.ContextHandler.Middleware)
|
||||
m.Use(middleware.OrgRedirect())
|
||||
|
||||
// needs to be after context handler
|
||||
if setting.EnforceDomain {
|
||||
m.Use(middleware.ValidateHostHeader(setting.Domain))
|
||||
m.Use(middleware.ValidateHostHeader(hs.Cfg.Domain))
|
||||
}
|
||||
|
||||
m.Use(middleware.HandleNoCacheHeader())
|
||||
@@ -433,7 +431,7 @@ func (hs *HTTPServer) mapStatic(m *macaron.Macaron, rootDir string, dir string,
|
||||
}
|
||||
}
|
||||
|
||||
if setting.Env == setting.Dev {
|
||||
if hs.Cfg.Env == setting.Dev {
|
||||
headers = func(c *macaron.Context) {
|
||||
c.Resp.Header().Set("Cache-Control", "max-age=0, must-revalidate, no-cache")
|
||||
}
|
||||
|
||||
+2
-2
@@ -300,7 +300,7 @@ func (hs *HTTPServer) getNavTree(c *models.ReqContext, hasEditPerm bool) ([]*dto
|
||||
{Text: "Stats", Id: "server-stats", Url: setting.AppSubUrl + "/admin/stats", Icon: "graph-bar"},
|
||||
}
|
||||
|
||||
if setting.LDAPEnabled {
|
||||
if hs.Cfg.LDAPEnabled {
|
||||
adminNavLinks = append(adminNavLinks, &dtos.NavLink{
|
||||
Text: "LDAP", Id: "ldap", Url: setting.AppSubUrl + "/admin/ldap", Icon: "book",
|
||||
})
|
||||
@@ -371,7 +371,7 @@ func (hs *HTTPServer) setIndexViewData(c *models.ReqContext) (*dtos.IndexViewDat
|
||||
|
||||
// special case when doing localhost call from image renderer
|
||||
if c.IsRenderCall && !hs.Cfg.ServeFromSubPath {
|
||||
appURL = fmt.Sprintf("%s://localhost:%s", setting.Protocol, setting.HttpPort)
|
||||
appURL = fmt.Sprintf("%s://localhost:%s", hs.Cfg.Protocol, setting.HttpPort)
|
||||
appSubURL = ""
|
||||
settings["appSubUrl"] = ""
|
||||
}
|
||||
|
||||
@@ -116,7 +116,7 @@ func (hs *HTTPServer) GetLDAPStatus(c *models.ReqContext) Response {
|
||||
return Error(http.StatusBadRequest, "LDAP is not enabled", nil)
|
||||
}
|
||||
|
||||
ldapConfig, err := getLDAPConfig()
|
||||
ldapConfig, err := getLDAPConfig(hs.Cfg)
|
||||
|
||||
if err != nil {
|
||||
return Error(http.StatusBadRequest, "Failed to obtain the LDAP configuration. Please verify the configuration and try again", err)
|
||||
@@ -158,7 +158,7 @@ func (hs *HTTPServer) PostSyncUserWithLDAP(c *models.ReqContext) Response {
|
||||
return Error(http.StatusBadRequest, "LDAP is not enabled", nil)
|
||||
}
|
||||
|
||||
ldapConfig, err := getLDAPConfig()
|
||||
ldapConfig, err := getLDAPConfig(hs.Cfg)
|
||||
if err != nil {
|
||||
return Error(http.StatusBadRequest, "Failed to obtain the LDAP configuration. Please verify the configuration and try again", err)
|
||||
}
|
||||
@@ -217,7 +217,7 @@ func (hs *HTTPServer) PostSyncUserWithLDAP(c *models.ReqContext) Response {
|
||||
upsertCmd := &models.UpsertUserCommand{
|
||||
ReqContext: c,
|
||||
ExternalUser: user,
|
||||
SignupAllowed: setting.LDAPAllowSignup,
|
||||
SignupAllowed: hs.Cfg.LDAPAllowSignup,
|
||||
}
|
||||
|
||||
err = bus.Dispatch(upsertCmd)
|
||||
@@ -235,7 +235,7 @@ func (hs *HTTPServer) GetUserFromLDAP(c *models.ReqContext) Response {
|
||||
return Error(http.StatusBadRequest, "LDAP is not enabled", nil)
|
||||
}
|
||||
|
||||
ldapConfig, err := getLDAPConfig()
|
||||
ldapConfig, err := getLDAPConfig(hs.Cfg)
|
||||
|
||||
if err != nil {
|
||||
return Error(http.StatusBadRequest, "Failed to obtain the LDAP configuration", err)
|
||||
|
||||
@@ -74,7 +74,7 @@ func getUserFromLDAPContext(t *testing.T, requestURL string) *scenarioContext {
|
||||
}
|
||||
|
||||
func TestGetUserFromLDAPAPIEndpoint_UserNotFound(t *testing.T) {
|
||||
getLDAPConfig = func() (*ldap.Config, error) {
|
||||
getLDAPConfig = func(*setting.Cfg) (*ldap.Config, error) {
|
||||
return &ldap.Config{}, nil
|
||||
}
|
||||
|
||||
@@ -131,7 +131,7 @@ func TestGetUserFromLDAPAPIEndpoint_OrgNotfound(t *testing.T) {
|
||||
return nil
|
||||
})
|
||||
|
||||
getLDAPConfig = func() (*ldap.Config, error) {
|
||||
getLDAPConfig = func(*setting.Cfg) (*ldap.Config, error) {
|
||||
return &ldap.Config{}, nil
|
||||
}
|
||||
|
||||
@@ -193,7 +193,7 @@ func TestGetUserFromLDAPAPIEndpoint(t *testing.T) {
|
||||
return nil
|
||||
})
|
||||
|
||||
getLDAPConfig = func() (*ldap.Config, error) {
|
||||
getLDAPConfig = func(*setting.Cfg) (*ldap.Config, error) {
|
||||
return &ldap.Config{}, nil
|
||||
}
|
||||
|
||||
@@ -273,7 +273,7 @@ func TestGetUserFromLDAPAPIEndpoint_WithTeamHandler(t *testing.T) {
|
||||
return nil
|
||||
})
|
||||
|
||||
getLDAPConfig = func() (*ldap.Config, error) {
|
||||
getLDAPConfig = func(*setting.Cfg) (*ldap.Config, error) {
|
||||
return &ldap.Config{}, nil
|
||||
}
|
||||
|
||||
@@ -349,7 +349,7 @@ func TestGetLDAPStatusAPIEndpoint(t *testing.T) {
|
||||
{Host: "10.0.0.5", Port: 361, Available: false, Error: errors.New("something is awfully wrong")},
|
||||
}
|
||||
|
||||
getLDAPConfig = func() (*ldap.Config, error) {
|
||||
getLDAPConfig = func(*setting.Cfg) (*ldap.Config, error) {
|
||||
return &ldap.Config{}, nil
|
||||
}
|
||||
|
||||
@@ -412,7 +412,7 @@ func postSyncUserWithLDAPContext(t *testing.T, requestURL string, preHook func(t
|
||||
|
||||
func TestPostSyncUserWithLDAPAPIEndpoint_Success(t *testing.T) {
|
||||
sc := postSyncUserWithLDAPContext(t, "/api/admin/ldap/sync/34", func(t *testing.T) {
|
||||
getLDAPConfig = func() (*ldap.Config, error) {
|
||||
getLDAPConfig = func(*setting.Cfg) (*ldap.Config, error) {
|
||||
return &ldap.Config{}, nil
|
||||
}
|
||||
|
||||
@@ -457,7 +457,7 @@ func TestPostSyncUserWithLDAPAPIEndpoint_Success(t *testing.T) {
|
||||
|
||||
func TestPostSyncUserWithLDAPAPIEndpoint_WhenUserNotFound(t *testing.T) {
|
||||
sc := postSyncUserWithLDAPContext(t, "/api/admin/ldap/sync/34", func(t *testing.T) {
|
||||
getLDAPConfig = func() (*ldap.Config, error) {
|
||||
getLDAPConfig = func(*setting.Cfg) (*ldap.Config, error) {
|
||||
return &ldap.Config{}, nil
|
||||
}
|
||||
|
||||
@@ -485,7 +485,7 @@ func TestPostSyncUserWithLDAPAPIEndpoint_WhenUserNotFound(t *testing.T) {
|
||||
|
||||
func TestPostSyncUserWithLDAPAPIEndpoint_WhenGrafanaAdmin(t *testing.T) {
|
||||
sc := postSyncUserWithLDAPContext(t, "/api/admin/ldap/sync/34", func(t *testing.T) {
|
||||
getLDAPConfig = func() (*ldap.Config, error) {
|
||||
getLDAPConfig = func(*setting.Cfg) (*ldap.Config, error) {
|
||||
return &ldap.Config{}, nil
|
||||
}
|
||||
|
||||
@@ -528,7 +528,7 @@ func TestPostSyncUserWithLDAPAPIEndpoint_WhenGrafanaAdmin(t *testing.T) {
|
||||
|
||||
func TestPostSyncUserWithLDAPAPIEndpoint_WhenUserNotInLDAP(t *testing.T) {
|
||||
sc := postSyncUserWithLDAPContext(t, "/api/admin/ldap/sync/34", func(t *testing.T) {
|
||||
getLDAPConfig = func() (*ldap.Config, error) {
|
||||
getLDAPConfig = func(*setting.Cfg) (*ldap.Config, error) {
|
||||
return &ldap.Config{}, nil
|
||||
}
|
||||
|
||||
|
||||
+11
-10
@@ -13,7 +13,7 @@ import (
|
||||
"github.com/grafana/grafana/pkg/infra/metrics"
|
||||
"github.com/grafana/grafana/pkg/infra/network"
|
||||
"github.com/grafana/grafana/pkg/login"
|
||||
"github.com/grafana/grafana/pkg/middleware"
|
||||
"github.com/grafana/grafana/pkg/middleware/cookies"
|
||||
"github.com/grafana/grafana/pkg/models"
|
||||
"github.com/grafana/grafana/pkg/setting"
|
||||
"github.com/grafana/grafana/pkg/util"
|
||||
@@ -61,12 +61,12 @@ func (hs *HTTPServer) ValidateRedirectTo(redirectTo string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (hs *HTTPServer) CookieOptionsFromCfg() middleware.CookieOptions {
|
||||
func (hs *HTTPServer) CookieOptionsFromCfg() cookies.CookieOptions {
|
||||
path := "/"
|
||||
if len(hs.Cfg.AppSubURL) > 0 {
|
||||
path = hs.Cfg.AppSubURL
|
||||
}
|
||||
return middleware.CookieOptions{
|
||||
return cookies.CookieOptions{
|
||||
Path: path,
|
||||
Secure: hs.Cfg.CookieSecure,
|
||||
SameSiteDisabled: hs.Cfg.CookieSameSiteDisabled,
|
||||
@@ -101,7 +101,7 @@ func (hs *HTTPServer) LoginView(c *models.ReqContext) {
|
||||
// therefore the loginError should be passed to the view data
|
||||
// and the view should return immediately before attempting
|
||||
// to login again via OAuth and enter to a redirect loop
|
||||
middleware.DeleteCookie(c.Resp, LoginErrorCookieName, hs.CookieOptionsFromCfg)
|
||||
cookies.DeleteCookie(c.Resp, LoginErrorCookieName, hs.CookieOptionsFromCfg)
|
||||
viewData.Settings["loginError"] = loginError
|
||||
c.HTML(200, getViewIndex(), viewData)
|
||||
return
|
||||
@@ -113,7 +113,7 @@ func (hs *HTTPServer) LoginView(c *models.ReqContext) {
|
||||
|
||||
if c.IsSignedIn {
|
||||
// Assign login token to auth proxy users if enable_login_token = true
|
||||
if setting.AuthProxyEnabled && setting.AuthProxyEnableLoginToken {
|
||||
if hs.Cfg.AuthProxyEnabled && hs.Cfg.AuthProxyEnableLoginToken {
|
||||
user := &models.User{Id: c.SignedInUser.UserId, Email: c.SignedInUser.Email, Login: c.SignedInUser.Login}
|
||||
err := hs.loginUserWithUser(user, c)
|
||||
if err != nil {
|
||||
@@ -129,7 +129,7 @@ func (hs *HTTPServer) LoginView(c *models.ReqContext) {
|
||||
log.Debugf("Ignored invalid redirect_to cookie value: %v", redirectTo)
|
||||
redirectTo = hs.Cfg.AppSubURL + "/"
|
||||
}
|
||||
middleware.DeleteCookie(c.Resp, "redirect_to", hs.CookieOptionsFromCfg)
|
||||
cookies.DeleteCookie(c.Resp, "redirect_to", hs.CookieOptionsFromCfg)
|
||||
c.Redirect(redirectTo)
|
||||
return
|
||||
}
|
||||
@@ -196,6 +196,7 @@ func (hs *HTTPServer) LoginPost(c *models.ReqContext, cmd dtos.LoginCommand) Res
|
||||
Username: cmd.User,
|
||||
Password: cmd.Password,
|
||||
IpAddress: c.Req.RemoteAddr,
|
||||
Cfg: hs.Cfg,
|
||||
}
|
||||
|
||||
err := bus.Dispatch(authQuery)
|
||||
@@ -236,7 +237,7 @@ func (hs *HTTPServer) LoginPost(c *models.ReqContext, cmd dtos.LoginCommand) Res
|
||||
} else {
|
||||
log.Infof("Ignored invalid redirect_to cookie value: %v", redirectTo)
|
||||
}
|
||||
middleware.DeleteCookie(c.Resp, "redirect_to", hs.CookieOptionsFromCfg)
|
||||
cookies.DeleteCookie(c.Resp, "redirect_to", hs.CookieOptionsFromCfg)
|
||||
}
|
||||
|
||||
metrics.MApiLoginPost.Inc()
|
||||
@@ -263,7 +264,7 @@ func (hs *HTTPServer) loginUserWithUser(user *models.User, c *models.ReqContext)
|
||||
}
|
||||
|
||||
hs.log.Info("Successful Login", "User", user.Email)
|
||||
middleware.WriteSessionCookie(c, userToken.UnhashedToken, hs.Cfg.LoginMaxLifetime)
|
||||
cookies.WriteSessionCookie(c, hs.Cfg, userToken.UnhashedToken, hs.Cfg.LoginMaxLifetime)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -278,7 +279,7 @@ func (hs *HTTPServer) Logout(c *models.ReqContext) {
|
||||
hs.log.Error("failed to revoke auth token", "error", err)
|
||||
}
|
||||
|
||||
middleware.WriteSessionCookie(c, "", -1)
|
||||
cookies.WriteSessionCookie(c, hs.Cfg, "", -1)
|
||||
|
||||
if setting.SignoutRedirectUrl != "" {
|
||||
c.Redirect(setting.SignoutRedirectUrl)
|
||||
@@ -309,7 +310,7 @@ func (hs *HTTPServer) trySetEncryptedCookie(ctx *models.ReqContext, cookieName s
|
||||
return err
|
||||
}
|
||||
|
||||
middleware.WriteCookie(ctx.Resp, cookieName, hex.EncodeToString(encryptedError), 60, hs.CookieOptionsFromCfg)
|
||||
cookies.WriteCookie(ctx.Resp, cookieName, hex.EncodeToString(encryptedError), 60, hs.CookieOptionsFromCfg)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ import (
|
||||
"github.com/grafana/grafana/pkg/infra/metrics"
|
||||
"github.com/grafana/grafana/pkg/login"
|
||||
"github.com/grafana/grafana/pkg/login/social"
|
||||
"github.com/grafana/grafana/pkg/middleware"
|
||||
"github.com/grafana/grafana/pkg/middleware/cookies"
|
||||
"github.com/grafana/grafana/pkg/models"
|
||||
"github.com/grafana/grafana/pkg/setting"
|
||||
)
|
||||
@@ -81,7 +81,7 @@ func (hs *HTTPServer) OAuthLogin(ctx *models.ReqContext) {
|
||||
}
|
||||
|
||||
hashedState := hashStatecode(state, setting.OAuthService.OAuthInfos[name].ClientSecret)
|
||||
middleware.WriteCookie(ctx.Resp, OauthStateCookieName, hashedState, hs.Cfg.OAuthCookieMaxAge, hs.CookieOptionsFromCfg)
|
||||
cookies.WriteCookie(ctx.Resp, OauthStateCookieName, hashedState, hs.Cfg.OAuthCookieMaxAge, hs.CookieOptionsFromCfg)
|
||||
if setting.OAuthService.OAuthInfos[name].HostedDomain == "" {
|
||||
ctx.Redirect(connect.AuthCodeURL(state, oauth2.AccessTypeOnline))
|
||||
} else {
|
||||
@@ -93,7 +93,7 @@ func (hs *HTTPServer) OAuthLogin(ctx *models.ReqContext) {
|
||||
cookieState := ctx.GetCookie(OauthStateCookieName)
|
||||
|
||||
// delete cookie
|
||||
middleware.DeleteCookie(ctx.Resp, OauthStateCookieName, hs.CookieOptionsFromCfg)
|
||||
cookies.DeleteCookie(ctx.Resp, OauthStateCookieName, hs.CookieOptionsFromCfg)
|
||||
|
||||
if cookieState == "" {
|
||||
hs.handleOAuthLoginError(ctx, loginInfo, LoginError{
|
||||
@@ -192,7 +192,7 @@ func (hs *HTTPServer) OAuthLogin(ctx *models.ReqContext) {
|
||||
|
||||
if redirectTo, err := url.QueryUnescape(ctx.GetCookie("redirect_to")); err == nil && len(redirectTo) > 0 {
|
||||
if err := hs.ValidateRedirectTo(redirectTo); err == nil {
|
||||
middleware.DeleteCookie(ctx.Resp, "redirect_to", hs.CookieOptionsFromCfg)
|
||||
cookies.DeleteCookie(ctx.Resp, "redirect_to", hs.CookieOptionsFromCfg)
|
||||
ctx.Redirect(redirectTo)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -592,8 +592,8 @@ func setupAuthProxyLoginTest(t *testing.T, enableLoginToken bool) *scenarioConte
|
||||
|
||||
setting.OAuthService = &setting.OAuther{}
|
||||
setting.OAuthService.OAuthInfos = make(map[string]*setting.OAuthInfo)
|
||||
setting.AuthProxyEnabled = true
|
||||
setting.AuthProxyEnableLoginToken = enableLoginToken
|
||||
hs.Cfg.AuthProxyEnabled = true
|
||||
hs.Cfg.AuthProxyEnableLoginToken = enableLoginToken
|
||||
|
||||
sc.m.Get(sc.url, sc.defaultHandler)
|
||||
sc.fakeReqNoAssertions("GET", sc.url).exec()
|
||||
|
||||
Reference in New Issue
Block a user