16171: Configurable "email" and "email_verified" OIDC claim keys.
[arvados.git] / lib / controller / localdb / login_oidc.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package localdb
6
7 import (
8         "bytes"
9         "context"
10         "crypto/hmac"
11         "crypto/sha256"
12         "encoding/base64"
13         "errors"
14         "fmt"
15         "net/http"
16         "net/url"
17         "strings"
18         "sync"
19         "text/template"
20         "time"
21
22         "git.arvados.org/arvados.git/lib/controller/rpc"
23         "git.arvados.org/arvados.git/sdk/go/arvados"
24         "git.arvados.org/arvados.git/sdk/go/auth"
25         "git.arvados.org/arvados.git/sdk/go/ctxlog"
26         "git.arvados.org/arvados.git/sdk/go/httpserver"
27         "github.com/coreos/go-oidc"
28         "golang.org/x/oauth2"
29         "google.golang.org/api/option"
30         "google.golang.org/api/people/v1"
31 )
32
33 type oidcLoginController struct {
34         Cluster            *arvados.Cluster
35         RailsProxy         *railsProxy
36         Issuer             string // OIDC issuer URL, e.g., "https://accounts.google.com"
37         ClientID           string
38         ClientSecret       string
39         UseGooglePeopleAPI bool   // Use Google People API to look up alternate email addresses
40         EmailClaim         string // OpenID claim to use as email address; typically "email"
41         EmailVerifiedClaim string // If non-empty, ensure claim value is true before accepting EmailClaim; typically "email_verified"
42
43         // override Google People API base URL for testing purposes
44         // (normally empty, set by google pkg to
45         // https://people.googleapis.com/)
46         peopleAPIBasePath string
47
48         provider   *oidc.Provider        // initialized by setup()
49         oauth2conf *oauth2.Config        // initialized by setup()
50         verifier   *oidc.IDTokenVerifier // initialized by setup()
51         mu         sync.Mutex            // protects setup()
52 }
53
54 // Initialize ctrl.provider and ctrl.oauth2conf.
55 func (ctrl *oidcLoginController) setup() error {
56         ctrl.mu.Lock()
57         defer ctrl.mu.Unlock()
58         if ctrl.provider != nil {
59                 // already set up
60                 return nil
61         }
62         redirURL, err := (*url.URL)(&ctrl.Cluster.Services.Controller.ExternalURL).Parse("/" + arvados.EndpointLogin.Path)
63         if err != nil {
64                 return fmt.Errorf("error making redirect URL: %s", err)
65         }
66         provider, err := oidc.NewProvider(context.Background(), ctrl.Issuer)
67         if err != nil {
68                 return err
69         }
70         ctrl.oauth2conf = &oauth2.Config{
71                 ClientID:     ctrl.ClientID,
72                 ClientSecret: ctrl.ClientSecret,
73                 Endpoint:     provider.Endpoint(),
74                 Scopes:       []string{oidc.ScopeOpenID, "profile", "email"},
75                 RedirectURL:  redirURL.String(),
76         }
77         ctrl.verifier = provider.Verifier(&oidc.Config{
78                 ClientID: ctrl.ClientID,
79         })
80         ctrl.provider = provider
81         return nil
82 }
83
84 func (ctrl *oidcLoginController) Logout(ctx context.Context, opts arvados.LogoutOptions) (arvados.LogoutResponse, error) {
85         return noopLogout(ctrl.Cluster, opts)
86 }
87
88 func (ctrl *oidcLoginController) Login(ctx context.Context, opts arvados.LoginOptions) (arvados.LoginResponse, error) {
89         err := ctrl.setup()
90         if err != nil {
91                 return loginError(fmt.Errorf("error setting up OpenID Connect provider: %s", err))
92         }
93         if opts.State == "" {
94                 // Initiate OIDC sign-in.
95                 if opts.ReturnTo == "" {
96                         return loginError(errors.New("missing return_to parameter"))
97                 }
98                 state := ctrl.newOAuth2State([]byte(ctrl.Cluster.SystemRootToken), opts.Remote, opts.ReturnTo)
99                 return arvados.LoginResponse{
100                         RedirectLocation: ctrl.oauth2conf.AuthCodeURL(state.String(),
101                                 // prompt=select_account tells Google
102                                 // to show the "choose which Google
103                                 // account" page, even if the client
104                                 // is currently logged in to exactly
105                                 // one Google account.
106                                 oauth2.SetAuthURLParam("prompt", "select_account")),
107                 }, nil
108         } else {
109                 // Callback after OIDC sign-in.
110                 state := ctrl.parseOAuth2State(opts.State)
111                 if !state.verify([]byte(ctrl.Cluster.SystemRootToken)) {
112                         return loginError(errors.New("invalid OAuth2 state"))
113                 }
114                 oauth2Token, err := ctrl.oauth2conf.Exchange(ctx, opts.Code)
115                 if err != nil {
116                         return loginError(fmt.Errorf("error in OAuth2 exchange: %s", err))
117                 }
118                 rawIDToken, ok := oauth2Token.Extra("id_token").(string)
119                 if !ok {
120                         return loginError(errors.New("error in OAuth2 exchange: no ID token in OAuth2 token"))
121                 }
122                 idToken, err := ctrl.verifier.Verify(ctx, rawIDToken)
123                 if err != nil {
124                         return loginError(fmt.Errorf("error verifying ID token: %s", err))
125                 }
126                 authinfo, err := ctrl.getAuthInfo(ctx, oauth2Token, idToken)
127                 if err != nil {
128                         return loginError(err)
129                 }
130                 ctxRoot := auth.NewContext(ctx, &auth.Credentials{Tokens: []string{ctrl.Cluster.SystemRootToken}})
131                 return ctrl.RailsProxy.UserSessionCreate(ctxRoot, rpc.UserSessionCreateOptions{
132                         ReturnTo: state.Remote + "," + state.ReturnTo,
133                         AuthInfo: *authinfo,
134                 })
135         }
136 }
137
138 func (ctrl *oidcLoginController) UserAuthenticate(ctx context.Context, opts arvados.UserAuthenticateOptions) (arvados.APIClientAuthorization, error) {
139         return arvados.APIClientAuthorization{}, httpserver.ErrorWithStatus(errors.New("username/password authentication is not available"), http.StatusBadRequest)
140 }
141
142 // Use a person's token to get all of their email addresses, with the
143 // primary address at index 0. The provided defaultAddr is always
144 // included in the returned slice, and is used as the primary if the
145 // Google API does not indicate one.
146 func (ctrl *oidcLoginController) getAuthInfo(ctx context.Context, token *oauth2.Token, idToken *oidc.IDToken) (*rpc.UserSessionAuthInfo, error) {
147         var ret rpc.UserSessionAuthInfo
148         defer ctxlog.FromContext(ctx).WithField("ret", &ret).Debug("getAuthInfo returned")
149
150         var claims map[string]interface{}
151         if err := idToken.Claims(&claims); err != nil {
152                 return nil, fmt.Errorf("error extracting claims from ID token: %s", err)
153         } else if verified, _ := claims[ctrl.EmailVerifiedClaim].(bool); verified || ctrl.EmailVerifiedClaim == "" {
154                 // Fall back to this info if the People API call
155                 // (below) doesn't return a primary && verified email.
156                 name, _ := claims["name"].(string)
157                 if names := strings.Fields(strings.TrimSpace(name)); len(names) > 1 {
158                         ret.FirstName = strings.Join(names[0:len(names)-1], " ")
159                         ret.LastName = names[len(names)-1]
160                 } else {
161                         ret.FirstName = names[0]
162                 }
163                 ret.Email, _ = claims[ctrl.EmailClaim].(string)
164         }
165
166         if !ctrl.UseGooglePeopleAPI {
167                 if ret.Email == "" {
168                         return nil, fmt.Errorf("cannot log in with unverified email address %q", claims[ctrl.EmailClaim])
169                 }
170                 return &ret, nil
171         }
172
173         svc, err := people.NewService(ctx, option.WithTokenSource(ctrl.oauth2conf.TokenSource(ctx, token)), option.WithScopes(people.UserEmailsReadScope))
174         if err != nil {
175                 return nil, fmt.Errorf("error setting up People API: %s", err)
176         }
177         if p := ctrl.peopleAPIBasePath; p != "" {
178                 // Override normal API endpoint (for testing)
179                 svc.BasePath = p
180         }
181         person, err := people.NewPeopleService(svc).Get("people/me").PersonFields("emailAddresses,names").Do()
182         if err != nil {
183                 if strings.Contains(err.Error(), "Error 403") && strings.Contains(err.Error(), "accessNotConfigured") {
184                         // Log the original API error, but display
185                         // only the "fix config" advice to the user.
186                         ctxlog.FromContext(ctx).WithError(err).WithField("email", ret.Email).Error("People API is not enabled")
187                         return nil, errors.New("configuration error: Login.GoogleAlternateEmailAddresses is true, but Google People API is not enabled")
188                 } else {
189                         return nil, fmt.Errorf("error getting profile info from People API: %s", err)
190                 }
191         }
192
193         // The given/family names returned by the People API and
194         // flagged as "primary" (if any) take precedence over the
195         // split-by-whitespace result from above.
196         for _, name := range person.Names {
197                 if name.Metadata != nil && name.Metadata.Primary {
198                         ret.FirstName = name.GivenName
199                         ret.LastName = name.FamilyName
200                         break
201                 }
202         }
203
204         altEmails := map[string]bool{}
205         if ret.Email != "" {
206                 altEmails[ret.Email] = true
207         }
208         for _, ea := range person.EmailAddresses {
209                 if ea.Metadata == nil || !ea.Metadata.Verified {
210                         ctxlog.FromContext(ctx).WithField("address", ea.Value).Info("skipping unverified email address")
211                         continue
212                 }
213                 altEmails[ea.Value] = true
214                 if ea.Metadata.Primary || ret.Email == "" {
215                         ret.Email = ea.Value
216                 }
217         }
218         if len(altEmails) == 0 {
219                 return nil, errors.New("cannot log in without a verified email address")
220         }
221         for ae := range altEmails {
222                 if ae != ret.Email {
223                         ret.AlternateEmails = append(ret.AlternateEmails, ae)
224                         if i := strings.Index(ae, "@"); i > 0 && strings.ToLower(ae[i+1:]) == strings.ToLower(ctrl.Cluster.Users.PreferDomainForUsername) {
225                                 ret.Username = strings.SplitN(ae[:i], "+", 2)[0]
226                         }
227                 }
228         }
229         return &ret, nil
230 }
231
232 func loginError(sendError error) (resp arvados.LoginResponse, err error) {
233         tmpl, err := template.New("error").Parse(`<h2>Login error:</h2><p>{{.}}</p>`)
234         if err != nil {
235                 return
236         }
237         err = tmpl.Execute(&resp.HTML, sendError.Error())
238         return
239 }
240
241 func (ctrl *oidcLoginController) newOAuth2State(key []byte, remote, returnTo string) oauth2State {
242         s := oauth2State{
243                 Time:     time.Now().Unix(),
244                 Remote:   remote,
245                 ReturnTo: returnTo,
246         }
247         s.HMAC = s.computeHMAC(key)
248         return s
249 }
250
251 type oauth2State struct {
252         HMAC     []byte // hash of other fields; see computeHMAC()
253         Time     int64  // creation time (unix timestamp)
254         Remote   string // remote cluster if requesting a salted token, otherwise blank
255         ReturnTo string // redirect target
256 }
257
258 func (ctrl *oidcLoginController) parseOAuth2State(encoded string) (s oauth2State) {
259         // Errors are not checked. If decoding/parsing fails, the
260         // token will be rejected by verify().
261         decoded, _ := base64.RawURLEncoding.DecodeString(encoded)
262         f := strings.Split(string(decoded), "\n")
263         if len(f) != 4 {
264                 return
265         }
266         fmt.Sscanf(f[0], "%x", &s.HMAC)
267         fmt.Sscanf(f[1], "%x", &s.Time)
268         fmt.Sscanf(f[2], "%s", &s.Remote)
269         fmt.Sscanf(f[3], "%s", &s.ReturnTo)
270         return
271 }
272
273 func (s oauth2State) verify(key []byte) bool {
274         if delta := time.Now().Unix() - s.Time; delta < 0 || delta > 300 {
275                 return false
276         }
277         return hmac.Equal(s.computeHMAC(key), s.HMAC)
278 }
279
280 func (s oauth2State) String() string {
281         var buf bytes.Buffer
282         enc := base64.NewEncoder(base64.RawURLEncoding, &buf)
283         fmt.Fprintf(enc, "%x\n%x\n%s\n%s", s.HMAC, s.Time, s.Remote, s.ReturnTo)
284         enc.Close()
285         return buf.String()
286 }
287
288 func (s oauth2State) computeHMAC(key []byte) []byte {
289         mac := hmac.New(sha256.New, key)
290         fmt.Fprintf(mac, "%x %s %s", s.Time, s.Remote, s.ReturnTo)
291         return mac.Sum(nil)
292 }