auth

Paddy 2015-01-18 Parent:fa8ee6a4507c Child:565a9335e035

116:e000b1c24fc0 Go to Latest

auth/client.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.1 --- a/client.go	Wed Jan 14 00:23:30 2015 -0500
     1.2 +++ b/client.go	Sun Jan 18 01:02:14 2015 -0500
     1.3 @@ -5,12 +5,15 @@
     1.4  	"encoding/hex"
     1.5  	"encoding/json"
     1.6  	"errors"
     1.7 -	"github.com/gorilla/mux"
     1.8 +	"log"
     1.9  	"net/http"
    1.10  	"net/url"
    1.11  	"strconv"
    1.12  	"time"
    1.13  
    1.14 +	"github.com/PuerkitoBio/purell"
    1.15 +	"github.com/gorilla/mux"
    1.16 +
    1.17  	"code.secondbit.org/uuid.hg"
    1.18  )
    1.19  
    1.20 @@ -37,24 +40,28 @@
    1.21  	ErrClientWebsiteTooLong = errors.New("client website must be at most 1024 characters")
    1.22  	// ErrClientWebsiteNotURL is returned when a Client's Website property is not a valid absolute URL.
    1.23  	ErrClientWebsiteNotURL = errors.New("client website must be a valid absolute URL")
    1.24 +	// ErrEndpointURINotURL is returned when an Endpoint's URI property is not a valid absolute URL.
    1.25 +	ErrEndpointURINotURL = errors.New("endpoint URI must be a valid absolute URL")
    1.26  )
    1.27  
    1.28  const (
    1.29  	clientTypePublic       = "public"
    1.30  	clientTypeConfidential = "confidential"
    1.31 +	minClientNameLen       = 2
    1.32 +	maxClientNameLen       = 24
    1.33  )
    1.34  
    1.35  // Client represents a client that grants access
    1.36  // to the auth server, exchanging grants for tokens,
    1.37  // and tokens for access.
    1.38  type Client struct {
    1.39 -	ID      uuid.ID
    1.40 -	Secret  string
    1.41 -	OwnerID uuid.ID
    1.42 -	Name    string
    1.43 -	Logo    string
    1.44 -	Website string
    1.45 -	Type    string
    1.46 +	ID      uuid.ID `json:"id,omitempty"`
    1.47 +	Secret  string  `json:"secret,omitempty"`
    1.48 +	OwnerID uuid.ID `json:"owner_id,omitempty"`
    1.49 +	Name    string  `json:"name,omitempty"`
    1.50 +	Logo    string  `json:"logo,omitempty"`
    1.51 +	Website string  `json:"website,omitempty"`
    1.52 +	Type    string  `json:"type,omitempty"`
    1.53  }
    1.54  
    1.55  // ApplyChange applies the properties of the passed
    1.56 @@ -169,10 +176,24 @@
    1.57  // following successful authorization grants and
    1.58  // exchanges for access tokens.
    1.59  type Endpoint struct {
    1.60 -	ID       uuid.ID
    1.61 -	ClientID uuid.ID
    1.62 -	URI      url.URL
    1.63 -	Added    time.Time
    1.64 +	ID            uuid.ID   `json:"id,omitempty"`
    1.65 +	ClientID      uuid.ID   `json:"client_id,omitempty"`
    1.66 +	URI           string    `json:"uri,omitempty"`
    1.67 +	NormalizedURI string    `json:"-"`
    1.68 +	Added         time.Time `json:"added,omitempty"`
    1.69 +}
    1.70 +
    1.71 +func normalizeURIString(in string) (string, error) {
    1.72 +	n, err := purell.NormalizeURLString(in, purell.FlagsUsuallySafeNonGreedy|purell.FlagSortQuery)
    1.73 +	if err != nil {
    1.74 +		log.Println(err)
    1.75 +		return in, ErrEndpointURINotURL
    1.76 +	}
    1.77 +	return n, nil
    1.78 +}
    1.79 +
    1.80 +func normalizeURI(in *url.URL) string {
    1.81 +	return purell.NormalizeURL(in, purell.FlagsUsuallySafeNonGreedy|purell.FlagSortQuery)
    1.82  }
    1.83  
    1.84  type sortedEndpoints []Endpoint
    1.85 @@ -304,7 +325,7 @@
    1.86  	m.endpointLock.RLock()
    1.87  	defer m.endpointLock.RUnlock()
    1.88  	for _, candidate := range m.endpoints[client.String()] {
    1.89 -		if endpoint == candidate.URI.String() {
    1.90 +		if endpoint == candidate.NormalizedURI {
    1.91  			return true, nil
    1.92  		}
    1.93  	}
    1.94 @@ -356,8 +377,19 @@
    1.95  		encode(w, r, http.StatusBadRequest, invalidFormatResponse)
    1.96  		return
    1.97  	}
    1.98 -	if req.Type != clientTypePublic && req.Type != clientTypeConfidential {
    1.99 +	if req.Type == "" {
   1.100 +		errors = append(errors, requestError{Slug: requestErrMissing, Field: "/type"})
   1.101 +	} else if req.Type != clientTypePublic && req.Type != clientTypeConfidential {
   1.102  		errors = append(errors, requestError{Slug: requestErrInvalidValue, Field: "/type"})
   1.103 +	}
   1.104 +	if req.Name == "" {
   1.105 +		errors = append(errors, requestError{Slug: requestErrMissing, Field: "/name"})
   1.106 +	} else if len(req.Name) < minClientNameLen {
   1.107 +		errors = append(errors, requestError{Slug: requestErrInsufficient, Field: "/name"})
   1.108 +	} else if len(req.Name) > maxClientNameLen {
   1.109 +		errors = append(errors, requestError{Slug: requestErrOverflow, Field: "/name"})
   1.110 +	}
   1.111 +	if len(errors) > 0 {
   1.112  		encode(w, r, http.StatusBadRequest, response{Errors: errors})
   1.113  		return
   1.114  	}
   1.115 @@ -395,10 +427,14 @@
   1.116  			errors = append(errors, requestError{Slug: requestErrInvalidFormat, Field: "/endpoints/" + strconv.Itoa(pos)})
   1.117  			continue
   1.118  		}
   1.119 +		if !uri.IsAbs() {
   1.120 +			errors = append(errors, requestError{Slug: requestErrInvalidValue, Field: "/endpoints/" + strconv.Itoa(pos)})
   1.121 +			continue
   1.122 +		}
   1.123  		endpoint := Endpoint{
   1.124  			ID:       uuid.NewID(),
   1.125  			ClientID: client.ID,
   1.126 -			URI:      *uri,
   1.127 +			URI:      uri.String(),
   1.128  			Added:    time.Now(),
   1.129  		}
   1.130  		endpoints = append(endpoints, endpoint)
   1.131 @@ -412,6 +448,7 @@
   1.132  	resp := response{
   1.133  		Clients:   []Client{client},
   1.134  		Endpoints: endpoints,
   1.135 +		Errors:    errors,
   1.136  	}
   1.137  	encode(w, r, http.StatusCreated, resp)
   1.138  }