auth

Paddy 2014-12-07 Parent:4cb65cf90217 Child:7f64033806bb

85:1dc4e152e3b0 Go to Latest

auth/oauth2.go

Break client verification out, break token returns out. Break client verification out into a helper function to avoid rewriting it for pretty much every grant. Break token returns out into a new function as part of the GrantType, so that implicit grants can redirect with the token value. Split returning the token as JSON into its own exported function, which can be used in multiple grants. Return more relevant information to the template when a user is deciding whether or not to authorize a grant.

History
1 package auth
3 import (
4 "crypto/sha256"
5 "encoding/hex"
6 "encoding/json"
7 "errors"
8 "html/template"
9 "log"
10 "net/http"
11 "net/url"
12 "sync"
13 "time"
15 "code.secondbit.org/pass"
16 "code.secondbit.org/uuid"
18 "github.com/gorilla/mux"
19 )
21 const (
22 authCookieName = "auth"
23 defaultGrantExpiration = 600 // default to ten minute grant expirations
24 getGrantTemplateName = "get_grant"
25 )
27 var (
28 // ErrNoAuth is returned when an Authorization header is not present or is empty.
29 ErrNoAuth = errors.New("no authorization header supplied")
30 // ErrInvalidAuthFormat is returned when an Authorization header is present but not the correct format.
31 ErrInvalidAuthFormat = errors.New("authorization header is not in a valid format")
32 // ErrIncorrectAuth is returned when a user authentication attempt does not match the stored values.
33 ErrIncorrectAuth = errors.New("invalid authentication")
34 // ErrInvalidPassphraseScheme is returned when an undefined passphrase scheme is used.
35 ErrInvalidPassphraseScheme = errors.New("invalid passphrase scheme")
36 // ErrNoSession is returned when no session ID is passed with a request.
37 ErrNoSession = errors.New("no session ID found")
39 grantTypesMap = grantTypes{types: map[string]GrantType{}}
40 )
42 type grantTypes struct {
43 types map[string]GrantType
44 sync.RWMutex
45 }
47 // GrantType defines a set of functions and metadata around a specific authorization grant strategy.
48 //
49 // The Validate function will be called when requests are made that match the GrantType, and should write any
50 // errors to the ResponseWriter. It is responsible for determining if the grant is valid and a token should be issued.
51 // It must return the scope the grant was for and the ID of the Profile that issued the grant, as well as if the grant
52 // is valid or not. It must not be nil.
53 //
54 // The Invalidate function will be called when the grant has successfully generated a token and the token has successfully
55 // been conveyed to the user. The Invalidate function is always called asynchronously, outside the request. It should take
56 // care of marking the grant as used, if the GrantType requires grants to be one-time only grants. The Invalidate function
57 // can be nil.
58 //
59 // IssuesRefresh determines whether the GrantType should yield a refresh token as well as an access token. If true, the client
60 // will be issued a refresh token.
61 //
62 // The ReturnToken will be called when a token is created and needs to be returned to the client. If it returns true, the token
63 // was successfully returned and the Invalidate function will be called asynchronously.
64 type GrantType struct {
65 Validate func(w http.ResponseWriter, r *http.Request, context Context) (scope string, profileID uuid.ID, valid bool)
66 Invalidate func(r *http.Request, context Context) bool
67 ReturnToken func(w http.ResponseWriter, r *http.Request, token Token, context Context) bool
68 IssuesRefresh bool
69 }
71 type tokenResponse struct {
72 AccessToken string `json:"access_token"`
73 TokenType string `json:"token_type,omitempty"`
74 ExpiresIn int32 `json:"expires_in,omitempty"`
75 RefreshToken string `json:"refresh_token,omitempty"`
76 }
78 type errorResponse struct {
79 Error string `json:"error"`
80 Description string `json:"error_description,omitempty"`
81 URI string `json:"error_uri,omitempty"`
82 }
84 // RegisterGrantType associates a string with a GrantType. When the string is used as the value for "grant_type" when obtaining
85 // an access token, the associated GrantType's properties will be used.
86 //
87 // RegisterGrantType should be called in the `init()` function of packages, much like database/sql registers drivers. It will panic
88 // if a GrantType tries to register under a string that already has a GrantType registered for it.
89 func RegisterGrantType(name string, g GrantType) {
90 grantTypesMap.Lock()
91 defer grantTypesMap.Unlock()
92 if _, ok := grantTypesMap.types[name]; ok {
93 panic("Duplicate registration of grant_type " + name)
94 }
95 grantTypesMap.types[name] = g
96 }
98 func findGrantType(name string) (GrantType, bool) {
99 grantTypesMap.RLock()
100 defer grantTypesMap.RUnlock()
101 t, ok := grantTypesMap.types[name]
102 return t, ok
103 }
105 func renderJSONError(enc *json.Encoder, errorType string) {
106 err := enc.Encode(errorResponse{
107 Error: errorType,
108 })
109 if err != nil {
110 // TODO(paddy): log this or something
111 }
112 }
114 func RenderJSONToken(w http.ResponseWriter, r *http.Request, token Token, context Context) bool {
115 enc := json.NewEncoder(w)
116 resp := tokenResponse{
117 AccessToken: token.AccessToken,
118 RefreshToken: token.RefreshToken,
119 ExpiresIn: token.ExpiresIn,
120 TokenType: token.TokenType,
121 }
122 err := enc.Encode(resp)
123 if err != nil {
124 // TODO(paddy): log this or something
125 return false
126 }
127 return true
128 }
130 func checkCookie(r *http.Request, context Context) (Session, error) {
131 cookie, err := r.Cookie(authCookieName)
132 if err == http.ErrNoCookie {
133 return Session{}, ErrNoSession
134 } else if err != nil {
135 log.Println(err)
136 return Session{}, err
137 }
138 sess, err := context.GetSession(cookie.Value)
139 if err == ErrSessionNotFound {
140 return Session{}, ErrInvalidSession
141 } else if err != nil {
142 return Session{}, err
143 }
144 if !sess.Active {
145 return Session{}, ErrInvalidSession
146 }
147 return sess, nil
148 }
150 func buildLoginRedirect(r *http.Request, context Context) string {
151 if context.loginURI == nil {
152 return ""
153 }
154 uri := *context.loginURI
155 q := uri.Query()
156 q.Set("from", r.URL.String())
157 uri.RawQuery = q.Encode()
158 return uri.String()
159 }
161 func authenticate(user, passphrase string, context Context) (Profile, error) {
162 profile, err := context.GetProfileByLogin(user)
163 if err != nil {
164 if err == ErrProfileNotFound || err == ErrLoginNotFound {
165 return Profile{}, ErrIncorrectAuth
166 }
167 return Profile{}, err
168 }
169 switch profile.PassphraseScheme {
170 case 1:
171 realPass, err := hex.DecodeString(profile.Passphrase)
172 if err != nil {
173 return Profile{}, err
174 }
175 candidate := pass.Check(sha256.New, profile.Iterations, []byte(passphrase), []byte(profile.Salt))
176 if !pass.Compare(candidate, realPass) {
177 return Profile{}, ErrIncorrectAuth
178 }
179 default:
180 return Profile{}, ErrInvalidPassphraseScheme
181 }
182 return profile, nil
183 }
185 func wrap(context Context, f func(w http.ResponseWriter, r *http.Request, context Context)) http.Handler {
186 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
187 f(w, r, context)
188 })
189 }
191 // RegisterOAuth2 adds handlers to the passed router to handle the OAuth2 endpoints.
192 func RegisterOAuth2(r *mux.Router, context Context) {
193 r.Handle("/authorize", wrap(context, GetGrantHandler))
194 r.Handle("/token", wrap(context, GetTokenHandler))
195 }
197 // GetGrantHandler presents and processes the page for asking a user to grant access
198 // to their data. See RFC 6749, Section 4.1.
199 func GetGrantHandler(w http.ResponseWriter, r *http.Request, context Context) {
200 session, err := checkCookie(r, context)
201 if err != nil {
202 if err == ErrNoSession || err == ErrInvalidSession {
203 redir := buildLoginRedirect(r, context)
204 if redir == "" {
205 log.Println("No login URL configured.")
206 w.WriteHeader(http.StatusInternalServerError)
207 context.Render(w, getGrantTemplateName, map[string]interface{}{
208 "internal_error": template.HTML("Missing login URL."),
209 })
210 return
211 }
212 http.Redirect(w, r, redir, http.StatusFound)
213 return
214 }
215 log.Println(err.Error())
216 w.WriteHeader(http.StatusInternalServerError)
217 context.Render(w, getGrantTemplateName, map[string]interface{}{
218 "internal_error": template.HTML(err.Error()),
219 })
220 return
221 }
222 if r.URL.Query().Get("client_id") == "" {
223 w.WriteHeader(http.StatusBadRequest)
224 context.Render(w, getGrantTemplateName, map[string]interface{}{
225 "error": template.HTML("Client ID must be specified in the request."),
226 })
227 return
228 }
229 clientID, err := uuid.Parse(r.URL.Query().Get("client_id"))
230 if err != nil {
231 w.WriteHeader(http.StatusBadRequest)
232 context.Render(w, getGrantTemplateName, map[string]interface{}{
233 "error": template.HTML("client_id is not a valid Client ID."),
234 })
235 return
236 }
237 redirectURI := r.URL.Query().Get("redirect_uri")
238 redirectURL, err := url.Parse(redirectURI)
239 if err != nil {
240 w.WriteHeader(http.StatusBadRequest)
241 context.Render(w, getGrantTemplateName, map[string]interface{}{
242 "error": template.HTML("The redirect_uri specified is not valid."),
243 })
244 return
245 }
246 client, err := context.GetClient(clientID)
247 if err != nil {
248 if err == ErrClientNotFound {
249 w.WriteHeader(http.StatusBadRequest)
250 context.Render(w, getGrantTemplateName, map[string]interface{}{
251 "error": template.HTML("The specified Client couldn’t be found."),
252 })
253 } else {
254 log.Println(err.Error())
255 w.WriteHeader(http.StatusInternalServerError)
256 context.Render(w, getGrantTemplateName, map[string]interface{}{
257 "internal_error": template.HTML(err.Error()),
258 })
259 }
260 return
261 }
262 // whether a redirect URI is valid or not depends on the number of endpoints
263 // the client has registered
264 numEndpoints, err := context.CountEndpoints(clientID)
265 if err != nil {
266 log.Println(err.Error())
267 w.WriteHeader(http.StatusInternalServerError)
268 context.Render(w, getGrantTemplateName, map[string]interface{}{
269 "internal_error": template.HTML(err.Error()),
270 })
271 return
272 }
273 var validURI bool
274 if redirectURI != "" {
275 // BUG(paddy): We really should normalize URIs before trying to compare them.
276 validURI, err = context.CheckEndpoint(clientID, redirectURI)
277 if err != nil {
278 log.Println(err.Error())
279 w.WriteHeader(http.StatusInternalServerError)
280 context.Render(w, getGrantTemplateName, map[string]interface{}{
281 "internal_error": template.HTML(err.Error()),
282 })
283 return
284 }
285 } else if redirectURI == "" && numEndpoints == 1 {
286 // if we don't specify the endpoint and there's only one endpoint, the
287 // request is valid, and we're redirecting to that one endpoint
288 validURI = true
289 endpoints, err := context.ListEndpoints(clientID, 1, 0)
290 if err != nil {
291 log.Println(err.Error())
292 w.WriteHeader(http.StatusInternalServerError)
293 context.Render(w, getGrantTemplateName, map[string]interface{}{
294 "internal_error": template.HTML(err.Error()),
295 })
296 return
297 }
298 if len(endpoints) != 1 {
299 validURI = false
300 } else {
301 u := endpoints[0].URI // Copy it here to avoid grabbing a pointer to the memstore
302 redirectURI = u.String()
303 redirectURL = &u
304 }
305 } else {
306 validURI = false
307 }
308 if !validURI {
309 w.WriteHeader(http.StatusBadRequest)
310 context.Render(w, getGrantTemplateName, map[string]interface{}{
311 "error": template.HTML("The redirect_uri specified is not valid."),
312 })
313 return
314 }
315 scope := r.URL.Query().Get("scope")
316 state := r.URL.Query().Get("state")
317 if r.URL.Query().Get("response_type") != "code" {
318 q := redirectURL.Query()
319 q.Add("error", "invalid_request")
320 q.Add("state", state)
321 redirectURL.RawQuery = q.Encode()
322 http.Redirect(w, r, redirectURL.String(), http.StatusFound)
323 return
324 }
325 if r.Method == "POST" {
326 // BUG(paddy): We need to implement CSRF protection when obtaining a grant code.
327 if r.PostFormValue("grant") == "approved" {
328 code := uuid.NewID().String()
329 grant := Grant{
330 Code: code,
331 Created: time.Now(),
332 ExpiresIn: defaultGrantExpiration,
333 ClientID: clientID,
334 Scope: scope,
335 RedirectURI: r.URL.Query().Get("redirect_uri"),
336 State: state,
337 ProfileID: session.ProfileID,
338 }
339 err := context.SaveGrant(grant)
340 if err != nil {
341 q := redirectURL.Query()
342 q.Add("error", "server_error")
343 q.Add("state", state)
344 redirectURL.RawQuery = q.Encode()
345 http.Redirect(w, r, redirectURL.String(), http.StatusFound)
346 return
347 }
348 q := redirectURL.Query()
349 q.Add("code", code)
350 q.Add("state", state)
351 redirectURL.RawQuery = q.Encode()
352 http.Redirect(w, r, redirectURL.String(), http.StatusFound)
353 return
354 }
355 q := redirectURL.Query()
356 q.Add("error", "access_denied")
357 q.Add("state", state)
358 redirectURL.RawQuery = q.Encode()
359 http.Redirect(w, r, redirectURL.String(), http.StatusFound)
360 return
361 }
362 profile, err := context.GetProfileByID(session.ProfileID)
363 if err != nil {
364 q := redirectURL.Query()
365 q.Add("error", "server_error")
366 q.Add("state", state)
367 redirectURL.RawQuery = q.Encode()
368 http.Redirect(w, r, redirectURL.String(), http.StatusFound)
369 return
370 }
371 w.WriteHeader(http.StatusOK)
372 context.Render(w, getGrantTemplateName, map[string]interface{}{
373 "client": client,
374 "redirectURL": redirectURL,
375 "scope": scope,
376 "profile": profile,
377 })
378 }
380 // GetTokenHandler allows a client to exchange an authorization grant for an
381 // access token. See RFC 6749 Section 4.1.3.
382 func GetTokenHandler(w http.ResponseWriter, r *http.Request, context Context) {
383 enc := json.NewEncoder(w)
384 grantType := r.PostFormValue("grant_type")
385 gt, ok := findGrantType(grantType)
386 if !ok {
387 w.WriteHeader(http.StatusBadRequest)
388 renderJSONError(enc, "invalid_request")
389 return
390 }
391 scope, profileID, valid := gt.Validate(w, r, context)
392 if !valid {
393 return
394 }
395 refresh := ""
396 if gt.IssuesRefresh {
397 refresh = uuid.NewID().String()
398 }
399 token := Token{
400 AccessToken: uuid.NewID().String(),
401 RefreshToken: refresh,
402 Created: time.Now(),
403 ExpiresIn: defaultTokenExpiration,
404 TokenType: "bearer",
405 Scope: scope,
406 ProfileID: profileID,
407 }
408 err := context.SaveToken(token)
409 if err != nil {
410 w.WriteHeader(http.StatusInternalServerError)
411 renderJSONError(enc, "server_error")
412 return
413 }
414 if gt.ReturnToken(w, r, token, context) && gt.Invalidate != nil {
415 go gt.Invalidate(r, context)
416 }
417 }
419 // TODO(paddy): exchange user credentials for access token
420 // TODO(paddy): exchange client credentials for access token
421 // TODO(paddy): implicit grant for access token
422 // TODO(paddy): exchange refresh token for access token