Commit b3a86816 by Bill Oley Committed by GitHub

OAuth: Support Forward OAuth Identity for backend data source plugins (#27055)

Adds support for the Forward OAuth Identity feature in backend data source plugins. 
Earlier this feature has only been supported for non-backend data source plugins.

Fixes #26023

Co-authored-by: Arve Knudsen <arve.knudsen@gmail.com>
Co-authored-by: Marcus Efraimsson <marcus.efraimsson@gmail.com>
parent b6bb069e
......@@ -2,7 +2,6 @@ package pluginproxy
import (
"bytes"
"context"
"errors"
"fmt"
"io/ioutil"
......@@ -14,18 +13,15 @@ import (
"strings"
"time"
"github.com/opentracing/opentracing-go"
"golang.org/x/oauth2"
"github.com/grafana/grafana/pkg/api/datasource"
"github.com/grafana/grafana/pkg/bus"
glog "github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/login/social"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/plugins"
"github.com/grafana/grafana/pkg/services/oauthtoken"
"github.com/grafana/grafana/pkg/setting"
"github.com/grafana/grafana/pkg/util"
"github.com/grafana/grafana/pkg/util/proxyutil"
"github.com/opentracing/opentracing-go"
)
var (
......@@ -211,8 +207,11 @@ func (proxy *DataSourceProxy) getDirector() func(req *http.Request) {
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)
if oauthtoken.IsOAuthPassThruEnabled(proxy.ds) {
if token := oauthtoken.GetCurrentOAuthToken(proxy.ctx.Req.Context(), proxy.ctx.SignedInUser); token != nil {
req.Header.Del("Authorization")
req.Header.Add("Authorization", fmt.Sprintf("%s %s", token.Type(), token.AccessToken))
}
}
}
}
......@@ -304,64 +303,3 @@ func checkWhiteList(c *models.ReqContext, host string) bool {
return true
}
func addOAuthPassThruAuth(c *models.ReqContext, req *http.Request) {
authInfoQuery := &models.GetAuthInfoQuery{UserId: c.UserId}
if err := bus.Dispatch(authInfoQuery); err != nil {
logger.Error("Error fetching oauth information for user", "userid", c.UserId, "username", c.Login, "error", err)
return
}
authProvider := authInfoQuery.Result.AuthModule
connect, err := social.GetConnector(authProvider)
if err != nil {
logger.Error("Failed to get OAuth connector", "error", err)
return
}
persistedToken := &oauth2.Token{
AccessToken: authInfoQuery.Result.OAuthAccessToken,
Expiry: authInfoQuery.Result.OAuthExpiry,
RefreshToken: authInfoQuery.Result.OAuthRefreshToken,
TokenType: authInfoQuery.Result.OAuthTokenType,
}
client, err := social.GetOAuthHttpClient(authProvider)
if err != nil {
logger.Error("Failed to create OAuth http client", "error", err)
return
}
oauthctx := context.WithValue(c.Req.Context(), oauth2.HTTPClient, client)
// TokenSource handles refreshing the token if it has expired
token, err := connect.TokenSource(oauthctx, persistedToken).Token()
if err != nil {
logger.Error("Failed to retrieve access token from OAuth provider", "provider", authInfoQuery.Result.AuthModule, "userid", c.UserId, "username", c.Login, "error", err)
return
}
// If the tokens are not the same, update the entry in the DB
if !tokensEq(persistedToken, token) {
updateAuthCommand := &models.UpdateAuthInfoCommand{
UserId: authInfoQuery.Result.UserId,
AuthModule: authInfoQuery.Result.AuthModule,
AuthId: authInfoQuery.Result.AuthId,
OAuthToken: token,
}
if err := bus.Dispatch(updateAuthCommand); err != nil {
logger.Error("Failed to update auth info during token refresh", "userid", c.UserId, "username", c.Login, "error", err)
return
}
logger.Debug("Updated OAuth info while proxying an OAuth pass-thru request", "userid", c.UserId, "username", c.Login)
}
req.Header.Del("Authorization")
req.Header.Add("Authorization", fmt.Sprintf("%s %s", token.Type(), token.AccessToken))
}
// tokensEq checks for OAuth2 token equivalence given the fields of the struct Grafana is interested in
func tokensEq(t1, t2 *oauth2.Token) bool {
return t1.AccessToken == t2.AccessToken &&
t1.RefreshToken == t2.RefreshToken &&
t1.Expiry == t2.Expiry &&
t1.TokenType == t2.TokenType
}
......@@ -4,13 +4,13 @@ import (
"context"
"fmt"
"github.com/grafana/grafana-plugin-sdk-go/backend/grpcplugin"
"github.com/grafana/grafana-plugin-sdk-go/backend"
"github.com/grafana/grafana-plugin-sdk-go/backend/grpcplugin"
"github.com/grafana/grafana-plugin-sdk-go/genproto/pluginv2"
"github.com/grafana/grafana/pkg/components/simplejson"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/models"
"github.com/grafana/grafana/pkg/services/oauthtoken"
"github.com/grafana/grafana/pkg/tsdb"
)
......@@ -51,6 +51,17 @@ func (tw *DatasourcePluginWrapperV2) Query(ctx context.Context, ds *models.DataS
return nil, err
}
if query.Headers == nil {
query.Headers = make(map[string]string)
}
if oauthtoken.IsOAuthPassThruEnabled(ds) {
if token := oauthtoken.GetCurrentOAuthToken(ctx, query.User); token != nil {
delete(query.Headers, "Authorization")
query.Headers["Authorization"] = fmt.Sprintf("%s %s", token.Type(), token.AccessToken)
}
}
pbQuery := &pluginv2.QueryDataRequest{
PluginContext: &pluginv2.PluginContext{
OrgId: ds.OrgId,
......
package oauthtoken
import (
"context"
"github.com/grafana/grafana/pkg/bus"
"github.com/grafana/grafana/pkg/infra/log"
"github.com/grafana/grafana/pkg/login/social"
"github.com/grafana/grafana/pkg/models"
"golang.org/x/oauth2"
)
var (
logger = log.New("oauthtoken")
)
// GetCurrentOAuthToken returns the OAuth token, if any, for the authenticated user. Will try to refresh the token if it has expired.
func GetCurrentOAuthToken(ctx context.Context, user *models.SignedInUser) *oauth2.Token {
if user == nil {
// No user, therefore no token
return nil
}
authInfoQuery := &models.GetAuthInfoQuery{UserId: user.UserId}
if err := bus.Dispatch(authInfoQuery); err != nil {
if err == models.ErrUserNotFound {
// Not necessarily an error. User may be logged in another way.
logger.Debug("no OAuth token for user found", "userId", user.UserId, "username", user.Login)
} else {
logger.Error("failed to get OAuth token for user", "userId", user.UserId, "username", user.Login, "error", err)
}
return nil
}
authProvider := authInfoQuery.Result.AuthModule
connect, err := social.GetConnector(authProvider)
if err != nil {
logger.Error("failed to get OAuth connector", "provider", authProvider, "error", err)
return nil
}
client, err := social.GetOAuthHttpClient(authProvider)
if err != nil {
logger.Error("failed to get OAuth http client", "provider", authProvider, "error", err)
return nil
}
ctx = context.WithValue(ctx, oauth2.HTTPClient, client)
persistedToken := &oauth2.Token{
AccessToken: authInfoQuery.Result.OAuthAccessToken,
Expiry: authInfoQuery.Result.OAuthExpiry,
RefreshToken: authInfoQuery.Result.OAuthRefreshToken,
TokenType: authInfoQuery.Result.OAuthTokenType,
}
// TokenSource handles refreshing the token if it has expired
token, err := connect.TokenSource(ctx, persistedToken).Token()
if err != nil {
logger.Error("failed to retrieve OAuth access token", "provider", authInfoQuery.Result.AuthModule, "userId", user.UserId, "username", user.Login, "error", err)
return nil
}
// If the tokens are not the same, update the entry in the DB
if !tokensEq(persistedToken, token) {
updateAuthCommand := &models.UpdateAuthInfoCommand{
UserId: authInfoQuery.Result.UserId,
AuthModule: authInfoQuery.Result.AuthModule,
AuthId: authInfoQuery.Result.AuthId,
OAuthToken: token,
}
if err := bus.Dispatch(updateAuthCommand); err != nil {
logger.Error("failed to update auth info during token refresh", "userId", user.UserId, "username", user.Login, "error", err)
return nil
}
logger.Debug("updated OAuth info for user", "userId", user.UserId, "username", user.Login)
}
return token
}
// IsOAuthPassThruEnabled returns true if Forward OAuth Identity (oauthPassThru) is enabled for the provided data source.
func IsOAuthPassThruEnabled(ds *models.DataSource) bool {
return ds.JsonData != nil && ds.JsonData.Get("oauthPassThru").MustBool()
}
// tokensEq checks for OAuth2 token equivalence given the fields of the struct Grafana is interested in
func tokensEq(t1, t2 *oauth2.Token) bool {
return t1.AccessToken == t2.AccessToken &&
t1.RefreshToken == t2.RefreshToken &&
t1.Expiry == t2.Expiry &&
t1.TokenType == t2.TokenType
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment