auth
auth/client.go
Add ListEndpoints handler. Add a handler responsible for returning the endpoints that exist on a client. It still needs unit tests, but appears to work as required.
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 "strings"
13 "time"
15 "github.com/PuerkitoBio/purell"
16 "github.com/gorilla/mux"
18 "code.secondbit.org/uuid.hg"
19 )
21 func init() {
22 RegisterGrantType("client_credentials", GrantType{
23 Validate: clientCredentialsValidate,
24 Invalidate: nil,
25 IssuesRefresh: true,
26 ReturnToken: RenderJSONToken,
27 AllowsPublic: false,
28 AuditString: clientCredentialsAuditString,
29 })
30 }
32 var (
33 // ErrNoClientStore is returned when a Context tries to act on a clientStore without setting one first.
34 ErrNoClientStore = errors.New("no clientStore was specified for the Context")
35 // ErrClientNotFound is returned when a Client is requested but not found in a clientStore.
36 ErrClientNotFound = errors.New("client not found in clientStore")
37 // ErrClientAlreadyExists is returned when a Client is added to a clientStore, but another Client with
38 // the same ID already exists in the clientStore.
39 ErrClientAlreadyExists = errors.New("client already exists in clientStore")
41 // ErrEmptyChange is returned when a Change has all its properties set to nil.
42 ErrEmptyChange = errors.New("change must have at least one property set")
43 // ErrClientNameTooShort is returned when a Client's Name property is too short.
44 ErrClientNameTooShort = errors.New("client name must be at least 2 characters")
45 // ErrClientNameTooLong is returned when a Client's Name property is too long.
46 ErrClientNameTooLong = errors.New("client name must be at most 32 characters")
47 // ErrClientLogoTooLong is returned when a Client's Logo property is too long.
48 ErrClientLogoTooLong = errors.New("client logo must be at most 1024 characters")
49 // ErrClientLogoNotURL is returned when a Client's Logo property is not a valid absolute URL.
50 ErrClientLogoNotURL = errors.New("client logo must be a valid absolute URL")
51 // ErrClientWebsiteTooLong is returned when a Client's Website property is too long.
52 ErrClientWebsiteTooLong = errors.New("client website must be at most 1024 characters")
53 // ErrClientWebsiteNotURL is returned when a Client's Website property is not a valid absolute URL.
54 ErrClientWebsiteNotURL = errors.New("client website must be a valid absolute URL")
55 // ErrEndpointURINotURL is returned when an Endpoint's URI property is not a valid absolute URL.
56 ErrEndpointURINotURL = errors.New("endpoint URI must be a valid absolute URL")
57 )
59 const (
60 clientTypePublic = "public"
61 clientTypeConfidential = "confidential"
62 minClientNameLen = 2
63 maxClientNameLen = 24
64 defaultClientResponseSize = 20
65 maxClientResponseSize = 50
66 defaultEndpointResponseSize = 20
67 maxEndpointResponseSize = 50
69 normalizeFlags = purell.FlagsUsuallySafeNonGreedy | purell.FlagSortQuery
70 )
72 // Client represents a client that grants access
73 // to the auth server, exchanging grants for tokens,
74 // and tokens for access.
75 type Client struct {
76 ID uuid.ID `json:"id,omitempty"`
77 Secret string `json:"secret,omitempty"`
78 OwnerID uuid.ID `json:"owner_id,omitempty"`
79 Name string `json:"name,omitempty"`
80 Logo string `json:"logo,omitempty"`
81 Website string `json:"website,omitempty"`
82 Type string `json:"type,omitempty"`
83 }
85 // ApplyChange applies the properties of the passed
86 // ClientChange to the Client object it is called on.
87 func (c *Client) ApplyChange(change ClientChange) {
88 if change.Secret != nil {
89 c.Secret = *change.Secret
90 }
91 if change.OwnerID != nil {
92 c.OwnerID = change.OwnerID
93 }
94 if change.Name != nil {
95 c.Name = *change.Name
96 }
97 if change.Logo != nil {
98 c.Logo = *change.Logo
99 }
100 if change.Website != nil {
101 c.Website = *change.Website
102 }
103 }
105 // ClientChange represents a bundle of options for
106 // updating a Client's mutable data.
107 type ClientChange struct {
108 Secret *string
109 OwnerID uuid.ID
110 Name *string
111 Logo *string
112 Website *string
113 }
115 // Validate checks the ClientChange it is called on
116 // and asserts its internal validity, or lack thereof.
117 func (c ClientChange) Validate() []error {
118 errors := []error{}
119 if c.Secret == nil && c.OwnerID == nil && c.Name == nil && c.Logo == nil && c.Website == nil {
120 errors = append(errors, ErrEmptyChange)
121 return errors
122 }
123 if c.Name != nil && len(*c.Name) < 2 {
124 errors = append(errors, ErrClientNameTooShort)
125 }
126 if c.Name != nil && len(*c.Name) > 32 {
127 errors = append(errors, ErrClientNameTooLong)
128 }
129 if c.Logo != nil && *c.Logo != "" {
130 if len(*c.Logo) > 1024 {
131 errors = append(errors, ErrClientLogoTooLong)
132 }
133 u, err := url.Parse(*c.Logo)
134 if err != nil || !u.IsAbs() {
135 errors = append(errors, ErrClientLogoNotURL)
136 }
137 }
138 if c.Website != nil && *c.Website != "" {
139 if len(*c.Website) > 140 {
140 errors = append(errors, ErrClientWebsiteTooLong)
141 }
142 u, err := url.Parse(*c.Website)
143 if err != nil || !u.IsAbs() {
144 errors = append(errors, ErrClientWebsiteNotURL)
145 }
146 }
147 return errors
148 }
150 func getClientAuth(w http.ResponseWriter, r *http.Request, allowPublic bool) (uuid.ID, string, bool) {
151 enc := json.NewEncoder(w)
152 clientIDStr, clientSecret, fromAuthHeader := r.BasicAuth()
153 if !fromAuthHeader {
154 clientIDStr = r.PostFormValue("client_id")
155 }
156 if clientIDStr == "" {
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 clientID, err := uuid.Parse(clientIDStr)
170 if err != nil {
171 log.Println("Error decoding client ID:", err)
172 w.WriteHeader(http.StatusUnauthorized)
173 if fromAuthHeader {
174 w.Header().Set("WWW-Authenticate", "Basic")
175 }
176 renderJSONError(enc, "invalid_client")
177 return nil, "", false
178 }
179 return clientID, clientSecret, true
180 }
182 func verifyClient(w http.ResponseWriter, r *http.Request, allowPublic bool, context Context) (uuid.ID, bool) {
183 enc := json.NewEncoder(w)
184 clientID, clientSecret, ok := getClientAuth(w, r, allowPublic)
185 if !ok {
186 return nil, false
187 }
188 _, _, fromAuthHeader := r.BasicAuth()
189 client, err := context.GetClient(clientID)
190 if err == ErrClientNotFound {
191 w.WriteHeader(http.StatusUnauthorized)
192 if fromAuthHeader {
193 w.Header().Set("WWW-Authenticate", "Basic")
194 }
195 renderJSONError(enc, "invalid_client")
196 return nil, false
197 } else if err != nil {
198 w.WriteHeader(http.StatusInternalServerError)
199 renderJSONError(enc, "server_error")
200 return nil, false
201 }
202 if client.Secret != clientSecret { // it's important that any client deemed "public" is not issued a client secret.
203 w.WriteHeader(http.StatusUnauthorized)
204 if fromAuthHeader {
205 w.Header().Set("WWW-Authenticate", "Basic")
206 }
207 renderJSONError(enc, "invalid_client")
208 return nil, false
209 }
210 return clientID, true
211 }
213 // Endpoint represents a single URI that a Client
214 // controls. Users will be redirected to these URIs
215 // following successful authorization grants and
216 // exchanges for access tokens.
217 type Endpoint struct {
218 ID uuid.ID `json:"id,omitempty"`
219 ClientID uuid.ID `json:"client_id,omitempty"`
220 URI string `json:"uri,omitempty"`
221 NormalizedURI string `json:"-"`
222 Added time.Time `json:"added,omitempty"`
223 }
225 func normalizeURIString(in string) (string, error) {
226 n, err := purell.NormalizeURLString(in, normalizeFlags)
227 if err != nil {
228 log.Println(err)
229 return in, ErrEndpointURINotURL
230 }
231 return n, nil
232 }
234 func normalizeURI(in *url.URL) string {
235 return purell.NormalizeURL(in, normalizeFlags)
236 }
238 type sortedEndpoints []Endpoint
240 func (s sortedEndpoints) Len() int {
241 return len(s)
242 }
244 func (s sortedEndpoints) Less(i, j int) bool {
245 return s[i].Added.Before(s[j].Added)
246 }
248 func (s sortedEndpoints) Swap(i, j int) {
249 s[i], s[j] = s[j], s[i]
250 }
252 type clientStore interface {
253 getClient(id uuid.ID) (Client, error)
254 saveClient(client Client) error
255 updateClient(id uuid.ID, change ClientChange) error
256 deleteClient(id uuid.ID) error
257 listClientsByOwner(ownerID uuid.ID, num, offset int) ([]Client, error)
259 addEndpoints(client uuid.ID, endpoint []Endpoint) error
260 removeEndpoint(client, endpoint uuid.ID) error
261 checkEndpoint(client uuid.ID, endpoint string) (bool, error)
262 listEndpoints(client uuid.ID, num, offset int) ([]Endpoint, error)
263 countEndpoints(client uuid.ID) (int64, error)
264 }
266 func (m *memstore) getClient(id uuid.ID) (Client, error) {
267 m.clientLock.RLock()
268 defer m.clientLock.RUnlock()
269 c, ok := m.clients[id.String()]
270 if !ok {
271 return Client{}, ErrClientNotFound
272 }
273 return c, nil
274 }
276 func (m *memstore) saveClient(client Client) error {
277 m.clientLock.Lock()
278 defer m.clientLock.Unlock()
279 if _, ok := m.clients[client.ID.String()]; ok {
280 return ErrClientAlreadyExists
281 }
282 m.clients[client.ID.String()] = client
283 m.profileClientLookup[client.OwnerID.String()] = append(m.profileClientLookup[client.OwnerID.String()], client.ID)
284 return nil
285 }
287 func (m *memstore) updateClient(id uuid.ID, change ClientChange) error {
288 m.clientLock.Lock()
289 defer m.clientLock.Unlock()
290 c, ok := m.clients[id.String()]
291 if !ok {
292 return ErrClientNotFound
293 }
294 c.ApplyChange(change)
295 m.clients[id.String()] = c
296 return nil
297 }
299 func (m *memstore) deleteClient(id uuid.ID) error {
300 client, err := m.getClient(id)
301 if err != nil {
302 return err
303 }
304 m.clientLock.Lock()
305 defer m.clientLock.Unlock()
306 delete(m.clients, id.String())
307 pos := -1
308 for p, item := range m.profileClientLookup[client.OwnerID.String()] {
309 if item.Equal(id) {
310 pos = p
311 break
312 }
313 }
314 if pos >= 0 {
315 m.profileClientLookup[client.OwnerID.String()] = append(m.profileClientLookup[client.OwnerID.String()][:pos], m.profileClientLookup[client.OwnerID.String()][pos+1:]...)
316 }
317 return nil
318 }
320 func (m *memstore) listClientsByOwner(ownerID uuid.ID, num, offset int) ([]Client, error) {
321 ids := m.lookupClientsByProfileID(ownerID.String())
322 if len(ids) > num+offset {
323 ids = ids[offset : num+offset]
324 } else if len(ids) > offset {
325 ids = ids[offset:]
326 } else {
327 return []Client{}, nil
328 }
329 clients := []Client{}
330 for _, id := range ids {
331 client, err := m.getClient(id)
332 if err != nil {
333 return []Client{}, err
334 }
335 clients = append(clients, client)
336 }
337 return clients, nil
338 }
340 func (m *memstore) addEndpoints(client uuid.ID, endpoints []Endpoint) error {
341 m.endpointLock.Lock()
342 defer m.endpointLock.Unlock()
343 m.endpoints[client.String()] = append(m.endpoints[client.String()], endpoints...)
344 return nil
345 }
347 func (m *memstore) removeEndpoint(client, endpoint uuid.ID) error {
348 m.endpointLock.Lock()
349 defer m.endpointLock.Unlock()
350 pos := -1
351 for p, item := range m.endpoints[client.String()] {
352 if item.ID.Equal(endpoint) {
353 pos = p
354 break
355 }
356 }
357 if pos >= 0 {
358 m.endpoints[client.String()] = append(m.endpoints[client.String()][:pos], m.endpoints[client.String()][pos+1:]...)
359 }
360 return nil
361 }
363 func (m *memstore) checkEndpoint(client uuid.ID, endpoint string) (bool, error) {
364 m.endpointLock.RLock()
365 defer m.endpointLock.RUnlock()
366 for _, candidate := range m.endpoints[client.String()] {
367 if endpoint == candidate.NormalizedURI {
368 return true, nil
369 }
370 }
371 return false, nil
372 }
374 func (m *memstore) listEndpoints(client uuid.ID, num, offset int) ([]Endpoint, error) {
375 m.endpointLock.RLock()
376 defer m.endpointLock.RUnlock()
377 return m.endpoints[client.String()], nil
378 }
380 func (m *memstore) countEndpoints(client uuid.ID) (int64, error) {
381 m.endpointLock.RLock()
382 defer m.endpointLock.RUnlock()
383 return int64(len(m.endpoints[client.String()])), nil
384 }
386 type newClientReq struct {
387 Name string `json:"name"`
388 Logo string `json:"logo"`
389 Website string `json:"website"`
390 Type string `json:"type"`
391 Endpoints []string `json:"endpoints"`
392 }
394 func RegisterClientHandlers(r *mux.Router, context Context) {
395 r.Handle("/clients", wrap(context, CreateClientHandler)).Methods("POST")
396 r.Handle("/clients", wrap(context, ListClientsHandler)).Methods("GET")
397 r.Handle("/clients/{id}", wrap(context, GetClientHandler)).Methods("GET")
398 r.Handle("/clients/{id}", wrap(context, UpdateClientHandler)).Methods("PATCH")
399 // BUG(paddy): We need to implement a handler to delete a client. Also, what should that do with the grants and tokens belonging to that client?
400 r.Handle("/clients/{id}/endpoints", wrap(context, AddEndpointsHandler)).Methods("POST")
401 // BUG(paddy): We need to implement a handler to remove an endpoint from a client.
402 r.Handle("/clients/{id}/endpoints", wrap(context, ListEndpointsHandler)).Methods("GET")
403 }
405 func CreateClientHandler(w http.ResponseWriter, r *http.Request, c Context) {
406 errors := []requestError{}
407 username, password, ok := r.BasicAuth()
408 if !ok {
409 errors = append(errors, requestError{Slug: requestErrAccessDenied})
410 encode(w, r, http.StatusUnauthorized, response{Errors: errors})
411 return
412 }
413 profile, err := authenticate(username, password, c)
414 if err != nil {
415 errors = append(errors, requestError{Slug: requestErrAccessDenied})
416 encode(w, r, http.StatusUnauthorized, response{Errors: errors})
417 return
418 }
419 var req newClientReq
420 decoder := json.NewDecoder(r.Body)
421 err = decoder.Decode(&req)
422 if err != nil {
423 encode(w, r, http.StatusBadRequest, invalidFormatResponse)
424 return
425 }
426 if req.Type == "" {
427 errors = append(errors, requestError{Slug: requestErrMissing, Field: "/type"})
428 } else if req.Type != clientTypePublic && req.Type != clientTypeConfidential {
429 errors = append(errors, requestError{Slug: requestErrInvalidValue, Field: "/type"})
430 }
431 if req.Name == "" {
432 errors = append(errors, requestError{Slug: requestErrMissing, Field: "/name"})
433 } else if len(req.Name) < minClientNameLen {
434 errors = append(errors, requestError{Slug: requestErrInsufficient, Field: "/name"})
435 } else if len(req.Name) > maxClientNameLen {
436 errors = append(errors, requestError{Slug: requestErrOverflow, Field: "/name"})
437 }
438 if len(errors) > 0 {
439 encode(w, r, http.StatusBadRequest, response{Errors: errors})
440 return
441 }
442 client := Client{
443 ID: uuid.NewID(),
444 OwnerID: profile.ID,
445 Name: req.Name,
446 Logo: req.Logo,
447 Website: req.Website,
448 Type: req.Type,
449 }
450 if client.Type == clientTypeConfidential {
451 secret := make([]byte, 32)
452 _, err = rand.Read(secret)
453 if err != nil {
454 encode(w, r, http.StatusInternalServerError, actOfGodResponse)
455 return
456 }
457 client.Secret = hex.EncodeToString(secret)
458 }
459 err = c.SaveClient(client)
460 if err != nil {
461 if err == ErrClientAlreadyExists {
462 errors = append(errors, requestError{Slug: requestErrConflict, Field: "/id"})
463 encode(w, r, http.StatusBadRequest, response{Errors: errors})
464 return
465 }
466 encode(w, r, http.StatusInternalServerError, actOfGodResponse)
467 return
468 }
469 endpoints := []Endpoint{}
470 for pos, u := range req.Endpoints {
471 uri, err := url.Parse(u)
472 if err != nil {
473 errors = append(errors, requestError{Slug: requestErrInvalidFormat, Field: "/endpoints/" + strconv.Itoa(pos)})
474 continue
475 }
476 if !uri.IsAbs() {
477 errors = append(errors, requestError{Slug: requestErrInvalidValue, Field: "/endpoints/" + strconv.Itoa(pos)})
478 continue
479 }
480 endpoint := Endpoint{
481 ID: uuid.NewID(),
482 ClientID: client.ID,
483 URI: uri.String(),
484 Added: time.Now(),
485 }
486 endpoints = append(endpoints, endpoint)
487 }
488 err = c.AddEndpoints(client.ID, endpoints)
489 if err != nil {
490 errors = append(errors, requestError{Slug: requestErrActOfGod})
491 encode(w, r, http.StatusInternalServerError, response{Errors: errors, Clients: []Client{client}})
492 return
493 }
494 resp := response{
495 Clients: []Client{client},
496 Endpoints: endpoints,
497 Errors: errors,
498 }
499 encode(w, r, http.StatusCreated, resp)
500 }
502 func GetClientHandler(w http.ResponseWriter, r *http.Request, c Context) {
503 errors := []requestError{}
504 vars := mux.Vars(r)
505 if vars["id"] == "" {
506 errors = append(errors, requestError{Slug: requestErrMissing, Param: "id"})
507 encode(w, r, http.StatusBadRequest, response{Errors: errors})
508 return
509 }
510 id, err := uuid.Parse(vars["id"])
511 if err != nil {
512 errors = append(errors, requestError{Slug: requestErrInvalidFormat, Param: "id"})
513 encode(w, r, http.StatusBadRequest, response{Errors: errors})
514 return
515 }
516 client, err := c.GetClient(id)
517 if err != nil {
518 if err == ErrClientNotFound {
519 errors = append(errors, requestError{Slug: requestErrNotFound, Param: "id"})
520 encode(w, r, http.StatusBadRequest, response{Errors: errors})
521 return
522 }
523 errors = append(errors, requestError{Slug: requestErrActOfGod})
524 encode(w, r, http.StatusInternalServerError, response{Errors: errors})
525 return
526 }
527 client.Secret = ""
528 // BUG(paddy): How should auth be handled for retrieving clients?
529 resp := response{
530 Clients: []Client{client},
531 Errors: errors,
532 }
533 encode(w, r, http.StatusOK, resp)
534 }
536 func ListClientsHandler(w http.ResponseWriter, r *http.Request, c Context) {
537 errors := []requestError{}
538 var err error
539 // BUG(paddy): If ids are provided in query params, retrieve only those clients
540 // BUG(paddy): We should have auth when listing clients
541 num := defaultClientResponseSize
542 offset := 0
543 ownerIDStr := r.URL.Query().Get("owner_id")
544 numStr := r.URL.Query().Get("num")
545 offsetStr := r.URL.Query().Get("offset")
546 if numStr != "" {
547 num, err = strconv.Atoi(numStr)
548 if err != nil {
549 errors = append(errors, requestError{Slug: requestErrInvalidFormat, Param: "num"})
550 }
551 if num > maxClientResponseSize {
552 errors = append(errors, requestError{Slug: requestErrOverflow, Param: "num"})
553 }
554 }
555 if offsetStr != "" {
556 offset, err = strconv.Atoi(offsetStr)
557 if err != nil {
558 errors = append(errors, requestError{Slug: requestErrInvalidFormat, Param: "offset"})
559 }
560 }
561 if ownerIDStr == "" {
562 errors = append(errors, requestError{Slug: requestErrMissing, Param: "owner_id"})
563 }
564 if len(errors) > 0 {
565 encode(w, r, http.StatusBadRequest, response{Errors: errors})
566 return
567 }
568 ownerID, err := uuid.Parse(ownerIDStr)
569 if err != nil {
570 errors = append(errors, requestError{Slug: requestErrInvalidFormat, Param: "owner_id"})
571 encode(w, r, http.StatusInternalServerError, response{Errors: errors})
572 return
573 }
574 clients, err := c.ListClientsByOwner(ownerID, num, offset)
575 if err != nil {
576 errors = append(errors, requestError{Slug: requestErrActOfGod})
577 encode(w, r, http.StatusInternalServerError, response{Errors: errors})
578 return
579 }
580 for pos, client := range clients {
581 client.Secret = ""
582 clients[pos] = client
583 }
584 resp := response{
585 Clients: clients,
586 Errors: errors,
587 }
588 encode(w, r, http.StatusOK, resp)
589 }
591 func UpdateClientHandler(w http.ResponseWriter, r *http.Request, c Context) {
592 errors := []requestError{}
593 vars := mux.Vars(r)
594 if _, ok := vars["id"]; !ok {
595 errors = append(errors, requestError{Slug: requestErrMissing, Param: "id"})
596 encode(w, r, http.StatusBadRequest, response{Errors: errors})
597 return
598 }
599 var change ClientChange
600 err := decode(r, &change)
601 if err != nil {
602 errors = append(errors, requestError{Slug: requestErrInvalidFormat, Field: "/"})
603 encode(w, r, http.StatusBadRequest, response{Errors: errors})
604 return
605 }
606 errs := change.Validate()
607 for _, err := range errs {
608 switch err {
609 case ErrEmptyChange:
610 errors = append(errors, requestError{Slug: requestErrMissing, Field: "/"})
611 case ErrClientNameTooShort:
612 errors = append(errors, requestError{Slug: requestErrInsufficient, Field: "/name"})
613 case ErrClientNameTooLong:
614 errors = append(errors, requestError{Slug: requestErrOverflow, Field: "/name"})
615 case ErrClientLogoTooLong:
616 errors = append(errors, requestError{Slug: requestErrOverflow, Field: "/logo"})
617 case ErrClientLogoNotURL:
618 errors = append(errors, requestError{Slug: requestErrInvalidFormat, Field: "/logo"})
619 case ErrClientWebsiteTooLong:
620 errors = append(errors, requestError{Slug: requestErrOverflow, Field: "/website"})
621 case ErrClientWebsiteNotURL:
622 errors = append(errors, requestError{Slug: requestErrInvalidFormat, Field: "/website"})
623 default:
624 log.Println("Unrecognised error from client change validation:", err)
625 }
626 }
627 id, err := uuid.Parse(vars["id"])
628 if err != nil {
629 errors = append(errors, requestError{Slug: requestErrInvalidFormat, Param: "id"})
630 }
631 if len(errors) > 0 {
632 encode(w, r, http.StatusBadRequest, response{Errors: errors})
633 return
634 }
635 client, err := c.GetClient(id)
636 if err == ErrClientNotFound {
637 errors = append(errors, requestError{Slug: requestErrNotFound, Param: "id"})
638 encode(w, r, http.StatusNotFound, response{Errors: errors})
639 return
640 } else if err != nil {
641 log.Println("Error retrieving client:", err)
642 errors = append(errors, requestError{Slug: requestErrActOfGod})
643 encode(w, r, http.StatusInternalServerError, response{Errors: errors})
644 return
645 }
646 if change.Secret != nil && client.Type == clientTypeConfidential {
647 secret := make([]byte, 32)
648 _, err = rand.Read(secret)
649 if err != nil {
650 encode(w, r, http.StatusInternalServerError, actOfGodResponse)
651 return
652 }
653 newSecret := hex.EncodeToString(secret)
654 change.Secret = &newSecret
655 }
656 err = c.UpdateClient(id, change)
657 if err != nil {
658 log.Println("Error updating client:", err)
659 errors = append(errors, requestError{Slug: requestErrActOfGod})
660 encode(w, r, http.StatusInternalServerError, response{Errors: errors})
661 return
662 }
663 client.ApplyChange(change)
664 encode(w, r, http.StatusOK, response{Clients: []Client{client}, Errors: errors})
665 return
666 }
668 func AddEndpointsHandler(w http.ResponseWriter, r *http.Request, c Context) {
669 type addEndpointReq struct {
670 Endpoints []string `json:"endpoints"`
671 }
672 errors := []requestError{}
673 vars := mux.Vars(r)
674 if vars["id"] == "" {
675 errors = append(errors, requestError{Slug: requestErrMissing, Param: "id"})
676 encode(w, r, http.StatusBadRequest, response{Errors: errors})
677 return
678 }
679 id, err := uuid.Parse(vars["id"])
680 if err != nil {
681 errors = append(errors, requestError{Slug: requestErrInvalidFormat, Param: "id"})
682 encode(w, r, http.StatusBadRequest, response{Errors: errors})
683 return
684 }
685 _, err = c.GetClient(id)
686 if err != nil {
687 if err == ErrClientNotFound {
688 errors = append(errors, requestError{Slug: requestErrNotFound, Param: "id"})
689 encode(w, r, http.StatusBadRequest, response{Errors: errors})
690 return
691 }
692 errors = append(errors, requestError{Slug: requestErrActOfGod})
693 encode(w, r, http.StatusInternalServerError, response{Errors: errors})
694 return
695 }
696 var req addEndpointReq
697 decoder := json.NewDecoder(r.Body)
698 err = decoder.Decode(&req)
699 if err != nil {
700 encode(w, r, http.StatusBadRequest, invalidFormatResponse)
701 return
702 }
703 if len(req.Endpoints) < 1 {
704 errors = append(errors, requestError{Slug: requestErrMissing, Field: "/endpoints"})
705 encode(w, r, http.StatusBadRequest, response{Errors: errors})
706 return
707 }
708 endpoints := []Endpoint{}
709 for pos, u := range req.Endpoints {
710 if parsed, err := url.Parse(u); err != nil {
711 errors = append(errors, requestError{Slug: requestErrInvalidFormat, Field: "/endpoints/" + strconv.Itoa(pos)})
712 continue
713 } else if !parsed.IsAbs() {
714 errors = append(errors, requestError{Slug: requestErrInvalidValue, Field: "/endpoints" + strconv.Itoa(pos)})
715 continue
716 }
717 e := Endpoint{
718 ID: uuid.NewID(),
719 ClientID: id,
720 URI: u,
721 Added: time.Now(),
722 }
723 endpoints = append(endpoints, e)
724 }
725 if len(errors) > 0 {
726 encode(w, r, http.StatusBadRequest, response{Errors: errors})
727 return
728 }
729 err = c.AddEndpoints(id, endpoints)
730 if err != nil {
731 encode(w, r, http.StatusInternalServerError, actOfGodResponse)
732 return
733 }
734 resp := response{
735 Errors: errors,
736 Endpoints: endpoints,
737 }
738 encode(w, r, http.StatusCreated, resp)
739 }
741 func ListEndpointsHandler(w http.ResponseWriter, r *http.Request, c Context) {
742 errors := []requestError{}
743 vars := mux.Vars(r)
744 clientID, err := uuid.Parse(vars["id"])
745 if err != nil {
746 errors = append(errors, requestError{Slug: requestErrInvalidFormat, Param: "client_id"})
747 encode(w, r, http.StatusBadRequest, response{Errors: errors})
748 return
749 }
750 num := defaultEndpointResponseSize
751 offset := 0
752 numStr := r.URL.Query().Get("num")
753 offsetStr := r.URL.Query().Get("offset")
754 if numStr != "" {
755 num, err = strconv.Atoi(numStr)
756 if err != nil {
757 errors = append(errors, requestError{Slug: requestErrInvalidFormat, Param: "num"})
758 }
759 if num > maxEndpointResponseSize {
760 errors = append(errors, requestError{Slug: requestErrOverflow, Param: "num"})
761 }
762 }
763 if offsetStr != "" {
764 offset, err = strconv.Atoi(offsetStr)
765 if err != nil {
766 errors = append(errors, requestError{Slug: requestErrInvalidFormat, Param: "offset"})
767 }
768 }
769 if len(errors) > 0 {
770 encode(w, r, http.StatusBadRequest, response{Errors: errors})
771 return
772 }
773 endpoints, err := c.ListEndpoints(clientID, num, offset)
774 if err != nil {
775 errors = append(errors, requestError{Slug: requestErrActOfGod})
776 encode(w, r, http.StatusInternalServerError, response{Errors: errors})
777 return
778 }
779 resp := response{
780 Endpoints: endpoints,
781 Errors: errors,
782 }
783 encode(w, r, http.StatusOK, resp)
784 }
786 func clientCredentialsValidate(w http.ResponseWriter, r *http.Request, context Context) (scopes []string, profileID uuid.ID, valid bool) {
787 scopes = strings.Split(r.PostFormValue("scope"), " ")
788 valid = true
789 return
790 }
792 func clientCredentialsAuditString(r *http.Request) string {
793 return "client_credentials"
794 }