Add oauth pass-thru option for datasources

This commit is contained in:
Sean Lafferty
2019-02-01 19:40:57 -05:00
parent 9e33f8b7c4
commit 5a59cdf0ef
12 changed files with 312 additions and 7 deletions

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,

View File

@@ -14,11 +14,14 @@ import (
"time"
"github.com/opentracing/opentracing-go"
"golang.org/x/oauth2"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/log"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/plugins"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/social"
"github.com/grafana/grafana/pkg/util"
)
@@ -215,6 +218,44 @@ 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() {
provider := proxy.ds.JsonData.Get("oauthPassThruProvider").MustString()
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)
}
cmd := &m.GetAuthInfoQuery{UserId: proxy.ctx.UserId, AuthModule: provider}
if err := bus.Dispatch(cmd); err != nil {
logger.Error("Error feching oauth information for user", "error", err)
}
// TokenSource handles refreshing the token if it has expired
token, err := connect.TokenSource(proxy.ctx.Req.Context(), &oauth2.Token{
AccessToken: cmd.Result.OAuthAccessToken,
Expiry: cmd.Result.OAuthExpiry,
RefreshToken: cmd.Result.OAuthRefreshToken,
TokenType: cmd.Result.OAuthTokenType,
}).Token()
if err != nil {
logger.Error("Failed to retrieve access token from oauth provider", "provider", cmd.Result.AuthModule)
}
// If the tokens are not the same, update the entry in the DB
if token.AccessToken != cmd.Result.OAuthAccessToken {
cmd2 := &m.UpdateAuthInfoCommand{
UserId: cmd.Result.Id,
AuthModule: cmd.Result.AuthModule,
AuthId: cmd.Result.AuthId,
OAuthToken: token,
}
if err := bus.Dispatch(cmd2); err != nil {
logger.Error("Failed to update access token during token refresh", "error", err)
}
}
req.Header.Del("Authorization")
req.Header.Add("Authorization", fmt.Sprintf("%s %s", token.Type(), token.AccessToken))
}
}
}

View File

@@ -9,13 +9,16 @@ 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"
m "github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/plugins"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/social"
"github.com/grafana/grafana/pkg/util"
. "github.com/smartystreets/goconvey/convey"
)
@@ -388,6 +391,55 @@ func TestDSRouteRule(t *testing.T) {
So(req.Header.Get("X-Canary"), ShouldEqual, "stillthere")
})
})
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,
"oauthPassThruProvider": "oauth_generic_oauth",
}),
}
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/")
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"))
})
})
})
}