This repository has been archived by the owner on Apr 17, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 22
/
route_handlers.go
795 lines (714 loc) · 27 KB
/
route_handlers.go
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
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
package service
import (
"bytes"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/xml"
"fmt"
"html/template"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
log "github.com/Sirupsen/logrus"
"github.com/crewjam/saml"
"github.com/dgrijalva/jwt-go"
"github.com/rancher/go-rancher/api"
"github.com/rancher/go-rancher/v2"
"github.com/rancher/rancher-auth-service/model"
"github.com/rancher/rancher-auth-service/server"
)
const (
redirectBackBase = "redirectBackBase"
redirectBackPath = "redirectBackPath"
postSamlTokenHTML = "/v1-auth/saml/tokenhtml"
tpl = `
<!DOCTYPE html>
<html>
<head>
<script>
window.onload = function() {
document.getElementById('TokenHTMLResponseForm').submit();
}
</script>
</head>
<body>
<form method="post" action="{{.URL}}" id="TokenHTMLResponseForm">
<input type="hidden" name="token" value="{{.Token}}" />
<input type="hidden" name="finalRedirectURL" value="{{.FinalRedirectURL}}" />
<input type="hidden" name="secure" value="{{.Secure}}" />
</form>
</body>
</html>`
)
//CreateToken is a handler for route /token and returns the jwt token after authenticating the user
func CreateToken(w http.ResponseWriter, r *http.Request) {
bytes, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Errorf("GetToken failed with error: %v", err)
}
var jsonInput map[string]string
err = json.Unmarshal(bytes, &jsonInput)
if err != nil {
log.Errorf("unmarshal failed with error: %v", err)
}
securityCode := jsonInput["code"]
accessToken := jsonInput["accessToken"]
if securityCode != "" {
log.Debugf("CreateToken called with securityCode")
//getToken
token, status, err := server.CreateToken(jsonInput)
if err != nil {
log.Errorf("GetToken failed with error: %v", err)
if status == 0 {
status = http.StatusInternalServerError
}
ReturnHTTPError(w, r, status, fmt.Sprintf("%v", err))
return
}
api.GetApiContext(r).Write(&token)
} else if accessToken != "" {
log.Debugf("RefreshToken called with accessToken %s", accessToken)
//getToken
token, status, err := server.RefreshToken(jsonInput)
if err != nil {
log.Errorf("GetToken failed with error: %v", err)
if status == 0 {
status = http.StatusInternalServerError
}
ReturnHTTPError(w, r, status, fmt.Sprintf("%v", err))
return
}
api.GetApiContext(r).Write(&token)
} else {
ReturnHTTPError(w, r, http.StatusBadRequest, "Bad Request, Please check the request content")
return
}
}
//GetIdentities is a handler for route /me/identities and returns group memberships and details of the user
func GetIdentities(w http.ResponseWriter, r *http.Request) {
apiContext := api.GetApiContext(r)
authHeader := r.Header.Get("Authorization")
if authHeader != "" {
// header value format will be "Bearer <token>"
if !strings.HasPrefix(authHeader, "Bearer ") {
log.Debugf("GetMyIdentities Failed to find Bearer token %v", authHeader)
ReturnHTTPError(w, r, http.StatusUnauthorized, "Unauthorized, please provide a valid token")
return
}
accessToken := strings.TrimPrefix(authHeader, "Bearer ")
identities, err := server.GetIdentities(accessToken)
if err == nil {
resp := client.IdentityCollection{}
resp.Data = identities
apiContext.Write(&resp)
} else {
//failed to get the user identities
log.Debugf("GetIdentities Failed with error %v", err)
ReturnHTTPError(w, r, http.StatusUnauthorized, "Unauthorized, failed to get identities")
return
}
} else {
log.Debug("No Authorization header found")
ReturnHTTPError(w, r, http.StatusUnauthorized, "Unauthorized, please provide a valid token")
return
}
}
//SearchIdentities is a handler for route /identities and filters (id + type or name) and returns the search results using the passed filters
func SearchIdentities(w http.ResponseWriter, r *http.Request) {
apiContext := api.GetApiContext(r)
authHeader := r.Header.Get("Authorization")
if authHeader != "" {
// header value format will be "Bearer <token>"
if !strings.HasPrefix(authHeader, "Bearer") {
log.Debugf("GetMyIdentities Failed to find Bearer token %v", authHeader)
ReturnHTTPError(w, r, http.StatusUnauthorized, "Unauthorized, please provide a valid token")
return
}
accessToken := strings.TrimPrefix(authHeader, "Bearer")
accessToken = strings.TrimSpace(accessToken)
//see which filters are passed, if none then error 400
externalID := r.URL.Query().Get("externalId")
externalIDType := r.URL.Query().Get("externalIdType")
name := r.URL.Query().Get("name")
if externalID != "" && externalIDType != "" {
log.Debugf("SearchIdentities by externalID: %v and externalIDType: %v", externalID, externalIDType)
//search by id and type
identity, err := server.GetIdentity(externalID, externalIDType, accessToken)
if err == nil {
log.Debugf("Found identity %v", identity)
apiContext.Write(&identity)
} else {
//failed to search the identities
log.Errorf("SearchIdentities Failed with error %v", err)
ReturnHTTPError(w, r, http.StatusInternalServerError, "Internal Server Error")
return
}
} else if name != "" {
log.Debugf("SearchIdentities by name: %v", name)
//Must call ldap SearchIdentities with exactMatch=true
identities, err := server.SearchIdentities(name, true, accessToken)
log.Debugf("Found identities %v", identities)
if err == nil {
resp := client.IdentityCollection{}
resp.Data = identities
apiContext.Write(&resp)
} else {
//failed to search the identities
log.Errorf("SearchIdentities Failed with error %v", err)
ReturnHTTPError(w, r, http.StatusInternalServerError, "Internal Server Error")
return
}
} else {
ReturnHTTPError(w, r, http.StatusBadRequest, "Bad Request, Please check the request content")
return
}
} else {
log.Debug("No Authorization header found")
ReturnHTTPError(w, r, http.StatusUnauthorized, "Unauthorized, please provide a valid token")
return
}
}
//UpdateConfig is a handler for POST /config, loads the provider with the config and saves the config back to Cattle database
func UpdateConfig(w http.ResponseWriter, r *http.Request) {
apiContext := api.GetApiContext(r)
bytes, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Errorf("UpdateConfig failed with error: %v", err)
ReturnHTTPError(w, r, http.StatusBadRequest, "Bad Request, Please check the request content")
return
}
var authConfig model.AuthConfig
err = json.Unmarshal(bytes, &authConfig)
if err != nil {
log.Errorf("UpdateConfig unmarshal failed with error: %v", err)
ReturnHTTPError(w, r, http.StatusBadRequest, "Bad Request, Please check the request content")
return
}
if authConfig.Provider == "" {
log.Errorf("UpdateConfig: Provider is a required field")
ReturnHTTPError(w, r, http.StatusBadRequest, "Bad Request, Please check the request content, Provider is a required field")
return
}
err = server.UpdateConfig(authConfig)
if err != nil {
log.Errorf("UpdateConfig failed with error: %v", err)
ReturnHTTPError(w, r, http.StatusBadRequest, "Bad Request, Please check the request content")
return
}
log.Debugf("Updated config, listing the config back")
//list the config and return in response
config, err := server.GetConfig("", true)
if err == nil {
apiContext.Write(&config)
} else {
//failed to get the config
log.Debugf("GetConfig failed with error %v", err)
ReturnHTTPError(w, r, http.StatusInternalServerError, "Failed to list the config")
return
}
}
//GetConfig is a handler for GET /config, lists the provider config
func GetConfig(w http.ResponseWriter, r *http.Request) {
apiContext := api.GetApiContext(r)
authHeader := r.Header.Get("Authorization")
var accessToken string
// header value format will be "Bearer <token>"
if authHeader != "" {
if !strings.HasPrefix(authHeader, "Bearer ") {
log.Errorf("GetMyIdentities Failed to find Bearer token %v", authHeader)
ReturnHTTPError(w, r, http.StatusUnauthorized, "Unauthorized, please provide a valid token")
return
}
accessToken = strings.TrimPrefix(authHeader, "Bearer ")
}
config, err := server.GetConfig(accessToken, true)
if err == nil {
apiContext.Write(&config)
} else {
//failed to get the config
log.Debugf("GetConfig failed with error %v", err)
ReturnHTTPError(w, r, http.StatusInternalServerError, "Failed to get the auth config")
return
}
}
//Reload is a handler for POST /reloadconfig, reloads the config from Cattle database and initializes the provider
func Reload(w http.ResponseWriter, r *http.Request) {
log.Debugf("Reload called")
_, err := server.Reload(false)
if err != nil {
//failed to reload the config from DB
log.Debugf("Reload failed with error %v", err)
ReturnHTTPError(w, r, http.StatusInternalServerError, "Failed to reload the auth config")
return
}
}
func addErrorToRedirect(redirectURL string, code string) string {
//add code query param to redirect
redirectURLInst, err := url.Parse(redirectURL)
if err == nil {
v := redirectURLInst.Query()
v.Add("errCode", code)
redirectURLInst.RawQuery = v.Encode()
redirectURL = redirectURLInst.String()
} else {
log.Errorf("Error parsing the URL %v ,error is: %v", redirectURL, err)
redirectURL = redirectURL + "?errCode=" + code
}
return redirectURL
}
//GetRedirectURL gets the redirect URL
func GetRedirectURL(w http.ResponseWriter, r *http.Request) {
redirectResponse, err := server.GetRedirectURL()
if err == nil {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(redirectResponse)
} else {
//failed to get the redirectURL
log.Debugf("GetRedirectUrl failed with error %v", err)
ReturnHTTPError(w, r, http.StatusInternalServerError, "Failed to get the redirect URL")
return
}
}
//DoSamlLogout redirects to Saml Logout
func DoSamlLogout(w http.ResponseWriter, r *http.Request) {
if server.SamlServiceProvider != nil {
if server.SamlServiceProvider.ServiceProvider.IDPMetadata != nil {
entityID := server.SamlServiceProvider.ServiceProvider.IDPMetadata.EntityID
entityURL, _ := url.Parse(entityID)
redirectURL := entityURL.Scheme + "://" + entityURL.Host + "/idp/profile/Logout"
log.Debugf("redirecting the user to %v", redirectURL)
http.Redirect(w, r, redirectURL, http.StatusFound)
return
}
log.Info("No Logout URL - Saml/Shibboleth IDPMetadata not found")
} else {
log.Info("No Logout URL - Saml/Shibboleth provider is not configured")
}
}
// TestLogin is a test API to check login with code before saving settings to db
func TestLogin(w http.ResponseWriter, r *http.Request) {
authHeader := r.Header.Get("Authorization")
cookies := r.Cookies()
var token string
for _, c := range cookies {
if c.Name == "token" {
token = c.Value
}
}
var accessToken string
// header value format will be "Bearer <token>"
if authHeader != "" {
if !strings.HasPrefix(authHeader, "Bearer ") {
log.Errorf("GetMyIdentities Failed to find Bearer token %v", authHeader)
ReturnHTTPError(w, r, http.StatusUnauthorized, "Unauthorized, please provide a valid token")
return
}
accessToken = strings.TrimPrefix(authHeader, "Bearer ")
}
bytes, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Errorf("TestLogin failed with error: %v", err)
ReturnHTTPError(w, r, http.StatusBadRequest, "Bad Request, Please check the request content")
return
}
var testAuthConfig model.TestAuthConfig
err = json.Unmarshal(bytes, &testAuthConfig)
if err != nil {
log.Errorf("TestLogin unmarshal failed with error: %v", err)
ReturnHTTPError(w, r, http.StatusBadRequest, "Bad Request, Please check the request content")
return
}
if testAuthConfig.AuthConfig.Provider == "" {
log.Errorf("UpdateConfig: Provider is a required field")
ReturnHTTPError(w, r, http.StatusBadRequest, "Bad request, Provider is a required field")
return
}
status, err := server.TestLogin(testAuthConfig, accessToken, token)
if err != nil {
log.Errorf("TestLogin GetProvider failed with error: %v", err)
if status == 0 {
status = http.StatusInternalServerError
}
ReturnHTTPError(w, r, status, fmt.Sprintf("%v", err))
}
}
// HandleSamlLogin is the endpoint for /saml/login endpoint
func HandleSamlLogin(w http.ResponseWriter, r *http.Request) {
var redirectBackBaseValue string
s := server.SamlServiceProvider
s.XForwardedProto = r.Header.Get("X-Forwarded-Proto")
if r.URL.Query() != nil {
redirectBackBaseValue = r.URL.Query().Get(redirectBackBase)
if redirectBackBaseValue == "" {
redirectBackBaseValue = server.GetRancherAPIHost()
}
} else {
redirectBackBaseValue = server.GetRancherAPIHost()
}
if !isWhitelisted(redirectBackBaseValue, s.RedirectWhitelist) {
log.Errorf("Cannot redirect to anything other than whitelisted domains and rancher api host")
redirectBackPathValue := r.URL.Query().Get(redirectBackPath)
redirectURL := server.GetSamlRedirectURL(server.GetRancherAPIHost(), redirectBackPathValue)
redirectURL = addErrorToRedirect(redirectURL, "422")
http.Redirect(w, r, redirectURL, http.StatusFound)
return
}
serviceProvider := s.ServiceProvider
if r.URL.Path == serviceProvider.AcsURL.Path {
return
}
binding := saml.HTTPRedirectBinding
bindingLocation := serviceProvider.GetSSOBindingLocation(binding)
if bindingLocation == "" {
binding = saml.HTTPPostBinding
bindingLocation = serviceProvider.GetSSOBindingLocation(binding)
}
req, err := serviceProvider.MakeAuthenticationRequest(bindingLocation)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// relayState is limited to 80 bytes but also must be integrety protected.
// this means that we cannot use a JWT because it is way to long. Instead
// we set a cookie that corresponds to the state
relayState := base64.URLEncoding.EncodeToString(randomBytes(42))
secretBlock := x509.MarshalPKCS1PrivateKey(serviceProvider.Key)
state := jwt.New(jwt.SigningMethodHS256)
claims := state.Claims.(jwt.MapClaims)
claims["id"] = req.ID
claims["uri"] = r.URL.String()
signedState, err := state.SignedString(secretBlock)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
s.ClientState.SetState(w, r, relayState, signedState)
if binding == saml.HTTPRedirectBinding {
redirectURL := req.Redirect(relayState)
w.Header().Add("Location", redirectURL.String())
w.WriteHeader(http.StatusFound)
return
}
if binding == saml.HTTPPostBinding {
w.Header().Add("Content-Security-Policy", ""+
"default-src; "+
"script-src 'sha256-AjPdJSbZmeWHnEc5ykvJFay8FTWeTeRbs9dutfZ0HqE='; "+
"reflected-xss block; referrer no-referrer;")
w.Header().Add("Content-type", "text/html")
w.Write([]byte(`<!DOCTYPE html><html><body>`))
w.Write(req.Post(relayState))
w.Write([]byte(`</body></html>`))
return
}
}
// ServeHTTP is the handler for /saml/metadata and /saml/acs endpoints
func ServeHTTP(w http.ResponseWriter, r *http.Request) {
serviceProvider := server.SamlServiceProvider.ServiceProvider
if r.URL.Path == serviceProvider.MetadataURL.Path {
buf, _ := xml.MarshalIndent(serviceProvider.Metadata(), "", " ")
w.Header().Set("Content-Type", "application/samlmetadata+xml")
w.Write(buf)
return
}
if r.URL.Path == serviceProvider.AcsURL.Path {
r.ParseForm()
assertion, err := serviceProvider.ParseResponse(r, getPossibleRequestIDs(r, server.SamlServiceProvider))
if err != nil {
if parseErr, ok := err.(*saml.InvalidResponseError); ok {
log.Errorf("RESPONSE: ===\n%s\n===\nNOW: %s\nERROR: %s",
parseErr.Response, parseErr.Now, parseErr.PrivateErr)
}
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
return
}
HandleSamlAssertion(w, r, assertion, server.SamlServiceProvider)
return
}
http.NotFoundHandler().ServeHTTP(w, r)
}
func getPossibleRequestIDs(r *http.Request, s *model.RancherSamlServiceProvider) []string {
rv := []string{}
for _, value := range s.ClientState.GetStates(r) {
jwtParser := jwt.Parser{
ValidMethods: []string{jwt.SigningMethodHS256.Name},
}
token, err := jwtParser.Parse(value, func(t *jwt.Token) (interface{}, error) {
secretBlock := x509.MarshalPKCS1PrivateKey(s.ServiceProvider.Key)
return secretBlock, nil
})
if err != nil || !token.Valid {
log.Debugf("... invalid token %s", err)
continue
}
claims := token.Claims.(jwt.MapClaims)
rv = append(rv, claims["id"].(string))
}
return rv
}
func randomBytes(n int) []byte {
rv := make([]byte, n)
if _, err := saml.RandReader.Read(rv); err != nil {
panic(err)
}
return rv
}
func GetRedirectParams(w http.ResponseWriter, r *http.Request, serviceProvider *model.RancherSamlServiceProvider) (redirectBackBaseValue string,
redirectBackPathValue string) {
redirectBackBaseValue = server.GetRancherAPIHost()
redirectBackPathValue = "/login/shibboleth-auth"
if serviceProvider.ServiceProvider.Key == nil {
log.Errorf("GetRedirectParams: No key found in service provider")
redirectURL := server.GetSamlRedirectURL(redirectBackBaseValue, redirectBackPathValue)
redirectURL = addErrorToRedirect(redirectURL, "403")
http.Redirect(w, r, redirectURL, http.StatusFound)
return
}
secretBlock := x509.MarshalPKCS1PrivateKey(serviceProvider.ServiceProvider.Key)
if relayState := r.Form.Get("RelayState"); relayState != "" {
stateValue := serviceProvider.ClientState.GetState(r, relayState)
if stateValue == "" {
log.Errorf("cannot find corresponding state: %s", relayState)
redirectURL := server.GetSamlRedirectURL(redirectBackBaseValue, redirectBackPathValue)
redirectURL = addErrorToRedirect(redirectURL, "403")
http.Redirect(w, r, redirectURL, http.StatusFound)
return
}
jwtParser := jwt.Parser{
ValidMethods: []string{jwt.SigningMethodHS256.Name},
}
state, err := jwtParser.Parse(stateValue, func(t *jwt.Token) (interface{}, error) {
return secretBlock, nil
})
if err != nil || !state.Valid {
log.Errorf("Cannot decode state JWT: %s (%s)", err, stateValue)
redirectURL := server.GetSamlRedirectURL(redirectBackBaseValue, redirectBackPathValue)
redirectURL = addErrorToRedirect(redirectURL, "403")
http.Redirect(w, r, redirectURL, http.StatusFound)
return
}
claims := state.Claims.(jwt.MapClaims)
if claims == nil {
redirectURL := server.GetSamlRedirectURL(redirectBackBaseValue, redirectBackPathValue)
redirectURL = addErrorToRedirect(redirectURL, "403")
http.Redirect(w, r, redirectURL, http.StatusFound)
return
}
redirectURI := claims["uri"].(string)
log.Debugf("RelayState used to get redirect params: %v", relayState)
log.Debugf("redirectURI from claims: %v", redirectURI)
query, err := url.Parse(redirectURI)
if err != nil {
log.Errorf("Error in getting query params")
redirectURL := server.GetSamlRedirectURL(redirectBackBaseValue, redirectBackPathValue)
redirectURL = addErrorToRedirect(redirectURL, "403")
http.Redirect(w, r, redirectURL, http.StatusFound)
return
}
parsedQuery, err := url.ParseQuery(query.RawQuery)
if err != nil {
log.Errorf("Error in parsing query params")
redirectURL := server.GetSamlRedirectURL(redirectBackBaseValue, redirectBackPathValue)
redirectURL = addErrorToRedirect(redirectURL, "403")
http.Redirect(w, r, redirectURL, http.StatusFound)
return
}
redirectBackBaseValue = parsedQuery.Get(redirectBackBase)
redirectBackPathValue = parsedQuery.Get(redirectBackPath)
log.Debugf("redirectBackBaseValue, redirectBackPathValue from claims: %v, %v", redirectBackBaseValue, redirectBackPathValue)
// delete the cookie
log.Debugf("Deleting relayState: %v", relayState)
serviceProvider.ClientState.DeleteState(w, r, relayState)
}
return redirectBackBaseValue, redirectBackPathValue
}
// HandleSamlAssertion processes/handles the assertion obtained by the POST to /saml/acs from IdP
func HandleSamlAssertion(w http.ResponseWriter, r *http.Request, assertion *saml.Assertion, serviceProvider *model.RancherSamlServiceProvider) {
redirectBackBaseValue, redirectBackPathValue := GetRedirectParams(w, r, serviceProvider)
log.Debugf("redirectBackBaseValue, redirectBackPathValue from GetRedirectParams: %v, %v", redirectBackBaseValue, redirectBackPathValue)
if redirectBackBaseValue == "" {
redirectBackBaseValue = server.GetRancherAPIHost()
}
redirectURL := server.GetSamlRedirectURL(redirectBackBaseValue, redirectBackPathValue)
if !isWhitelisted(redirectBackBaseValue, serviceProvider.RedirectWhitelist) {
log.Errorf("Cannot redirect to anything other than whitelisted domains and rancher api host")
redirectURL := server.GetSamlRedirectURL(server.GetRancherAPIHost(), redirectBackPathValue)
redirectURL = addErrorToRedirect(redirectURL, "422")
http.Redirect(w, r, redirectURL, http.StatusFound)
return
}
samlData := make(map[string][]string)
for _, attributeStatement := range assertion.AttributeStatements {
for _, attr := range attributeStatement.Attributes {
attrName := attr.FriendlyName
if attrName == "" {
attrName = attr.Name
}
for _, value := range attr.Values {
samlData[attrName] = append(samlData[attrName], value.Value)
}
}
}
rancherAPI := server.GetRancherAPIHost()
//get the SAML data, create a jwt token and POST to /v1/token with code = "jwt token"
mapB, _ := json.Marshal(samlData)
inputJSON := make(map[string]string)
inputJSON["code"] = string(mapB)
outputJSON := make(map[string]interface{})
tokenURL := rancherAPI + "/v1/token"
log.Debugf("HandleSamlAssertion: tokenURL %v ", tokenURL)
err := server.RancherClient.Post(tokenURL, inputJSON, &outputJSON)
if err != nil {
//failed to get token from cattle
log.Errorf("HandleSamlAssertion failed to Get token from cattle with error %v", err.Error())
if strings.Contains(err.Error(), "401") {
//add error=401 query param to redirect
redirectURL = addErrorToRedirect(redirectURL, "401")
} else if strings.Contains(err.Error(), "403") {
redirectURL = addErrorToRedirect(redirectURL, "403")
} else {
redirectURL = addErrorToRedirect(redirectURL, "500")
}
http.Redirect(w, r, redirectURL, http.StatusFound)
return
}
jwt := outputJSON["jwt"].(string)
log.Debugf("HandleSamlAssertion: Got token %v ", jwt)
secure := false
XForwardedProtoValue := serviceProvider.XForwardedProto
if XForwardedProtoValue == "https" {
secure = true
}
/* token is created at this point. If the redirectBackBase is not same as the current URL's domain, then we cannot set the token as cookie
yet. So we will first send a 200 POST to /v1-auth/saml/tokenhtml, which will contain token cookie and redirectBackBase in HTML body,
and JS which will submit form on load to redirect URL. The handler for v1-auth/saml/tokenhtml will then set the token as cookie
*/
query, err := url.Parse(redirectBackBaseValue)
if err != nil {
log.Errorf("HandleSamlAssertion: Error in parsing redirectBackBaseValue: %v", err)
redirectURL = addErrorToRedirect(redirectURL, "500")
http.Redirect(w, r, redirectURL, http.StatusFound)
return
}
log.Debugf("HandleSamlAssertion: r.URL: %v, host: %v, redirectBackBaseValue: %v, redirectBackBaseValue.host: %v", r.URL, r.Host, redirectBackBaseValue,
query.Host)
if query.Host != r.Host {
newRedirectURL := redirectBackBaseValue + postSamlTokenHTML
w.Header().Add("Content-type", "text/html")
tmpl := template.Must(template.New("saml-post-form").Parse(tpl))
data := struct {
URL string
Token string
FinalRedirectURL string
Secure bool
}{
URL: newRedirectURL,
Token: jwt,
FinalRedirectURL: redirectURL,
Secure: secure,
}
log.Debugf("HandleSamlAssertion: Adding data to template: %#v", data)
rv := bytes.Buffer{}
if err := tmpl.Execute(&rv, data); err != nil {
redirectURL = addErrorToRedirect(redirectURL, "500")
http.Redirect(w, r, redirectURL, http.StatusFound)
return
}
w.Write(rv.Bytes())
return
}
// else, if redirectBackBase is same as the current URL, continue and set this token as cookie
tokenCookie := &http.Cookie{
Name: "token",
Value: jwt,
Secure: secure,
MaxAge: 0,
Path: "/",
}
http.SetCookie(w, tokenCookie)
log.Debugf("JWT token: %v", jwt)
log.Debugf("redirecting the user with cookie %v to %v", tokenCookie, redirectURL)
http.Redirect(w, r, redirectURL, http.StatusFound)
return
}
func PostSamlTokenHTML(w http.ResponseWriter, r *http.Request) {
var token, finalRedirectURL string
var secure bool
var err error
if err = r.ParseForm(); err != nil {
log.Errorf("PostSamlTokenHTML: Error in parsing forn: %v", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
tokenArr, ok := r.Form["token"]
if !ok || len(tokenArr) == 0 {
log.Errorf("PostSamlTokenHTML: No token provided in POST request: %v", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
token = tokenArr[0]
log.Debugf("PostSamlTokenHTML: token in the post form: %v", token)
finalRedirectURLArr, ok := r.Form["finalRedirectURL"]
if !ok || len(finalRedirectURLArr) == 0 {
log.Errorf("PostSamlTokenHTML: No finalRedirectURL provided in POST request: %v", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
finalRedirectURL = finalRedirectURLArr[0]
log.Debugf("PostSamlTokenHTML: finalRedirectURL in the post form: %v", finalRedirectURL)
secureArr, ok := r.Form["secure"]
if !ok || len(secureArr) == 0 {
log.Errorf("PostSamlTokenHTML: No secure parameter provided in POST request: %v", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
secureStr := secureArr[0]
secure, err = strconv.ParseBool(secureStr)
if err != nil {
log.Errorf("PostSamlTokenHTML: Error in parsing secure flag for token: %v", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
log.Debugf("PostSamlTokenHTML: secure attribute in the post form: %v, and original: %v", secure, secureStr)
tokenCookie := &http.Cookie{
Name: "token",
Value: token,
Secure: secure,
MaxAge: 0,
Path: "/",
}
http.SetCookie(w, tokenCookie)
log.Debugf("redirecting the user with cookie %v to %v", tokenCookie, finalRedirectURL)
http.Redirect(w, r, finalRedirectURL, http.StatusFound)
}
func isWhitelisted(redirectBackBaseValue string, redirectWhitelist string) bool {
var redirectBackBaseDomainNonPort string
if redirectBackBaseValue == server.GetRancherAPIHost() {
return true
}
redirectURL, err := url.Parse(redirectBackBaseValue)
if err != nil {
log.Errorf("Error in parsing redirect URL")
return false
}
redirectBackBaseDomain := redirectURL.Host
if strings.Contains(redirectBackBaseDomain, ":") {
d := strings.SplitN(redirectBackBaseDomain, ":", 2)
redirectBackBaseDomainNonPort = d[0]
}
// comma separated list of whitelisted domains to redirect to
if redirectWhitelist != "" {
whitelistedDomains := strings.Split(redirectWhitelist, ",")
log.Debugf("Whitelisted domains provided: %v, redirectBackBase: %v, redirectBackBaseNonPort: %v", whitelistedDomains,
redirectBackBaseDomain, redirectBackBaseDomainNonPort)
for _, w := range whitelistedDomains {
if w == redirectBackBaseDomain || w == redirectBackBaseDomainNonPort {
log.Debugf("Whitelisted domain matched: %v", w)
return true
}
}
}
return false
}