forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
grant.go
297 lines (260 loc) · 8.65 KB
/
grant.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
package grant
import (
"fmt"
"html/template"
"net/http"
"net/url"
"strings"
kapi "k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/auth/user"
"k8s.io/kubernetes/pkg/util"
"github.com/golang/glog"
"github.com/openshift/origin/pkg/auth/authenticator"
"github.com/openshift/origin/pkg/auth/server/csrf"
oapi "github.com/openshift/origin/pkg/oauth/api"
"github.com/openshift/origin/pkg/oauth/registry/oauthclient"
"github.com/openshift/origin/pkg/oauth/registry/oauthclientauthorization"
"github.com/openshift/origin/pkg/oauth/scope"
)
const (
thenParam = "then"
csrfParam = "csrf"
clientIDParam = "client_id"
userNameParam = "user_name"
scopesParam = "scopes"
redirectURIParam = "redirect_uri"
approveParam = "approve"
denyParam = "deny"
)
// FormRenderer is responsible for rendering a Form to prompt the user
// to approve or reject a requested OAuth scope grant.
type FormRenderer interface {
Render(form Form, w http.ResponseWriter, req *http.Request)
}
type Form struct {
Action string
Error string
Values FormValues
}
type FormValues struct {
Then string
ThenParam string
CSRF string
CSRFParam string
ClientID string
ClientIDParam string
UserName string
UserNameParam string
Scopes string
ScopesParam string
RedirectURI string
RedirectURIParam string
ApproveParam string
DenyParam string
}
type Grant struct {
auth authenticator.Request
csrf csrf.CSRF
render FormRenderer
clientregistry oauthclient.Registry
authregistry oauthclientauthorization.Registry
}
func NewGrant(csrf csrf.CSRF, auth authenticator.Request, render FormRenderer, clientregistry oauthclient.Registry, authregistry oauthclientauthorization.Registry) *Grant {
return &Grant{
auth: auth,
csrf: csrf,
render: render,
clientregistry: clientregistry,
authregistry: authregistry,
}
}
// Install registers the grant handler into a mux. It is expected that the
// provided prefix will serve all operations. Path MUST NOT end in a slash.
func (l *Grant) Install(mux Mux, paths ...string) {
for _, path := range paths {
path = strings.TrimRight(path, "/")
mux.HandleFunc(path, l.ServeHTTP)
}
}
func (l *Grant) ServeHTTP(w http.ResponseWriter, req *http.Request) {
user, ok, err := l.auth.AuthenticateRequest(req)
if err != nil || !ok {
l.redirect("You must reauthenticate before continuing", w, req)
return
}
switch req.Method {
case "GET":
l.handleForm(user, w, req)
case "POST":
l.handleGrant(user, w, req)
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}
func (l *Grant) handleForm(user user.Info, w http.ResponseWriter, req *http.Request) {
q := req.URL.Query()
then := q.Get("then")
clientID := q.Get("client_id")
scopes := q.Get("scopes")
redirectURI := q.Get("redirect_uri")
client, err := l.clientregistry.GetClient(kapi.NewContext(), clientID)
if err != nil || client == nil {
l.failed("Could not find client for client_id", w, req)
return
}
uri, err := getBaseURL(req)
if err != nil {
glog.Errorf("Unable to generate base URL: %v", err)
http.Error(w, "Unable to determine URL", http.StatusInternalServerError)
return
}
csrf, err := l.csrf.Generate(w, req)
if err != nil {
glog.Errorf("Unable to generate CSRF token: %v", err)
l.failed("Could not generate CSRF token", w, req)
return
}
form := Form{
Action: uri.String(),
Values: FormValues{
Then: then,
ThenParam: thenParam,
CSRF: csrf,
CSRFParam: csrfParam,
ClientID: client.Name,
ClientIDParam: clientIDParam,
UserName: user.GetName(),
UserNameParam: userNameParam,
Scopes: scopes,
ScopesParam: scopesParam,
RedirectURI: redirectURI,
RedirectURIParam: redirectURIParam,
ApproveParam: approveParam,
DenyParam: denyParam,
},
}
l.render.Render(form, w, req)
}
func (l *Grant) handleGrant(user user.Info, w http.ResponseWriter, req *http.Request) {
if ok, err := l.csrf.Check(req, req.FormValue("csrf")); !ok || err != nil {
glog.Errorf("Unable to check CSRF token: %v", err)
l.failed("Invalid CSRF token", w, req)
return
}
then := req.FormValue("then")
scopes := req.FormValue("scopes")
if len(req.FormValue(approveParam)) == 0 {
// Redirect with rejection param
url, err := url.Parse(then)
if len(then) == 0 || err != nil {
l.failed("Access denied, but no redirect URL was specified", w, req)
return
}
q := url.Query()
q.Set("error", "access_denied")
url.RawQuery = q.Encode()
http.Redirect(w, req, url.String(), http.StatusFound)
return
}
clientID := req.FormValue("client_id")
client, err := l.clientregistry.GetClient(kapi.NewContext(), clientID)
if err != nil || client == nil {
l.failed("Could not find client for client_id", w, req)
return
}
clientAuthID := l.authregistry.ClientAuthorizationName(user.GetName(), client.Name)
ctx := kapi.NewContext()
clientAuth, err := l.authregistry.GetClientAuthorization(ctx, clientAuthID)
if err == nil && clientAuth != nil {
// Add new scopes and update
clientAuth.Scopes = scope.Add(clientAuth.Scopes, scope.Split(scopes))
if _, err = l.authregistry.UpdateClientAuthorization(ctx, clientAuth); err != nil {
glog.Errorf("Unable to update authorization: %v", err)
l.failed("Could not update client authorization", w, req)
return
}
} else {
// Make sure client name, user name, grant scope, expiration, and redirect uri match
clientAuth = &oapi.OAuthClientAuthorization{
UserName: user.GetName(),
UserUID: user.GetUID(),
ClientName: client.Name,
Scopes: scope.Split(scopes),
}
clientAuth.Name = clientAuthID
if _, err = l.authregistry.CreateClientAuthorization(ctx, clientAuth); err != nil {
glog.Errorf("Unable to create authorization: %v", err)
l.failed("Could not create client authorization", w, req)
return
}
}
if len(then) == 0 {
l.failed("Approval granted, but no redirect URL was specified", w, req)
return
}
http.Redirect(w, req, then, http.StatusFound)
}
func (l *Grant) failed(reason string, w http.ResponseWriter, req *http.Request) {
form := Form{
Error: reason,
}
l.render.Render(form, w, req)
}
func (l *Grant) redirect(reason string, w http.ResponseWriter, req *http.Request) {
then := req.FormValue("then")
// TODO: validate then
if len(then) == 0 {
l.failed(reason, w, req)
return
}
http.Redirect(w, req, then, http.StatusFound)
}
func getBaseURL(req *http.Request) (*url.URL, error) {
uri, err := url.Parse(req.RequestURI)
if err != nil {
return nil, err
}
uri.Scheme, uri.Host, uri.RawQuery, uri.Fragment = req.URL.Scheme, req.URL.Host, "", ""
return uri, nil
}
// DefaultFormRenderer displays a page prompting the user to approve an OAuth grant.
// The requesting client id, requested scopes, and redirect URI are displayed to the user.
var DefaultFormRenderer = grantTemplateRenderer{}
type grantTemplateRenderer struct{}
func (r grantTemplateRenderer) Render(form Form, w http.ResponseWriter, req *http.Request) {
w.Header().Add("Content-Type", "text/html")
w.WriteHeader(http.StatusOK)
if err := grantTemplate.Execute(w, form); err != nil {
util.HandleError(fmt.Errorf("unable to render grant template: %v", err))
}
}
// TODO: allow template to be read from an external file
var grantTemplate = template.Must(template.New("grantForm").Parse(`
<style>
body { font-family: sans-serif; font-size: 12pt; margin: 2em 5%; background-color: #F9F9F9; }
pre { padding-left: 1em; border-left: .25em solid #eee; }
a { color: #00f; text-decoration: none; }
a:hover { text-decoration: underline; }
</style>
{{ if .Error }}
<div class="message">{{ .Error }}</div>
{{ else }}
<form action="{{ .Action }}" method="POST">
<input type="hidden" name="{{ .Values.ThenParam }}" value="{{ .Values.Then }}">
<input type="hidden" name="{{ .Values.CSRFParam }}" value="{{ .Values.CSRF }}">
<input type="hidden" name="{{ .Values.ClientIDParam }}" value="{{ .Values.ClientID }}">
<input type="hidden" name="{{ .Values.UserNameParam }}" value="{{ .Values.UserName }}">
<input type="hidden" name="{{ .Values.ScopesParam }}" value="{{ .Values.Scopes }}">
<input type="hidden" name="{{ .Values.RedirectURIParam }}" value="{{ .Values.RedirectURI }}">
<h3>Approve Client?</h3>
<p>Do you approve granting an access token to the following OAuth client?</p>
<pre>
Client: {{ .Values.ClientID }}
Scope: {{ .Values.Scopes }}
URI: {{ .Values.RedirectURI }}
</pre>
<input type="submit" name="{{ .Values.ApproveParam }}" value="Approve">
<input type="submit" name="{{ .Values.DenyParam }}" value="Reject">
</form>
{{ end }}
`))