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