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