auth
69:42bc3e44f4fe Browse Files
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).
context.go grant.go http.go profile.go profile_test.go token.go
1.1 --- a/context.go Sun Nov 09 00:22:38 2014 -0500 1.2 +++ b/context.go Tue Nov 11 21:13:16 2014 -0500 1.3 @@ -18,6 +18,7 @@ 1.4 grants grantStore 1.5 profiles profileStore 1.6 tokens tokenStore 1.7 + sessions sessionStore 1.8 } 1.9 1.10 // Render uses the HTML templates associated with the Context to render the 1.11 @@ -163,11 +164,11 @@ 1.12 1.13 // GetProfileByLogin returns the Profile associated with the specified Login from the profileStore associated 1.14 // with the Context. 1.15 -func (c Context) GetProfileByLogin(loginType, value string) (Profile, error) { 1.16 +func (c Context) GetProfileByLogin(value string) (Profile, error) { 1.17 if c.profiles == nil { 1.18 return Profile{}, ErrNoProfileStore 1.19 } 1.20 - return c.profiles.getProfileByLogin(loginType, value) 1.21 + return c.profiles.getProfileByLogin(value) 1.22 } 1.23 1.24 // SaveProfile inserts the passed Profile into the profileStore associated with the Context. 1.25 @@ -217,20 +218,20 @@ 1.26 // RemoveLogin removes the specified Login from the profileStore associated with the Context, provided 1.27 // the Login has a ProfileID property that matches the profile ID passed in. It also disassociates the 1.28 // deleted Login from the Profile in login.ProfileID. 1.29 -func (c Context) RemoveLogin(loginType, value string, profile uuid.ID) error { 1.30 +func (c Context) RemoveLogin(value string, profile uuid.ID) error { 1.31 if c.profiles == nil { 1.32 return ErrNoProfileStore 1.33 } 1.34 - return c.profiles.removeLogin(loginType, value, profile) 1.35 + return c.profiles.removeLogin(value, profile) 1.36 } 1.37 1.38 // RecordLoginUse sets the LastUsed property of the Login specified in the profileStore associated with 1.39 // the Context to the value passed in as when. 1.40 -func (c Context) RecordLoginUse(loginType, value string, when time.Time) error { 1.41 +func (c Context) RecordLoginUse(value string, when time.Time) error { 1.42 if c.profiles == nil { 1.43 return ErrNoProfileStore 1.44 } 1.45 - return c.profiles.recordLoginUse(loginType, value, when) 1.46 + return c.profiles.recordLoginUse(value, when) 1.47 } 1.48 1.49 // ListLogins returns a slice of up to num Logins associated with the specified Profile from the profileStore 1.50 @@ -277,3 +278,39 @@ 1.51 } 1.52 return c.tokens.getTokensByProfileID(profileID, num, offset) 1.53 } 1.54 + 1.55 +// CreateSession stores the passed Session in the sessionStore associated with the Context. 1.56 +func (c Context) CreateSession(session Session) error { 1.57 + if c.sessions == nil { 1.58 + return ErrNoSessionStore 1.59 + } 1.60 + return c.sessions.createSession(session) 1.61 +} 1.62 + 1.63 +// GetSession returns the Session specified from the sessionStore associated with the Context. 1.64 +func (c Context) GetSession(id string) (Session, error) { 1.65 + if c.sessions == nil { 1.66 + return Session{}, ErrNoSessionStore 1.67 + } 1.68 + return c.sessions.getSession(id) 1.69 +} 1.70 + 1.71 +// RemoveSession removes the Session identified by the passed ID from the sessionStore associated with 1.72 +// the Context. 1.73 +func (c Context) RemoveSession(id string) error { 1.74 + if c.sessions == nil { 1.75 + return ErrNoSessionStore 1.76 + } 1.77 + return c.sessions.removeSession(id) 1.78 +} 1.79 + 1.80 +// ListSessions returns a slice of up to num Sessions from the sessionStore associated with the Context, 1.81 +// ordered by the date they were created, descending. If before.IsZero() returns false, only Sessions 1.82 +// that were created before that time will be returned. If profile is not nil, only Sessions belonging to 1.83 +// that Profile will be returned. 1.84 +func (c Context) ListSessions(profile uuid.ID, before time.Time, num int64) ([]Session, error) { 1.85 + if c.sessions != nil { 1.86 + return []Session{}, ErrNoSessionStore 1.87 + } 1.88 + return c.sessions.listSessions(profile, before, num) 1.89 +}
2.1 --- a/grant.go Sun Nov 09 00:22:38 2014 -0500 2.2 +++ b/grant.go Tue Nov 11 21:13:16 2014 -0500 2.3 @@ -27,6 +27,7 @@ 2.4 Scope string 2.5 RedirectURI string 2.6 State string 2.7 + ProfileID uuid.ID 2.8 } 2.9 2.10 type grantStore interface {
3.1 --- a/http.go Sun Nov 09 00:22:38 2014 -0500 3.2 +++ b/http.go Tue Nov 11 21:13:16 2014 -0500 3.3 @@ -1,22 +1,125 @@ 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 - defaultGrantExpiration = 600 // default to ten minute grant expirations 3.26 ) 3.27 3.28 +var ( 3.29 + // ErrNoAuth is returned when an Authorization header is not present or is empty. 3.30 + ErrNoAuth = errors.New("no authorization header supplied") 3.31 + // ErrInvalidAuthFormat is returned when an Authorization header is present but not the correct format. 3.32 + ErrInvalidAuthFormat = errors.New("authorization header is not in a valid format") 3.33 + // ErrIncorrectAuth is returned when a user authentication attempt does not match the stored values. 3.34 + ErrIncorrectAuth = errors.New("invalid authentication") 3.35 + // ErrInvalidPassphraseScheme is returned when an undefined passphrase scheme is used. 3.36 + ErrInvalidPassphraseScheme = errors.New("invalid passphrase scheme") 3.37 + // ErrNoSession is returned when no session ID is passed with a request. 3.38 + ErrNoSession = errors.New("no session ID found") 3.39 +) 3.40 + 3.41 +type tokenResponse struct { 3.42 + AccessToken string `json:"access_token"` 3.43 + TokenType string `json:"token_type,omitempty"` 3.44 + ExpiresIn int32 `json:"expires_in,omitempty"` 3.45 + RefreshToken string `json:"refresh_token,omitempty"` 3.46 +} 3.47 + 3.48 +func getBasicAuth(r *http.Request) (un, pass string, err error) { 3.49 + auth := r.Header.Get("Authorization") 3.50 + if auth == "" { 3.51 + return "", "", ErrNoAuth 3.52 + } 3.53 + pieces := strings.SplitN(auth, " ", 2) 3.54 + if pieces[0] != "Basic" { 3.55 + return "", "", ErrInvalidAuthFormat 3.56 + } 3.57 + decoded, err := base64.StdEncoding.DecodeString(pieces[1]) 3.58 + if err != nil { 3.59 + // TODO(paddy): should probably log this... 3.60 + return "", "", ErrInvalidAuthFormat 3.61 + } 3.62 + info := strings.SplitN(string(decoded), ":", 2) 3.63 + return info[0], info[1], nil 3.64 +} 3.65 + 3.66 +func checkCookie(r *http.Request, context Context) (Session, error) { 3.67 + cookie, err := r.Cookie(authCookieName) 3.68 + if err != nil { 3.69 + if err == http.ErrNoCookie { 3.70 + return Session{}, ErrNoSession 3.71 + } 3.72 + return Session{}, err 3.73 + } 3.74 + if cookie.Name != authCookieName || !cookie.Expires.After(time.Now()) || 3.75 + !cookie.Secure || !cookie.HttpOnly { 3.76 + return Session{}, ErrInvalidSession 3.77 + } 3.78 + sess, err := context.GetSession(cookie.Value) 3.79 + if err == ErrSessionNotFound { 3.80 + return Session{}, ErrInvalidSession 3.81 + } else if err != nil { 3.82 + return Session{}, err 3.83 + } 3.84 + if !sess.Active { 3.85 + return Session{}, ErrInvalidSession 3.86 + } 3.87 + return sess, nil 3.88 +} 3.89 + 3.90 +func authenticate(user, passphrase string, context Context) (Profile, error) { 3.91 + profile, err := context.GetProfileByLogin(user) 3.92 + if err != nil { 3.93 + if err == ErrProfileNotFound { 3.94 + return Profile{}, ErrIncorrectAuth 3.95 + } 3.96 + return Profile{}, err 3.97 + } 3.98 + switch profile.PassphraseScheme { 3.99 + case 1: 3.100 + candidate := pass.Check(sha256.New, profile.Iterations, []byte(passphrase), []byte(profile.Salt)) 3.101 + if !pass.Compare(candidate, []byte(profile.Passphrase)) { 3.102 + return Profile{}, ErrIncorrectAuth 3.103 + } 3.104 + default: 3.105 + // TODO(paddy): return some error 3.106 + return Profile{}, ErrInvalidPassphraseScheme 3.107 + } 3.108 + return profile, nil 3.109 +} 3.110 + 3.111 // GetGrantHandler presents and processes the page for asking a user to grant access 3.112 // to their data. See RFC 6749, Section 4.1. 3.113 func GetGrantHandler(w http.ResponseWriter, r *http.Request, context Context) { 3.114 + session, err := checkCookie(r, context) 3.115 + if err != nil { 3.116 + if err == ErrNoSession { 3.117 + // TODO(paddy): redirect to login screen 3.118 + //return 3.119 + } 3.120 + if err == ErrInvalidSession { 3.121 + // TODO(paddy): return an access denied error 3.122 + //return 3.123 + } 3.124 + // TODO(paddy): return a server error 3.125 + //return 3.126 + } 3.127 if r.URL.Query().Get("client_id") == "" { 3.128 w.WriteHeader(http.StatusBadRequest) 3.129 context.Render(w, getGrantTemplateName, map[string]interface{}{ 3.130 @@ -126,8 +229,9 @@ 3.131 ExpiresIn: defaultGrantExpiration, 3.132 ClientID: clientID, 3.133 Scope: scope, 3.134 - RedirectURI: redirectURI, 3.135 + RedirectURI: r.URL.Query().Get("redirect_uri"), 3.136 State: state, 3.137 + ProfileID: session.ProfileID, 3.138 } 3.139 err := context.SaveGrant(grant) 3.140 if err != nil { 3.141 @@ -158,7 +262,88 @@ 3.142 }) 3.143 } 3.144 3.145 -// TODO(paddy): exchange code for access token 3.146 +// GetTokenHandler allows a client to exchange an authorization grant for an 3.147 +// access token. See RFC 6749 Section 4.1.3. 3.148 +func GetTokenHandler(w http.ResponseWriter, r *http.Request, context Context) { 3.149 + enc := json.NewEncoder(w) 3.150 + grantType := r.PostFormValue("grant_type") 3.151 + if grantType != "authorization_code" { 3.152 + // TODO(paddy): render invalid request JSON 3.153 + return 3.154 + } 3.155 + code := r.PostFormValue("code") 3.156 + if code == "" { 3.157 + // TODO(paddy): render invalid request JSON 3.158 + return 3.159 + } 3.160 + redirectURI := r.PostFormValue("redirect_uri") 3.161 + clientIDStr, clientSecret, err := getBasicAuth(r) 3.162 + if err != nil { 3.163 + // TODO(paddy): render access denied 3.164 + return 3.165 + } 3.166 + if clientIDStr == "" && err == nil { 3.167 + clientIDStr = r.PostFormValue("client_id") 3.168 + } 3.169 + // TODO(paddy): client ID can also come from Basic auth 3.170 + clientID, err := uuid.Parse(clientIDStr) 3.171 + if err != nil { 3.172 + // TODO(paddy): render invalid request JSON 3.173 + return 3.174 + } 3.175 + client, err := context.GetClient(clientID) 3.176 + if err != nil { 3.177 + if err == ErrClientNotFound { 3.178 + // TODO(paddy): render invalid request JSON 3.179 + } else { 3.180 + // TODO(paddy): render internal server error JSON 3.181 + } 3.182 + return 3.183 + } 3.184 + if client.Secret != clientSecret { 3.185 + // TODO(paddy): render invalid request JSON 3.186 + return 3.187 + } 3.188 + grant, err := context.GetGrant(code) 3.189 + if err != nil { 3.190 + if err == ErrGrantNotFound { 3.191 + // TODO(paddy): return error 3.192 + return 3.193 + } 3.194 + // TODO(paddy): return error 3.195 + } 3.196 + if grant.RedirectURI != redirectURI { 3.197 + // TODO(paddy): return error 3.198 + } 3.199 + if !grant.ClientID.Equal(clientID) { 3.200 + // TODO(paddy): return error 3.201 + } 3.202 + token := Token{ 3.203 + AccessToken: uuid.NewID().String(), 3.204 + RefreshToken: uuid.NewID().String(), 3.205 + Created: time.Now(), 3.206 + ExpiresIn: defaultTokenExpiration, 3.207 + TokenType: "", // TODO(paddy): fill in token type 3.208 + Scope: grant.Scope, 3.209 + ProfileID: grant.ProfileID, 3.210 + } 3.211 + err = context.SaveToken(token) 3.212 + if err != nil { 3.213 + // TODO(paddy): return error 3.214 + } 3.215 + resp := tokenResponse{ 3.216 + AccessToken: token.AccessToken, 3.217 + RefreshToken: token.RefreshToken, 3.218 + ExpiresIn: token.ExpiresIn, 3.219 + TokenType: token.TokenType, 3.220 + } 3.221 + err = enc.Encode(resp) 3.222 + if err != nil { 3.223 + // TODO(paddy): log this or something 3.224 + return 3.225 + } 3.226 +} 3.227 + 3.228 // TODO(paddy): exchange user credentials for access token 3.229 // TODO(paddy): exchange client credentials for access token 3.230 // TODO(paddy): implicit grant for access token
4.1 --- a/profile.go Sun Nov 09 00:22:38 2014 -0500 4.2 +++ b/profile.go Tue Nov 11 21:13:16 2014 -0500 4.3 @@ -12,6 +12,8 @@ 4.4 MinPassphraseLength = 6 4.5 // MaxPassphraseLength is the maximum length, in bytes, of a passphrase, exclusive. 4.6 MaxPassphraseLength = 64 4.7 + // CurPassphraseScheme is the current passphrase scheme. Incrememnt it when we use a different passphrase scheme 4.8 + CurPassphraseScheme = 1 4.9 ) 4.10 4.11 var ( 4.12 @@ -52,7 +54,7 @@ 4.13 ID uuid.ID 4.14 Name string 4.15 Passphrase string 4.16 - Iterations int64 4.17 + Iterations int 4.18 Salt string 4.19 PassphraseScheme int 4.20 Compromised bool 4.21 @@ -110,7 +112,7 @@ 4.22 type ProfileChange struct { 4.23 Name *string 4.24 Passphrase *string 4.25 - Iterations *int64 4.26 + Iterations *int 4.27 Salt *string 4.28 PassphraseScheme *int 4.29 Compromised *bool 4.30 @@ -183,15 +185,15 @@ 4.31 4.32 type profileStore interface { 4.33 getProfileByID(id uuid.ID) (Profile, error) 4.34 - getProfileByLogin(loginType, value string) (Profile, error) 4.35 + getProfileByLogin(value string) (Profile, error) 4.36 saveProfile(profile Profile) error 4.37 updateProfile(id uuid.ID, change ProfileChange) error 4.38 updateProfiles(ids []uuid.ID, change BulkProfileChange) error 4.39 deleteProfile(id uuid.ID) error 4.40 4.41 addLogin(login Login) error 4.42 - removeLogin(loginType, value string, profile uuid.ID) error 4.43 - recordLoginUse(loginType, value string, when time.Time) error 4.44 + removeLogin(value string, profile uuid.ID) error 4.45 + recordLoginUse(value string, when time.Time) error 4.46 listLogins(profile uuid.ID, num, offset int) ([]Login, error) 4.47 } 4.48 4.49 @@ -205,10 +207,10 @@ 4.50 return p, nil 4.51 } 4.52 4.53 -func (m *memstore) getProfileByLogin(loginType, value string) (Profile, error) { 4.54 +func (m *memstore) getProfileByLogin(value string) (Profile, error) { 4.55 m.loginLock.RLock() 4.56 defer m.loginLock.RUnlock() 4.57 - login, ok := m.logins[loginType+":"+value] 4.58 + login, ok := m.logins[value] 4.59 if !ok { 4.60 return Profile{}, ErrLoginNotFound 4.61 } 4.62 @@ -273,29 +275,29 @@ 4.63 func (m *memstore) addLogin(login Login) error { 4.64 m.loginLock.Lock() 4.65 defer m.loginLock.Unlock() 4.66 - _, ok := m.logins[login.Type+":"+login.Value] 4.67 + _, ok := m.logins[login.Value] 4.68 if ok { 4.69 return ErrLoginAlreadyExists 4.70 } 4.71 - m.logins[login.Type+":"+login.Value] = login 4.72 - m.profileLoginLookup[login.ProfileID.String()] = append(m.profileLoginLookup[login.ProfileID.String()], login.Type+":"+login.Value) 4.73 + m.logins[login.Value] = login 4.74 + m.profileLoginLookup[login.ProfileID.String()] = append(m.profileLoginLookup[login.ProfileID.String()], login.Value) 4.75 return nil 4.76 } 4.77 4.78 -func (m *memstore) removeLogin(loginType, value string, profile uuid.ID) error { 4.79 +func (m *memstore) removeLogin(value string, profile uuid.ID) error { 4.80 m.loginLock.Lock() 4.81 defer m.loginLock.Unlock() 4.82 - l, ok := m.logins[loginType+":"+value] 4.83 + l, ok := m.logins[value] 4.84 if !ok { 4.85 return ErrLoginNotFound 4.86 } 4.87 if !l.ProfileID.Equal(profile) { 4.88 return ErrLoginNotFound 4.89 } 4.90 - delete(m.logins, loginType+":"+value) 4.91 + delete(m.logins, value) 4.92 pos := -1 4.93 for p, id := range m.profileLoginLookup[profile.String()] { 4.94 - if id == loginType+":"+value { 4.95 + if id == value { 4.96 pos = p 4.97 break 4.98 } 4.99 @@ -306,15 +308,15 @@ 4.100 return nil 4.101 } 4.102 4.103 -func (m *memstore) recordLoginUse(loginType, value string, when time.Time) error { 4.104 +func (m *memstore) recordLoginUse(value string, when time.Time) error { 4.105 m.loginLock.Lock() 4.106 defer m.loginLock.Unlock() 4.107 - l, ok := m.logins[loginType+":"+value] 4.108 + l, ok := m.logins[value] 4.109 if !ok { 4.110 return ErrLoginNotFound 4.111 } 4.112 l.LastUsed = when 4.113 - m.logins[loginType+":"+value] = l 4.114 + m.logins[value] = l 4.115 return nil 4.116 } 4.117
5.1 --- a/profile_test.go Sun Nov 09 00:22:38 2014 -0500 5.2 +++ b/profile_test.go Tue Nov 11 21:13:16 2014 -0500 5.3 @@ -149,7 +149,7 @@ 5.4 } 5.5 for i := 0; i < variations; i++ { 5.6 var name, passphrase, salt, passphraseReset string 5.7 - var iterations int64 5.8 + var iterations int 5.9 var lockedUntil, passphraseResetCreated, lastSeen time.Time 5.10 var passphraseScheme int 5.11 var compromised bool 5.12 @@ -168,7 +168,7 @@ 5.13 expectation.Passphrase = passphrase 5.14 } 5.15 if i&profileChangeIterations != 0 { 5.16 - iterations = int64(i) 5.17 + iterations = i 5.18 change.Iterations = &iterations 5.19 expectation.Iterations = iterations 5.20 } 5.21 @@ -331,7 +331,7 @@ 5.22 t.Errorf("Expected `%v` in the `%s` field of login retrieved from %T, got `%v`", expectation, field, store, result) 5.23 } 5.24 lastUsed := time.Now() 5.25 - err = store.recordLoginUse(login.Type, login.Value, lastUsed) 5.26 + err = store.recordLoginUse(login.Value, lastUsed) 5.27 if err != nil { 5.28 t.Errorf("Error recording use of login to %T: %s", store, err) 5.29 } 5.30 @@ -347,7 +347,7 @@ 5.31 if !match { 5.32 t.Errorf("Expected `%v` in the `%s` field of login retrieved from %T, got `%v`", expectation, field, store, result) 5.33 } 5.34 - err = store.removeLogin(login.Type, login.Value, login.ProfileID) 5.35 + err = store.removeLogin(login.Value, login.ProfileID) 5.36 if err != nil { 5.37 t.Errorf("Error removing login from %T: %s", store, err) 5.38 } 5.39 @@ -355,7 +355,7 @@ 5.40 if len(retrieved) != 0 { 5.41 t.Errorf("Expected 0 login results from %T, got %d: %+v", store, len(retrieved), retrieved) 5.42 } 5.43 - err = store.removeLogin(login.Type, login.Value, login.ProfileID) 5.44 + err = store.removeLogin(login.Value, login.ProfileID) 5.45 if err != ErrLoginNotFound { 5.46 t.Errorf("Expected ErrLoginNotFound from %T, got %+v", store, err) 5.47 } 5.48 @@ -394,7 +394,7 @@ 5.49 if err != nil { 5.50 t.Errorf("Error storing login in %T: %s", store, err) 5.51 } 5.52 - retrieved, err := store.getProfileByLogin(login.Type, login.Value) 5.53 + retrieved, err := store.getProfileByLogin(login.Value) 5.54 if err != nil { 5.55 t.Errorf("Error retrieving profile by login from %T: %s", store, err) 5.56 } 5.57 @@ -410,7 +410,7 @@ 5.58 passphraseScheme := 1 5.59 passphraseReset := "reset" 5.60 salt := "salt" 5.61 - iterations := int64(100) 5.62 + iterations := 100 5.63 shortPassphrase := "a" 5.64 longPassphrase := "this passphrase is much too long for anyone to remember, and therefore should probably be discouraged by the software, don't you think?" 5.65 emptyName := ""
6.1 --- a/token.go Sun Nov 09 00:22:38 2014 -0500 6.2 +++ b/token.go Tue Nov 11 21:13:16 2014 -0500 6.3 @@ -7,6 +7,10 @@ 6.4 "code.secondbit.org/uuid" 6.5 ) 6.6 6.7 +const ( 6.8 + defaultTokenExpiration = 3600 // one hour 6.9 +) 6.10 + 6.11 var ( 6.12 // ErrNoTokenStore is returned when a Context tries to act on a tokenStore without setting one first. 6.13 ErrNoTokenStore = errors.New("no tokenStore was specified for the Context")