forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
296 lines (248 loc) · 7.86 KB
/
handler.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
package external
import (
"encoding/base64"
"errors"
"fmt"
"net/http"
"net/url"
"github.com/GoogleCloudPlatform/kubernetes/pkg/auth/user"
"github.com/RangelReale/osincli"
"github.com/golang/glog"
authapi "github.com/openshift/origin/pkg/auth/api"
"github.com/openshift/origin/pkg/auth/oauth/handlers"
"github.com/openshift/origin/pkg/auth/server/csrf"
)
// Handler exposes an external oauth provider flow (including the call back) as an oauth.handlers.AuthenticationHandler to allow our internal oauth
// server to use an external oauth provider for authentication
type Handler struct {
provider Provider
state State
clientConfig *osincli.ClientConfig
client *osincli.Client
success handlers.AuthenticationSuccessHandler
errorHandler handlers.AuthenticationErrorHandler
mapper authapi.UserIdentityMapper
}
func NewExternalOAuthRedirector(provider Provider, state State, redirectURL string, success handlers.AuthenticationSuccessHandler, errorHandler handlers.AuthenticationErrorHandler, mapper authapi.UserIdentityMapper) (*Handler, error) {
clientConfig, err := provider.NewConfig()
if err != nil {
return nil, err
}
clientConfig.RedirectUrl = redirectURL
client, err := osincli.NewClient(clientConfig)
if err != nil {
return nil, err
}
transport, err := provider.GetTransport()
if err != nil {
return nil, err
}
client.Transport = transport
return &Handler{
provider: provider,
state: state,
clientConfig: clientConfig,
client: client,
success: success,
errorHandler: errorHandler,
mapper: mapper,
}, nil
}
// AuthenticationRedirect implements oauth.handlers.RedirectAuthHandler
func (h *Handler) AuthenticationRedirect(w http.ResponseWriter, req *http.Request) error {
glog.V(4).Infof("Authentication needed for %v", h)
authReq := h.client.NewAuthorizeRequest(osincli.CODE)
h.provider.AddCustomParameters(authReq)
state, err := h.state.Generate(w, req)
if err != nil {
glog.V(4).Infof("Error generating state: %v", err)
return err
}
oauthURL := authReq.GetAuthorizeUrlWithParams(state)
glog.V(4).Infof("redirect to %v", oauthURL)
http.Redirect(w, req, oauthURL.String(), http.StatusFound)
return nil
}
// ServeHTTP handles the callback request in response to an external oauth flow
func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
// Extract auth code
authReq := h.client.NewAuthorizeRequest(osincli.CODE)
authData, err := authReq.HandleRequest(req)
if err != nil {
glog.V(4).Infof("Error handling request: %v", err)
h.handleError(err, w, req)
return
}
glog.V(4).Infof("Got auth data")
// Validate state before making any server-to-server calls
ok, err := h.state.Check(authData.State, req)
if !ok {
glog.V(4).Infof("State is invalid")
err := errors.New("State is invalid")
h.handleError(err, w, req)
return
}
if err != nil {
glog.V(4).Infof("Error verifying state: %v", err)
h.handleError(err, w, req)
return
}
// Exchange code for a token
accessReq := h.client.NewAccessRequest(osincli.AUTHORIZATION_CODE, authData)
accessData, err := accessReq.GetToken()
if err != nil {
glog.V(4).Infof("Error getting access token: %v", err)
h.handleError(err, w, req)
return
}
glog.V(4).Infof("Got access data")
identity, ok, err := h.provider.GetUserIdentity(accessData)
if err != nil {
glog.V(4).Infof("Error getting userIdentityInfo info: %v", err)
h.handleError(err, w, req)
return
}
if !ok {
glog.V(4).Infof("Could not get userIdentityInfo info from access token")
err := errors.New("Could not get userIdentityInfo info from access token")
h.handleError(err, w, req)
return
}
user, err := h.mapper.UserFor(identity)
glog.V(4).Infof("Got userIdentityMapping: %#v", user)
if err != nil {
glog.V(4).Infof("Error creating or updating mapping for: %#v due to %v", identity, err)
h.handleError(err, w, req)
return
}
_, err = h.success.AuthenticationSucceeded(user, authData.State, w, req)
if err != nil {
glog.V(4).Infof("Error calling success handler: %v", err)
h.handleError(err, w, req)
return
}
}
func (h *Handler) handleError(err error, w http.ResponseWriter, req *http.Request) {
handled, err := h.errorHandler.AuthenticationError(err, w, req)
if handled {
return
}
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(`An error occurred`))
}
// defaultState provides default state-building, validation, and parsing to contain CSRF and "then" redirection
type defaultState struct {
csrf csrf.CSRF
}
// RedirectorState combines state generation/verification with redirections on authentication success and error
type RedirectorState interface {
State
handlers.AuthenticationSuccessHandler
handlers.AuthenticationErrorHandler
}
func CSRFRedirectingState(csrf csrf.CSRF) RedirectorState {
return &defaultState{csrf}
}
func (d *defaultState) Generate(w http.ResponseWriter, req *http.Request) (string, error) {
then := req.URL.String()
if len(then) == 0 {
return "", errors.New("Cannot generate state: request has no URL")
}
csrfToken, err := d.csrf.Generate(w, req)
if err != nil {
return "", err
}
state := url.Values{
"csrf": {csrfToken},
"then": {then},
}
return encodeState(state)
}
func (d *defaultState) Check(state string, req *http.Request) (bool, error) {
values, err := decodeState(state)
if err != nil {
return false, err
}
csrf := values.Get("csrf")
ok, err := d.csrf.Check(req, csrf)
if err != nil {
return false, err
}
if !ok {
return false, fmt.Errorf("State did not contain a valid CSRF token")
}
then := values.Get("then")
if then == "" {
return false, errors.New("State did not contain a redirect")
}
return true, nil
}
func (d *defaultState) AuthenticationSucceeded(user user.Info, state string, w http.ResponseWriter, req *http.Request) (bool, error) {
values, err := decodeState(state)
if err != nil {
return false, err
}
then := values.Get("then")
if len(then) == 0 {
return false, errors.New("No redirect given")
}
http.Redirect(w, req, then, http.StatusFound)
return true, nil
}
// AuthenticationError handles the very specific case where the remote OAuth provider returned an error
// In that case, attempt to redirect to the "then" URL with all error parameters echoed
// In any other case, or if an error is encountered, returns false and the original error
func (d *defaultState) AuthenticationError(err error, w http.ResponseWriter, req *http.Request) (bool, error) {
// only handle errors that came from the remote OAuth provider...
osinErr, ok := err.(*osincli.Error)
if !ok {
return false, err
}
// with an OAuth error...
if len(osinErr.Id) == 0 {
return false, err
}
// if they embedded valid state...
ok, stateErr := d.Check(osinErr.State, req)
if !ok || stateErr != nil {
return false, err
}
// if the state decodes...
values, err := decodeState(osinErr.State)
if err != nil {
return false, err
}
// if it contains a redirect...
then := values.Get("then")
if len(then) == 0 {
return false, err
}
// which parses...
thenURL, urlErr := url.Parse(then)
if urlErr != nil {
return false, err
}
// Add in the error, error_description, error_uri params to the "then" redirect
q := thenURL.Query()
q.Set("error", osinErr.Id)
if len(osinErr.Description) > 0 {
q.Set("error_description", osinErr.Description)
}
if len(osinErr.URI) > 0 {
q.Set("error_uri", osinErr.URI)
}
thenURL.RawQuery = q.Encode()
http.Redirect(w, req, thenURL.String(), http.StatusFound)
return true, nil
}
// URL-encode, then base-64 encode for OAuth providers that don't do a good job of treating the state param like an opaque value
func encodeState(values url.Values) (string, error) {
return base64.URLEncoding.EncodeToString([]byte(values.Encode())), nil
}
func decodeState(state string) (url.Values, error) {
decodedState, err := base64.URLEncoding.DecodeString(state)
if err != nil {
return nil, err
}
return url.ParseQuery(string(decodedState))
}