auth

Paddy 2014-11-11 Parent:ade4f4afd898 Child:ff7bf5bd0df3

73:4ae226929e92 Browse Files

Rename http.go. We're going to have a lot of HTTP handlers, and I'd rather make it clear that this is taking care of our OAuth2 HTTP logic. So rename the file, and we'll put the API handlers in their files, or something.

http.go http_test.go oauth2.go oauth2_test.go

     1.1 --- a/http.go	Tue Nov 11 21:20:39 2014 -0500
     1.2 +++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.3 @@ -1,347 +0,0 @@
     1.4 -package auth
     1.5 -
     1.6 -import (
     1.7 -	"encoding/base64"
     1.8 -	"encoding/json"
     1.9 -	"errors"
    1.10 -	"html/template"
    1.11 -	"net/http"
    1.12 -	"net/url"
    1.13 -	"strings"
    1.14 -	"time"
    1.15 -
    1.16 -	"crypto/sha256"
    1.17 -	"code.secondbit.org/pass"
    1.18 -	"code.secondbit.org/uuid"
    1.19 -)
    1.20 -
    1.21 -const (
    1.22 -	authCookieName         = "auth"
    1.23 -	defaultGrantExpiration = 600 // default to ten minute grant expirations
    1.24 -	getGrantTemplateName   = "get_grant"
    1.25 -)
    1.26 -
    1.27 -var (
    1.28 -	// ErrNoAuth is returned when an Authorization header is not present or is empty.
    1.29 -	ErrNoAuth = errors.New("no authorization header supplied")
    1.30 -	// ErrInvalidAuthFormat is returned when an Authorization header is present but not the correct format.
    1.31 -	ErrInvalidAuthFormat = errors.New("authorization header is not in a valid format")
    1.32 -	// ErrIncorrectAuth is returned when a user authentication attempt does not match the stored values.
    1.33 -	ErrIncorrectAuth = errors.New("invalid authentication")
    1.34 -	// ErrInvalidPassphraseScheme is returned when an undefined passphrase scheme is used.
    1.35 -	ErrInvalidPassphraseScheme = errors.New("invalid passphrase scheme")
    1.36 -	// ErrNoSession is returned when no session ID is passed with a request.
    1.37 -	ErrNoSession = errors.New("no session ID found")
    1.38 -)
    1.39 -
    1.40 -type tokenResponse struct {
    1.41 -	AccessToken  string `json:"access_token"`
    1.42 -	TokenType    string `json:"token_type,omitempty"`
    1.43 -	ExpiresIn    int32  `json:"expires_in,omitempty"`
    1.44 -	RefreshToken string `json:"refresh_token,omitempty"`
    1.45 -}
    1.46 -
    1.47 -func getBasicAuth(r *http.Request) (un, pass string, err error) {
    1.48 -	auth := r.Header.Get("Authorization")
    1.49 -	if auth == "" {
    1.50 -		return "", "", ErrNoAuth
    1.51 -	}
    1.52 -	pieces := strings.SplitN(auth, " ", 2)
    1.53 -	if pieces[0] != "Basic" {
    1.54 -		return "", "", ErrInvalidAuthFormat
    1.55 -	}
    1.56 -	decoded, err := base64.StdEncoding.DecodeString(pieces[1])
    1.57 -	if err != nil {
    1.58 -		return "", "", ErrInvalidAuthFormat
    1.59 -	}
    1.60 -	info := strings.SplitN(string(decoded), ":", 2)
    1.61 -	return info[0], info[1], nil
    1.62 -}
    1.63 -
    1.64 -func checkCookie(r *http.Request, context Context) (Session, error) {
    1.65 -	cookie, err := r.Cookie(authCookieName)
    1.66 -	if err != nil {
    1.67 -		if err == http.ErrNoCookie {
    1.68 -			return Session{}, ErrNoSession
    1.69 -		}
    1.70 -		return Session{}, err
    1.71 -	}
    1.72 -	if cookie.Name != authCookieName || !cookie.Expires.After(time.Now()) ||
    1.73 -		!cookie.Secure || !cookie.HttpOnly {
    1.74 -		return Session{}, ErrInvalidSession
    1.75 -	}
    1.76 -	sess, err := context.GetSession(cookie.Value)
    1.77 -	if err == ErrSessionNotFound {
    1.78 -		return Session{}, ErrInvalidSession
    1.79 -	} else if err != nil {
    1.80 -		return Session{}, err
    1.81 -	}
    1.82 -	if !sess.Active {
    1.83 -		return Session{}, ErrInvalidSession
    1.84 -	}
    1.85 -	return sess, nil
    1.86 -}
    1.87 -
    1.88 -func authenticate(user, passphrase string, context Context) (Profile, error) {
    1.89 -	profile, err := context.GetProfileByLogin(user)
    1.90 -	if err != nil {
    1.91 -		if err == ErrProfileNotFound {
    1.92 -			return Profile{}, ErrIncorrectAuth
    1.93 -		}
    1.94 -		return Profile{}, err
    1.95 -	}
    1.96 -	switch profile.PassphraseScheme {
    1.97 -	case 1:
    1.98 -		candidate := pass.Check(sha256.New, profile.Iterations, []byte(passphrase), []byte(profile.Salt))
    1.99 -		if !pass.Compare(candidate, []byte(profile.Passphrase)) {
   1.100 -			return Profile{}, ErrIncorrectAuth
   1.101 -		}
   1.102 -	default:
   1.103 -		return Profile{}, ErrInvalidPassphraseScheme
   1.104 -	}
   1.105 -	return profile, nil
   1.106 -}
   1.107 -
   1.108 -// GetGrantHandler presents and processes the page for asking a user to grant access
   1.109 -// to their data. See RFC 6749, Section 4.1.
   1.110 -func GetGrantHandler(w http.ResponseWriter, r *http.Request, context Context) {
   1.111 -	session, err := checkCookie(r, context)
   1.112 -	if err != nil {
   1.113 -		if err == ErrNoSession {
   1.114 -			// TODO(paddy): redirect to login screen
   1.115 -			//return
   1.116 -		}
   1.117 -		if err == ErrInvalidSession {
   1.118 -			// TODO(paddy): return an access denied error
   1.119 -			//return
   1.120 -		}
   1.121 -		// TODO(paddy): return a server error
   1.122 -		//return
   1.123 -	}
   1.124 -	if r.URL.Query().Get("client_id") == "" {
   1.125 -		w.WriteHeader(http.StatusBadRequest)
   1.126 -		context.Render(w, getGrantTemplateName, map[string]interface{}{
   1.127 -			"error": template.HTML("Client ID must be specified in the request."),
   1.128 -		})
   1.129 -		return
   1.130 -	}
   1.131 -	clientID, err := uuid.Parse(r.URL.Query().Get("client_id"))
   1.132 -	if err != nil {
   1.133 -		w.WriteHeader(http.StatusBadRequest)
   1.134 -		context.Render(w, getGrantTemplateName, map[string]interface{}{
   1.135 -			"error": template.HTML("client_id is not a valid Client ID."),
   1.136 -		})
   1.137 -		return
   1.138 -	}
   1.139 -	redirectURI := r.URL.Query().Get("redirect_uri")
   1.140 -	redirectURL, err := url.Parse(redirectURI)
   1.141 -	if err != nil {
   1.142 -		w.WriteHeader(http.StatusBadRequest)
   1.143 -		context.Render(w, getGrantTemplateName, map[string]interface{}{
   1.144 -			"error": template.HTML("The redirect_uri specified is not valid."),
   1.145 -		})
   1.146 -		return
   1.147 -	}
   1.148 -	client, err := context.GetClient(clientID)
   1.149 -	if err != nil {
   1.150 -		if err == ErrClientNotFound {
   1.151 -			w.WriteHeader(http.StatusBadRequest)
   1.152 -			context.Render(w, getGrantTemplateName, map[string]interface{}{
   1.153 -				"error": template.HTML("The specified Client couldn’t be found."),
   1.154 -			})
   1.155 -		} else {
   1.156 -			w.WriteHeader(http.StatusInternalServerError)
   1.157 -			context.Render(w, getGrantTemplateName, map[string]interface{}{
   1.158 -				"internal_error": template.HTML(err.Error()),
   1.159 -			})
   1.160 -		}
   1.161 -		return
   1.162 -	}
   1.163 -	// whether a redirect URI is valid or not depends on the number of endpoints
   1.164 -	// the client has registered
   1.165 -	numEndpoints, err := context.CountEndpoints(clientID)
   1.166 -	if err != nil {
   1.167 -		w.WriteHeader(http.StatusInternalServerError)
   1.168 -		context.Render(w, getGrantTemplateName, map[string]interface{}{
   1.169 -			"internal_error": template.HTML(err.Error()),
   1.170 -		})
   1.171 -		return
   1.172 -	}
   1.173 -	var validURI bool
   1.174 -	if redirectURI != "" {
   1.175 -		// BUG(paddy): We really should normalize URIs before trying to compare them.
   1.176 -		validURI, err = context.CheckEndpoint(clientID, redirectURI)
   1.177 -		if err != nil {
   1.178 -			w.WriteHeader(http.StatusInternalServerError)
   1.179 -			context.Render(w, getGrantTemplateName, map[string]interface{}{
   1.180 -				"internal_error": template.HTML(err.Error()),
   1.181 -			})
   1.182 -			return
   1.183 -		}
   1.184 -	} else if redirectURI == "" && numEndpoints == 1 {
   1.185 -		// if we don't specify the endpoint and there's only one endpoint, the
   1.186 -		// request is valid, and we're redirecting to that one endpoint
   1.187 -		validURI = true
   1.188 -		endpoints, err := context.ListEndpoints(clientID, 1, 0)
   1.189 -		if err != nil {
   1.190 -			w.WriteHeader(http.StatusInternalServerError)
   1.191 -			context.Render(w, getGrantTemplateName, map[string]interface{}{
   1.192 -				"internal_error": template.HTML(err.Error()),
   1.193 -			})
   1.194 -			return
   1.195 -		}
   1.196 -		if len(endpoints) != 1 {
   1.197 -			validURI = false
   1.198 -		} else {
   1.199 -			u := endpoints[0].URI // Copy it here to avoid grabbing a pointer to the memstore
   1.200 -			redirectURI = u.String()
   1.201 -			redirectURL = &u
   1.202 -		}
   1.203 -	} else {
   1.204 -		validURI = false
   1.205 -	}
   1.206 -	if !validURI {
   1.207 -		w.WriteHeader(http.StatusBadRequest)
   1.208 -		context.Render(w, getGrantTemplateName, map[string]interface{}{
   1.209 -			"error": template.HTML("The redirect_uri specified is not valid."),
   1.210 -		})
   1.211 -		return
   1.212 -	}
   1.213 -	scope := r.URL.Query().Get("scope")
   1.214 -	state := r.URL.Query().Get("state")
   1.215 -	if r.URL.Query().Get("response_type") != "code" {
   1.216 -		q := redirectURL.Query()
   1.217 -		q.Add("error", "invalid_request")
   1.218 -		q.Add("state", state)
   1.219 -		redirectURL.RawQuery = q.Encode()
   1.220 -		http.Redirect(w, r, redirectURL.String(), http.StatusFound)
   1.221 -		return
   1.222 -	}
   1.223 -	if r.Method == "POST" {
   1.224 -		// BUG(paddy): We need to implement CSRF protection when obtaining a grant code.
   1.225 -		if r.PostFormValue("grant") == "approved" {
   1.226 -			code := uuid.NewID().String()
   1.227 -			grant := Grant{
   1.228 -				Code:        code,
   1.229 -				Created:     time.Now(),
   1.230 -				ExpiresIn:   defaultGrantExpiration,
   1.231 -				ClientID:    clientID,
   1.232 -				Scope:       scope,
   1.233 -				RedirectURI: r.URL.Query().Get("redirect_uri"),
   1.234 -				State:       state,
   1.235 -				ProfileID:   session.ProfileID,
   1.236 -			}
   1.237 -			err := context.SaveGrant(grant)
   1.238 -			if err != nil {
   1.239 -				q := redirectURL.Query()
   1.240 -				q.Add("error", "server_error")
   1.241 -				q.Add("state", state)
   1.242 -				redirectURL.RawQuery = q.Encode()
   1.243 -				http.Redirect(w, r, redirectURL.String(), http.StatusFound)
   1.244 -				return
   1.245 -			}
   1.246 -			q := redirectURL.Query()
   1.247 -			q.Add("code", code)
   1.248 -			q.Add("state", state)
   1.249 -			redirectURL.RawQuery = q.Encode()
   1.250 -			http.Redirect(w, r, redirectURL.String(), http.StatusFound)
   1.251 -			return
   1.252 -		}
   1.253 -		q := redirectURL.Query()
   1.254 -		q.Add("error", "access_denied")
   1.255 -		q.Add("state", state)
   1.256 -		redirectURL.RawQuery = q.Encode()
   1.257 -		http.Redirect(w, r, redirectURL.String(), http.StatusFound)
   1.258 -		return
   1.259 -	}
   1.260 -	w.WriteHeader(http.StatusOK)
   1.261 -	context.Render(w, getGrantTemplateName, map[string]interface{}{
   1.262 -		"client": client,
   1.263 -	})
   1.264 -}
   1.265 -
   1.266 -// GetTokenHandler allows a client to exchange an authorization grant for an
   1.267 -// access token. See RFC 6749 Section 4.1.3.
   1.268 -func GetTokenHandler(w http.ResponseWriter, r *http.Request, context Context) {
   1.269 -	enc := json.NewEncoder(w)
   1.270 -	grantType := r.PostFormValue("grant_type")
   1.271 -	if grantType != "authorization_code" {
   1.272 -		// TODO(paddy): render invalid request JSON
   1.273 -		return
   1.274 -	}
   1.275 -	code := r.PostFormValue("code")
   1.276 -	if code == "" {
   1.277 -		// TODO(paddy): render invalid request JSON
   1.278 -		return
   1.279 -	}
   1.280 -	redirectURI := r.PostFormValue("redirect_uri")
   1.281 -	clientIDStr, clientSecret, err := getBasicAuth(r)
   1.282 -	if err != nil {
   1.283 -		// TODO(paddy): render access denied
   1.284 -		return
   1.285 -	}
   1.286 -	if clientIDStr == "" && err == nil {
   1.287 -		clientIDStr = r.PostFormValue("client_id")
   1.288 -	}
   1.289 -	clientID, err := uuid.Parse(clientIDStr)
   1.290 -	if err != nil {
   1.291 -		// TODO(paddy): render invalid request JSON
   1.292 -		return
   1.293 -	}
   1.294 -	client, err := context.GetClient(clientID)
   1.295 -	if err != nil {
   1.296 -		if err == ErrClientNotFound {
   1.297 -			// TODO(paddy): render invalid request JSON
   1.298 -		} else {
   1.299 -			// TODO(paddy): render internal server error JSON
   1.300 -		}
   1.301 -		return
   1.302 -	}
   1.303 -	if client.Secret != clientSecret {
   1.304 -		// TODO(paddy): render invalid request JSON
   1.305 -		return
   1.306 -	}
   1.307 -	grant, err := context.GetGrant(code)
   1.308 -	if err != nil {
   1.309 -		if err == ErrGrantNotFound {
   1.310 -			// TODO(paddy): return error
   1.311 -			return
   1.312 -		}
   1.313 -		// TODO(paddy): return error
   1.314 -	}
   1.315 -	if grant.RedirectURI != redirectURI {
   1.316 -		// TODO(paddy): return error
   1.317 -	}
   1.318 -	if !grant.ClientID.Equal(clientID) {
   1.319 -		// TODO(paddy): return error
   1.320 -	}
   1.321 -	token := Token{
   1.322 -		AccessToken:  uuid.NewID().String(),
   1.323 -		RefreshToken: uuid.NewID().String(),
   1.324 -		Created:      time.Now(),
   1.325 -		ExpiresIn:    defaultTokenExpiration,
   1.326 -		TokenType:    "", // TODO(paddy): fill in token type
   1.327 -		Scope:        grant.Scope,
   1.328 -		ProfileID:    grant.ProfileID,
   1.329 -	}
   1.330 -	err = context.SaveToken(token)
   1.331 -	if err != nil {
   1.332 -		// TODO(paddy): return error
   1.333 -	}
   1.334 -	resp := tokenResponse{
   1.335 -		AccessToken:  token.AccessToken,
   1.336 -		RefreshToken: token.RefreshToken,
   1.337 -		ExpiresIn:    token.ExpiresIn,
   1.338 -		TokenType:    token.TokenType,
   1.339 -	}
   1.340 -	err = enc.Encode(resp)
   1.341 -	if err != nil {
   1.342 -		// TODO(paddy): log this or something
   1.343 -		return
   1.344 -	}
   1.345 -}
   1.346 -
   1.347 -// TODO(paddy): exchange user credentials for access token
   1.348 -// TODO(paddy): exchange client credentials for access token
   1.349 -// TODO(paddy): implicit grant for access token
   1.350 -// TODO(paddy): exchange refresh token for access token
     2.1 --- a/http_test.go	Tue Nov 11 21:20:39 2014 -0500
     2.2 +++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
     2.3 @@ -1,451 +0,0 @@
     2.4 -package auth
     2.5 -
     2.6 -import (
     2.7 -	"bytes"
     2.8 -	"html/template"
     2.9 -	"io/ioutil"
    2.10 -	"net/http"
    2.11 -	"net/http/httptest"
    2.12 -	"net/url"
    2.13 -	"testing"
    2.14 -	"time"
    2.15 -
    2.16 -	"code.secondbit.org/uuid"
    2.17 -)
    2.18 -
    2.19 -const (
    2.20 -	scopeSet = 1 << iota
    2.21 -	stateSet
    2.22 -	uriSet
    2.23 -)
    2.24 -
    2.25 -func stripParam(param string, u *url.URL) {
    2.26 -	q := u.Query()
    2.27 -	q.Del(param)
    2.28 -	u.RawQuery = q.Encode()
    2.29 -}
    2.30 -
    2.31 -func TestGetGrantCodeSuccess(t *testing.T) {
    2.32 -	t.Parallel()
    2.33 -	store := NewMemstore()
    2.34 -	testContext := Context{
    2.35 -		template: template.Must(template.New(getGrantTemplateName).Parse("Get auth grant")),
    2.36 -		clients:  store,
    2.37 -		grants:   store,
    2.38 -		profiles: store,
    2.39 -		tokens:   store,
    2.40 -	}
    2.41 -	client := Client{
    2.42 -		ID:      uuid.NewID(),
    2.43 -		Secret:  "super secret!",
    2.44 -		OwnerID: uuid.NewID(),
    2.45 -		Name:    "My test client",
    2.46 -		Logo:    "https://secondbit.org/logo.png",
    2.47 -		Website: "https://secondbit.org",
    2.48 -		Type:    "public",
    2.49 -	}
    2.50 -	uri, err := url.Parse("https://test.secondbit.org/redirect")
    2.51 -	if err != nil {
    2.52 -		t.Fatal("Can't parse URL:", err)
    2.53 -	}
    2.54 -	endpoint := Endpoint{
    2.55 -		ID:       uuid.NewID(),
    2.56 -		ClientID: client.ID,
    2.57 -		URI:      *uri,
    2.58 -		Added:    time.Now(),
    2.59 -	}
    2.60 -	err = testContext.SaveClient(client)
    2.61 -	if err != nil {
    2.62 -		t.Fatal("Can't store client:", err)
    2.63 -	}
    2.64 -	err = testContext.AddEndpoint(client.ID, endpoint)
    2.65 -	if err != nil {
    2.66 -		t.Fatal("Can't store endpoint:", err)
    2.67 -	}
    2.68 -	req, err := http.NewRequest("GET", "https://test.auth.secondbit.org/oauth2/grant", nil)
    2.69 -	if err != nil {
    2.70 -		t.Fatal("Can't build request:", err)
    2.71 -	}
    2.72 -	for i := 0; i < 1<<3; i++ {
    2.73 -		w := httptest.NewRecorder()
    2.74 -		params := url.Values{}
    2.75 -		// see OAuth 2.0 spec, section 4.1.1
    2.76 -		params.Set("response_type", "code")
    2.77 -		params.Set("client_id", client.ID.String())
    2.78 -		if i&uriSet != 0 {
    2.79 -			params.Set("redirect_uri", endpoint.URI.String())
    2.80 -		}
    2.81 -		if i&scopeSet != 0 {
    2.82 -			params.Set("scope", "testscope")
    2.83 -		}
    2.84 -		if i&stateSet != 0 {
    2.85 -			params.Set("state", "my super secure state string")
    2.86 -		}
    2.87 -		req.URL.RawQuery = params.Encode()
    2.88 -		req.Method = "GET"
    2.89 -		req.Body = nil
    2.90 -		req.Header.Del("Content-Type")
    2.91 -		GetGrantHandler(w, req, testContext)
    2.92 -		if w.Code != http.StatusOK {
    2.93 -			t.Errorf("Expected status code to be %d, got %d for %s", http.StatusOK, w.Code, req.URL.String())
    2.94 -		}
    2.95 -		if w.Body.String() != "Get auth grant" {
    2.96 -			t.Errorf("Expected body to be `%s`, got `%s` for %s", "Get auth grant", w.Body.String(), req.URL.String())
    2.97 -		}
    2.98 -		req.Method = "POST"
    2.99 -		req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
   2.100 -		w = httptest.NewRecorder()
   2.101 -		data := url.Values{}
   2.102 -		data.Set("grant", "approved")
   2.103 -		body := bytes.NewBufferString(data.Encode())
   2.104 -		req.Body = ioutil.NopCloser(body)
   2.105 -		GetGrantHandler(w, req, testContext)
   2.106 -		if w.Code != http.StatusFound {
   2.107 -			t.Errorf("Expected status code to be %d, got %d for %s", http.StatusFound, w.Code, req.URL.String())
   2.108 -		}
   2.109 -		redirectedTo := w.Header().Get("Location")
   2.110 -		red, err := url.Parse(redirectedTo)
   2.111 -		if err != nil {
   2.112 -			t.Fatalf(`Being redirected to a non-URL "%s" threw error "%s" for "%s"\n`, redirectedTo, err, req.URL.String())
   2.113 -		}
   2.114 -		t.Log("Redirected to", redirectedTo)
   2.115 -		if red.Query().Get("code") == "" {
   2.116 -			t.Fatalf(`Expected code param in redirect URL to be set, but it wasn't for %s`, req.URL.String())
   2.117 -		}
   2.118 -		if _, err := testContext.GetGrant(red.Query().Get("code")); err != nil {
   2.119 -			t.Fatalf(`Unexpected error "%s: retrieving the grant "%s" supplied in the redirect URL for %s`, err, red.Query().Get("code"), req.URL.String())
   2.120 -		}
   2.121 -		err = testContext.DeleteGrant(red.Query().Get("code"))
   2.122 -		if err != nil {
   2.123 -			t.Log(`Unexpected error "%s" deleting grant "%s" for %s`, err, red.Query().Get("code"), req.URL.String())
   2.124 -		}
   2.125 -		stripParam("code", red)
   2.126 -		if red.Query().Get("state") != params.Get("state") {
   2.127 -			t.Errorf(`Expected state param in redirect URL to be "%s", got "%s" for %s`, params.Get("state"), red.Query().Get("state"), req.URL.String())
   2.128 -		}
   2.129 -		stripParam("state", red)
   2.130 -		if red.String() != endpoint.URI.String() {
   2.131 -			t.Errorf(`Expected redirect URL to be "%s", got "%s"`, endpoint.URI.String(), red.String())
   2.132 -		}
   2.133 -	}
   2.134 -}
   2.135 -
   2.136 -func TestGetGrantCodeInvalidClient(t *testing.T) {
   2.137 -	t.Parallel()
   2.138 -	store := NewMemstore()
   2.139 -	testContext := Context{
   2.140 -		template: template.Must(template.New(getGrantTemplateName).Parse("{{ .error }}")),
   2.141 -		clients:  store,
   2.142 -		grants:   store,
   2.143 -		profiles: store,
   2.144 -		tokens:   store,
   2.145 -	}
   2.146 -	client := Client{
   2.147 -		ID:      uuid.NewID(),
   2.148 -		Secret:  "super secret!",
   2.149 -		OwnerID: uuid.NewID(),
   2.150 -		Name:    "My test client",
   2.151 -		Type:    "public",
   2.152 -	}
   2.153 -	err := testContext.SaveClient(client)
   2.154 -	if err != nil {
   2.155 -		t.Fatal("Can't store client:", err)
   2.156 -	}
   2.157 -	req, err := http.NewRequest("GET", "https://test.auth.secondbit.org/oauth2/grant", nil)
   2.158 -	if err != nil {
   2.159 -		t.Fatal("Can't build request:", err)
   2.160 -	}
   2.161 -	w := httptest.NewRecorder()
   2.162 -	params := url.Values{}
   2.163 -	params.Set("response_type", "code")
   2.164 -	params.Set("redirect_uri", "https://test.secondbit.org/")
   2.165 -	req.URL.RawQuery = params.Encode()
   2.166 -	GetGrantHandler(w, req, testContext)
   2.167 -	if w.Code != http.StatusBadRequest {
   2.168 -		t.Errorf("Expected status code to be %d, got %d", http.StatusBadRequest, w.Code)
   2.169 -	}
   2.170 -	if w.Body.String() != "Client ID must be specified in the request." {
   2.171 -		t.Errorf(`Expected output to be "%s", got "%s" instead.`, "Client ID must be specified in the request.", w.Body.String())
   2.172 -	}
   2.173 -	w = httptest.NewRecorder()
   2.174 -	params.Set("client_id", "Not an ID")
   2.175 -	req.URL.RawQuery = params.Encode()
   2.176 -	GetGrantHandler(w, req, testContext)
   2.177 -	if w.Code != http.StatusBadRequest {
   2.178 -		t.Errorf("Expected status code to be %d, got %d", http.StatusBadRequest, w.Code)
   2.179 -	}
   2.180 -	if w.Body.String() != "client_id is not a valid Client ID." {
   2.181 -		t.Errorf(`Expected output to be "%s", got "%s" instead.`, "client_id is not a valid Client ID.", w.Body.String())
   2.182 -	}
   2.183 -	w = httptest.NewRecorder()
   2.184 -	params.Set("client_id", uuid.NewID().String())
   2.185 -	req.URL.RawQuery = params.Encode()
   2.186 -	GetGrantHandler(w, req, testContext)
   2.187 -	if w.Code != http.StatusBadRequest {
   2.188 -		t.Errorf("Expected status code to be %d, got %d", http.StatusBadRequest, w.Code)
   2.189 -	}
   2.190 -	if w.Body.String() != "The specified Client couldn&rsquo;t be found." {
   2.191 -		t.Errorf(`Expected output to be "%s", got "%s" instead.`, "The specified Client couldn&rsquo;t be found.", w.Body.String())
   2.192 -	}
   2.193 -}
   2.194 -
   2.195 -func TestGetGrantCodeInvalidURI(t *testing.T) {
   2.196 -	t.Parallel()
   2.197 -	store := NewMemstore()
   2.198 -	testContext := Context{
   2.199 -		template: template.Must(template.New(getGrantTemplateName).Parse("{{ .error }}")),
   2.200 -		clients:  store,
   2.201 -		grants:   store,
   2.202 -		profiles: store,
   2.203 -		tokens:   store,
   2.204 -	}
   2.205 -	client := Client{
   2.206 -		ID:      uuid.NewID(),
   2.207 -		Secret:  "super secret!",
   2.208 -		OwnerID: uuid.NewID(),
   2.209 -		Name:    "My test client",
   2.210 -		Type:    "public",
   2.211 -	}
   2.212 -	uri, err := url.Parse("https://test.secondbit.org/redirect")
   2.213 -	if err != nil {
   2.214 -		t.Fatal("Can't parse URL:", err)
   2.215 -	}
   2.216 -	err = testContext.SaveClient(client)
   2.217 -	if err != nil {
   2.218 -		t.Fatal("Can't store client:", err)
   2.219 -	}
   2.220 -	req, err := http.NewRequest("GET", "https://test.auth.secondbit.org/oauth2/grant", nil)
   2.221 -	if err != nil {
   2.222 -		t.Fatal("Can't build request:", err)
   2.223 -	}
   2.224 -	w := httptest.NewRecorder()
   2.225 -	params := url.Values{}
   2.226 -	params.Set("response_type", "code")
   2.227 -	params.Set("client_id", client.ID.String())
   2.228 -	req.URL.RawQuery = params.Encode()
   2.229 -	GetGrantHandler(w, req, testContext)
   2.230 -	if w.Code != http.StatusBadRequest {
   2.231 -		t.Errorf("Expected status code to be %d, got %d", http.StatusBadRequest, w.Code)
   2.232 -	}
   2.233 -	if w.Body.String() != "The redirect_uri specified is not valid." {
   2.234 -		t.Errorf(`Expected output to be "%s", got "%s" instead.`, "The redirect_uri specified is not valid.", w.Body.String())
   2.235 -	}
   2.236 -	endpoint := Endpoint{
   2.237 -		ID:       uuid.NewID(),
   2.238 -		ClientID: client.ID,
   2.239 -		URI:      *uri,
   2.240 -		Added:    time.Now(),
   2.241 -	}
   2.242 -	err = testContext.AddEndpoint(client.ID, endpoint)
   2.243 -	if err != nil {
   2.244 -		t.Fatal("Can't store endpoint:", err)
   2.245 -	}
   2.246 -	w = httptest.NewRecorder()
   2.247 -	params.Set("redirect_uri", "https://test.secondbit.org/wrong")
   2.248 -	req.URL.RawQuery = params.Encode()
   2.249 -	GetGrantHandler(w, req, testContext)
   2.250 -	if w.Code != http.StatusBadRequest {
   2.251 -		t.Errorf("Expected status code to be %d, got %d", http.StatusBadRequest, w.Code)
   2.252 -	}
   2.253 -	if w.Body.String() != "The redirect_uri specified is not valid." {
   2.254 -		t.Errorf(`Expected output to be "%s", got "%s" instead.`, "The redirect_uri specified is not valid.", w.Body.String())
   2.255 -	}
   2.256 -	endpoint2 := Endpoint{
   2.257 -		ID:       uuid.NewID(),
   2.258 -		ClientID: client.ID,
   2.259 -		URI:      *uri,
   2.260 -		Added:    time.Now(),
   2.261 -	}
   2.262 -	err = testContext.AddEndpoint(client.ID, endpoint2)
   2.263 -	if err != nil {
   2.264 -		t.Fatal("Can't store endpoint:", err)
   2.265 -	}
   2.266 -	w = httptest.NewRecorder()
   2.267 -	params.Set("redirect_uri", "")
   2.268 -	req.URL.RawQuery = params.Encode()
   2.269 -	GetGrantHandler(w, req, testContext)
   2.270 -	if w.Code != http.StatusBadRequest {
   2.271 -		t.Errorf("Expected status code to be %d, got %d", http.StatusBadRequest, w.Code)
   2.272 -	}
   2.273 -	if w.Body.String() != "The redirect_uri specified is not valid." {
   2.274 -		t.Errorf(`Expected output to be "%s", got "%s" instead.`, "The redirect_uri specified is not valid.", w.Body.String())
   2.275 -	}
   2.276 -	w = httptest.NewRecorder()
   2.277 -	params.Set("redirect_uri", "://not a URL")
   2.278 -	req.URL.RawQuery = params.Encode()
   2.279 -	GetGrantHandler(w, req, testContext)
   2.280 -	if w.Code != http.StatusBadRequest {
   2.281 -		t.Errorf("Expected status code to be %d, got %d", http.StatusBadRequest, w.Code)
   2.282 -	}
   2.283 -	if w.Body.String() != "The redirect_uri specified is not valid." {
   2.284 -		t.Errorf(`Expected output to be "%s", got "%s" instead.`, "The redirect_uri specified is not valid.", w.Body.String())
   2.285 -	}
   2.286 -}
   2.287 -
   2.288 -func TestGetGrantCodeInvalidResponseType(t *testing.T) {
   2.289 -	t.Parallel()
   2.290 -	store := NewMemstore()
   2.291 -	testContext := Context{
   2.292 -		template: template.Must(template.New(getGrantTemplateName).Parse("{{ .error }}")),
   2.293 -		clients:  store,
   2.294 -		grants:   store,
   2.295 -		profiles: store,
   2.296 -		tokens:   store,
   2.297 -	}
   2.298 -	client := Client{
   2.299 -		ID:      uuid.NewID(),
   2.300 -		Secret:  "super secret!",
   2.301 -		OwnerID: uuid.NewID(),
   2.302 -		Name:    "My test client",
   2.303 -		Logo:    "https://secondbit.org/logo.png",
   2.304 -		Website: "https://secondbit.org",
   2.305 -		Type:    "public",
   2.306 -	}
   2.307 -	uri, err := url.Parse("https://test.secondbit.org/redirect")
   2.308 -	if err != nil {
   2.309 -		t.Fatal("Can't parse URL:", err)
   2.310 -	}
   2.311 -	endpoint := Endpoint{
   2.312 -		ID:       uuid.NewID(),
   2.313 -		ClientID: client.ID,
   2.314 -		URI:      *uri,
   2.315 -		Added:    time.Now(),
   2.316 -	}
   2.317 -	err = testContext.SaveClient(client)
   2.318 -	if err != nil {
   2.319 -		t.Fatal("Can't store client:", err)
   2.320 -	}
   2.321 -	err = testContext.AddEndpoint(client.ID, endpoint)
   2.322 -	if err != nil {
   2.323 -		t.Fatal("Can't store endpoint:", err)
   2.324 -	}
   2.325 -	req, err := http.NewRequest("GET", "https://test.auth.secondbit.org/oauth2/grant", nil)
   2.326 -	if err != nil {
   2.327 -		t.Fatal("Can't build request:", err)
   2.328 -	}
   2.329 -	params := url.Values{}
   2.330 -	params.Set("response_type", "totally not code")
   2.331 -	params.Set("client_id", client.ID.String())
   2.332 -	params.Set("redirect_uri", endpoint.URI.String())
   2.333 -	params.Set("scope", "testscope")
   2.334 -	params.Set("state", "my super secure state string")
   2.335 -	req.URL.RawQuery = params.Encode()
   2.336 -	w := httptest.NewRecorder()
   2.337 -	GetGrantHandler(w, req, testContext)
   2.338 -	if w.Code != http.StatusFound {
   2.339 -		t.Errorf("Expected status code to be %d, got %d", http.StatusFound, w.Code)
   2.340 -	}
   2.341 -	redirectedTo := w.Header().Get("Location")
   2.342 -	red, err := url.Parse(redirectedTo)
   2.343 -	if err != nil {
   2.344 -		t.Fatalf("Being redirected to a non-URL (%s) threw error: %s\n", redirectedTo, err)
   2.345 -	}
   2.346 -	if red.Query().Get("error") != "invalid_request" {
   2.347 -		t.Errorf(`Expected error param in redirect URL to be "%s", got "%s"`, "invalid_request", red.Query().Get("error"))
   2.348 -	}
   2.349 -	stripParam("error", red)
   2.350 -	if red.Query().Get("state") != params.Get("state") {
   2.351 -		t.Errorf(`Expected state param in redirect URL to be "%s", got "%s"`, params.Get("state"), red.Query().Get("state"))
   2.352 -	}
   2.353 -	stripParam("state", red)
   2.354 -	if red.String() != endpoint.URI.String() {
   2.355 -		t.Errorf(`Expected redirect URL to be "%s", got "%s"`, endpoint.URI.String(), red.String())
   2.356 -	}
   2.357 -	stripParam("response_type", req.URL)
   2.358 -	w = httptest.NewRecorder()
   2.359 -	GetGrantHandler(w, req, testContext)
   2.360 -	if w.Code != http.StatusFound {
   2.361 -		t.Errorf("Expected status code to be %d, got %d", http.StatusFound, w.Code)
   2.362 -	}
   2.363 -	redirectedTo = w.Header().Get("Location")
   2.364 -	red, err = url.Parse(redirectedTo)
   2.365 -	if err != nil {
   2.366 -		t.Fatalf("Being redirected to a non-URL (%s) threw error: %s\n", redirectedTo, err)
   2.367 -	}
   2.368 -	if red.Query().Get("error") != "invalid_request" {
   2.369 -		t.Errorf(`Expected error param in redirect URL to be "%s", got "%s"`, "invalid_request", red.Query().Get("error"))
   2.370 -	}
   2.371 -	stripParam("error", red)
   2.372 -	if red.Query().Get("state") != params.Get("state") {
   2.373 -		t.Errorf(`Expected state param in redirect URL to be "%s", got "%s"`, params.Get("state"), red.Query().Get("state"))
   2.374 -	}
   2.375 -	stripParam("state", red)
   2.376 -	if red.String() != endpoint.URI.String() {
   2.377 -		t.Errorf(`Expected redirect URL to be "%s", got "%s"`, endpoint.URI.String(), red.String())
   2.378 -	}
   2.379 -}
   2.380 -
   2.381 -func TestGetGrantCodeDenied(t *testing.T) {
   2.382 -	t.Parallel()
   2.383 -	store := NewMemstore()
   2.384 -	testContext := Context{
   2.385 -		template: template.Must(template.New(getGrantTemplateName).Parse("{{ .error }}")),
   2.386 -		clients:  store,
   2.387 -		grants:   store,
   2.388 -		profiles: store,
   2.389 -		tokens:   store,
   2.390 -	}
   2.391 -	client := Client{
   2.392 -		ID:      uuid.NewID(),
   2.393 -		Secret:  "super secret!",
   2.394 -		OwnerID: uuid.NewID(),
   2.395 -		Name:    "My test client",
   2.396 -		Logo:    "https://secondbit.org/logo.png",
   2.397 -		Website: "https://secondbit.org",
   2.398 -		Type:    "public",
   2.399 -	}
   2.400 -	uri, err := url.Parse("https://test.secondbit.org/redirect")
   2.401 -	if err != nil {
   2.402 -		t.Fatal("Can't parse URL:", err)
   2.403 -	}
   2.404 -	endpoint := Endpoint{
   2.405 -		ID:       uuid.NewID(),
   2.406 -		ClientID: client.ID,
   2.407 -		URI:      *uri,
   2.408 -		Added:    time.Now(),
   2.409 -	}
   2.410 -	err = testContext.SaveClient(client)
   2.411 -	if err != nil {
   2.412 -		t.Fatal("Can't store client:", err)
   2.413 -	}
   2.414 -	err = testContext.AddEndpoint(client.ID, endpoint)
   2.415 -	if err != nil {
   2.416 -		t.Fatal("Can't store endpoint:", err)
   2.417 -	}
   2.418 -	req, err := http.NewRequest("GET", "https://test.auth.secondbit.org/oauth2/grant", nil)
   2.419 -	if err != nil {
   2.420 -		t.Fatal("Can't build request:", err)
   2.421 -	}
   2.422 -	params := url.Values{}
   2.423 -	params.Set("response_type", "code")
   2.424 -	params.Set("client_id", client.ID.String())
   2.425 -	params.Set("redirect_uri", endpoint.URI.String())
   2.426 -	params.Set("scope", "testscope")
   2.427 -	params.Set("state", "my super secure state string")
   2.428 -	data := url.Values{}
   2.429 -	data.Set("grant", "denied")
   2.430 -	req.URL.RawQuery = params.Encode()
   2.431 -	req.Body = ioutil.NopCloser(bytes.NewBufferString(data.Encode()))
   2.432 -	req.Method = "POST"
   2.433 -	w := httptest.NewRecorder()
   2.434 -	GetGrantHandler(w, req, testContext)
   2.435 -	if w.Code != http.StatusFound {
   2.436 -		t.Errorf("Expected status code to be %d, got %d", http.StatusFound, w.Code)
   2.437 -	}
   2.438 -	redirectedTo := w.Header().Get("Location")
   2.439 -	red, err := url.Parse(redirectedTo)
   2.440 -	if err != nil {
   2.441 -		t.Fatalf("Being redirected to a non-URL (%s) threw error: %s\n", redirectedTo, err)
   2.442 -	}
   2.443 -	if red.Query().Get("error") != "access_denied" {
   2.444 -		t.Errorf(`Expected error param in redirect URL to be "%s", got "%s"`, "access_denied", red.Query().Get("error"))
   2.445 -	}
   2.446 -	stripParam("error", red)
   2.447 -	if red.Query().Get("state") != params.Get("state") {
   2.448 -		t.Errorf(`Expected state param in redirect URL to be "%s", got "%s"`, params.Get("state"), red.Query().Get("state"))
   2.449 -	}
   2.450 -	stripParam("state", red)
   2.451 -	if red.String() != endpoint.URI.String() {
   2.452 -		t.Errorf(`Expected redirect URL to be "%s", got "%s"`, endpoint.URI.String(), red.String())
   2.453 -	}
   2.454 -}
     3.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     3.2 +++ b/oauth2.go	Tue Nov 11 21:22:57 2014 -0500
     3.3 @@ -0,0 +1,347 @@
     3.4 +package auth
     3.5 +
     3.6 +import (
     3.7 +	"encoding/base64"
     3.8 +	"encoding/json"
     3.9 +	"errors"
    3.10 +	"html/template"
    3.11 +	"net/http"
    3.12 +	"net/url"
    3.13 +	"strings"
    3.14 +	"time"
    3.15 +
    3.16 +	"crypto/sha256"
    3.17 +	"code.secondbit.org/pass"
    3.18 +	"code.secondbit.org/uuid"
    3.19 +)
    3.20 +
    3.21 +const (
    3.22 +	authCookieName         = "auth"
    3.23 +	defaultGrantExpiration = 600 // default to ten minute grant expirations
    3.24 +	getGrantTemplateName   = "get_grant"
    3.25 +)
    3.26 +
    3.27 +var (
    3.28 +	// ErrNoAuth is returned when an Authorization header is not present or is empty.
    3.29 +	ErrNoAuth = errors.New("no authorization header supplied")
    3.30 +	// ErrInvalidAuthFormat is returned when an Authorization header is present but not the correct format.
    3.31 +	ErrInvalidAuthFormat = errors.New("authorization header is not in a valid format")
    3.32 +	// ErrIncorrectAuth is returned when a user authentication attempt does not match the stored values.
    3.33 +	ErrIncorrectAuth = errors.New("invalid authentication")
    3.34 +	// ErrInvalidPassphraseScheme is returned when an undefined passphrase scheme is used.
    3.35 +	ErrInvalidPassphraseScheme = errors.New("invalid passphrase scheme")
    3.36 +	// ErrNoSession is returned when no session ID is passed with a request.
    3.37 +	ErrNoSession = errors.New("no session ID found")
    3.38 +)
    3.39 +
    3.40 +type tokenResponse struct {
    3.41 +	AccessToken  string `json:"access_token"`
    3.42 +	TokenType    string `json:"token_type,omitempty"`
    3.43 +	ExpiresIn    int32  `json:"expires_in,omitempty"`
    3.44 +	RefreshToken string `json:"refresh_token,omitempty"`
    3.45 +}
    3.46 +
    3.47 +func getBasicAuth(r *http.Request) (un, pass string, err error) {
    3.48 +	auth := r.Header.Get("Authorization")
    3.49 +	if auth == "" {
    3.50 +		return "", "", ErrNoAuth
    3.51 +	}
    3.52 +	pieces := strings.SplitN(auth, " ", 2)
    3.53 +	if pieces[0] != "Basic" {
    3.54 +		return "", "", ErrInvalidAuthFormat
    3.55 +	}
    3.56 +	decoded, err := base64.StdEncoding.DecodeString(pieces[1])
    3.57 +	if err != nil {
    3.58 +		return "", "", ErrInvalidAuthFormat
    3.59 +	}
    3.60 +	info := strings.SplitN(string(decoded), ":", 2)
    3.61 +	return info[0], info[1], nil
    3.62 +}
    3.63 +
    3.64 +func checkCookie(r *http.Request, context Context) (Session, error) {
    3.65 +	cookie, err := r.Cookie(authCookieName)
    3.66 +	if err != nil {
    3.67 +		if err == http.ErrNoCookie {
    3.68 +			return Session{}, ErrNoSession
    3.69 +		}
    3.70 +		return Session{}, err
    3.71 +	}
    3.72 +	if cookie.Name != authCookieName || !cookie.Expires.After(time.Now()) ||
    3.73 +		!cookie.Secure || !cookie.HttpOnly {
    3.74 +		return Session{}, ErrInvalidSession
    3.75 +	}
    3.76 +	sess, err := context.GetSession(cookie.Value)
    3.77 +	if err == ErrSessionNotFound {
    3.78 +		return Session{}, ErrInvalidSession
    3.79 +	} else if err != nil {
    3.80 +		return Session{}, err
    3.81 +	}
    3.82 +	if !sess.Active {
    3.83 +		return Session{}, ErrInvalidSession
    3.84 +	}
    3.85 +	return sess, nil
    3.86 +}
    3.87 +
    3.88 +func authenticate(user, passphrase string, context Context) (Profile, error) {
    3.89 +	profile, err := context.GetProfileByLogin(user)
    3.90 +	if err != nil {
    3.91 +		if err == ErrProfileNotFound {
    3.92 +			return Profile{}, ErrIncorrectAuth
    3.93 +		}
    3.94 +		return Profile{}, err
    3.95 +	}
    3.96 +	switch profile.PassphraseScheme {
    3.97 +	case 1:
    3.98 +		candidate := pass.Check(sha256.New, profile.Iterations, []byte(passphrase), []byte(profile.Salt))
    3.99 +		if !pass.Compare(candidate, []byte(profile.Passphrase)) {
   3.100 +			return Profile{}, ErrIncorrectAuth
   3.101 +		}
   3.102 +	default:
   3.103 +		return Profile{}, ErrInvalidPassphraseScheme
   3.104 +	}
   3.105 +	return profile, nil
   3.106 +}
   3.107 +
   3.108 +// GetGrantHandler presents and processes the page for asking a user to grant access
   3.109 +// to their data. See RFC 6749, Section 4.1.
   3.110 +func GetGrantHandler(w http.ResponseWriter, r *http.Request, context Context) {
   3.111 +	session, err := checkCookie(r, context)
   3.112 +	if err != nil {
   3.113 +		if err == ErrNoSession {
   3.114 +			// TODO(paddy): redirect to login screen
   3.115 +			//return
   3.116 +		}
   3.117 +		if err == ErrInvalidSession {
   3.118 +			// TODO(paddy): return an access denied error
   3.119 +			//return
   3.120 +		}
   3.121 +		// TODO(paddy): return a server error
   3.122 +		//return
   3.123 +	}
   3.124 +	if r.URL.Query().Get("client_id") == "" {
   3.125 +		w.WriteHeader(http.StatusBadRequest)
   3.126 +		context.Render(w, getGrantTemplateName, map[string]interface{}{
   3.127 +			"error": template.HTML("Client ID must be specified in the request."),
   3.128 +		})
   3.129 +		return
   3.130 +	}
   3.131 +	clientID, err := uuid.Parse(r.URL.Query().Get("client_id"))
   3.132 +	if err != nil {
   3.133 +		w.WriteHeader(http.StatusBadRequest)
   3.134 +		context.Render(w, getGrantTemplateName, map[string]interface{}{
   3.135 +			"error": template.HTML("client_id is not a valid Client ID."),
   3.136 +		})
   3.137 +		return
   3.138 +	}
   3.139 +	redirectURI := r.URL.Query().Get("redirect_uri")
   3.140 +	redirectURL, err := url.Parse(redirectURI)
   3.141 +	if err != nil {
   3.142 +		w.WriteHeader(http.StatusBadRequest)
   3.143 +		context.Render(w, getGrantTemplateName, map[string]interface{}{
   3.144 +			"error": template.HTML("The redirect_uri specified is not valid."),
   3.145 +		})
   3.146 +		return
   3.147 +	}
   3.148 +	client, err := context.GetClient(clientID)
   3.149 +	if err != nil {
   3.150 +		if err == ErrClientNotFound {
   3.151 +			w.WriteHeader(http.StatusBadRequest)
   3.152 +			context.Render(w, getGrantTemplateName, map[string]interface{}{
   3.153 +				"error": template.HTML("The specified Client couldn&rsquo;t be found."),
   3.154 +			})
   3.155 +		} else {
   3.156 +			w.WriteHeader(http.StatusInternalServerError)
   3.157 +			context.Render(w, getGrantTemplateName, map[string]interface{}{
   3.158 +				"internal_error": template.HTML(err.Error()),
   3.159 +			})
   3.160 +		}
   3.161 +		return
   3.162 +	}
   3.163 +	// whether a redirect URI is valid or not depends on the number of endpoints
   3.164 +	// the client has registered
   3.165 +	numEndpoints, err := context.CountEndpoints(clientID)
   3.166 +	if err != nil {
   3.167 +		w.WriteHeader(http.StatusInternalServerError)
   3.168 +		context.Render(w, getGrantTemplateName, map[string]interface{}{
   3.169 +			"internal_error": template.HTML(err.Error()),
   3.170 +		})
   3.171 +		return
   3.172 +	}
   3.173 +	var validURI bool
   3.174 +	if redirectURI != "" {
   3.175 +		// BUG(paddy): We really should normalize URIs before trying to compare them.
   3.176 +		validURI, err = context.CheckEndpoint(clientID, redirectURI)
   3.177 +		if err != nil {
   3.178 +			w.WriteHeader(http.StatusInternalServerError)
   3.179 +			context.Render(w, getGrantTemplateName, map[string]interface{}{
   3.180 +				"internal_error": template.HTML(err.Error()),
   3.181 +			})
   3.182 +			return
   3.183 +		}
   3.184 +	} else if redirectURI == "" && numEndpoints == 1 {
   3.185 +		// if we don't specify the endpoint and there's only one endpoint, the
   3.186 +		// request is valid, and we're redirecting to that one endpoint
   3.187 +		validURI = true
   3.188 +		endpoints, err := context.ListEndpoints(clientID, 1, 0)
   3.189 +		if err != nil {
   3.190 +			w.WriteHeader(http.StatusInternalServerError)
   3.191 +			context.Render(w, getGrantTemplateName, map[string]interface{}{
   3.192 +				"internal_error": template.HTML(err.Error()),
   3.193 +			})
   3.194 +			return
   3.195 +		}
   3.196 +		if len(endpoints) != 1 {
   3.197 +			validURI = false
   3.198 +		} else {
   3.199 +			u := endpoints[0].URI // Copy it here to avoid grabbing a pointer to the memstore
   3.200 +			redirectURI = u.String()
   3.201 +			redirectURL = &u
   3.202 +		}
   3.203 +	} else {
   3.204 +		validURI = false
   3.205 +	}
   3.206 +	if !validURI {
   3.207 +		w.WriteHeader(http.StatusBadRequest)
   3.208 +		context.Render(w, getGrantTemplateName, map[string]interface{}{
   3.209 +			"error": template.HTML("The redirect_uri specified is not valid."),
   3.210 +		})
   3.211 +		return
   3.212 +	}
   3.213 +	scope := r.URL.Query().Get("scope")
   3.214 +	state := r.URL.Query().Get("state")
   3.215 +	if r.URL.Query().Get("response_type") != "code" {
   3.216 +		q := redirectURL.Query()
   3.217 +		q.Add("error", "invalid_request")
   3.218 +		q.Add("state", state)
   3.219 +		redirectURL.RawQuery = q.Encode()
   3.220 +		http.Redirect(w, r, redirectURL.String(), http.StatusFound)
   3.221 +		return
   3.222 +	}
   3.223 +	if r.Method == "POST" {
   3.224 +		// BUG(paddy): We need to implement CSRF protection when obtaining a grant code.
   3.225 +		if r.PostFormValue("grant") == "approved" {
   3.226 +			code := uuid.NewID().String()
   3.227 +			grant := Grant{
   3.228 +				Code:        code,
   3.229 +				Created:     time.Now(),
   3.230 +				ExpiresIn:   defaultGrantExpiration,
   3.231 +				ClientID:    clientID,
   3.232 +				Scope:       scope,
   3.233 +				RedirectURI: r.URL.Query().Get("redirect_uri"),
   3.234 +				State:       state,
   3.235 +				ProfileID:   session.ProfileID,
   3.236 +			}
   3.237 +			err := context.SaveGrant(grant)
   3.238 +			if err != nil {
   3.239 +				q := redirectURL.Query()
   3.240 +				q.Add("error", "server_error")
   3.241 +				q.Add("state", state)
   3.242 +				redirectURL.RawQuery = q.Encode()
   3.243 +				http.Redirect(w, r, redirectURL.String(), http.StatusFound)
   3.244 +				return
   3.245 +			}
   3.246 +			q := redirectURL.Query()
   3.247 +			q.Add("code", code)
   3.248 +			q.Add("state", state)
   3.249 +			redirectURL.RawQuery = q.Encode()
   3.250 +			http.Redirect(w, r, redirectURL.String(), http.StatusFound)
   3.251 +			return
   3.252 +		}
   3.253 +		q := redirectURL.Query()
   3.254 +		q.Add("error", "access_denied")
   3.255 +		q.Add("state", state)
   3.256 +		redirectURL.RawQuery = q.Encode()
   3.257 +		http.Redirect(w, r, redirectURL.String(), http.StatusFound)
   3.258 +		return
   3.259 +	}
   3.260 +	w.WriteHeader(http.StatusOK)
   3.261 +	context.Render(w, getGrantTemplateName, map[string]interface{}{
   3.262 +		"client": client,
   3.263 +	})
   3.264 +}
   3.265 +
   3.266 +// GetTokenHandler allows a client to exchange an authorization grant for an
   3.267 +// access token. See RFC 6749 Section 4.1.3.
   3.268 +func GetTokenHandler(w http.ResponseWriter, r *http.Request, context Context) {
   3.269 +	enc := json.NewEncoder(w)
   3.270 +	grantType := r.PostFormValue("grant_type")
   3.271 +	if grantType != "authorization_code" {
   3.272 +		// TODO(paddy): render invalid request JSON
   3.273 +		return
   3.274 +	}
   3.275 +	code := r.PostFormValue("code")
   3.276 +	if code == "" {
   3.277 +		// TODO(paddy): render invalid request JSON
   3.278 +		return
   3.279 +	}
   3.280 +	redirectURI := r.PostFormValue("redirect_uri")
   3.281 +	clientIDStr, clientSecret, err := getBasicAuth(r)
   3.282 +	if err != nil {
   3.283 +		// TODO(paddy): render access denied
   3.284 +		return
   3.285 +	}
   3.286 +	if clientIDStr == "" && err == nil {
   3.287 +		clientIDStr = r.PostFormValue("client_id")
   3.288 +	}
   3.289 +	clientID, err := uuid.Parse(clientIDStr)
   3.290 +	if err != nil {
   3.291 +		// TODO(paddy): render invalid request JSON
   3.292 +		return
   3.293 +	}
   3.294 +	client, err := context.GetClient(clientID)
   3.295 +	if err != nil {
   3.296 +		if err == ErrClientNotFound {
   3.297 +			// TODO(paddy): render invalid request JSON
   3.298 +		} else {
   3.299 +			// TODO(paddy): render internal server error JSON
   3.300 +		}
   3.301 +		return
   3.302 +	}
   3.303 +	if client.Secret != clientSecret {
   3.304 +		// TODO(paddy): render invalid request JSON
   3.305 +		return
   3.306 +	}
   3.307 +	grant, err := context.GetGrant(code)
   3.308 +	if err != nil {
   3.309 +		if err == ErrGrantNotFound {
   3.310 +			// TODO(paddy): return error
   3.311 +			return
   3.312 +		}
   3.313 +		// TODO(paddy): return error
   3.314 +	}
   3.315 +	if grant.RedirectURI != redirectURI {
   3.316 +		// TODO(paddy): return error
   3.317 +	}
   3.318 +	if !grant.ClientID.Equal(clientID) {
   3.319 +		// TODO(paddy): return error
   3.320 +	}
   3.321 +	token := Token{
   3.322 +		AccessToken:  uuid.NewID().String(),
   3.323 +		RefreshToken: uuid.NewID().String(),
   3.324 +		Created:      time.Now(),
   3.325 +		ExpiresIn:    defaultTokenExpiration,
   3.326 +		TokenType:    "", // TODO(paddy): fill in token type
   3.327 +		Scope:        grant.Scope,
   3.328 +		ProfileID:    grant.ProfileID,
   3.329 +	}
   3.330 +	err = context.SaveToken(token)
   3.331 +	if err != nil {
   3.332 +		// TODO(paddy): return error
   3.333 +	}
   3.334 +	resp := tokenResponse{
   3.335 +		AccessToken:  token.AccessToken,
   3.336 +		RefreshToken: token.RefreshToken,
   3.337 +		ExpiresIn:    token.ExpiresIn,
   3.338 +		TokenType:    token.TokenType,
   3.339 +	}
   3.340 +	err = enc.Encode(resp)
   3.341 +	if err != nil {
   3.342 +		// TODO(paddy): log this or something
   3.343 +		return
   3.344 +	}
   3.345 +}
   3.346 +
   3.347 +// TODO(paddy): exchange user credentials for access token
   3.348 +// TODO(paddy): exchange client credentials for access token
   3.349 +// TODO(paddy): implicit grant for access token
   3.350 +// TODO(paddy): exchange refresh token for access token
     4.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     4.2 +++ b/oauth2_test.go	Tue Nov 11 21:22:57 2014 -0500
     4.3 @@ -0,0 +1,451 @@
     4.4 +package auth
     4.5 +
     4.6 +import (
     4.7 +	"bytes"
     4.8 +	"html/template"
     4.9 +	"io/ioutil"
    4.10 +	"net/http"
    4.11 +	"net/http/httptest"
    4.12 +	"net/url"
    4.13 +	"testing"
    4.14 +	"time"
    4.15 +
    4.16 +	"code.secondbit.org/uuid"
    4.17 +)
    4.18 +
    4.19 +const (
    4.20 +	scopeSet = 1 << iota
    4.21 +	stateSet
    4.22 +	uriSet
    4.23 +)
    4.24 +
    4.25 +func stripParam(param string, u *url.URL) {
    4.26 +	q := u.Query()
    4.27 +	q.Del(param)
    4.28 +	u.RawQuery = q.Encode()
    4.29 +}
    4.30 +
    4.31 +func TestGetGrantCodeSuccess(t *testing.T) {
    4.32 +	t.Parallel()
    4.33 +	store := NewMemstore()
    4.34 +	testContext := Context{
    4.35 +		template: template.Must(template.New(getGrantTemplateName).Parse("Get auth grant")),
    4.36 +		clients:  store,
    4.37 +		grants:   store,
    4.38 +		profiles: store,
    4.39 +		tokens:   store,
    4.40 +	}
    4.41 +	client := Client{
    4.42 +		ID:      uuid.NewID(),
    4.43 +		Secret:  "super secret!",
    4.44 +		OwnerID: uuid.NewID(),
    4.45 +		Name:    "My test client",
    4.46 +		Logo:    "https://secondbit.org/logo.png",
    4.47 +		Website: "https://secondbit.org",
    4.48 +		Type:    "public",
    4.49 +	}
    4.50 +	uri, err := url.Parse("https://test.secondbit.org/redirect")
    4.51 +	if err != nil {
    4.52 +		t.Fatal("Can't parse URL:", err)
    4.53 +	}
    4.54 +	endpoint := Endpoint{
    4.55 +		ID:       uuid.NewID(),
    4.56 +		ClientID: client.ID,
    4.57 +		URI:      *uri,
    4.58 +		Added:    time.Now(),
    4.59 +	}
    4.60 +	err = testContext.SaveClient(client)
    4.61 +	if err != nil {
    4.62 +		t.Fatal("Can't store client:", err)
    4.63 +	}
    4.64 +	err = testContext.AddEndpoint(client.ID, endpoint)
    4.65 +	if err != nil {
    4.66 +		t.Fatal("Can't store endpoint:", err)
    4.67 +	}
    4.68 +	req, err := http.NewRequest("GET", "https://test.auth.secondbit.org/oauth2/grant", nil)
    4.69 +	if err != nil {
    4.70 +		t.Fatal("Can't build request:", err)
    4.71 +	}
    4.72 +	for i := 0; i < 1<<3; i++ {
    4.73 +		w := httptest.NewRecorder()
    4.74 +		params := url.Values{}
    4.75 +		// see OAuth 2.0 spec, section 4.1.1
    4.76 +		params.Set("response_type", "code")
    4.77 +		params.Set("client_id", client.ID.String())
    4.78 +		if i&uriSet != 0 {
    4.79 +			params.Set("redirect_uri", endpoint.URI.String())
    4.80 +		}
    4.81 +		if i&scopeSet != 0 {
    4.82 +			params.Set("scope", "testscope")
    4.83 +		}
    4.84 +		if i&stateSet != 0 {
    4.85 +			params.Set("state", "my super secure state string")
    4.86 +		}
    4.87 +		req.URL.RawQuery = params.Encode()
    4.88 +		req.Method = "GET"
    4.89 +		req.Body = nil
    4.90 +		req.Header.Del("Content-Type")
    4.91 +		GetGrantHandler(w, req, testContext)
    4.92 +		if w.Code != http.StatusOK {
    4.93 +			t.Errorf("Expected status code to be %d, got %d for %s", http.StatusOK, w.Code, req.URL.String())
    4.94 +		}
    4.95 +		if w.Body.String() != "Get auth grant" {
    4.96 +			t.Errorf("Expected body to be `%s`, got `%s` for %s", "Get auth grant", w.Body.String(), req.URL.String())
    4.97 +		}
    4.98 +		req.Method = "POST"
    4.99 +		req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
   4.100 +		w = httptest.NewRecorder()
   4.101 +		data := url.Values{}
   4.102 +		data.Set("grant", "approved")
   4.103 +		body := bytes.NewBufferString(data.Encode())
   4.104 +		req.Body = ioutil.NopCloser(body)
   4.105 +		GetGrantHandler(w, req, testContext)
   4.106 +		if w.Code != http.StatusFound {
   4.107 +			t.Errorf("Expected status code to be %d, got %d for %s", http.StatusFound, w.Code, req.URL.String())
   4.108 +		}
   4.109 +		redirectedTo := w.Header().Get("Location")
   4.110 +		red, err := url.Parse(redirectedTo)
   4.111 +		if err != nil {
   4.112 +			t.Fatalf(`Being redirected to a non-URL "%s" threw error "%s" for "%s"\n`, redirectedTo, err, req.URL.String())
   4.113 +		}
   4.114 +		t.Log("Redirected to", redirectedTo)
   4.115 +		if red.Query().Get("code") == "" {
   4.116 +			t.Fatalf(`Expected code param in redirect URL to be set, but it wasn't for %s`, req.URL.String())
   4.117 +		}
   4.118 +		if _, err := testContext.GetGrant(red.Query().Get("code")); err != nil {
   4.119 +			t.Fatalf(`Unexpected error "%s: retrieving the grant "%s" supplied in the redirect URL for %s`, err, red.Query().Get("code"), req.URL.String())
   4.120 +		}
   4.121 +		err = testContext.DeleteGrant(red.Query().Get("code"))
   4.122 +		if err != nil {
   4.123 +			t.Log(`Unexpected error "%s" deleting grant "%s" for %s`, err, red.Query().Get("code"), req.URL.String())
   4.124 +		}
   4.125 +		stripParam("code", red)
   4.126 +		if red.Query().Get("state") != params.Get("state") {
   4.127 +			t.Errorf(`Expected state param in redirect URL to be "%s", got "%s" for %s`, params.Get("state"), red.Query().Get("state"), req.URL.String())
   4.128 +		}
   4.129 +		stripParam("state", red)
   4.130 +		if red.String() != endpoint.URI.String() {
   4.131 +			t.Errorf(`Expected redirect URL to be "%s", got "%s"`, endpoint.URI.String(), red.String())
   4.132 +		}
   4.133 +	}
   4.134 +}
   4.135 +
   4.136 +func TestGetGrantCodeInvalidClient(t *testing.T) {
   4.137 +	t.Parallel()
   4.138 +	store := NewMemstore()
   4.139 +	testContext := Context{
   4.140 +		template: template.Must(template.New(getGrantTemplateName).Parse("{{ .error }}")),
   4.141 +		clients:  store,
   4.142 +		grants:   store,
   4.143 +		profiles: store,
   4.144 +		tokens:   store,
   4.145 +	}
   4.146 +	client := Client{
   4.147 +		ID:      uuid.NewID(),
   4.148 +		Secret:  "super secret!",
   4.149 +		OwnerID: uuid.NewID(),
   4.150 +		Name:    "My test client",
   4.151 +		Type:    "public",
   4.152 +	}
   4.153 +	err := testContext.SaveClient(client)
   4.154 +	if err != nil {
   4.155 +		t.Fatal("Can't store client:", err)
   4.156 +	}
   4.157 +	req, err := http.NewRequest("GET", "https://test.auth.secondbit.org/oauth2/grant", nil)
   4.158 +	if err != nil {
   4.159 +		t.Fatal("Can't build request:", err)
   4.160 +	}
   4.161 +	w := httptest.NewRecorder()
   4.162 +	params := url.Values{}
   4.163 +	params.Set("response_type", "code")
   4.164 +	params.Set("redirect_uri", "https://test.secondbit.org/")
   4.165 +	req.URL.RawQuery = params.Encode()
   4.166 +	GetGrantHandler(w, req, testContext)
   4.167 +	if w.Code != http.StatusBadRequest {
   4.168 +		t.Errorf("Expected status code to be %d, got %d", http.StatusBadRequest, w.Code)
   4.169 +	}
   4.170 +	if w.Body.String() != "Client ID must be specified in the request." {
   4.171 +		t.Errorf(`Expected output to be "%s", got "%s" instead.`, "Client ID must be specified in the request.", w.Body.String())
   4.172 +	}
   4.173 +	w = httptest.NewRecorder()
   4.174 +	params.Set("client_id", "Not an ID")
   4.175 +	req.URL.RawQuery = params.Encode()
   4.176 +	GetGrantHandler(w, req, testContext)
   4.177 +	if w.Code != http.StatusBadRequest {
   4.178 +		t.Errorf("Expected status code to be %d, got %d", http.StatusBadRequest, w.Code)
   4.179 +	}
   4.180 +	if w.Body.String() != "client_id is not a valid Client ID." {
   4.181 +		t.Errorf(`Expected output to be "%s", got "%s" instead.`, "client_id is not a valid Client ID.", w.Body.String())
   4.182 +	}
   4.183 +	w = httptest.NewRecorder()
   4.184 +	params.Set("client_id", uuid.NewID().String())
   4.185 +	req.URL.RawQuery = params.Encode()
   4.186 +	GetGrantHandler(w, req, testContext)
   4.187 +	if w.Code != http.StatusBadRequest {
   4.188 +		t.Errorf("Expected status code to be %d, got %d", http.StatusBadRequest, w.Code)
   4.189 +	}
   4.190 +	if w.Body.String() != "The specified Client couldn&rsquo;t be found." {
   4.191 +		t.Errorf(`Expected output to be "%s", got "%s" instead.`, "The specified Client couldn&rsquo;t be found.", w.Body.String())
   4.192 +	}
   4.193 +}
   4.194 +
   4.195 +func TestGetGrantCodeInvalidURI(t *testing.T) {
   4.196 +	t.Parallel()
   4.197 +	store := NewMemstore()
   4.198 +	testContext := Context{
   4.199 +		template: template.Must(template.New(getGrantTemplateName).Parse("{{ .error }}")),
   4.200 +		clients:  store,
   4.201 +		grants:   store,
   4.202 +		profiles: store,
   4.203 +		tokens:   store,
   4.204 +	}
   4.205 +	client := Client{
   4.206 +		ID:      uuid.NewID(),
   4.207 +		Secret:  "super secret!",
   4.208 +		OwnerID: uuid.NewID(),
   4.209 +		Name:    "My test client",
   4.210 +		Type:    "public",
   4.211 +	}
   4.212 +	uri, err := url.Parse("https://test.secondbit.org/redirect")
   4.213 +	if err != nil {
   4.214 +		t.Fatal("Can't parse URL:", err)
   4.215 +	}
   4.216 +	err = testContext.SaveClient(client)
   4.217 +	if err != nil {
   4.218 +		t.Fatal("Can't store client:", err)
   4.219 +	}
   4.220 +	req, err := http.NewRequest("GET", "https://test.auth.secondbit.org/oauth2/grant", nil)
   4.221 +	if err != nil {
   4.222 +		t.Fatal("Can't build request:", err)
   4.223 +	}
   4.224 +	w := httptest.NewRecorder()
   4.225 +	params := url.Values{}
   4.226 +	params.Set("response_type", "code")
   4.227 +	params.Set("client_id", client.ID.String())
   4.228 +	req.URL.RawQuery = params.Encode()
   4.229 +	GetGrantHandler(w, req, testContext)
   4.230 +	if w.Code != http.StatusBadRequest {
   4.231 +		t.Errorf("Expected status code to be %d, got %d", http.StatusBadRequest, w.Code)
   4.232 +	}
   4.233 +	if w.Body.String() != "The redirect_uri specified is not valid." {
   4.234 +		t.Errorf(`Expected output to be "%s", got "%s" instead.`, "The redirect_uri specified is not valid.", w.Body.String())
   4.235 +	}
   4.236 +	endpoint := Endpoint{
   4.237 +		ID:       uuid.NewID(),
   4.238 +		ClientID: client.ID,
   4.239 +		URI:      *uri,
   4.240 +		Added:    time.Now(),
   4.241 +	}
   4.242 +	err = testContext.AddEndpoint(client.ID, endpoint)
   4.243 +	if err != nil {
   4.244 +		t.Fatal("Can't store endpoint:", err)
   4.245 +	}
   4.246 +	w = httptest.NewRecorder()
   4.247 +	params.Set("redirect_uri", "https://test.secondbit.org/wrong")
   4.248 +	req.URL.RawQuery = params.Encode()
   4.249 +	GetGrantHandler(w, req, testContext)
   4.250 +	if w.Code != http.StatusBadRequest {
   4.251 +		t.Errorf("Expected status code to be %d, got %d", http.StatusBadRequest, w.Code)
   4.252 +	}
   4.253 +	if w.Body.String() != "The redirect_uri specified is not valid." {
   4.254 +		t.Errorf(`Expected output to be "%s", got "%s" instead.`, "The redirect_uri specified is not valid.", w.Body.String())
   4.255 +	}
   4.256 +	endpoint2 := Endpoint{
   4.257 +		ID:       uuid.NewID(),
   4.258 +		ClientID: client.ID,
   4.259 +		URI:      *uri,
   4.260 +		Added:    time.Now(),
   4.261 +	}
   4.262 +	err = testContext.AddEndpoint(client.ID, endpoint2)
   4.263 +	if err != nil {
   4.264 +		t.Fatal("Can't store endpoint:", err)
   4.265 +	}
   4.266 +	w = httptest.NewRecorder()
   4.267 +	params.Set("redirect_uri", "")
   4.268 +	req.URL.RawQuery = params.Encode()
   4.269 +	GetGrantHandler(w, req, testContext)
   4.270 +	if w.Code != http.StatusBadRequest {
   4.271 +		t.Errorf("Expected status code to be %d, got %d", http.StatusBadRequest, w.Code)
   4.272 +	}
   4.273 +	if w.Body.String() != "The redirect_uri specified is not valid." {
   4.274 +		t.Errorf(`Expected output to be "%s", got "%s" instead.`, "The redirect_uri specified is not valid.", w.Body.String())
   4.275 +	}
   4.276 +	w = httptest.NewRecorder()
   4.277 +	params.Set("redirect_uri", "://not a URL")
   4.278 +	req.URL.RawQuery = params.Encode()
   4.279 +	GetGrantHandler(w, req, testContext)
   4.280 +	if w.Code != http.StatusBadRequest {
   4.281 +		t.Errorf("Expected status code to be %d, got %d", http.StatusBadRequest, w.Code)
   4.282 +	}
   4.283 +	if w.Body.String() != "The redirect_uri specified is not valid." {
   4.284 +		t.Errorf(`Expected output to be "%s", got "%s" instead.`, "The redirect_uri specified is not valid.", w.Body.String())
   4.285 +	}
   4.286 +}
   4.287 +
   4.288 +func TestGetGrantCodeInvalidResponseType(t *testing.T) {
   4.289 +	t.Parallel()
   4.290 +	store := NewMemstore()
   4.291 +	testContext := Context{
   4.292 +		template: template.Must(template.New(getGrantTemplateName).Parse("{{ .error }}")),
   4.293 +		clients:  store,
   4.294 +		grants:   store,
   4.295 +		profiles: store,
   4.296 +		tokens:   store,
   4.297 +	}
   4.298 +	client := Client{
   4.299 +		ID:      uuid.NewID(),
   4.300 +		Secret:  "super secret!",
   4.301 +		OwnerID: uuid.NewID(),
   4.302 +		Name:    "My test client",
   4.303 +		Logo:    "https://secondbit.org/logo.png",
   4.304 +		Website: "https://secondbit.org",
   4.305 +		Type:    "public",
   4.306 +	}
   4.307 +	uri, err := url.Parse("https://test.secondbit.org/redirect")
   4.308 +	if err != nil {
   4.309 +		t.Fatal("Can't parse URL:", err)
   4.310 +	}
   4.311 +	endpoint := Endpoint{
   4.312 +		ID:       uuid.NewID(),
   4.313 +		ClientID: client.ID,
   4.314 +		URI:      *uri,
   4.315 +		Added:    time.Now(),
   4.316 +	}
   4.317 +	err = testContext.SaveClient(client)
   4.318 +	if err != nil {
   4.319 +		t.Fatal("Can't store client:", err)
   4.320 +	}
   4.321 +	err = testContext.AddEndpoint(client.ID, endpoint)
   4.322 +	if err != nil {
   4.323 +		t.Fatal("Can't store endpoint:", err)
   4.324 +	}
   4.325 +	req, err := http.NewRequest("GET", "https://test.auth.secondbit.org/oauth2/grant", nil)
   4.326 +	if err != nil {
   4.327 +		t.Fatal("Can't build request:", err)
   4.328 +	}
   4.329 +	params := url.Values{}
   4.330 +	params.Set("response_type", "totally not code")
   4.331 +	params.Set("client_id", client.ID.String())
   4.332 +	params.Set("redirect_uri", endpoint.URI.String())
   4.333 +	params.Set("scope", "testscope")
   4.334 +	params.Set("state", "my super secure state string")
   4.335 +	req.URL.RawQuery = params.Encode()
   4.336 +	w := httptest.NewRecorder()
   4.337 +	GetGrantHandler(w, req, testContext)
   4.338 +	if w.Code != http.StatusFound {
   4.339 +		t.Errorf("Expected status code to be %d, got %d", http.StatusFound, w.Code)
   4.340 +	}
   4.341 +	redirectedTo := w.Header().Get("Location")
   4.342 +	red, err := url.Parse(redirectedTo)
   4.343 +	if err != nil {
   4.344 +		t.Fatalf("Being redirected to a non-URL (%s) threw error: %s\n", redirectedTo, err)
   4.345 +	}
   4.346 +	if red.Query().Get("error") != "invalid_request" {
   4.347 +		t.Errorf(`Expected error param in redirect URL to be "%s", got "%s"`, "invalid_request", red.Query().Get("error"))
   4.348 +	}
   4.349 +	stripParam("error", red)
   4.350 +	if red.Query().Get("state") != params.Get("state") {
   4.351 +		t.Errorf(`Expected state param in redirect URL to be "%s", got "%s"`, params.Get("state"), red.Query().Get("state"))
   4.352 +	}
   4.353 +	stripParam("state", red)
   4.354 +	if red.String() != endpoint.URI.String() {
   4.355 +		t.Errorf(`Expected redirect URL to be "%s", got "%s"`, endpoint.URI.String(), red.String())
   4.356 +	}
   4.357 +	stripParam("response_type", req.URL)
   4.358 +	w = httptest.NewRecorder()
   4.359 +	GetGrantHandler(w, req, testContext)
   4.360 +	if w.Code != http.StatusFound {
   4.361 +		t.Errorf("Expected status code to be %d, got %d", http.StatusFound, w.Code)
   4.362 +	}
   4.363 +	redirectedTo = w.Header().Get("Location")
   4.364 +	red, err = url.Parse(redirectedTo)
   4.365 +	if err != nil {
   4.366 +		t.Fatalf("Being redirected to a non-URL (%s) threw error: %s\n", redirectedTo, err)
   4.367 +	}
   4.368 +	if red.Query().Get("error") != "invalid_request" {
   4.369 +		t.Errorf(`Expected error param in redirect URL to be "%s", got "%s"`, "invalid_request", red.Query().Get("error"))
   4.370 +	}
   4.371 +	stripParam("error", red)
   4.372 +	if red.Query().Get("state") != params.Get("state") {
   4.373 +		t.Errorf(`Expected state param in redirect URL to be "%s", got "%s"`, params.Get("state"), red.Query().Get("state"))
   4.374 +	}
   4.375 +	stripParam("state", red)
   4.376 +	if red.String() != endpoint.URI.String() {
   4.377 +		t.Errorf(`Expected redirect URL to be "%s", got "%s"`, endpoint.URI.String(), red.String())
   4.378 +	}
   4.379 +}
   4.380 +
   4.381 +func TestGetGrantCodeDenied(t *testing.T) {
   4.382 +	t.Parallel()
   4.383 +	store := NewMemstore()
   4.384 +	testContext := Context{
   4.385 +		template: template.Must(template.New(getGrantTemplateName).Parse("{{ .error }}")),
   4.386 +		clients:  store,
   4.387 +		grants:   store,
   4.388 +		profiles: store,
   4.389 +		tokens:   store,
   4.390 +	}
   4.391 +	client := Client{
   4.392 +		ID:      uuid.NewID(),
   4.393 +		Secret:  "super secret!",
   4.394 +		OwnerID: uuid.NewID(),
   4.395 +		Name:    "My test client",
   4.396 +		Logo:    "https://secondbit.org/logo.png",
   4.397 +		Website: "https://secondbit.org",
   4.398 +		Type:    "public",
   4.399 +	}
   4.400 +	uri, err := url.Parse("https://test.secondbit.org/redirect")
   4.401 +	if err != nil {
   4.402 +		t.Fatal("Can't parse URL:", err)
   4.403 +	}
   4.404 +	endpoint := Endpoint{
   4.405 +		ID:       uuid.NewID(),
   4.406 +		ClientID: client.ID,
   4.407 +		URI:      *uri,
   4.408 +		Added:    time.Now(),
   4.409 +	}
   4.410 +	err = testContext.SaveClient(client)
   4.411 +	if err != nil {
   4.412 +		t.Fatal("Can't store client:", err)
   4.413 +	}
   4.414 +	err = testContext.AddEndpoint(client.ID, endpoint)
   4.415 +	if err != nil {
   4.416 +		t.Fatal("Can't store endpoint:", err)
   4.417 +	}
   4.418 +	req, err := http.NewRequest("GET", "https://test.auth.secondbit.org/oauth2/grant", nil)
   4.419 +	if err != nil {
   4.420 +		t.Fatal("Can't build request:", err)
   4.421 +	}
   4.422 +	params := url.Values{}
   4.423 +	params.Set("response_type", "code")
   4.424 +	params.Set("client_id", client.ID.String())
   4.425 +	params.Set("redirect_uri", endpoint.URI.String())
   4.426 +	params.Set("scope", "testscope")
   4.427 +	params.Set("state", "my super secure state string")
   4.428 +	data := url.Values{}
   4.429 +	data.Set("grant", "denied")
   4.430 +	req.URL.RawQuery = params.Encode()
   4.431 +	req.Body = ioutil.NopCloser(bytes.NewBufferString(data.Encode()))
   4.432 +	req.Method = "POST"
   4.433 +	w := httptest.NewRecorder()
   4.434 +	GetGrantHandler(w, req, testContext)
   4.435 +	if w.Code != http.StatusFound {
   4.436 +		t.Errorf("Expected status code to be %d, got %d", http.StatusFound, w.Code)
   4.437 +	}
   4.438 +	redirectedTo := w.Header().Get("Location")
   4.439 +	red, err := url.Parse(redirectedTo)
   4.440 +	if err != nil {
   4.441 +		t.Fatalf("Being redirected to a non-URL (%s) threw error: %s\n", redirectedTo, err)
   4.442 +	}
   4.443 +	if red.Query().Get("error") != "access_denied" {
   4.444 +		t.Errorf(`Expected error param in redirect URL to be "%s", got "%s"`, "access_denied", red.Query().Get("error"))
   4.445 +	}
   4.446 +	stripParam("error", red)
   4.447 +	if red.Query().Get("state") != params.Get("state") {
   4.448 +		t.Errorf(`Expected state param in redirect URL to be "%s", got "%s"`, params.Get("state"), red.Query().Get("state"))
   4.449 +	}
   4.450 +	stripParam("state", red)
   4.451 +	if red.String() != endpoint.URI.String() {
   4.452 +		t.Errorf(`Expected redirect URL to be "%s", got "%s"`, endpoint.URI.String(), red.String())
   4.453 +	}
   4.454 +}