auth
auth/session.go
Test around client types and secrets. Implement a test that the CreateClient handler will correctly create a confidential client and issue a secret for it. Also, just generally test that clients that are confidential are issued secrets and clients that are public are not.
1 package auth
3 import (
4 "crypto/sha256"
5 "encoding/hex"
6 "encoding/json"
7 "errors"
8 "log"
9 "net/http"
10 "sort"
11 "time"
13 "code.secondbit.org/pass.hg"
14 "code.secondbit.org/uuid.hg"
15 "github.com/gorilla/mux"
16 )
18 const (
19 loginTemplateName = "login"
20 )
22 func init() {
23 RegisterGrantType("password", GrantType{
24 Validate: credentialsValidate,
25 Invalidate: nil,
26 IssuesRefresh: true,
27 ReturnToken: RenderJSONToken,
28 AuditString: credentialsAuditString,
29 })
30 }
32 var (
33 // ErrNoSessionStore is returned when a Context tries to act on a sessionStore without setting on first.
34 ErrNoSessionStore = errors.New("no sessionStore was specified for the Context")
35 // ErrSessionNotFound is returned when a Session is requested but not found in the sessionStore.
36 ErrSessionNotFound = errors.New("session not found in sessionStore")
37 // ErrInvalidSession is returned when a Session is specified but is not valid.
38 ErrInvalidSession = errors.New("session is not valid")
39 // ErrSessionAlreadyExists is returned when a sessionStore tries to store a Session with an ID that already exists in the sessionStore.
40 ErrSessionAlreadyExists = errors.New("session already exists")
42 passphraseSchemes = map[int]passphraseScheme{
43 1: {
44 check: pbkdf2sha256check,
45 create: pbkdf2sha256create,
46 calculateIterations: pbkdf2sha256calc,
47 },
48 }
49 )
51 type passphraseScheme struct {
52 check func(profile Profile, passphrase string) (bool, error)
53 create func(passphrase string, iterations int) (result, salt string, err error)
54 calculateIterations func() (int, error)
55 }
57 // Session represents a user's authenticated session, associating it with a profile
58 // and some audit data.
59 type Session struct {
60 ID string
61 IP string
62 UserAgent string
63 ProfileID uuid.ID
64 Login string
65 Created time.Time
66 Active bool
67 }
69 type sortedSessions []Session
71 func (s sortedSessions) Len() int {
72 return len(s)
73 }
75 func (s sortedSessions) Less(i, j int) bool {
76 return s[i].Created.After(s[j].Created)
77 }
79 func (s sortedSessions) Swap(i, j int) {
80 s[i], s[j] = s[j], s[i]
81 }
83 type sessionStore interface {
84 createSession(session Session) error
85 getSession(id string) (Session, error)
86 removeSession(id string) error
87 listSessions(profile uuid.ID, before time.Time, num int64) ([]Session, error)
88 }
90 func (m *memstore) createSession(session Session) error {
91 m.sessionLock.Lock()
92 defer m.sessionLock.Unlock()
93 if _, ok := m.sessions[session.ID]; ok {
94 return ErrSessionAlreadyExists
95 }
96 m.sessions[session.ID] = session
97 return nil
98 }
100 func (m *memstore) getSession(id string) (Session, error) {
101 m.sessionLock.RLock()
102 defer m.sessionLock.RUnlock()
103 if _, ok := m.sessions[id]; !ok {
104 return Session{}, ErrSessionNotFound
105 }
106 return m.sessions[id], nil
107 }
109 func (m *memstore) removeSession(id string) error {
110 m.sessionLock.Lock()
111 defer m.sessionLock.Unlock()
112 if _, ok := m.sessions[id]; !ok {
113 return ErrSessionNotFound
114 }
115 delete(m.sessions, id)
116 return nil
117 }
119 func (m *memstore) listSessions(profile uuid.ID, before time.Time, num int64) ([]Session, error) {
120 m.sessionLock.RLock()
121 defer m.sessionLock.RUnlock()
122 res := []Session{}
123 for _, session := range m.sessions {
124 if int64(len(res)) >= num {
125 break
126 }
127 if profile != nil && !profile.Equal(session.ProfileID) {
128 continue
129 }
130 if !before.IsZero() && session.Created.After(before) {
131 continue
132 }
133 res = append(res, session)
134 }
135 sorted := sortedSessions(res)
136 sort.Sort(sorted)
137 res = []Session(sorted)
138 return res, nil
139 }
141 // RegisterSessionHandlers adds handlers to the passed router to handle the session endpoints, like login and logout.
142 func RegisterSessionHandlers(r *mux.Router, context Context) {
143 r.Handle("/login", wrap(context, CreateSessionHandler))
144 }
146 func checkCookie(r *http.Request, context Context) (Session, error) {
147 cookie, err := r.Cookie(authCookieName)
148 if err == http.ErrNoCookie {
149 return Session{}, ErrNoSession
150 } else if err != nil {
151 log.Println(err)
152 return Session{}, err
153 }
154 sess, err := context.GetSession(cookie.Value)
155 if err == ErrSessionNotFound {
156 return Session{}, ErrInvalidSession
157 } else if err != nil {
158 return Session{}, err
159 }
160 if !sess.Active {
161 return Session{}, ErrInvalidSession
162 }
163 return sess, nil
164 }
166 func buildLoginRedirect(r *http.Request, context Context) string {
167 if context.loginURI == nil {
168 return ""
169 }
170 uri := *context.loginURI
171 q := uri.Query()
172 q.Set("from", r.URL.String())
173 uri.RawQuery = q.Encode()
174 return uri.String()
175 }
177 func pbkdf2sha256check(profile Profile, passphrase string) (bool, error) {
178 realPass, err := hex.DecodeString(profile.Passphrase)
179 if err != nil {
180 return false, err
181 }
182 realSalt, err := hex.DecodeString(profile.Salt)
183 if err != nil {
184 return false, err
185 }
186 candidate := pass.Check(sha256.New, profile.Iterations, []byte(passphrase), []byte(realSalt))
187 if !pass.Compare(candidate, realPass) {
188 return false, ErrIncorrectAuth
189 }
190 return true, nil
191 }
193 func pbkdf2sha256create(passphrase string, iters int) (result, salt string, err error) {
194 passBytes, saltBytes, err := pass.Create(sha256.New, iters, []byte(passphrase))
195 if err != nil {
196 return "", "", err
197 }
198 result = hex.EncodeToString(passBytes)
199 salt = hex.EncodeToString(saltBytes)
200 return result, salt, err
201 }
203 func pbkdf2sha256calc() (int, error) {
204 return pass.CalculateIterations(sha256.New)
205 }
207 func authenticate(user, passphrase string, context Context) (Profile, error) {
208 profile, err := context.GetProfileByLogin(user)
209 if err != nil {
210 if err == ErrProfileNotFound || err == ErrLoginNotFound {
211 return Profile{}, ErrIncorrectAuth
212 }
213 return Profile{}, err
214 }
215 if profile.Compromised {
216 return Profile{}, ErrProfileCompromised
217 }
218 if !profile.LockedUntil.IsZero() && profile.LockedUntil.After(time.Now()) {
219 return profile, ErrProfileLocked
220 }
221 scheme, ok := passphraseSchemes[profile.PassphraseScheme]
222 if !ok {
223 return Profile{}, ErrInvalidPassphraseScheme
224 }
225 result, err := scheme.check(profile, passphrase)
226 if !result {
227 return Profile{}, err
228 }
229 return profile, nil
230 }
232 // CreateSessionHandler allows the user to log into their account and create their session.
233 func CreateSessionHandler(w http.ResponseWriter, r *http.Request, context Context) {
234 // BUG(paddy): Creating a session needs CSRF protection, right? This whole thing should get a security audit
235 errors := []error{}
236 if r.Method == "POST" {
237 profile, err := authenticate(r.PostFormValue("login"), r.PostFormValue("passphrase"), context)
238 if err == nil {
239 ip := r.Header.Get("X-Forwarded-For")
240 if ip == "" {
241 ip = r.RemoteAddr
242 }
243 session := Session{
244 ID: uuid.NewID().String(),
245 IP: ip,
246 UserAgent: r.UserAgent(),
247 ProfileID: profile.ID,
248 Login: r.PostFormValue("login"),
249 Created: time.Now(),
250 Active: true,
251 }
252 err = context.CreateSession(session)
253 if err != nil {
254 w.WriteHeader(http.StatusInternalServerError)
255 w.Write([]byte(err.Error()))
256 return
257 }
258 // BUG(paddy): really need to do a security audit on our cookie
259 cookie := http.Cookie{
260 Name: authCookieName,
261 Value: session.ID,
262 Expires: time.Now().Add(24 * 7 * time.Hour),
263 HttpOnly: true,
264 }
265 http.SetCookie(w, &cookie)
266 redirectTo := r.URL.Query().Get("from")
267 if redirectTo == "" {
268 redirectTo = "/"
269 }
270 http.Redirect(w, r, redirectTo, http.StatusFound)
271 return
272 } else if err != ErrIncorrectAuth && err != ErrProfileCompromised && err != ErrProfileLocked {
273 w.WriteHeader(http.StatusInternalServerError)
274 w.Write([]byte(err.Error()))
275 return
276 } else {
277 errors = append(errors, err)
278 }
279 }
280 context.Render(w, loginTemplateName, map[string]interface{}{
281 "errors": errors,
282 })
283 }
285 func credentialsValidate(w http.ResponseWriter, r *http.Request, context Context) (scope string, profileID uuid.ID, valid bool) {
286 enc := json.NewEncoder(w)
287 username := r.PostFormValue("username")
288 password := r.PostFormValue("password")
289 scope = r.PostFormValue("scope")
290 profile, err := authenticate(username, password, context)
291 if err != nil {
292 if err == ErrIncorrectAuth || err == ErrProfileCompromised || err == ErrProfileLocked {
293 w.WriteHeader(http.StatusBadRequest)
294 renderJSONError(enc, "invalid_grant")
295 return
296 }
297 w.WriteHeader(http.StatusInternalServerError)
298 w.Write([]byte(err.Error()))
299 return
300 }
301 profileID = profile.ID
302 valid = true
303 return
304 }
306 func credentialsAuditString(r *http.Request) string {
307 return "credentials"
308 }