2015-03-30 19:30:27 +00:00
|
|
|
package providers
|
|
|
|
|
|
|
|
import (
|
2015-06-23 17:23:47 +00:00
|
|
|
"bytes"
|
2015-03-30 19:30:27 +00:00
|
|
|
"encoding/base64"
|
2015-05-21 03:23:48 +00:00
|
|
|
"encoding/json"
|
|
|
|
"errors"
|
2015-06-23 17:23:47 +00:00
|
|
|
"fmt"
|
2015-08-20 10:07:02 +00:00
|
|
|
"io"
|
2015-06-23 17:23:47 +00:00
|
|
|
"io/ioutil"
|
|
|
|
"net/http"
|
2015-03-30 19:30:27 +00:00
|
|
|
"net/url"
|
|
|
|
"strings"
|
2015-06-23 11:23:39 +00:00
|
|
|
"time"
|
2015-08-20 10:07:02 +00:00
|
|
|
|
2019-02-10 16:37:45 +00:00
|
|
|
"github.com/pusher/oauth2_proxy/logger"
|
2019-05-05 12:33:13 +00:00
|
|
|
"github.com/pusher/oauth2_proxy/pkg/apis/sessions"
|
2015-08-20 10:07:02 +00:00
|
|
|
"golang.org/x/oauth2"
|
|
|
|
"golang.org/x/oauth2/google"
|
2019-03-05 14:07:10 +00:00
|
|
|
admin "google.golang.org/api/admin/directory/v1"
|
2017-03-28 13:58:18 +00:00
|
|
|
"google.golang.org/api/googleapi"
|
2015-03-30 19:30:27 +00:00
|
|
|
)
|
|
|
|
|
2018-12-20 10:37:59 +00:00
|
|
|
// GoogleProvider represents an Google based Identity Provider
|
2015-03-30 19:30:27 +00:00
|
|
|
type GoogleProvider struct {
|
|
|
|
*ProviderData
|
2015-11-08 23:47:44 +00:00
|
|
|
RedeemRefreshURL *url.URL
|
2015-08-20 10:07:02 +00:00
|
|
|
// GroupValidator is a function that determines if the passed email is in
|
|
|
|
// the configured Google group.
|
|
|
|
GroupValidator func(string) bool
|
2015-03-30 19:30:27 +00:00
|
|
|
}
|
|
|
|
|
2019-05-07 10:44:19 +00:00
|
|
|
type claims struct {
|
|
|
|
Subject string `json:"sub"`
|
|
|
|
Email string `json:"email"`
|
|
|
|
EmailVerified bool `json:"email_verified"`
|
|
|
|
}
|
|
|
|
|
2018-12-20 10:37:59 +00:00
|
|
|
// NewGoogleProvider initiates a new GoogleProvider
|
2015-03-30 19:30:27 +00:00
|
|
|
func NewGoogleProvider(p *ProviderData) *GoogleProvider {
|
2015-03-31 16:59:07 +00:00
|
|
|
p.ProviderName = "Google"
|
2015-11-08 23:47:44 +00:00
|
|
|
if p.LoginURL.String() == "" {
|
|
|
|
p.LoginURL = &url.URL{Scheme: "https",
|
2015-03-30 19:30:27 +00:00
|
|
|
Host: "accounts.google.com",
|
2015-06-23 17:23:47 +00:00
|
|
|
Path: "/o/oauth2/auth",
|
|
|
|
// to get a refresh token. see https://developers.google.com/identity/protocols/OAuth2WebServer#offline
|
|
|
|
RawQuery: "access_type=offline",
|
|
|
|
}
|
2015-03-30 19:30:27 +00:00
|
|
|
}
|
2015-11-08 23:47:44 +00:00
|
|
|
if p.RedeemURL.String() == "" {
|
|
|
|
p.RedeemURL = &url.URL{Scheme: "https",
|
2015-06-23 17:23:47 +00:00
|
|
|
Host: "www.googleapis.com",
|
|
|
|
Path: "/oauth2/v3/token"}
|
2015-03-30 19:30:27 +00:00
|
|
|
}
|
2015-11-08 23:47:44 +00:00
|
|
|
if p.ValidateURL.String() == "" {
|
|
|
|
p.ValidateURL = &url.URL{Scheme: "https",
|
2015-05-08 21:13:35 +00:00
|
|
|
Host: "www.googleapis.com",
|
|
|
|
Path: "/oauth2/v1/tokeninfo"}
|
|
|
|
}
|
2015-03-30 19:30:27 +00:00
|
|
|
if p.Scope == "" {
|
|
|
|
p.Scope = "profile email"
|
|
|
|
}
|
2015-08-20 10:07:02 +00:00
|
|
|
|
|
|
|
return &GoogleProvider{
|
|
|
|
ProviderData: p,
|
|
|
|
// Set a default GroupValidator to just always return valid (true), it will
|
|
|
|
// be overwritten if we configured a Google group restriction.
|
|
|
|
GroupValidator: func(email string) bool {
|
|
|
|
return true
|
|
|
|
},
|
|
|
|
}
|
2015-03-30 19:30:27 +00:00
|
|
|
}
|
|
|
|
|
2019-05-07 10:44:19 +00:00
|
|
|
func claimsFromIDToken(idToken string) (*claims, error) {
|
2015-05-21 03:23:48 +00:00
|
|
|
|
2015-03-30 19:30:27 +00:00
|
|
|
// id_token is a base64 encode ID token payload
|
|
|
|
// https://developers.google.com/accounts/docs/OAuth2Login#obtainuserinfo
|
2015-06-23 11:23:39 +00:00
|
|
|
jwt := strings.Split(idToken, ".")
|
2018-03-09 00:44:11 +00:00
|
|
|
jwtData := strings.TrimSuffix(jwt[1], "=")
|
|
|
|
b, err := base64.RawURLEncoding.DecodeString(jwtData)
|
2015-03-30 19:30:27 +00:00
|
|
|
if err != nil {
|
2019-05-07 10:44:19 +00:00
|
|
|
return nil, err
|
2015-03-30 19:30:27 +00:00
|
|
|
}
|
2015-05-21 03:23:48 +00:00
|
|
|
|
2019-05-07 10:44:19 +00:00
|
|
|
c := &claims{}
|
|
|
|
err = json.Unmarshal(b, c)
|
2015-03-30 19:30:27 +00:00
|
|
|
if err != nil {
|
2019-05-07 10:44:19 +00:00
|
|
|
return nil, err
|
2015-03-30 19:30:27 +00:00
|
|
|
}
|
2019-05-07 10:44:19 +00:00
|
|
|
if c.Email == "" {
|
|
|
|
return nil, errors.New("missing email")
|
2015-05-21 03:23:48 +00:00
|
|
|
}
|
2019-05-07 10:44:19 +00:00
|
|
|
if !c.EmailVerified {
|
|
|
|
return nil, fmt.Errorf("email %s not listed as verified", c.Email)
|
2015-06-23 11:23:39 +00:00
|
|
|
}
|
2019-05-07 10:44:19 +00:00
|
|
|
return c, nil
|
2015-03-30 19:30:27 +00:00
|
|
|
}
|
|
|
|
|
2018-12-20 10:37:59 +00:00
|
|
|
// Redeem exchanges the OAuth2 authentication token for an ID token
|
2019-05-05 12:33:13 +00:00
|
|
|
func (p *GoogleProvider) Redeem(redirectURL, code string) (s *sessions.SessionState, err error) {
|
2015-06-23 17:23:47 +00:00
|
|
|
if code == "" {
|
|
|
|
err = errors.New("missing code")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
params := url.Values{}
|
2015-11-08 23:47:44 +00:00
|
|
|
params.Add("redirect_uri", redirectURL)
|
2015-06-23 17:23:47 +00:00
|
|
|
params.Add("client_id", p.ClientID)
|
|
|
|
params.Add("client_secret", p.ClientSecret)
|
|
|
|
params.Add("code", code)
|
|
|
|
params.Add("grant_type", "authorization_code")
|
|
|
|
var req *http.Request
|
2015-11-08 23:47:44 +00:00
|
|
|
req, err = http.NewRequest("POST", p.RedeemURL.String(), bytes.NewBufferString(params.Encode()))
|
2015-06-23 17:23:47 +00:00
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
|
|
|
|
|
|
|
resp, err := http.DefaultClient.Do(req)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
2015-06-23 11:23:39 +00:00
|
|
|
var body []byte
|
2015-06-23 17:23:47 +00:00
|
|
|
body, err = ioutil.ReadAll(resp.Body)
|
|
|
|
resp.Body.Close()
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if resp.StatusCode != 200 {
|
2015-11-08 23:47:44 +00:00
|
|
|
err = fmt.Errorf("got %d from %q %s", resp.StatusCode, p.RedeemURL.String(), body)
|
2015-06-23 17:23:47 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
var jsonResponse struct {
|
|
|
|
AccessToken string `json:"access_token"`
|
|
|
|
RefreshToken string `json:"refresh_token"`
|
2015-06-23 11:23:39 +00:00
|
|
|
ExpiresIn int64 `json:"expires_in"`
|
2018-11-29 14:26:41 +00:00
|
|
|
IDToken string `json:"id_token"`
|
2015-06-23 17:23:47 +00:00
|
|
|
}
|
|
|
|
err = json.Unmarshal(body, &jsonResponse)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
2019-05-07 10:44:19 +00:00
|
|
|
c, err := claimsFromIDToken(jsonResponse.IDToken)
|
2015-06-23 11:23:39 +00:00
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
2019-05-05 12:33:13 +00:00
|
|
|
s = &sessions.SessionState{
|
2015-06-23 11:23:39 +00:00
|
|
|
AccessToken: jsonResponse.AccessToken,
|
2018-01-27 10:14:19 +00:00
|
|
|
IDToken: jsonResponse.IDToken,
|
2019-05-07 14:32:46 +00:00
|
|
|
CreatedAt: time.Now(),
|
2015-06-23 11:23:39 +00:00
|
|
|
ExpiresOn: time.Now().Add(time.Duration(jsonResponse.ExpiresIn) * time.Second).Truncate(time.Second),
|
|
|
|
RefreshToken: jsonResponse.RefreshToken,
|
2019-05-07 10:44:19 +00:00
|
|
|
Email: c.Email,
|
|
|
|
User: c.Subject,
|
2015-06-23 11:23:39 +00:00
|
|
|
}
|
2015-06-23 17:23:47 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2015-08-20 10:07:02 +00:00
|
|
|
// SetGroupRestriction configures the GoogleProvider to restrict access to the
|
|
|
|
// specified group(s). AdminEmail has to be an administrative email on the domain that is
|
|
|
|
// checked. CredentialsFile is the path to a json file containing a Google service
|
|
|
|
// account credentials.
|
|
|
|
func (p *GoogleProvider) SetGroupRestriction(groups []string, adminEmail string, credentialsReader io.Reader) {
|
|
|
|
adminService := getAdminService(adminEmail, credentialsReader)
|
|
|
|
p.GroupValidator = func(email string) bool {
|
|
|
|
return userInGroup(adminService, groups, email)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func getAdminService(adminEmail string, credentialsReader io.Reader) *admin.Service {
|
|
|
|
data, err := ioutil.ReadAll(credentialsReader)
|
|
|
|
if err != nil {
|
2019-02-10 16:37:45 +00:00
|
|
|
logger.Fatal("can't read Google credentials file:", err)
|
2015-08-20 10:07:02 +00:00
|
|
|
}
|
|
|
|
conf, err := google.JWTConfigFromJSON(data, admin.AdminDirectoryUserReadonlyScope, admin.AdminDirectoryGroupReadonlyScope)
|
|
|
|
if err != nil {
|
2019-02-10 16:37:45 +00:00
|
|
|
logger.Fatal("can't load Google credentials file:", err)
|
2015-08-20 10:07:02 +00:00
|
|
|
}
|
|
|
|
conf.Subject = adminEmail
|
|
|
|
|
|
|
|
client := conf.Client(oauth2.NoContext)
|
|
|
|
adminService, err := admin.New(client)
|
|
|
|
if err != nil {
|
2019-02-10 16:37:45 +00:00
|
|
|
logger.Fatal(err)
|
2015-08-20 10:07:02 +00:00
|
|
|
}
|
|
|
|
return adminService
|
|
|
|
}
|
|
|
|
|
|
|
|
func userInGroup(service *admin.Service, groups []string, email string) bool {
|
|
|
|
user, err := fetchUser(service, email)
|
|
|
|
if err != nil {
|
2019-02-10 16:37:45 +00:00
|
|
|
logger.Printf("error fetching user: %v", err)
|
2015-08-20 10:07:02 +00:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
id := user.Id
|
|
|
|
custID := user.CustomerId
|
|
|
|
|
|
|
|
for _, group := range groups {
|
|
|
|
members, err := fetchGroupMembers(service, group)
|
|
|
|
if err != nil {
|
2017-03-28 13:58:18 +00:00
|
|
|
if err, ok := err.(*googleapi.Error); ok && err.Code == 404 {
|
2019-02-10 16:37:45 +00:00
|
|
|
logger.Printf("error fetching members for group %s: group does not exist", group)
|
2017-03-28 13:58:18 +00:00
|
|
|
} else {
|
2019-02-10 16:37:45 +00:00
|
|
|
logger.Printf("error fetching group members: %v", err)
|
2017-03-28 13:58:18 +00:00
|
|
|
return false
|
|
|
|
}
|
2015-08-20 10:07:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
for _, member := range members {
|
|
|
|
switch member.Type {
|
|
|
|
case "CUSTOMER":
|
|
|
|
if member.Id == custID {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
case "USER":
|
|
|
|
if member.Id == id {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
func fetchUser(service *admin.Service, email string) (*admin.User, error) {
|
|
|
|
user, err := service.Users.Get(email).Do()
|
|
|
|
return user, err
|
|
|
|
}
|
|
|
|
|
|
|
|
func fetchGroupMembers(service *admin.Service, group string) ([]*admin.Member, error) {
|
|
|
|
members := []*admin.Member{}
|
|
|
|
pageToken := ""
|
|
|
|
for {
|
|
|
|
req := service.Members.List(group)
|
|
|
|
if pageToken != "" {
|
|
|
|
req.PageToken(pageToken)
|
|
|
|
}
|
|
|
|
r, err := req.Do()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
for _, member := range r.Members {
|
|
|
|
members = append(members, member)
|
|
|
|
}
|
|
|
|
if r.NextPageToken == "" {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
pageToken = r.NextPageToken
|
|
|
|
}
|
|
|
|
return members, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// ValidateGroup validates that the provided email exists in the configured Google
|
|
|
|
// group(s).
|
|
|
|
func (p *GoogleProvider) ValidateGroup(email string) bool {
|
|
|
|
return p.GroupValidator(email)
|
|
|
|
}
|
|
|
|
|
2018-12-20 10:37:59 +00:00
|
|
|
// RefreshSessionIfNeeded checks if the session has expired and uses the
|
|
|
|
// RefreshToken to fetch a new ID token if required
|
2019-05-05 12:33:13 +00:00
|
|
|
func (p *GoogleProvider) RefreshSessionIfNeeded(s *sessions.SessionState) (bool, error) {
|
2015-06-23 11:23:39 +00:00
|
|
|
if s == nil || s.ExpiresOn.After(time.Now()) || s.RefreshToken == "" {
|
|
|
|
return false, nil
|
|
|
|
}
|
|
|
|
|
2019-03-05 14:07:10 +00:00
|
|
|
newToken, newIDToken, duration, err := p.redeemRefreshToken(s.RefreshToken)
|
2015-06-23 11:23:39 +00:00
|
|
|
if err != nil {
|
|
|
|
return false, err
|
|
|
|
}
|
2015-08-20 10:07:02 +00:00
|
|
|
|
|
|
|
// re-check that the user is in the proper google group(s)
|
|
|
|
if !p.ValidateGroup(s.Email) {
|
|
|
|
return false, fmt.Errorf("%s is no longer in the group(s)", s.Email)
|
|
|
|
}
|
|
|
|
|
2015-06-23 11:23:39 +00:00
|
|
|
origExpiration := s.ExpiresOn
|
|
|
|
s.AccessToken = newToken
|
2019-03-05 14:07:10 +00:00
|
|
|
s.IDToken = newIDToken
|
2015-06-23 11:23:39 +00:00
|
|
|
s.ExpiresOn = time.Now().Add(duration).Truncate(time.Second)
|
2019-02-10 16:37:45 +00:00
|
|
|
logger.Printf("refreshed access token %s (expired on %s)", s, origExpiration)
|
2015-06-23 11:23:39 +00:00
|
|
|
return true, nil
|
|
|
|
}
|
|
|
|
|
2019-03-05 14:07:10 +00:00
|
|
|
func (p *GoogleProvider) redeemRefreshToken(refreshToken string) (token string, idToken string, expires time.Duration, err error) {
|
2015-06-23 17:23:47 +00:00
|
|
|
// https://developers.google.com/identity/protocols/OAuth2WebServer#refresh
|
|
|
|
params := url.Values{}
|
|
|
|
params.Add("client_id", p.ClientID)
|
|
|
|
params.Add("client_secret", p.ClientSecret)
|
|
|
|
params.Add("refresh_token", refreshToken)
|
|
|
|
params.Add("grant_type", "refresh_token")
|
|
|
|
var req *http.Request
|
2015-11-08 23:47:44 +00:00
|
|
|
req, err = http.NewRequest("POST", p.RedeemURL.String(), bytes.NewBufferString(params.Encode()))
|
2015-06-23 17:23:47 +00:00
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
|
|
|
|
|
|
|
resp, err := http.DefaultClient.Do(req)
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
var body []byte
|
|
|
|
body, err = ioutil.ReadAll(resp.Body)
|
|
|
|
resp.Body.Close()
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if resp.StatusCode != 200 {
|
2015-11-08 23:47:44 +00:00
|
|
|
err = fmt.Errorf("got %d from %q %s", resp.StatusCode, p.RedeemURL.String(), body)
|
2015-06-23 17:23:47 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2015-06-23 11:23:39 +00:00
|
|
|
var data struct {
|
2015-06-23 17:23:47 +00:00
|
|
|
AccessToken string `json:"access_token"`
|
2015-06-23 11:23:39 +00:00
|
|
|
ExpiresIn int64 `json:"expires_in"`
|
2019-03-05 14:07:10 +00:00
|
|
|
IDToken string `json:"id_token"`
|
2015-06-23 17:23:47 +00:00
|
|
|
}
|
2015-06-23 11:23:39 +00:00
|
|
|
err = json.Unmarshal(body, &data)
|
2015-06-23 17:23:47 +00:00
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
2015-06-23 11:23:39 +00:00
|
|
|
token = data.AccessToken
|
2019-03-05 14:07:10 +00:00
|
|
|
idToken = data.IDToken
|
2015-06-23 11:23:39 +00:00
|
|
|
expires = time.Duration(data.ExpiresIn) * time.Second
|
|
|
|
return
|
2015-06-23 17:23:47 +00:00
|
|
|
}
|