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.
14 "github.com/PuerkitoBio/purell"
15 "github.com/gorilla/mux"
17 "code.secondbit.org/uuid.hg"
21 RegisterGrantType("client_credentials", GrantType{
22 Validate: clientCredentialsValidate,
25 ReturnToken: RenderJSONToken,
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")
58 clientTypePublic = "public"
59 clientTypeConfidential = "confidential"
64 // Client represents a client that grants access
65 // to the auth server, exchanging grants for tokens,
66 // and tokens for access.
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"`
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
83 if change.OwnerID != nil {
84 c.OwnerID = change.OwnerID
86 if change.Name != nil {
89 if change.Logo != nil {
92 if change.Website != nil {
93 c.Website = *change.Website
97 // ClientChange represents a bundle of options for
98 // updating a Client's mutable data.
99 type ClientChange struct {
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
113 if c.Name != nil && len(*c.Name) < 2 {
114 return ErrClientNameTooShort
116 if c.Name != nil && len(*c.Name) > 32 {
117 return ErrClientNameTooLong
119 if c.Logo != nil && *c.Logo != "" {
120 if len(*c.Logo) > 1024 {
121 return ErrClientLogoTooLong
123 u, err := url.Parse(*c.Logo)
124 if err != nil || !u.IsAbs() {
125 return ErrClientLogoNotURL
128 if c.Website != nil && *c.Website != "" {
129 if len(*c.Website) > 140 {
130 return ErrClientWebsiteTooLong
132 u, err := url.Parse(*c.Website)
133 if err != nil || !u.IsAbs() {
134 return ErrClientWebsiteNotURL
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()
144 clientIDStr = r.PostFormValue("client_id")
146 if clientIDStr == "" {
147 w.WriteHeader(http.StatusUnauthorized)
149 w.Header().Set("WWW-Authenticate", "Basic")
151 renderJSONError(enc, "invalid_client")
152 return nil, "", false
154 clientID, err := uuid.Parse(clientIDStr)
156 log.Println("Error decoding client ID:", err)
157 w.WriteHeader(http.StatusUnauthorized)
159 w.Header().Set("WWW-Authenticate", "Basic")
161 renderJSONError(enc, "invalid_client")
162 return nil, "", false
164 if !allowPublic && !fromAuthHeader {
165 w.WriteHeader(http.StatusBadRequest)
166 renderJSONError(enc, "unauthorized_client")
167 return nil, "", false
169 return clientID, clientSecret, true
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)
178 _, _, fromAuthHeader := r.BasicAuth()
179 client, err := context.GetClient(clientID)
180 if err == ErrClientNotFound {
181 w.WriteHeader(http.StatusUnauthorized)
183 w.Header().Set("WWW-Authenticate", "Basic")
185 renderJSONError(enc, "invalid_client")
187 } else if err != nil {
188 w.WriteHeader(http.StatusInternalServerError)
189 renderJSONError(enc, "server_error")
192 if client.Secret != clientSecret { // it's important that any client deemed "public" is not issued a client secret.
193 w.WriteHeader(http.StatusUnauthorized)
195 w.Header().Set("WWW-Authenticate", "Basic")
197 renderJSONError(enc, "invalid_client")
200 return clientID, true
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"`
215 func normalizeURIString(in string) (string, error) {
216 n, err := purell.NormalizeURLString(in, purell.FlagsUsuallySafeNonGreedy|purell.FlagSortQuery)
219 return in, ErrEndpointURINotURL
224 func normalizeURI(in *url.URL) string {
225 return purell.NormalizeURL(in, purell.FlagsUsuallySafeNonGreedy|purell.FlagSortQuery)
228 type sortedEndpoints []Endpoint
230 func (s sortedEndpoints) Len() int {
234 func (s sortedEndpoints) Less(i, j int) bool {
235 return s[i].Added.Before(s[j].Added)
238 func (s sortedEndpoints) Swap(i, j int) {
239 s[i], s[j] = s[j], s[i]
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)
256 func (m *memstore) getClient(id uuid.ID) (Client, error) {
258 defer m.clientLock.RUnlock()
259 c, ok := m.clients[id.String()]
261 return Client{}, ErrClientNotFound
266 func (m *memstore) saveClient(client Client) error {
268 defer m.clientLock.Unlock()
269 if _, ok := m.clients[client.ID.String()]; ok {
270 return ErrClientAlreadyExists
272 m.clients[client.ID.String()] = client
273 m.profileClientLookup[client.OwnerID.String()] = append(m.profileClientLookup[client.OwnerID.String()], client.ID)
277 func (m *memstore) updateClient(id uuid.ID, change ClientChange) error {
279 defer m.clientLock.Unlock()
280 c, ok := m.clients[id.String()]
282 return ErrClientNotFound
284 c.ApplyChange(change)
285 m.clients[id.String()] = c
289 func (m *memstore) deleteClient(id uuid.ID) error {
290 client, err := m.getClient(id)
295 defer m.clientLock.Unlock()
296 delete(m.clients, id.String())
298 for p, item := range m.profileClientLookup[client.OwnerID.String()] {
305 m.profileClientLookup[client.OwnerID.String()] = append(m.profileClientLookup[client.OwnerID.String()][:pos], m.profileClientLookup[client.OwnerID.String()][pos+1:]...)
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 {
317 return []Client{}, nil
319 clients := []Client{}
320 for _, id := range ids {
321 client, err := m.getClient(id)
323 return []Client{}, err
325 clients = append(clients, client)
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...)
337 func (m *memstore) removeEndpoint(client, endpoint uuid.ID) error {
338 m.endpointLock.Lock()
339 defer m.endpointLock.Unlock()
341 for p, item := range m.endpoints[client.String()] {
342 if item.ID.Equal(endpoint) {
348 m.endpoints[client.String()] = append(m.endpoints[client.String()][:pos], m.endpoints[client.String()][pos+1:]...)
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 {
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
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
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"`
384 func RegisterClientHandlers(r *mux.Router, context Context) {
385 r.Handle("/clients", wrap(context, CreateClientHandler)).Methods("POST")
388 func CreateClientHandler(w http.ResponseWriter, r *http.Request, c Context) {
389 errors := []requestError{}
390 username, password, ok := r.BasicAuth()
392 errors = append(errors, requestError{Slug: requestErrAccessDenied})
393 encode(w, r, http.StatusUnauthorized, response{Errors: errors})
396 profile, err := authenticate(username, password, c)
398 errors = append(errors, requestError{Slug: requestErrAccessDenied})
399 encode(w, r, http.StatusUnauthorized, response{Errors: errors})
403 decoder := json.NewDecoder(r.Body)
404 err = decoder.Decode(&req)
406 encode(w, r, http.StatusBadRequest, invalidFormatResponse)
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"})
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"})
422 encode(w, r, http.StatusBadRequest, response{Errors: errors})
430 Website: req.Website,
433 if client.Type == clientTypeConfidential {
434 secret := make([]byte, 32)
435 _, err = rand.Read(secret)
437 encode(w, r, http.StatusInternalServerError, actOfGodResponse)
440 client.Secret = hex.EncodeToString(secret)
442 err = c.SaveClient(client)
444 if err == ErrClientAlreadyExists {
445 errors = append(errors, requestError{Slug: requestErrConflict, Field: "/id"})
446 encode(w, r, http.StatusBadRequest, response{Errors: errors})
449 encode(w, r, http.StatusInternalServerError, actOfGodResponse)
452 endpoints := []Endpoint{}
453 for pos, u := range req.Endpoints {
454 uri, err := url.Parse(u)
456 errors = append(errors, requestError{Slug: requestErrInvalidFormat, Field: "/endpoints/" + strconv.Itoa(pos)})
460 errors = append(errors, requestError{Slug: requestErrInvalidValue, Field: "/endpoints/" + strconv.Itoa(pos)})
463 endpoint := Endpoint{
469 endpoints = append(endpoints, endpoint)
471 err = c.AddEndpoints(client.ID, endpoints)
473 errors = append(errors, requestError{Slug: requestErrActOfGod})
474 encode(w, r, http.StatusInternalServerError, response{Errors: errors, Clients: []Client{client}})
478 Clients: []Client{client},
479 Endpoints: endpoints,
482 encode(w, r, http.StatusCreated, resp)
485 func clientCredentialsValidate(w http.ResponseWriter, r *http.Request, context Context) (scope string, profileID uuid.ID, valid bool) {
486 scope = r.PostFormValue("scope")