auth

Paddy 2014-11-11 Parent:752c2fb9731c Child:c8b0208c9e5d

69:42bc3e44f4fe Go to Latest

auth/http.go

Stub out sessions. Stop using the Login type when getting profile by Login, removing Logins, or recording Login use. The Login value has to be unique, anyways, and we don't actually know the Login type when getting a profile by Login. That's sort of the point. Create the concept of Sessions and a sessionStore type to manage our authentication sessions with the server. As per OWASP, we're basically just going to use a transparent, SHA256-generated random string as an ID, and store it client-side and server-side and just pass it back and forth. Add the ProfileID to the Grant type, because we need to remember who granted access. That's sort of important. Set a defaultGrantExpiration constant to an hour, so we have that one constant when creating new Grants. Create a helper that pulls the session ID out of an auth cookie, checks it against the sessionStore, and returns the Session if it's valid. Create a helper that pulls the username and password out of a basic auth header. Create a helper that authenticates a user's login and passphrase, checking them against the profileStore securely. Stub out how the cookie checking is going to work for getting grant approval. Fix the stored Grant RedirectURI to be the passed in redirect URI, not the RedirectURI that we ultimately redirect to. This is in accordance with the spec. Store the profile ID from our session in the created Grant. Stub out a GetTokenHandler that will allow users to exchange a Grant for a Token. Set a constant for the current passphrase scheme, which we will increment for each revision to the passphrase scheme, for backwards compatibility. Change the Profile iterations property to an int, not an int64, to match the code.secondbit.org/pass library (which is matching the PBKDF2 library).

History
     1.1 --- a/http.go	Sun Nov 09 00:22:38 2014 -0500
     1.2 +++ b/http.go	Tue Nov 11 21:13:16 2014 -0500
     1.3 @@ -1,22 +1,125 @@
     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 -	defaultGrantExpiration = 600 // default to ten minute grant expirations
    1.26  )
    1.27  
    1.28 +var (
    1.29 +	// ErrNoAuth is returned when an Authorization header is not present or is empty.
    1.30 +	ErrNoAuth = errors.New("no authorization header supplied")
    1.31 +	// ErrInvalidAuthFormat is returned when an Authorization header is present but not the correct format.
    1.32 +	ErrInvalidAuthFormat = errors.New("authorization header is not in a valid format")
    1.33 +	// ErrIncorrectAuth is returned when a user authentication attempt does not match the stored values.
    1.34 +	ErrIncorrectAuth = errors.New("invalid authentication")
    1.35 +	// ErrInvalidPassphraseScheme is returned when an undefined passphrase scheme is used.
    1.36 +	ErrInvalidPassphraseScheme = errors.New("invalid passphrase scheme")
    1.37 +	// ErrNoSession is returned when no session ID is passed with a request.
    1.38 +	ErrNoSession = errors.New("no session ID found")
    1.39 +)
    1.40 +
    1.41 +type tokenResponse struct {
    1.42 +	AccessToken  string `json:"access_token"`
    1.43 +	TokenType    string `json:"token_type,omitempty"`
    1.44 +	ExpiresIn    int32  `json:"expires_in,omitempty"`
    1.45 +	RefreshToken string `json:"refresh_token,omitempty"`
    1.46 +}
    1.47 +
    1.48 +func getBasicAuth(r *http.Request) (un, pass string, err error) {
    1.49 +	auth := r.Header.Get("Authorization")
    1.50 +	if auth == "" {
    1.51 +		return "", "", ErrNoAuth
    1.52 +	}
    1.53 +	pieces := strings.SplitN(auth, " ", 2)
    1.54 +	if pieces[0] != "Basic" {
    1.55 +		return "", "", ErrInvalidAuthFormat
    1.56 +	}
    1.57 +	decoded, err := base64.StdEncoding.DecodeString(pieces[1])
    1.58 +	if err != nil {
    1.59 +		// TODO(paddy): should probably log this...
    1.60 +		return "", "", ErrInvalidAuthFormat
    1.61 +	}
    1.62 +	info := strings.SplitN(string(decoded), ":", 2)
    1.63 +	return info[0], info[1], nil
    1.64 +}
    1.65 +
    1.66 +func checkCookie(r *http.Request, context Context) (Session, error) {
    1.67 +	cookie, err := r.Cookie(authCookieName)
    1.68 +	if err != nil {
    1.69 +		if err == http.ErrNoCookie {
    1.70 +			return Session{}, ErrNoSession
    1.71 +		}
    1.72 +		return Session{}, err
    1.73 +	}
    1.74 +	if cookie.Name != authCookieName || !cookie.Expires.After(time.Now()) ||
    1.75 +		!cookie.Secure || !cookie.HttpOnly {
    1.76 +		return Session{}, ErrInvalidSession
    1.77 +	}
    1.78 +	sess, err := context.GetSession(cookie.Value)
    1.79 +	if err == ErrSessionNotFound {
    1.80 +		return Session{}, ErrInvalidSession
    1.81 +	} else if err != nil {
    1.82 +		return Session{}, err
    1.83 +	}
    1.84 +	if !sess.Active {
    1.85 +		return Session{}, ErrInvalidSession
    1.86 +	}
    1.87 +	return sess, nil
    1.88 +}
    1.89 +
    1.90 +func authenticate(user, passphrase string, context Context) (Profile, error) {
    1.91 +	profile, err := context.GetProfileByLogin(user)
    1.92 +	if err != nil {
    1.93 +		if err == ErrProfileNotFound {
    1.94 +			return Profile{}, ErrIncorrectAuth
    1.95 +		}
    1.96 +		return Profile{}, err
    1.97 +	}
    1.98 +	switch profile.PassphraseScheme {
    1.99 +	case 1:
   1.100 +		candidate := pass.Check(sha256.New, profile.Iterations, []byte(passphrase), []byte(profile.Salt))
   1.101 +		if !pass.Compare(candidate, []byte(profile.Passphrase)) {
   1.102 +			return Profile{}, ErrIncorrectAuth
   1.103 +		}
   1.104 +	default:
   1.105 +		// TODO(paddy): return some error
   1.106 +		return Profile{}, ErrInvalidPassphraseScheme
   1.107 +	}
   1.108 +	return profile, nil
   1.109 +}
   1.110 +
   1.111  // GetGrantHandler presents and processes the page for asking a user to grant access
   1.112  // to their data. See RFC 6749, Section 4.1.
   1.113  func GetGrantHandler(w http.ResponseWriter, r *http.Request, context Context) {
   1.114 +	session, err := checkCookie(r, context)
   1.115 +	if err != nil {
   1.116 +		if err == ErrNoSession {
   1.117 +			// TODO(paddy): redirect to login screen
   1.118 +			//return
   1.119 +		}
   1.120 +		if err == ErrInvalidSession {
   1.121 +			// TODO(paddy): return an access denied error
   1.122 +			//return
   1.123 +		}
   1.124 +		// TODO(paddy): return a server error
   1.125 +		//return
   1.126 +	}
   1.127  	if r.URL.Query().Get("client_id") == "" {
   1.128  		w.WriteHeader(http.StatusBadRequest)
   1.129  		context.Render(w, getGrantTemplateName, map[string]interface{}{
   1.130 @@ -126,8 +229,9 @@
   1.131  				ExpiresIn:   defaultGrantExpiration,
   1.132  				ClientID:    clientID,
   1.133  				Scope:       scope,
   1.134 -				RedirectURI: redirectURI,
   1.135 +				RedirectURI: r.URL.Query().Get("redirect_uri"),
   1.136  				State:       state,
   1.137 +				ProfileID:   session.ProfileID,
   1.138  			}
   1.139  			err := context.SaveGrant(grant)
   1.140  			if err != nil {
   1.141 @@ -158,7 +262,88 @@
   1.142  	})
   1.143  }
   1.144  
   1.145 -// TODO(paddy): exchange code for access token
   1.146 +// GetTokenHandler allows a client to exchange an authorization grant for an
   1.147 +// access token. See RFC 6749 Section 4.1.3.
   1.148 +func GetTokenHandler(w http.ResponseWriter, r *http.Request, context Context) {
   1.149 +	enc := json.NewEncoder(w)
   1.150 +	grantType := r.PostFormValue("grant_type")
   1.151 +	if grantType != "authorization_code" {
   1.152 +		// TODO(paddy): render invalid request JSON
   1.153 +		return
   1.154 +	}
   1.155 +	code := r.PostFormValue("code")
   1.156 +	if code == "" {
   1.157 +		// TODO(paddy): render invalid request JSON
   1.158 +		return
   1.159 +	}
   1.160 +	redirectURI := r.PostFormValue("redirect_uri")
   1.161 +	clientIDStr, clientSecret, err := getBasicAuth(r)
   1.162 +	if err != nil {
   1.163 +		// TODO(paddy): render access denied
   1.164 +		return
   1.165 +	}
   1.166 +	if clientIDStr == "" && err == nil {
   1.167 +		clientIDStr = r.PostFormValue("client_id")
   1.168 +	}
   1.169 +	// TODO(paddy): client ID can also come from Basic auth
   1.170 +	clientID, err := uuid.Parse(clientIDStr)
   1.171 +	if err != nil {
   1.172 +		// TODO(paddy): render invalid request JSON
   1.173 +		return
   1.174 +	}
   1.175 +	client, err := context.GetClient(clientID)
   1.176 +	if err != nil {
   1.177 +		if err == ErrClientNotFound {
   1.178 +			// TODO(paddy): render invalid request JSON
   1.179 +		} else {
   1.180 +			// TODO(paddy): render internal server error JSON
   1.181 +		}
   1.182 +		return
   1.183 +	}
   1.184 +	if client.Secret != clientSecret {
   1.185 +		// TODO(paddy): render invalid request JSON
   1.186 +		return
   1.187 +	}
   1.188 +	grant, err := context.GetGrant(code)
   1.189 +	if err != nil {
   1.190 +		if err == ErrGrantNotFound {
   1.191 +			// TODO(paddy): return error
   1.192 +			return
   1.193 +		}
   1.194 +		// TODO(paddy): return error
   1.195 +	}
   1.196 +	if grant.RedirectURI != redirectURI {
   1.197 +		// TODO(paddy): return error
   1.198 +	}
   1.199 +	if !grant.ClientID.Equal(clientID) {
   1.200 +		// TODO(paddy): return error
   1.201 +	}
   1.202 +	token := Token{
   1.203 +		AccessToken:  uuid.NewID().String(),
   1.204 +		RefreshToken: uuid.NewID().String(),
   1.205 +		Created:      time.Now(),
   1.206 +		ExpiresIn:    defaultTokenExpiration,
   1.207 +		TokenType:    "", // TODO(paddy): fill in token type
   1.208 +		Scope:        grant.Scope,
   1.209 +		ProfileID:    grant.ProfileID,
   1.210 +	}
   1.211 +	err = context.SaveToken(token)
   1.212 +	if err != nil {
   1.213 +		// TODO(paddy): return error
   1.214 +	}
   1.215 +	resp := tokenResponse{
   1.216 +		AccessToken:  token.AccessToken,
   1.217 +		RefreshToken: token.RefreshToken,
   1.218 +		ExpiresIn:    token.ExpiresIn,
   1.219 +		TokenType:    token.TokenType,
   1.220 +	}
   1.221 +	err = enc.Encode(resp)
   1.222 +	if err != nil {
   1.223 +		// TODO(paddy): log this or something
   1.224 +		return
   1.225 +	}
   1.226 +}
   1.227 +
   1.228  // TODO(paddy): exchange user credentials for access token
   1.229  // TODO(paddy): exchange client credentials for access token
   1.230  // TODO(paddy): implicit grant for access token