forked from kyma-project/kyma
/
idtokenprovider.go
164 lines (145 loc) · 4.58 KB
/
idtokenprovider.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
package graphql
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"regexp"
"strings"
"log"
"github.com/pkg/errors"
"golang.org/x/net/html"
)
type idTokenProvider interface {
fetchIdToken() (string, error)
}
type dexIdTokenProvider struct {
httpClient *http.Client
config idProviderConfig
}
func newDexIdTokenProvider(httpClient *http.Client, config idProviderConfig) idTokenProvider {
// turn off follow-redirects
httpClient.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}
return &dexIdTokenProvider{httpClient, config}
}
func (p *dexIdTokenProvider) fetchIdToken() (string, error) {
flowResult, err := p.implicitFlow()
if err != nil {
return "", err
}
return flowResult["id_token"], nil
}
func (p *dexIdTokenProvider) implicitFlow() (map[string]string, error) {
authorizeResp, err := p.httpClient.PostForm(p.config.DexConfig.AuthorizeEndpoint, url.Values{
"response_type": {"id_token token"},
"client_id": {p.config.ClientConfig.ID},
"redirect_uri": {p.config.ClientConfig.RedirectUri},
"scope": {"openid profile email groups"},
"nonce": {"vF7FAQlqq41CObeUFYY0ggv1qEELvfHaXQ0ER4XM"},
})
if err != nil {
return nil, err
}
switch authorizeResp.StatusCode {
case http.StatusFound:
case http.StatusOK:
default:
return nil, fmt.Errorf("got unexpected response on authorize: %d - %s", authorizeResp.StatusCode, readRespBody(authorizeResp))
}
// /auth/local?req=qruhpy2cqjvv4hcrbuu44mf4v
var loginEndpoint string
if authorizeResp.StatusCode == http.StatusOK {
loginEndpoint, err = getLocalAuthEndpoint(authorizeResp.Body)
if err != nil {
return nil, errors.Wrapf(err, "while fetching link to static authentication")
}
} else {
loginEndpoint = authorizeResp.Header.Get("location")
if strings.Contains(loginEndpoint, "#.*error") {
return nil, fmt.Errorf("login - Redirected with error: '%s'", loginEndpoint)
}
}
if _, err := p.httpClient.Get(p.config.DexConfig.BaseUrl + loginEndpoint); err != nil {
return nil, errors.Wrap(err, "while performing HTTP GET on login endpoint")
}
loginResp, err := p.httpClient.PostForm(p.config.DexConfig.BaseUrl+loginEndpoint, url.Values{
"login": {p.config.UserCredentials.Username},
"password": {p.config.UserCredentials.Password},
})
if err != nil {
return nil, errors.Wrap(err, "while performing HTTP POST on login endpoint")
}
if loginResp.StatusCode < 300 || loginResp.StatusCode > 399 {
return nil, fmt.Errorf("login - response error: '%s' - %s", loginResp.Status, readRespBody(loginResp))
}
// /approval?req=qruhpy2cqjvv4hcrbuu44mf4v
approvalEndpoint := loginResp.Header.Get("location")
if strings.Contains(approvalEndpoint, "#.*error") {
return nil, fmt.Errorf("approval - Redirected with error: '%s'", approvalEndpoint)
}
approvalResp, err := p.httpClient.Get(p.config.DexConfig.BaseUrl + approvalEndpoint)
if err != nil {
return nil, err
}
if approvalResp.StatusCode < 300 || approvalResp.StatusCode > 399 {
return nil, errors.New(fmt.Sprintf("Approval - response error: '%s' - %s", approvalResp.Status, readRespBody(approvalResp)))
}
clientEndpoint := approvalResp.Header.Get("location")
if strings.Contains(clientEndpoint, "#.*error") {
return nil, fmt.Errorf("client - Redirected with error: '%s'", clientEndpoint)
}
parsedUrl, parseErr := url.Parse(clientEndpoint)
if parseErr != nil {
return nil, parseErr
}
result := make(map[string]string)
fragmentParams := strings.Split(parsedUrl.Fragment, "&")
for _, param := range fragmentParams {
keyAndValue := strings.Split(param, "=")
result[keyAndValue[0]] = keyAndValue[1]
}
return result, nil
}
func readRespBody(resp *http.Response) string {
defer func() {
err := resp.Body.Close()
if err != nil {
log.Printf("WARNING: Unable to close response body. Cause: %v", err)
}
}()
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Printf("WARNING: Unable to read response body (status: '%s'). Root cause: %v", resp.Status, err)
return "<<Error reading response body>>"
}
return string(b)
}
func getLocalAuthEndpoint(body io.Reader) (string, error) {
z := html.NewTokenizer(body)
for {
nt := z.Next()
if nt == html.ErrorToken {
return "", errors.New("got HTML error token")
}
token := z.Token()
if "a" != token.Data {
continue
}
for _, attr := range token.Attr {
if attr.Key != "href" {
continue
}
match, err := regexp.MatchString("/auth/local.*", attr.Val)
if err != nil {
log.Printf("WARNING: Unable to match string. Cause: %v", err)
return "", err
}
if match {
return attr.Val, nil
}
}
}
}