git.iko.soy/typeable/oauth2-proxy
on proxy-mapping help sign in
312 lines 9.5 kB history raw
1package providers
3import (
4 "bytes"
5 "context"
6 "encoding/base64"
7 "encoding/json"
8 "errors"
9 "fmt"
10 "io"
11 "io/ioutil"
12 "net/url"
13 "strings"
14 "time"
16 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/sessions"
17 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger"
18 "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/requests"
19 "golang.org/x/oauth2/google"
20 admin "google.golang.org/api/admin/directory/v1"
21 "google.golang.org/api/googleapi"
22 "google.golang.org/api/option"
25// GoogleProvider represents an Google based Identity Provider
26type GoogleProvider struct {
27 *ProviderData
28 RedeemRefreshURL *url.URL
29 // GroupValidator is a function that determines if the passed email is in
30 // the configured Google group.
31 GroupValidator func(string) bool
34var _ Provider = (*GoogleProvider)(nil)
36type claims struct {
37 Subject string `json:"sub"`
38 Email string `json:"email"`
39 EmailVerified bool `json:"email_verified"`
42const (
43 googleProviderName = "Google"
44 googleDefaultScope = "profile email"
47var (
48 // Default Login URL for Google.
49 // Pre-parsed URL of https://accounts.google.com/o/oauth2/auth?access_type=offline.
50 googleDefaultLoginURL = &url.URL{
51 Scheme: "https",
52 Host: "accounts.google.com",
53 Path: "/o/oauth2/auth",
54 // to get a refresh token. see https://developers.google.com/identity/protocols/OAuth2WebServer#offline
55 RawQuery: "access_type=offline",
56 }
58 // Default Redeem URL for Google.
59 // Pre-parsed URL of https://www.googleapis.com/oauth2/v3/token.
60 googleDefaultRedeemURL = &url.URL{
61 Scheme: "https",
62 Host: "www.googleapis.com",
63 Path: "/oauth2/v3/token",
64 }
66 // Default Validation URL for Google.
67 // Pre-parsed URL of https://www.googleapis.com/oauth2/v1/tokeninfo.
68 googleDefaultValidateURL = &url.URL{
69 Scheme: "https",
70 Host: "www.googleapis.com",
71 Path: "/oauth2/v1/tokeninfo",
72 }
75// NewGoogleProvider initiates a new GoogleProvider
76func NewGoogleProvider(p *ProviderData) *GoogleProvider {
77 p.setProviderDefaults(providerDefaults{
78 name: googleProviderName,
79 loginURL: googleDefaultLoginURL,
80 redeemURL: googleDefaultRedeemURL,
81 profileURL: nil,
82 validateURL: googleDefaultValidateURL,
83 scope: googleDefaultScope,
84 })
85 return &GoogleProvider{
86 ProviderData: p,
87 // Set a default GroupValidator to just always return valid (true), it will
88 // be overwritten if we configured a Google group restriction.
89 GroupValidator: func(email string) bool {
90 return true
91 },
92 }
95func claimsFromIDToken(idToken string) (*claims, error) {
97 // id_token is a base64 encode ID token payload
98 // https://developers.google.com/accounts/docs/OAuth2Login#obtainuserinfo
99 jwt := strings.Split(idToken, ".")
100 jwtData := strings.TrimSuffix(jwt[1], "=")
101 b, err := base64.RawURLEncoding.DecodeString(jwtData)
102 if err != nil {
103 return nil, err
104 }
106 c := &claims{}
107 err = json.Unmarshal(b, c)
108 if err != nil {
109 return nil, err
110 }
111 if c.Email == "" {
112 return nil, errors.New("missing email")
113 }
114 if !c.EmailVerified {
115 return nil, fmt.Errorf("email %s not listed as verified", c.Email)
116 }
117 return c, nil
120// Redeem exchanges the OAuth2 authentication token for an ID token
121func (p *GoogleProvider) Redeem(ctx context.Context, redirectURL, code string) (s *sessions.SessionState, err error) {
122 if code == "" {
123 err = errors.New("missing code")
124 return
125 }
126 clientSecret, err := p.GetClientSecret()
127 if err != nil {
128 return
129 }
131 params := url.Values{}
132 params.Add("redirect_uri", redirectURL)
133 params.Add("client_id", p.ClientID)
134 params.Add("client_secret", clientSecret)
135 params.Add("code", code)
136 params.Add("grant_type", "authorization_code")
138 var jsonResponse struct {
139 AccessToken string `json:"access_token"`
140 RefreshToken string `json:"refresh_token"`
141 ExpiresIn int64 `json:"expires_in"`
142 IDToken string `json:"id_token"`
143 }
145 err = requests.New(p.RedeemURL.String()).
146 WithContext(ctx).
147 WithMethod("POST").
148 WithBody(bytes.NewBufferString(params.Encode())).
149 SetHeader("Content-Type", "application/x-www-form-urlencoded").
150 Do().
151 UnmarshalInto(&jsonResponse)
152 if err != nil {
153 return nil, err
154 }
156 c, err := claimsFromIDToken(jsonResponse.IDToken)
157 if err != nil {
158 return
159 }
161 created := time.Now()
162 expires := time.Now().Add(time.Duration(jsonResponse.ExpiresIn) * time.Second).Truncate(time.Second)
163 s = &sessions.SessionState{
164 AccessToken: jsonResponse.AccessToken,
165 IDToken: jsonResponse.IDToken,
166 CreatedAt: &created,
167 ExpiresOn: &expires,
168 RefreshToken: jsonResponse.RefreshToken,
169 Email: c.Email,
170 User: c.Subject,
171 }
172 return
175// SetGroupRestriction configures the GoogleProvider to restrict access to the
176// specified group(s). AdminEmail has to be an administrative email on the domain that is
177// checked. CredentialsFile is the path to a json file containing a Google service
178// account credentials.
179func (p *GoogleProvider) SetGroupRestriction(groups []string, adminEmail string, credentialsReader io.Reader) {
180 adminService := getAdminService(adminEmail, credentialsReader)
181 p.GroupValidator = func(email string) bool {
182 return userInGroup(adminService, groups, email)
183 }
186func getAdminService(adminEmail string, credentialsReader io.Reader) *admin.Service {
187 data, err := ioutil.ReadAll(credentialsReader)
188 if err != nil {
189 logger.Fatal("can't read Google credentials file:", err)
190 }
191 conf, err := google.JWTConfigFromJSON(data, admin.AdminDirectoryUserReadonlyScope, admin.AdminDirectoryGroupReadonlyScope)
192 if err != nil {
193 logger.Fatal("can't load Google credentials file:", err)
194 }
195 conf.Subject = adminEmail
197 ctx := context.Background()
198 client := conf.Client(ctx)
199 adminService, err := admin.NewService(ctx, option.WithHTTPClient(client))
200 if err != nil {
201 logger.Fatal(err)
202 }
203 return adminService
206func userInGroup(service *admin.Service, groups []string, email string) bool {
207 for _, group := range groups {
208 // Use the HasMember API to checking for the user's presence in each group or nested subgroups
209 req := service.Members.HasMember(group, email)
210 r, err := req.Do()
211 if err != nil {
212 gerr, ok := err.(*googleapi.Error)
213 switch {
214 case ok && gerr.Code == 404:
215 logger.Errorf("error checking membership in group %s: group does not exist", group)
216 case ok && gerr.Code == 400:
217 // It is possible for Members.HasMember to return false even if the email is a group member.
218 // One case that can cause this is if the user email is from a different domain than the group,
219 // e.g. "member@otherdomain.com" in the group "group@mydomain.com" will result in a 400 error
220 // from the HasMember API. In that case, attempt to query the member object directly from the group.
221 req := service.Members.Get(group, email)
222 r, err := req.Do()
224 if err != nil {
225 logger.Errorf("error using get API to check member %s of google group %s: user not in the group", email, group)
226 continue
227 }
229 // If the non-domain user is found within the group, still verify that they are "ACTIVE".
230 // Do not count the user as belonging to a group if they have another status ("ARCHIVED", "SUSPENDED", or "UNKNOWN").
231 if r.Status == "ACTIVE" {
232 return true
233 }
234 default:
235 logger.Errorf("error checking group membership: %v", err)
236 }
237 continue
238 }
239 if r.IsMember {
240 return true
241 }
242 }
243 return false
246// ValidateGroup validates that the provided email exists in the configured Google
247// group(s).
248func (p *GoogleProvider) ValidateGroup(email string) bool {
249 return p.GroupValidator(email)
252// RefreshSessionIfNeeded checks if the session has expired and uses the
253// RefreshToken to fetch a new ID token if required
254func (p *GoogleProvider) RefreshSessionIfNeeded(ctx context.Context, s *sessions.SessionState) (bool, error) {
255 if s == nil || (s.ExpiresOn != nil && s.ExpiresOn.After(time.Now())) || s.RefreshToken == "" {
256 return false, nil
257 }
259 newToken, newIDToken, duration, err := p.redeemRefreshToken(ctx, s.RefreshToken)
260 if err != nil {
261 return false, err
262 }
264 // re-check that the user is in the proper google group(s)
265 if !p.ValidateGroup(s.Email) {
266 return false, fmt.Errorf("%s is no longer in the group(s)", s.Email)
267 }
269 origExpiration := s.ExpiresOn
270 expires := time.Now().Add(duration).Truncate(time.Second)
271 s.AccessToken = newToken
272 s.IDToken = newIDToken
273 s.ExpiresOn = &expires
274 logger.Printf("refreshed access token %s (expired on %s)", s, origExpiration)
275 return true, nil
278func (p *GoogleProvider) redeemRefreshToken(ctx context.Context, refreshToken string) (token string, idToken string, expires time.Duration, err error) {
279 // https://developers.google.com/identity/protocols/OAuth2WebServer#refresh
280 clientSecret, err := p.GetClientSecret()
281 if err != nil {
282 return
283 }
285 params := url.Values{}
286 params.Add("client_id", p.ClientID)
287 params.Add("client_secret", clientSecret)
288 params.Add("refresh_token", refreshToken)
289 params.Add("grant_type", "refresh_token")
291 var data struct {
292 AccessToken string `json:"access_token"`
293 ExpiresIn int64 `json:"expires_in"`
294 IDToken string `json:"id_token"`
295 }
297 err = requests.New(p.RedeemURL.String()).
298 WithContext(ctx).
299 WithMethod("POST").
300 WithBody(bytes.NewBufferString(params.Encode())).
301 SetHeader("Content-Type", "application/x-www-form-urlencoded").
302 Do().
303 UnmarshalInto(&data)
304 if err != nil {
305 return "", "", 0, err
306 }
308 token = data.AccessToken
309 idToken = data.IDToken
310 expires = time.Duration(data.ExpiresIn) * time.Second
311 return