Make all tests that deal with the store interfaces go through the Context. This
is mainly important so that pre- and post- save/retrieval/deletion/whatever
transforms can be done without doing them in every single implementation of the
store.
Change the Endpoint URI property to be a string, not a *url.URL. This makes
testing easier, JSON responses cleaner, and is all around just a better
strategy. Just because we turn it into a URL every now and then doesn't mean
that's how we need to store it.
Add JSON tags to the Client type and Endpoint type.
Create normalizeURI and normalizeURIString methods to... well, normalize the
Endpoint URIs. This makes it so that we can compare them, and forgive some
arbitrary user behaviour (like slashes, etc.)
Add a NormalizedURI property to the Endpoint type. This is where we store the
NormalizedURI, which is what we'll be using when we want to check if an endpoint
is valid or not. For the sake of tests and predictability, however, we always
want to redirect to the URI, not the NormalizedURI.
Add checks to the Client creation API endpoint to give better errors. Now
leaving out the Type won't be considered an invalid type, it will be considered
a missing parameter. An empty name will be reported as a missing parameter, a
name with too few characters will be reported as an insufficient name, and a
name with too many characters will be reported as an overflow name. We gather as
many of these errors as apply before returning.
Check if an Endpoint URI is absolute before adding it as an endpoint, or return
an invalid value error if it is not.
Always return the errors array when creating a client. We could succeed in
creating one or more things and still have errors. We should return anything
that's created _as well as_ any errors encountered.
Add unit testing for our CreateClientHandler.
Fix our oauth2 tests so that if there's an error in the body, it's in the test
logs. This should help debugging significantly.
Fix our oauth2 tests so that the Profile only requires 1 iteration for its
password hashing. This means each time we want to validate a session, it doesn't
add a full second to our test runs. This is a big speed improvement for our
tests.
Add test helper methods for comparing API errors, API responses, and filling in
server-generated information in a response that it's impossible to have an
expectation around (e.g., IDs) so that we can use our comparison helpers to
check if a response is as we expect it.
Fix a typo in our Context helpers that was reporting no sessionStore being set
_only_ when a sessionStore was set. So yes, the opposite of what we wanted.
Oops. This was discovered by passing all our tests through the context. methods
instead of operating on the stores themselves.
12 "code.secondbit.org/pass.hg"
13 "code.secondbit.org/uuid.hg"
14 "github.com/gorilla/mux"
18 loginTemplateName = "login"
22 // ErrNoSessionStore is returned when a Context tries to act on a sessionStore without setting on first.
23 ErrNoSessionStore = errors.New("no sessionStore was specified for the Context")
24 // ErrSessionNotFound is returned when a Session is requested but not found in the sessionStore.
25 ErrSessionNotFound = errors.New("session not found in sessionStore")
26 // ErrInvalidSession is returned when a Session is specified but is not valid.
27 ErrInvalidSession = errors.New("session is not valid")
28 // ErrSessionAlreadyExists is returned when a sessionStore tries to store a Session with an ID that already exists in the sessionStore.
29 ErrSessionAlreadyExists = errors.New("session already exists")
31 passphraseSchemes = map[int]passphraseScheme{
33 check: pbkdf2sha256check,
34 create: pbkdf2sha256create,
35 calculateIterations: pbkdf2sha256calc,
40 type passphraseScheme struct {
41 check func(profile Profile, passphrase string) (bool, error)
42 create func(passphrase string, iterations int) (result, salt string, err error)
43 calculateIterations func() (int, error)
46 // Session represents a user's authenticated session, associating it with a profile
47 // and some audit data.
58 type sortedSessions []Session
60 func (s sortedSessions) Len() int {
64 func (s sortedSessions) Less(i, j int) bool {
65 return s[i].Created.After(s[j].Created)
68 func (s sortedSessions) Swap(i, j int) {
69 s[i], s[j] = s[j], s[i]
72 type sessionStore interface {
73 createSession(session Session) error
74 getSession(id string) (Session, error)
75 removeSession(id string) error
76 listSessions(profile uuid.ID, before time.Time, num int64) ([]Session, error)
79 func (m *memstore) createSession(session Session) error {
81 defer m.sessionLock.Unlock()
82 if _, ok := m.sessions[session.ID]; ok {
83 return ErrSessionAlreadyExists
85 m.sessions[session.ID] = session
89 func (m *memstore) getSession(id string) (Session, error) {
91 defer m.sessionLock.RUnlock()
92 if _, ok := m.sessions[id]; !ok {
93 return Session{}, ErrSessionNotFound
95 return m.sessions[id], nil
98 func (m *memstore) removeSession(id string) error {
100 defer m.sessionLock.Unlock()
101 if _, ok := m.sessions[id]; !ok {
102 return ErrSessionNotFound
104 delete(m.sessions, id)
108 func (m *memstore) listSessions(profile uuid.ID, before time.Time, num int64) ([]Session, error) {
109 m.sessionLock.RLock()
110 defer m.sessionLock.RUnlock()
112 for _, session := range m.sessions {
113 if int64(len(res)) >= num {
116 if profile != nil && !profile.Equal(session.ProfileID) {
119 if !before.IsZero() && session.Created.After(before) {
122 res = append(res, session)
124 sorted := sortedSessions(res)
126 res = []Session(sorted)
130 // RegisterSessionHandlers adds handlers to the passed router to handle the session endpoints, like login and logout.
131 func RegisterSessionHandlers(r *mux.Router, context Context) {
132 r.Handle("/login", wrap(context, CreateSessionHandler))
135 func checkCookie(r *http.Request, context Context) (Session, error) {
136 cookie, err := r.Cookie(authCookieName)
137 if err == http.ErrNoCookie {
138 return Session{}, ErrNoSession
139 } else if err != nil {
141 return Session{}, err
143 sess, err := context.GetSession(cookie.Value)
144 if err == ErrSessionNotFound {
145 return Session{}, ErrInvalidSession
146 } else if err != nil {
147 return Session{}, err
150 return Session{}, ErrInvalidSession
155 func buildLoginRedirect(r *http.Request, context Context) string {
156 if context.loginURI == nil {
159 uri := *context.loginURI
161 q.Set("from", r.URL.String())
162 uri.RawQuery = q.Encode()
166 func pbkdf2sha256check(profile Profile, passphrase string) (bool, error) {
167 realPass, err := hex.DecodeString(profile.Passphrase)
171 realSalt, err := hex.DecodeString(profile.Salt)
175 candidate := pass.Check(sha256.New, profile.Iterations, []byte(passphrase), []byte(realSalt))
176 if !pass.Compare(candidate, realPass) {
177 return false, ErrIncorrectAuth
182 func pbkdf2sha256create(passphrase string, iters int) (result, salt string, err error) {
183 passBytes, saltBytes, err := pass.Create(sha256.New, iters, []byte(passphrase))
187 result = hex.EncodeToString(passBytes)
188 salt = hex.EncodeToString(saltBytes)
189 return result, salt, err
192 func pbkdf2sha256calc() (int, error) {
193 return pass.CalculateIterations(sha256.New)
196 func authenticate(user, passphrase string, context Context) (Profile, error) {
197 profile, err := context.GetProfileByLogin(user)
199 if err == ErrProfileNotFound || err == ErrLoginNotFound {
200 return Profile{}, ErrIncorrectAuth
202 return Profile{}, err
204 if profile.Compromised {
205 return Profile{}, ErrProfileCompromised
207 if !profile.LockedUntil.IsZero() && profile.LockedUntil.After(time.Now()) {
208 return profile, ErrProfileLocked
210 scheme, ok := passphraseSchemes[profile.PassphraseScheme]
212 return Profile{}, ErrInvalidPassphraseScheme
214 result, err := scheme.check(profile, passphrase)
216 return Profile{}, err
221 // CreateSessionHandler allows the user to log into their account and create their session.
222 func CreateSessionHandler(w http.ResponseWriter, r *http.Request, context Context) {
223 // BUG(paddy): Creating a session needs CSRF protection, right? This whole thing should get a security audit
225 if r.Method == "POST" {
226 profile, err := authenticate(r.PostFormValue("login"), r.PostFormValue("passphrase"), context)
228 ip := r.Header.Get("X-Forwarded-For")
233 ID: uuid.NewID().String(),
235 UserAgent: r.UserAgent(),
236 ProfileID: profile.ID,
237 Login: r.PostFormValue("login"),
241 err = context.CreateSession(session)
243 w.WriteHeader(http.StatusInternalServerError)
244 w.Write([]byte(err.Error()))
247 // BUG(paddy): really need to do a security audit on our cookie
248 cookie := http.Cookie{
249 Name: authCookieName,
251 Expires: time.Now().Add(24 * 7 * time.Hour),
254 http.SetCookie(w, &cookie)
255 redirectTo := r.URL.Query().Get("from")
256 if redirectTo == "" {
259 http.Redirect(w, r, redirectTo, http.StatusFound)
261 } else if err != ErrIncorrectAuth && err != ErrProfileCompromised && err != ErrProfileLocked {
262 w.WriteHeader(http.StatusInternalServerError)
263 w.Write([]byte(err.Error()))
266 errors = append(errors, err)
269 context.Render(w, loginTemplateName, map[string]interface{}{