1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
|
package auth
import (
"context"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/gorilla/securecookie"
"github.com/gorilla/sessions"
"github.com/sirupsen/logrus"
"gitlab.com/gitlab-org/labkit/log"
"golang.org/x/crypto/hkdf"
"gitlab.com/gitlab-org/gitlab-pages/internal/errortracking"
"gitlab.com/gitlab-org/gitlab-pages/internal/httperrors"
"gitlab.com/gitlab-org/gitlab-pages/internal/httptransport"
"gitlab.com/gitlab-org/gitlab-pages/internal/logging"
"gitlab.com/gitlab-org/gitlab-pages/internal/request"
"gitlab.com/gitlab-org/gitlab-pages/internal/source"
)
// nolint: gosec
// gosec: G101: Potential hardcoded credentials
// auth constants, not credentials
const (
apiURLUserTemplate = "%s/api/v4/user"
apiURLProjectTemplate = "%s/api/v4/projects/%d/pages_access"
authorizeURLTemplate = "%s/oauth/authorize?client_id=%s&redirect_uri=%s&response_type=code&state=%s&scope=%s"
tokenURLTemplate = "%s/oauth/token"
callbackPath = "/auth"
authorizeProxyTemplate = "%s?domain=%s&state=%s"
authSessionMaxAge = 60 * 10 // 10 minutes
failAuthErrMsg = "failed to authenticate request"
fetchAccessTokenErrMsg = "fetching access token failed"
queryParameterErrMsg = "failed to parse domain query parameter"
saveSessionErrMsg = "failed to save the session"
)
var (
errResponseNotOk = errors.New("response was not ok")
errAuthNotConfigured = errors.New("authentication is not configured")
errGenerateKeys = errors.New("could not generate auth keys")
)
// Auth handles authenticating users with GitLab API
type Auth struct {
pagesDomain string
clientID string
clientSecret string
redirectURI string
internalGitlabServer string // used for exchanging OAuth code for token and Accessing API and checking if the user has access to the project
publicGitlabServer string // used for redirecting users to gitlab on the start of OAuth workflow
authSecret string
authScope string
jwtSigningKey []byte
jwtExpiry time.Duration
apiClient *http.Client
store sessions.Store
now func() time.Time // allows to stub time.Now() easily in tests
}
type tokenResponse struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
RefreshToken string `json:"refresh_token"`
}
type errorResponse struct {
Error string `json:"error"`
ErrorDescription string `json:"error_description"`
}
type domain interface {
GetProjectID(r *http.Request) uint64
ServeNotFoundAuthFailed(w http.ResponseWriter, r *http.Request)
}
func (a *Auth) getSessionFromStore(r *http.Request) (*sessions.Session, error) {
session, err := a.store.Get(r, "gitlab-pages")
if session != nil {
// Cookie just for this domain
session.Options.Path = "/"
session.Options.HttpOnly = true
session.Options.Secure = request.IsHTTPS(r)
session.Options.MaxAge = authSessionMaxAge
}
return session, err
}
func (a *Auth) checkSession(w http.ResponseWriter, r *http.Request) (*sessions.Session, error) {
// Create or get session
session, errsession := a.getSessionFromStore(r)
if errsession != nil {
// Save cookie again
errsave := session.Save(r, w)
if errsave != nil {
logRequest(r).WithError(errsave).Error(saveSessionErrMsg)
errortracking.CaptureErrWithReqAndStackTrace(errsave, r)
httperrors.Serve500(w)
return nil, errsave
}
http.Redirect(w, r, getRequestAddress(r), http.StatusFound)
return nil, errsession
}
return session, nil
}
// TryAuthenticate tries to authenticate user and fetch access token if request is a callback to /auth?
func (a *Auth) TryAuthenticate(w http.ResponseWriter, r *http.Request, domains source.Source) bool {
if a == nil {
return false
}
session, err := a.checkSession(w, r)
if err != nil {
return true
}
// Request is for auth
if r.URL.Path != callbackPath {
return false
}
logRequest(r).Info("Receive OAuth authentication callback")
if a.handleProxyingAuth(session, w, r, domains) {
return true
}
// If callback is not successful
errorParam := r.URL.Query().Get("error")
if errorParam != "" {
logRequest(r).WithField("error", errorParam).Warn("OAuth endpoint returned error")
httperrors.Serve401(w)
return true
}
if verifyCodeAndStateGiven(r) {
a.checkAuthenticationResponse(session, w, r)
return true
}
return false
}
func (a *Auth) checkAuthenticationResponse(session *sessions.Session, w http.ResponseWriter, r *http.Request) {
if !validateState(r, session) {
// State is NOT ok
logRequest(r).Warn("Authentication state did not match expected")
httperrors.Serve401(w)
return
}
redirectURI, ok := session.Values["uri"].(string)
if !ok {
logRequest(r).Error("Can not extract redirect uri from session")
httperrors.Serve500(w)
return
}
decryptedCode, err := a.DecryptCode(r.URL.Query().Get("code"), getRequestDomain(r))
if err != nil {
logRequest(r).WithError(err).Error("failed to decrypt secure code")
errortracking.CaptureErrWithReqAndStackTrace(err, r)
httperrors.Serve500(w)
return
}
// Fetch access token with authorization code
token, err := a.fetchAccessToken(r.Context(), decryptedCode)
if err != nil {
// Fetching token not OK
logRequest(r).WithError(err).WithField(
"redirect_uri", redirectURI,
).Error(fetchAccessTokenErrMsg)
errortracking.CaptureErrWithReqAndStackTrace(err, r, errortracking.WithField("redirect_uri", redirectURI))
httperrors.Serve503(w)
return
}
// Store access token
session.Values["access_token"] = token.AccessToken
err = session.Save(r, w)
if err != nil {
logRequest(r).WithError(err).Error(saveSessionErrMsg)
errortracking.CaptureErrWithReqAndStackTrace(err, r)
httperrors.Serve500(w)
return
}
// Redirect back to requested URI
logRequest(r).WithField(
"redirect_uri", redirectURI,
).Info("Authentication was successful, redirecting user back to requested page")
http.Redirect(w, r, redirectURI, http.StatusFound)
}
func (a *Auth) domainAllowed(ctx context.Context, name string, domains source.Source) bool {
isConfigured := (name == a.pagesDomain) || strings.HasSuffix(name, "."+a.pagesDomain)
if isConfigured {
return true
}
domain, err := domains.GetDomain(ctx, name)
// domain exists and there is no error
return (domain != nil && err == nil)
}
func (a *Auth) handleProxyingAuth(session *sessions.Session, w http.ResponseWriter, r *http.Request, domains source.Source) bool {
// handle auth callback e.g. https://gitlab.io/auth?domain=domain&state=state
if shouldProxyAuthToGitlab(r) {
domain := r.URL.Query().Get("domain")
state := r.URL.Query().Get("state")
proxyurl, err := url.Parse(domain)
if err != nil {
logRequest(r).WithField("domain", domain).Error(queryParameterErrMsg)
errortracking.CaptureErrWithReqAndStackTrace(err, r, errortracking.WithField("domain", domain))
httperrors.Serve500(w)
return true
}
host, _, err := net.SplitHostPort(proxyurl.Host)
if err != nil {
host = proxyurl.Host
}
if !a.domainAllowed(r.Context(), host, domains) {
logRequest(r).WithField("domain", host).Warn("Domain is not configured")
httperrors.Serve401(w)
return true
}
logRequest(r).WithField("domain", domain).Info("User is authenticating via domain")
session.Values["proxy_auth_domain"] = domain
err = session.Save(r, w)
if err != nil {
logRequest(r).WithError(err).Error(saveSessionErrMsg)
errortracking.CaptureErrWithReqAndStackTrace(err, r)
httperrors.Serve500(w)
return true
}
url := fmt.Sprintf(authorizeURLTemplate, a.publicGitlabServer, a.clientID, a.redirectURI, state, a.authScope)
logRequest(r).WithFields(logrus.Fields{
"public_gitlab_server": a.publicGitlabServer,
"pages_domain": domain,
}).Info("Redirecting user to gitlab for oauth")
http.Redirect(w, r, url, http.StatusFound)
return true
}
// If auth request callback should be proxied to custom domain
// redirect to originating domain set in the cookie as proxy_auth_domain
if shouldProxyCallbackToCustomDomain(session) {
// Get domain started auth process
proxyDomain := session.Values["proxy_auth_domain"].(string)
logRequest(r).WithField("domain", proxyDomain).Info("Redirecting auth callback to custom domain")
// Clear proxying from session
delete(session.Values, "proxy_auth_domain")
err := session.Save(r, w)
if err != nil {
logRequest(r).WithError(err).Error(saveSessionErrMsg)
errortracking.CaptureErrWithReqAndStackTrace(err, r)
httperrors.Serve500(w)
return true
}
query := r.URL.Query()
// prevent https://tools.ietf.org/html/rfc6749#section-10.6 and
// https://gitlab.com/gitlab-org/gitlab-pages/-/issues/262 by encrypting
// and signing the OAuth code
signedCode, err := a.EncryptAndSignCode(proxyDomain, query.Get("code"))
if err != nil {
logRequest(r).WithError(err).Error(saveSessionErrMsg)
errortracking.CaptureErrWithReqAndStackTrace(err, r)
httperrors.Serve503(w)
return true
}
// prevent forwarding access token, more context on the security issue
// https://gitlab.com/gitlab-org/gitlab/-/issues/285244#note_451266051
query.Del("token")
// replace code with signed code
query.Set("code", signedCode)
// Redirect pages to originating domain with code and state to finish
// authentication process
http.Redirect(w, r, proxyDomain+r.URL.Path+"?"+query.Encode(), http.StatusFound)
return true
}
return false
}
func getRequestAddress(r *http.Request) string {
if request.IsHTTPS(r) {
return "https://" + r.Host + r.RequestURI
}
return "http://" + r.Host + r.RequestURI
}
func getRequestDomain(r *http.Request) string {
if request.IsHTTPS(r) {
return "https://" + r.Host
}
return "http://" + r.Host
}
func shouldProxyAuthToGitlab(r *http.Request) bool {
return r.URL.Query().Get("domain") != "" && r.URL.Query().Get("state") != ""
}
func shouldProxyCallbackToCustomDomain(session *sessions.Session) bool {
return session.Values["proxy_auth_domain"] != nil
}
func validateState(r *http.Request, session *sessions.Session) bool {
state := r.URL.Query().Get("state")
if state == "" {
// No state param
return false
}
// Check state
if session.Values["state"] == nil || session.Values["state"].(string) != state {
// State does not match
return false
}
// State ok
return true
}
func verifyCodeAndStateGiven(r *http.Request) bool {
return r.URL.Query().Get("code") != "" && r.URL.Query().Get("state") != ""
}
func (a *Auth) fetchAccessToken(ctx context.Context, code string) (tokenResponse, error) {
token := tokenResponse{}
// Prepare request
fetchURL, err := url.Parse(fmt.Sprintf(tokenURLTemplate, a.internalGitlabServer))
if err != nil {
return token, err
}
content := url.Values{}
content.Set("client_id", a.clientID)
content.Set("client_secret", a.clientSecret)
content.Set("code", code)
content.Set("grant_type", "authorization_code")
content.Set("redirect_uri", a.redirectURI)
req, err := http.NewRequestWithContext(ctx, "POST", fetchURL.String(), strings.NewReader(content.Encode()))
if err != nil {
return token, err
}
// Request token
resp, err := a.apiClient.Do(req)
if err != nil {
return token, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
err = errResponseNotOk
errortracking.CaptureErrWithReqAndStackTrace(err, req)
return token, err
}
// Parse response
err = json.NewDecoder(resp.Body).Decode(&token)
if err != nil {
return token, err
}
return token, nil
}
func (a *Auth) checkSessionIsValid(w http.ResponseWriter, r *http.Request) *sessions.Session {
session, err := a.checkSession(w, r)
if err != nil {
return nil
}
// redirect to /auth?domain=%s&state=%s
if a.checkTokenExists(session, w, r) {
return nil
}
return session
}
func (a *Auth) checkTokenExists(session *sessions.Session, w http.ResponseWriter, r *http.Request) bool {
// If no access token redirect to OAuth login page
if session.Values["access_token"] == nil {
logRequest(r).Debug("No access token exists, redirecting user to OAuth2 login")
// Generate state hash and store requested address
state := base64.URLEncoding.EncodeToString(securecookie.GenerateRandomKey(16))
session.Values["state"] = state
session.Values["uri"] = getRequestAddress(r)
// Clear possible proxying
delete(session.Values, "proxy_auth_domain")
err := session.Save(r, w)
if err != nil {
logRequest(r).WithError(err).Error(saveSessionErrMsg)
errortracking.CaptureErrWithReqAndStackTrace(err, r)
httperrors.Serve500(w)
return true
}
// Because the pages domain might be in public suffix list, we have to
// redirect to pages domain to trigger authorization flow
http.Redirect(w, r, a.getProxyAddress(r, state), http.StatusFound)
return true
}
return false
}
func (a *Auth) getProxyAddress(r *http.Request, state string) string {
return fmt.Sprintf(authorizeProxyTemplate, a.redirectURI, getRequestDomain(r), state)
}
func destroySession(session *sessions.Session, w http.ResponseWriter, r *http.Request) {
logRequest(r).Debug("Destroying session")
// Invalidate access token and redirect back for refreshing and re-authenticating
delete(session.Values, "access_token")
err := session.Save(r, w)
if err != nil {
logRequest(r).WithError(err).Error(saveSessionErrMsg)
errortracking.CaptureErrWithReqAndStackTrace(err, r)
httperrors.Serve500(w)
return
}
http.Redirect(w, r, getRequestAddress(r), http.StatusFound)
}
// IsAuthSupported checks if pages is running with the authentication support
func (a *Auth) IsAuthSupported() bool {
return a != nil
}
func (a *Auth) checkAuthentication(w http.ResponseWriter, r *http.Request, domain domain) bool {
session := a.checkSessionIsValid(w, r)
if session == nil {
return true
}
projectID := domain.GetProjectID(r)
// Access token exists, authorize request
var url string
if projectID > 0 {
url = fmt.Sprintf(apiURLProjectTemplate, a.internalGitlabServer, projectID)
} else {
url = fmt.Sprintf(apiURLUserTemplate, a.internalGitlabServer)
}
req, err := http.NewRequestWithContext(r.Context(), "GET", url, nil)
if err != nil {
logRequest(r).WithError(err).Error(failAuthErrMsg)
errortracking.CaptureErrWithReqAndStackTrace(err, r)
httperrors.Serve500(w)
return true
}
req.Header.Add("Authorization", "Bearer "+session.Values["access_token"].(string))
resp, err := a.apiClient.Do(req)
if err != nil {
logRequest(r).WithError(err).Error("Failed to retrieve info with token")
errortracking.CaptureErrWithReqAndStackTrace(err, r)
// call serve404 handler when auth fails
domain.ServeNotFoundAuthFailed(w, r)
return true
}
defer resp.Body.Close()
if checkResponseForInvalidToken(resp, session, w, r) {
return true
}
if resp.StatusCode != http.StatusOK {
// call serve404 handler when auth fails
err := fmt.Errorf("unexpected response fetching access token status: %d", resp.StatusCode)
logRequest(r).WithError(err).WithFields(log.Fields{
"status": resp.StatusCode,
"status_text": resp.Status,
}).Error("Unexpected response fetching access token")
errortracking.CaptureErrWithReqAndStackTrace(err, r)
domain.ServeNotFoundAuthFailed(w, r)
return true
}
return false
}
// CheckAuthenticationWithoutProject checks if user is authenticated and has a valid token
func (a *Auth) CheckAuthenticationWithoutProject(w http.ResponseWriter, r *http.Request, domain domain) bool {
if a == nil {
// No auth supported
return false
}
return a.checkAuthentication(w, r, domain)
}
// GetTokenIfExists returns the token if it exists
func (a *Auth) GetTokenIfExists(w http.ResponseWriter, r *http.Request) (string, error) {
if a == nil {
return "", nil
}
session, err := a.checkSession(w, r)
if err != nil {
return "", errors.New("error retrieving the session")
}
if session.Values["access_token"] != nil {
return session.Values["access_token"].(string), nil
}
return "", nil
}
// RequireAuth will trigger authentication flow if no token exists
func (a *Auth) RequireAuth(w http.ResponseWriter, r *http.Request) bool {
return a.checkSessionIsValid(w, r) == nil
}
// CheckAuthentication checks if user is authenticated and has access to the project
// will return contentServed = false when authFailed = true
func (a *Auth) CheckAuthentication(w http.ResponseWriter, r *http.Request, domain domain) bool {
logRequest(r).Debug("Authenticate request")
if a == nil {
logRequest(r).Error(errAuthNotConfigured)
errortracking.CaptureErrWithReqAndStackTrace(errAuthNotConfigured, r)
httperrors.Serve500(w)
return true
}
return a.checkAuthentication(w, r, domain)
}
// CheckResponseForInvalidToken checks response for invalid token and destroys session if it was invalid
func (a *Auth) CheckResponseForInvalidToken(w http.ResponseWriter, r *http.Request,
resp *http.Response,
) bool {
if a == nil {
// No auth supported
return false
}
session, err := a.checkSession(w, r)
if err != nil {
return true
}
if checkResponseForInvalidToken(resp, session, w, r) {
return true
}
return false
}
func checkResponseForInvalidToken(resp *http.Response, session *sessions.Session, w http.ResponseWriter, r *http.Request) bool {
if resp.StatusCode == http.StatusUnauthorized {
errResp := errorResponse{}
// Parse response
defer resp.Body.Close()
err := json.NewDecoder(resp.Body).Decode(&errResp)
if err != nil {
errortracking.CaptureErrWithReqAndStackTrace(err, r)
return false
}
if errResp.Error == "invalid_token" {
// Token is invalid
logRequest(r).Warn("Access token was invalid, destroying session")
destroySession(session, w, r)
return true
}
}
return false
}
func logRequest(r *http.Request) *logrus.Entry {
return logging.LogRequest(r).WithField("state", r.URL.Query().Get("state"))
}
// generateKeys derives count hkdf keys from a secret, ensuring the key is
// the same for the same secret used across multiple instances
func generateKeys(secret string, count int) ([][]byte, error) {
keys := make([][]byte, count)
hkdfReader := hkdf.New(sha256.New, []byte(secret), []byte{}, []byte("PAGES_SIGNING_AND_ENCRYPTION_KEY"))
for i := 0; i < count; i++ {
key := make([]byte, 32)
if _, err := io.ReadFull(hkdfReader, key); err != nil {
return nil, err
}
keys[i] = key
}
if len(keys) < count {
return nil, errGenerateKeys
}
return keys, nil
}
// New when authentication supported this will be used to create authentication handler
func New(pagesDomain, storeSecret, clientID, clientSecret, redirectURI, internalGitlabServer, publicGitlabServer, authScope string) (*Auth, error) {
// generate 3 keys, 2 for the cookie store and 1 for JWT signing
keys, err := generateKeys(storeSecret, 3)
if err != nil {
return nil, err
}
return &Auth{
pagesDomain: pagesDomain,
clientID: clientID,
clientSecret: clientSecret,
redirectURI: redirectURI,
internalGitlabServer: strings.TrimRight(internalGitlabServer, "/"),
publicGitlabServer: strings.TrimRight(publicGitlabServer, "/"),
apiClient: &http.Client{
Timeout: 5 * time.Second,
Transport: httptransport.DefaultTransport,
},
store: sessions.NewCookieStore(keys[0], keys[1]),
authSecret: storeSecret,
authScope: authScope,
jwtSigningKey: keys[2],
jwtExpiry: time.Minute,
now: time.Now,
}, nil
}
|