auth

Paddy 2015-01-18 Parent:c03b5eb3179e Child:0a1e16b9c141

116:e000b1c24fc0 Go to Latest

auth/authcode.go

Make all tests that deal with the store interfaces go through the Context. This is mainly important so that pre- and post- save/retrieval/deletion/whatever transforms can be done without doing them in every single implementation of the store. Change the Endpoint URI property to be a string, not a *url.URL. This makes testing easier, JSON responses cleaner, and is all around just a better strategy. Just because we turn it into a URL every now and then doesn't mean that's how we need to store it. Add JSON tags to the Client type and Endpoint type. Create normalizeURI and normalizeURIString methods to... well, normalize the Endpoint URIs. This makes it so that we can compare them, and forgive some arbitrary user behaviour (like slashes, etc.) Add a NormalizedURI property to the Endpoint type. This is where we store the NormalizedURI, which is what we'll be using when we want to check if an endpoint is valid or not. For the sake of tests and predictability, however, we always want to redirect to the URI, not the NormalizedURI. Add checks to the Client creation API endpoint to give better errors. Now leaving out the Type won't be considered an invalid type, it will be considered a missing parameter. An empty name will be reported as a missing parameter, a name with too few characters will be reported as an insufficient name, and a name with too many characters will be reported as an overflow name. We gather as many of these errors as apply before returning. Check if an Endpoint URI is absolute before adding it as an endpoint, or return an invalid value error if it is not. Always return the errors array when creating a client. We could succeed in creating one or more things and still have errors. We should return anything that's created _as well as_ any errors encountered. Add unit testing for our CreateClientHandler. Fix our oauth2 tests so that if there's an error in the body, it's in the test logs. This should help debugging significantly. Fix our oauth2 tests so that the Profile only requires 1 iteration for its password hashing. This means each time we want to validate a session, it doesn't add a full second to our test runs. This is a big speed improvement for our tests. Add test helper methods for comparing API errors, API responses, and filling in server-generated information in a response that it's impossible to have an expectation around (e.g., IDs) so that we can use our comparison helpers to check if a response is as we expect it. Fix a typo in our Context helpers that was reporting no sessionStore being set _only_ when a sessionStore was set. So yes, the opposite of what we wanted. Oops. This was discovered by passing all our tests through the context. methods instead of operating on the stores themselves.

History
1 package auth
3 import (
4 "encoding/json"
5 "errors"
6 "net/http"
7 "time"
9 "code.secondbit.org/uuid.hg"
10 )
12 func init() {
13 RegisterGrantType("authorization_code", GrantType{
14 Validate: authCodeGrantValidate,
15 Invalidate: authCodeGrantInvalidate,
16 IssuesRefresh: true,
17 ReturnToken: RenderJSONToken,
18 })
19 }
21 var (
22 // ErrNoAuthorizationCodeStore is returned when a Context tries to act on a authorizationCodeStore without setting one first.
23 ErrNoAuthorizationCodeStore = errors.New("no authorizationCodeStore was specified for the Context")
24 // ErrAuthorizationCodeNotFound is returned when an AuthorizationCode is requested but not found in the authorizationCodeStore.
25 ErrAuthorizationCodeNotFound = errors.New("authorization code not found in authorizationCodeStore")
26 // ErrAuthorizationCodeAlreadyExists is returned when an AuthorizationCode is added to a authorizationCodeStore, but another AuthorizationCode with the
27 // same Code already exists in the authorizationCodeStore.
28 ErrAuthorizationCodeAlreadyExists = errors.New("authorization code already exists in authorizationCodeStore")
29 )
31 // AuthorizationCode represents an authorization grant made by a user to a Client, to
32 // access user data within a defined Scope for a limited amount of time.
33 type AuthorizationCode struct {
34 Code string
35 Created time.Time
36 ExpiresIn int32
37 ClientID uuid.ID
38 Scope string
39 RedirectURI string
40 State string
41 ProfileID uuid.ID
42 Used bool
43 }
45 type authorizationCodeStore interface {
46 getAuthorizationCode(code string) (AuthorizationCode, error)
47 saveAuthorizationCode(authCode AuthorizationCode) error
48 deleteAuthorizationCode(code string) error
49 useAuthorizationCode(code string) error
50 }
52 func (m *memstore) getAuthorizationCode(code string) (AuthorizationCode, error) {
53 m.authCodeLock.RLock()
54 defer m.authCodeLock.RUnlock()
55 authCode, ok := m.authCodes[code]
56 if !ok {
57 return AuthorizationCode{}, ErrAuthorizationCodeNotFound
58 }
59 return authCode, nil
60 }
62 func (m *memstore) saveAuthorizationCode(authCode AuthorizationCode) error {
63 m.authCodeLock.Lock()
64 defer m.authCodeLock.Unlock()
65 _, ok := m.authCodes[authCode.Code]
66 if ok {
67 return ErrAuthorizationCodeAlreadyExists
68 }
69 m.authCodes[authCode.Code] = authCode
70 return nil
71 }
73 func (m *memstore) deleteAuthorizationCode(code string) error {
74 m.authCodeLock.Lock()
75 defer m.authCodeLock.Unlock()
76 _, ok := m.authCodes[code]
77 if !ok {
78 return ErrAuthorizationCodeNotFound
79 }
80 delete(m.authCodes, code)
81 return nil
82 }
84 func (m *memstore) useAuthorizationCode(code string) error {
85 m.authCodeLock.Lock()
86 defer m.authCodeLock.Unlock()
87 a, ok := m.authCodes[code]
88 if !ok {
89 return ErrAuthorizationCodeNotFound
90 }
91 a.Used = true
92 m.authCodes[code] = a
93 return nil
94 }
96 func authCodeGrantValidate(w http.ResponseWriter, r *http.Request, context Context) (scope string, profileID uuid.ID, valid bool) {
97 enc := json.NewEncoder(w)
98 code := r.PostFormValue("code")
99 if code == "" {
100 w.WriteHeader(http.StatusBadRequest)
101 renderJSONError(enc, "invalid_request")
102 return
103 }
104 clientID, success := verifyClient(w, r, true, context)
105 if !success {
106 return
107 }
108 authCode, err := context.GetAuthorizationCode(code)
109 if err != nil {
110 if err == ErrAuthorizationCodeNotFound {
111 w.WriteHeader(http.StatusBadRequest)
112 renderJSONError(enc, "invalid_grant")
113 return
114 }
115 w.WriteHeader(http.StatusInternalServerError)
116 renderJSONError(enc, "server_error")
117 return
118 }
119 redirectURI := r.PostFormValue("redirect_uri")
120 if authCode.RedirectURI != redirectURI {
121 w.WriteHeader(http.StatusBadRequest)
122 renderJSONError(enc, "invalid_grant")
123 return
124 }
125 if !authCode.ClientID.Equal(clientID) {
126 w.WriteHeader(http.StatusBadRequest)
127 renderJSONError(enc, "invalid_grant")
128 return
129 }
130 return authCode.Scope, authCode.ProfileID, true
131 }
133 func authCodeGrantInvalidate(r *http.Request, context Context) error {
134 code := r.PostFormValue("code")
135 if code == "" {
136 return ErrAuthorizationCodeNotFound
137 }
138 return context.UseAuthorizationCode(code)
139 }