auth

Paddy 2015-01-18 Parent:823517aad893 Child:d14f0a81498c

123:0a1e16b9c141 Go to Latest

auth/client.go

Refactor verifyClient, implement refresh tokens. Refactor verifyClient into verifyClient and getClientAuth. We moved verifyClient out of each of the GrantType's validation functions and into the access token endpoint, where it will be called before the GrantType's validation function. Yay, less code repetition. And seeing as we always want to verify the client, that seems like a good way to prevent things like 118a69954621 from happening. This did, however, force us to add an AllowsPublic property to the GrantType, so the token endpoint knows whether or not a public Client is valid for any given GrantType. We also implemented the refresh token grant type, which required adding ClientID and RefreshRevoked as properties on the Token type. We need ClientID because we need to constrain refresh tokens to the client that issued them. We also should probably keep track of which tokens belong to which clients, just as a general rule of thumb. RefreshRevoked had to be created, next to Revoked, because the AccessToken could be revoked and the RefreshToken still valid, or vice versa. Notably, when you issue a new refresh token, the old one is revoked, but the access token is still valid. It remains to be seen whether this is a good way to track things or not. The number of duplicated properties lead me to believe our type is not a great representation of the underlying concepts.

History
1 package auth
3 import (
4 "crypto/rand"
5 "encoding/hex"
6 "encoding/json"
7 "errors"
8 "log"
9 "net/http"
10 "net/url"
11 "strconv"
12 "time"
14 "github.com/PuerkitoBio/purell"
15 "github.com/gorilla/mux"
17 "code.secondbit.org/uuid.hg"
18 )
20 func init() {
21 RegisterGrantType("client_credentials", GrantType{
22 Validate: clientCredentialsValidate,
23 Invalidate: nil,
24 IssuesRefresh: true,
25 ReturnToken: RenderJSONToken,
26 AllowsPublic: false,
27 })
28 }
30 var (
31 // ErrNoClientStore is returned when a Context tries to act on a clientStore without setting one first.
32 ErrNoClientStore = errors.New("no clientStore was specified for the Context")
33 // ErrClientNotFound is returned when a Client is requested but not found in a clientStore.
34 ErrClientNotFound = errors.New("client not found in clientStore")
35 // ErrClientAlreadyExists is returned when a Client is added to a clientStore, but another Client with
36 // the same ID already exists in the clientStore.
37 ErrClientAlreadyExists = errors.New("client already exists in clientStore")
39 // ErrEmptyChange is returned when a Change has all its properties set to nil.
40 ErrEmptyChange = errors.New("change must have at least one property set")
41 // ErrClientNameTooShort is returned when a Client's Name property is too short.
42 ErrClientNameTooShort = errors.New("client name must be at least 2 characters")
43 // ErrClientNameTooLong is returned when a Client's Name property is too long.
44 ErrClientNameTooLong = errors.New("client name must be at most 32 characters")
45 // ErrClientLogoTooLong is returned when a Client's Logo property is too long.
46 ErrClientLogoTooLong = errors.New("client logo must be at most 1024 characters")
47 // ErrClientLogoNotURL is returned when a Client's Logo property is not a valid absolute URL.
48 ErrClientLogoNotURL = errors.New("client logo must be a valid absolute URL")
49 // ErrClientWebsiteTooLong is returned when a Client's Website property is too long.
50 ErrClientWebsiteTooLong = errors.New("client website must be at most 1024 characters")
51 // ErrClientWebsiteNotURL is returned when a Client's Website property is not a valid absolute URL.
52 ErrClientWebsiteNotURL = errors.New("client website must be a valid absolute URL")
53 // ErrEndpointURINotURL is returned when an Endpoint's URI property is not a valid absolute URL.
54 ErrEndpointURINotURL = errors.New("endpoint URI must be a valid absolute URL")
55 )
57 const (
58 clientTypePublic = "public"
59 clientTypeConfidential = "confidential"
60 minClientNameLen = 2
61 maxClientNameLen = 24
62 )
64 // Client represents a client that grants access
65 // to the auth server, exchanging grants for tokens,
66 // and tokens for access.
67 type Client struct {
68 ID uuid.ID `json:"id,omitempty"`
69 Secret string `json:"secret,omitempty"`
70 OwnerID uuid.ID `json:"owner_id,omitempty"`
71 Name string `json:"name,omitempty"`
72 Logo string `json:"logo,omitempty"`
73 Website string `json:"website,omitempty"`
74 Type string `json:"type,omitempty"`
75 }
77 // ApplyChange applies the properties of the passed
78 // ClientChange to the Client object it is called on.
79 func (c *Client) ApplyChange(change ClientChange) {
80 if change.Secret != nil {
81 c.Secret = *change.Secret
82 }
83 if change.OwnerID != nil {
84 c.OwnerID = change.OwnerID
85 }
86 if change.Name != nil {
87 c.Name = *change.Name
88 }
89 if change.Logo != nil {
90 c.Logo = *change.Logo
91 }
92 if change.Website != nil {
93 c.Website = *change.Website
94 }
95 }
97 // ClientChange represents a bundle of options for
98 // updating a Client's mutable data.
99 type ClientChange struct {
100 Secret *string
101 OwnerID uuid.ID
102 Name *string
103 Logo *string
104 Website *string
105 }
107 // Validate checks the ClientChange it is called on
108 // and asserts its internal validity, or lack thereof.
109 func (c ClientChange) Validate() error {
110 if c.Secret == nil && c.OwnerID == nil && c.Name == nil && c.Logo == nil && c.Website == nil {
111 return ErrEmptyChange
112 }
113 if c.Name != nil && len(*c.Name) < 2 {
114 return ErrClientNameTooShort
115 }
116 if c.Name != nil && len(*c.Name) > 32 {
117 return ErrClientNameTooLong
118 }
119 if c.Logo != nil && *c.Logo != "" {
120 if len(*c.Logo) > 1024 {
121 return ErrClientLogoTooLong
122 }
123 u, err := url.Parse(*c.Logo)
124 if err != nil || !u.IsAbs() {
125 return ErrClientLogoNotURL
126 }
127 }
128 if c.Website != nil && *c.Website != "" {
129 if len(*c.Website) > 140 {
130 return ErrClientWebsiteTooLong
131 }
132 u, err := url.Parse(*c.Website)
133 if err != nil || !u.IsAbs() {
134 return ErrClientWebsiteNotURL
135 }
136 }
137 return nil
138 }
140 func getClientAuth(w http.ResponseWriter, r *http.Request, allowPublic bool) (uuid.ID, string, bool) {
141 enc := json.NewEncoder(w)
142 clientIDStr, clientSecret, fromAuthHeader := r.BasicAuth()
143 if !fromAuthHeader {
144 clientIDStr = r.PostFormValue("client_id")
145 }
146 if clientIDStr == "" {
147 w.WriteHeader(http.StatusUnauthorized)
148 if fromAuthHeader {
149 w.Header().Set("WWW-Authenticate", "Basic")
150 }
151 renderJSONError(enc, "invalid_client")
152 return nil, "", false
153 }
154 clientID, err := uuid.Parse(clientIDStr)
155 if err != nil {
156 log.Println("Error decoding client ID:", err)
157 w.WriteHeader(http.StatusUnauthorized)
158 if fromAuthHeader {
159 w.Header().Set("WWW-Authenticate", "Basic")
160 }
161 renderJSONError(enc, "invalid_client")
162 return nil, "", false
163 }
164 if !allowPublic && !fromAuthHeader {
165 w.WriteHeader(http.StatusBadRequest)
166 renderJSONError(enc, "unauthorized_client")
167 return nil, "", false
168 }
169 return clientID, clientSecret, true
170 }
172 func verifyClient(w http.ResponseWriter, r *http.Request, allowPublic bool, context Context) (uuid.ID, bool) {
173 enc := json.NewEncoder(w)
174 clientID, clientSecret, ok := getClientAuth(w, r, allowPublic)
175 if !ok {
176 return nil, false
177 }
178 _, _, fromAuthHeader := r.BasicAuth()
179 client, err := context.GetClient(clientID)
180 if err == ErrClientNotFound {
181 w.WriteHeader(http.StatusUnauthorized)
182 if fromAuthHeader {
183 w.Header().Set("WWW-Authenticate", "Basic")
184 }
185 renderJSONError(enc, "invalid_client")
186 return nil, false
187 } else if err != nil {
188 w.WriteHeader(http.StatusInternalServerError)
189 renderJSONError(enc, "server_error")
190 return nil, false
191 }
192 if client.Secret != clientSecret { // it's important that any client deemed "public" is not issued a client secret.
193 w.WriteHeader(http.StatusUnauthorized)
194 if fromAuthHeader {
195 w.Header().Set("WWW-Authenticate", "Basic")
196 }
197 renderJSONError(enc, "invalid_client")
198 return nil, false
199 }
200 return clientID, true
201 }
203 // Endpoint represents a single URI that a Client
204 // controls. Users will be redirected to these URIs
205 // following successful authorization grants and
206 // exchanges for access tokens.
207 type Endpoint struct {
208 ID uuid.ID `json:"id,omitempty"`
209 ClientID uuid.ID `json:"client_id,omitempty"`
210 URI string `json:"uri,omitempty"`
211 NormalizedURI string `json:"-"`
212 Added time.Time `json:"added,omitempty"`
213 }
215 func normalizeURIString(in string) (string, error) {
216 n, err := purell.NormalizeURLString(in, purell.FlagsUsuallySafeNonGreedy|purell.FlagSortQuery)
217 if err != nil {
218 log.Println(err)
219 return in, ErrEndpointURINotURL
220 }
221 return n, nil
222 }
224 func normalizeURI(in *url.URL) string {
225 return purell.NormalizeURL(in, purell.FlagsUsuallySafeNonGreedy|purell.FlagSortQuery)
226 }
228 type sortedEndpoints []Endpoint
230 func (s sortedEndpoints) Len() int {
231 return len(s)
232 }
234 func (s sortedEndpoints) Less(i, j int) bool {
235 return s[i].Added.Before(s[j].Added)
236 }
238 func (s sortedEndpoints) Swap(i, j int) {
239 s[i], s[j] = s[j], s[i]
240 }
242 type clientStore interface {
243 getClient(id uuid.ID) (Client, error)
244 saveClient(client Client) error
245 updateClient(id uuid.ID, change ClientChange) error
246 deleteClient(id uuid.ID) error
247 listClientsByOwner(ownerID uuid.ID, num, offset int) ([]Client, error)
249 addEndpoints(client uuid.ID, endpoint []Endpoint) error
250 removeEndpoint(client, endpoint uuid.ID) error
251 checkEndpoint(client uuid.ID, endpoint string) (bool, error)
252 listEndpoints(client uuid.ID, num, offset int) ([]Endpoint, error)
253 countEndpoints(client uuid.ID) (int64, error)
254 }
256 func (m *memstore) getClient(id uuid.ID) (Client, error) {
257 m.clientLock.RLock()
258 defer m.clientLock.RUnlock()
259 c, ok := m.clients[id.String()]
260 if !ok {
261 return Client{}, ErrClientNotFound
262 }
263 return c, nil
264 }
266 func (m *memstore) saveClient(client Client) error {
267 m.clientLock.Lock()
268 defer m.clientLock.Unlock()
269 if _, ok := m.clients[client.ID.String()]; ok {
270 return ErrClientAlreadyExists
271 }
272 m.clients[client.ID.String()] = client
273 m.profileClientLookup[client.OwnerID.String()] = append(m.profileClientLookup[client.OwnerID.String()], client.ID)
274 return nil
275 }
277 func (m *memstore) updateClient(id uuid.ID, change ClientChange) error {
278 m.clientLock.Lock()
279 defer m.clientLock.Unlock()
280 c, ok := m.clients[id.String()]
281 if !ok {
282 return ErrClientNotFound
283 }
284 c.ApplyChange(change)
285 m.clients[id.String()] = c
286 return nil
287 }
289 func (m *memstore) deleteClient(id uuid.ID) error {
290 client, err := m.getClient(id)
291 if err != nil {
292 return err
293 }
294 m.clientLock.Lock()
295 defer m.clientLock.Unlock()
296 delete(m.clients, id.String())
297 pos := -1
298 for p, item := range m.profileClientLookup[client.OwnerID.String()] {
299 if item.Equal(id) {
300 pos = p
301 break
302 }
303 }
304 if pos >= 0 {
305 m.profileClientLookup[client.OwnerID.String()] = append(m.profileClientLookup[client.OwnerID.String()][:pos], m.profileClientLookup[client.OwnerID.String()][pos+1:]...)
306 }
307 return nil
308 }
310 func (m *memstore) listClientsByOwner(ownerID uuid.ID, num, offset int) ([]Client, error) {
311 ids := m.lookupClientsByProfileID(ownerID.String())
312 if len(ids) > num+offset {
313 ids = ids[offset : num+offset]
314 } else if len(ids) > offset {
315 ids = ids[offset:]
316 } else {
317 return []Client{}, nil
318 }
319 clients := []Client{}
320 for _, id := range ids {
321 client, err := m.getClient(id)
322 if err != nil {
323 return []Client{}, err
324 }
325 clients = append(clients, client)
326 }
327 return clients, nil
328 }
330 func (m *memstore) addEndpoints(client uuid.ID, endpoints []Endpoint) error {
331 m.endpointLock.Lock()
332 defer m.endpointLock.Unlock()
333 m.endpoints[client.String()] = append(m.endpoints[client.String()], endpoints...)
334 return nil
335 }
337 func (m *memstore) removeEndpoint(client, endpoint uuid.ID) error {
338 m.endpointLock.Lock()
339 defer m.endpointLock.Unlock()
340 pos := -1
341 for p, item := range m.endpoints[client.String()] {
342 if item.ID.Equal(endpoint) {
343 pos = p
344 break
345 }
346 }
347 if pos >= 0 {
348 m.endpoints[client.String()] = append(m.endpoints[client.String()][:pos], m.endpoints[client.String()][pos+1:]...)
349 }
350 return nil
351 }
353 func (m *memstore) checkEndpoint(client uuid.ID, endpoint string) (bool, error) {
354 m.endpointLock.RLock()
355 defer m.endpointLock.RUnlock()
356 for _, candidate := range m.endpoints[client.String()] {
357 if endpoint == candidate.NormalizedURI {
358 return true, nil
359 }
360 }
361 return false, nil
362 }
364 func (m *memstore) listEndpoints(client uuid.ID, num, offset int) ([]Endpoint, error) {
365 m.endpointLock.RLock()
366 defer m.endpointLock.RUnlock()
367 return m.endpoints[client.String()], nil
368 }
370 func (m *memstore) countEndpoints(client uuid.ID) (int64, error) {
371 m.endpointLock.RLock()
372 defer m.endpointLock.RUnlock()
373 return int64(len(m.endpoints[client.String()])), nil
374 }
376 type newClientReq struct {
377 Name string `json:"name"`
378 Logo string `json:"logo"`
379 Website string `json:"website"`
380 Type string `json:"type"`
381 Endpoints []string `json:"endpoints"`
382 }
384 func RegisterClientHandlers(r *mux.Router, context Context) {
385 r.Handle("/clients", wrap(context, CreateClientHandler)).Methods("POST")
386 }
388 func CreateClientHandler(w http.ResponseWriter, r *http.Request, c Context) {
389 errors := []requestError{}
390 username, password, ok := r.BasicAuth()
391 if !ok {
392 errors = append(errors, requestError{Slug: requestErrAccessDenied})
393 encode(w, r, http.StatusUnauthorized, response{Errors: errors})
394 return
395 }
396 profile, err := authenticate(username, password, c)
397 if err != nil {
398 errors = append(errors, requestError{Slug: requestErrAccessDenied})
399 encode(w, r, http.StatusUnauthorized, response{Errors: errors})
400 return
401 }
402 var req newClientReq
403 decoder := json.NewDecoder(r.Body)
404 err = decoder.Decode(&req)
405 if err != nil {
406 encode(w, r, http.StatusBadRequest, invalidFormatResponse)
407 return
408 }
409 if req.Type == "" {
410 errors = append(errors, requestError{Slug: requestErrMissing, Field: "/type"})
411 } else if req.Type != clientTypePublic && req.Type != clientTypeConfidential {
412 errors = append(errors, requestError{Slug: requestErrInvalidValue, Field: "/type"})
413 }
414 if req.Name == "" {
415 errors = append(errors, requestError{Slug: requestErrMissing, Field: "/name"})
416 } else if len(req.Name) < minClientNameLen {
417 errors = append(errors, requestError{Slug: requestErrInsufficient, Field: "/name"})
418 } else if len(req.Name) > maxClientNameLen {
419 errors = append(errors, requestError{Slug: requestErrOverflow, Field: "/name"})
420 }
421 if len(errors) > 0 {
422 encode(w, r, http.StatusBadRequest, response{Errors: errors})
423 return
424 }
425 client := Client{
426 ID: uuid.NewID(),
427 OwnerID: profile.ID,
428 Name: req.Name,
429 Logo: req.Logo,
430 Website: req.Website,
431 Type: req.Type,
432 }
433 if client.Type == clientTypeConfidential {
434 secret := make([]byte, 32)
435 _, err = rand.Read(secret)
436 if err != nil {
437 encode(w, r, http.StatusInternalServerError, actOfGodResponse)
438 return
439 }
440 client.Secret = hex.EncodeToString(secret)
441 }
442 err = c.SaveClient(client)
443 if err != nil {
444 if err == ErrClientAlreadyExists {
445 errors = append(errors, requestError{Slug: requestErrConflict, Field: "/id"})
446 encode(w, r, http.StatusBadRequest, response{Errors: errors})
447 return
448 }
449 encode(w, r, http.StatusInternalServerError, actOfGodResponse)
450 return
451 }
452 endpoints := []Endpoint{}
453 for pos, u := range req.Endpoints {
454 uri, err := url.Parse(u)
455 if err != nil {
456 errors = append(errors, requestError{Slug: requestErrInvalidFormat, Field: "/endpoints/" + strconv.Itoa(pos)})
457 continue
458 }
459 if !uri.IsAbs() {
460 errors = append(errors, requestError{Slug: requestErrInvalidValue, Field: "/endpoints/" + strconv.Itoa(pos)})
461 continue
462 }
463 endpoint := Endpoint{
464 ID: uuid.NewID(),
465 ClientID: client.ID,
466 URI: uri.String(),
467 Added: time.Now(),
468 }
469 endpoints = append(endpoints, endpoint)
470 }
471 err = c.AddEndpoints(client.ID, endpoints)
472 if err != nil {
473 errors = append(errors, requestError{Slug: requestErrActOfGod})
474 encode(w, r, http.StatusInternalServerError, response{Errors: errors, Clients: []Client{client}})
475 return
476 }
477 resp := response{
478 Clients: []Client{client},
479 Endpoints: endpoints,
480 Errors: errors,
481 }
482 encode(w, r, http.StatusCreated, resp)
483 }
485 func clientCredentialsValidate(w http.ResponseWriter, r *http.Request, context Context) (scope string, profileID uuid.ID, valid bool) {
486 scope = r.PostFormValue("scope")
487 valid = true
488 return
489 }