Merge pull request #15205 from seanlaff/12556-oauth-pass-thru

Add oauth pass-thru option for datasources
This commit is contained in:
Daniel Lee
2019-03-25 21:52:20 +01:00
committed by GitHub
10 changed files with 379 additions and 15 deletions
+1
View File
@@ -165,6 +165,7 @@ func (hs *HTTPServer) OAuthLogin(ctx *m.ReqContext) {
extUser := &m.ExternalUserInfo{
AuthModule: "oauth_" + name,
OAuthToken: token,
AuthId: userInfo.Id,
Name: userInfo.Name,
Login: userInfo.Login,
+50
View File
@@ -14,8 +14,11 @@ import (
"time"
"github.com/opentracing/opentracing-go"
"golang.org/x/oauth2"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/log"
"github.com/grafana/grafana/pkg/login/social"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/plugins"
"github.com/grafana/grafana/pkg/setting"
@@ -221,6 +224,10 @@ func (proxy *DataSourceProxy) getDirector() func(req *http.Request) {
if proxy.route != nil {
ApplyRoute(proxy.ctx.Req.Context(), req, proxy.proxyPath, proxy.route, proxy.ds)
}
if proxy.ds.JsonData != nil && proxy.ds.JsonData.Get("oauthPassThru").MustBool() {
addOAuthPassThruAuth(proxy.ctx, req)
}
}
}
@@ -311,3 +318,46 @@ func checkWhiteList(c *m.ReqContext, host string) bool {
return true
}
func addOAuthPassThruAuth(c *m.ReqContext, req *http.Request) {
authInfoQuery := &m.GetAuthInfoQuery{UserId: c.UserId}
if err := bus.Dispatch(authInfoQuery); err != nil {
logger.Error("Error feching oauth information for user", "error", err)
return
}
provider := authInfoQuery.Result.AuthModule
connect, ok := social.SocialMap[strings.TrimPrefix(provider, "oauth_")] // The socialMap keys don't have "oauth_" prefix, but everywhere else in the system does
if !ok {
logger.Error("Failed to find oauth provider with given name", "provider", provider)
return
}
// TokenSource handles refreshing the token if it has expired
token, err := connect.TokenSource(c.Req.Context(), &oauth2.Token{
AccessToken: authInfoQuery.Result.OAuthAccessToken,
Expiry: authInfoQuery.Result.OAuthExpiry,
RefreshToken: authInfoQuery.Result.OAuthRefreshToken,
TokenType: authInfoQuery.Result.OAuthTokenType,
}).Token()
if err != nil {
logger.Error("Failed to retrieve access token from oauth provider", "provider", authInfoQuery.Result.AuthModule)
return
}
// If the tokens are not the same, update the entry in the DB
if token.AccessToken != authInfoQuery.Result.OAuthAccessToken {
updateAuthCommand := &m.UpdateAuthInfoCommand{
UserId: authInfoQuery.Result.Id,
AuthModule: authInfoQuery.Result.AuthModule,
AuthId: authInfoQuery.Result.AuthId,
OAuthToken: token,
}
if err := bus.Dispatch(updateAuthCommand); err != nil {
logger.Error("Failed to update access token during token refresh", "error", err)
return
}
}
req.Header.Del("Authorization")
req.Header.Add("Authorization", fmt.Sprintf("%s %s", token.Type(), token.AccessToken))
}
+51
View File
@@ -9,10 +9,13 @@ import (
"testing"
"time"
"golang.org/x/oauth2"
macaron "gopkg.in/macaron.v1"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/log"
"github.com/grafana/grafana/pkg/login/social"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/plugins"
"github.com/grafana/grafana/pkg/setting"
@@ -389,6 +392,54 @@ func TestDSRouteRule(t *testing.T) {
})
})
Convey("When proxying a datasource that has oauth token pass-thru enabled", func() {
social.SocialMap["generic_oauth"] = &social.SocialGenericOAuth{
SocialBase: &social.SocialBase{
Config: &oauth2.Config{},
},
}
bus.AddHandler("test", func(query *m.GetAuthInfoQuery) error {
query.Result = &m.UserAuth{
Id: 1,
UserId: 1,
AuthModule: "generic_oauth",
OAuthAccessToken: "testtoken",
OAuthRefreshToken: "testrefreshtoken",
OAuthTokenType: "Bearer",
OAuthExpiry: time.Now().AddDate(0, 0, 1),
}
return nil
})
plugin := &plugins.DataSourcePlugin{}
ds := &m.DataSource{
Type: "custom-datasource",
Url: "http://host/root/",
JsonData: simplejson.NewFromAny(map[string]interface{}{
"oauthPassThru": true,
}),
}
req, _ := http.NewRequest("GET", "http://localhost/asd", nil)
ctx := &m.ReqContext{
SignedInUser: &m.SignedInUser{UserId: 1},
Context: &macaron.Context{
Req: macaron.Request{Request: req},
},
}
proxy := NewDataSourceProxy(ds, plugin, ctx, "/path/to/folder/", &setting.Cfg{})
req, err := http.NewRequest(http.MethodGet, "http://grafana.com/sub", nil)
So(err, ShouldBeNil)
proxy.getDirector()(req)
Convey("Should have access token in header", func() {
So(req.Header.Get("Authorization"), ShouldEqual, fmt.Sprintf("%s %s", "Bearer", "testtoken"))
})
})
Convey("When SendUserHeader config is enabled", func() {
req := getDatasourceProxiedRequest(
&m.ReqContext{