auth
auth/profile.go
Do a first, naive pass at storing profiles in Postgres. This is untested against an actual database. It's a best-guess attempt at SQL. It _should_ work. I think. Start storing things in Postgres, starting with Profiles and Logins. This necessitates the addition of a Deleted property to the Profile type, because I'm not deleting those in case of accidental deletion. Logins, though, we'll delete. This also necessitates updating the profileStore interface to no longer have a deleteProfile method, because we're tracking that through updates now. Then we need to update our profileStore tests, because they no longer clean up after themselves. Which, come to think of it, may cause some problems later.
1 package auth
3 import (
4 "encoding/json"
5 "errors"
6 "net/http"
7 "regexp"
8 "strings"
9 "time"
11 "code.secondbit.org/uuid.hg"
12 "github.com/extemporalgenome/slug"
13 "github.com/gorilla/mux"
14 )
16 const (
17 // MinPassphraseLength is the minimum length, in bytes, of a passphrase, exclusive.
18 MinPassphraseLength = 6
19 // MaxPassphraseLength is the maximum length, in bytes, of a passphrase, exclusive.
20 MaxPassphraseLength = 64
21 // CurPassphraseScheme is the current passphrase scheme. Incrememnt it when we use a different passphrase scheme
22 CurPassphraseScheme = 1
23 // MaxNameLength is the maximum length, in bytes, of a name, exclusive.
24 MaxNameLength = 64
25 // MaxUsernameLength is the maximum length, in bytes, of a username, exclusive.
26 MaxUsernameLength = 16
27 // MaxEmailLength is the maximum length, in bytes, of an email address, exclusive.
28 MaxEmailLength = 64
29 )
31 var (
32 // ErrNoProfileStore is returned when a Context tries to act on a profileStore without setting one first.
33 ErrNoProfileStore = errors.New("no profileStore was specified for the Context")
34 // ErrProfileAlreadyExists is returned when a Profile is added to a profileStore, but another Profile with
35 // the same ID already exists in the profileStore.
36 ErrProfileAlreadyExists = errors.New("profile already exists in profileStore")
37 // ErrProfileNotFound is returned when a Profile is requested but not found in the profileStore.
38 ErrProfileNotFound = errors.New("profile not found in profileStore")
39 // ErrLoginAlreadyExists is returned when a Login is added to a profileStore, but another Login with the same
40 // Type and Value already exists in the profileStore.
41 ErrLoginAlreadyExists = errors.New("login already exists in profileStore")
42 // ErrLoginNotFound is returned when a Login is requested but not found in the profileStore.
43 ErrLoginNotFound = errors.New("login not found in profileStore")
45 // ErrMissingPassphrase is returned when a ProfileChange is validated but does not contain a
46 // Passphrase, and requires one.
47 ErrMissingPassphrase = errors.New("missing passphrase")
48 // ErrMissingPassphraseReset is returned when a ProfileChange is validated but does not contain
49 // a PassphraseReset, and requires one.
50 ErrMissingPassphraseReset = errors.New("missing passphrase reset")
51 // ErrMissingPassphraseResetCreated is returned when a ProfileChange is validated but does not
52 // contain a PassphraseResetCreated, and requires one.
53 ErrMissingPassphraseResetCreated = errors.New("missing passphrase reset created timestamp")
54 // ErrPassphraseTooShort is returned when a ProfileChange is validated and contains a Passphrase,
55 // but the Passphrase is shorter than MinPassphraseLength.
56 ErrPassphraseTooShort = errors.New("passphrase too short")
57 // ErrPassphraseTooLong is returned when a ProfileChange is validated and contains a Passphrase,
58 // but the Passphrase is longer than MaxPassphraseLength.
59 ErrPassphraseTooLong = errors.New("passphrase too long")
61 // ErrProfileCompromised is returned when a user tries to log in with a profile that is suspected
62 // of being compromised.
63 ErrProfileCompromised = errors.New("profile compromised")
64 // ErrProfileLocked is returned when a user tries to log in with a profile that is locked for a certain
65 // duration, to prevent brute force attacks.
66 ErrProfileLocked = errors.New("profile locked")
67 )
69 // Profile represents a single user of the service,
70 // including their authentication information, but not
71 // including their username or email.
72 type Profile struct {
73 ID uuid.ID `json:"id,omitempty"`
74 Name string `json:"name,omitempty"`
75 Passphrase string `json:"-"`
76 Iterations int `json:"-"`
77 Salt string `json:"-"`
78 PassphraseScheme int `json:"-"`
79 Compromised bool `json:"-"`
80 LockedUntil time.Time `json:"-"`
81 PassphraseReset string `json:"-"`
82 PassphraseResetCreated time.Time `json:"-"`
83 Created time.Time `json:"created,omitempty"`
84 LastSeen time.Time `json:"last_seen,omitempty"`
85 Deleted bool `json:"deleted,omitempty"`
86 }
88 // ApplyChange applies the properties of the passed ProfileChange
89 // to the Profile it is called on.
90 func (p *Profile) ApplyChange(change ProfileChange) {
91 if change.Name != nil {
92 p.Name = *change.Name
93 }
94 if change.Passphrase != nil {
95 p.Passphrase = *change.Passphrase
96 }
97 if change.Iterations != nil {
98 p.Iterations = *change.Iterations
99 }
100 if change.Salt != nil {
101 p.Salt = *change.Salt
102 }
103 if change.PassphraseScheme != nil {
104 p.PassphraseScheme = *change.PassphraseScheme
105 }
106 if change.Compromised != nil {
107 p.Compromised = *change.Compromised
108 }
109 if change.LockedUntil != nil {
110 p.LockedUntil = *change.LockedUntil
111 }
112 if change.PassphraseReset != nil {
113 p.PassphraseReset = *change.PassphraseReset
114 }
115 if change.PassphraseResetCreated != nil {
116 p.PassphraseResetCreated = *change.PassphraseResetCreated
117 }
118 if change.LastSeen != nil {
119 p.LastSeen = *change.LastSeen
120 }
121 if change.Deleted != nil {
122 p.Deleted = *change.Deleted
123 }
124 }
126 // ApplyBulkChange applies the properties of the passed BulkProfileChange
127 // to the Profile it is called on.
128 func (p *Profile) ApplyBulkChange(change BulkProfileChange) {
129 if change.Compromised != nil {
130 p.Compromised = *change.Compromised
131 }
132 }
134 // ProfileChange represents a single atomic change to a Profile's mutable data.
135 type ProfileChange struct {
136 Name *string
137 Passphrase *string
138 Iterations *int
139 Salt *string
140 PassphraseScheme *int
141 Compromised *bool
142 LockedUntil *time.Time
143 PassphraseReset *string
144 PassphraseResetCreated *time.Time
145 LastSeen *time.Time
146 Deleted *bool
147 }
149 // Validate checks the ProfileChange it is called on
150 // and asserts its internal validity, or lack thereof.
151 // A descriptive error will be returned in the case of
152 // an invalid change.
153 func (c ProfileChange) Validate() error {
154 if c.Name == nil && c.Passphrase == nil && c.Iterations == nil && c.Salt == nil && c.PassphraseScheme == nil && c.Compromised == nil && c.LockedUntil == nil && c.PassphraseReset == nil && c.PassphraseResetCreated == nil && c.LastSeen == nil && c.Deleted == nil {
155 return ErrEmptyChange
156 }
157 if c.PassphraseScheme != nil && c.Passphrase == nil {
158 return ErrMissingPassphrase
159 }
160 if c.PassphraseReset != nil && c.PassphraseResetCreated == nil {
161 return ErrMissingPassphraseResetCreated
162 }
163 if c.PassphraseReset == nil && c.PassphraseResetCreated != nil {
164 return ErrMissingPassphraseReset
165 }
166 if c.Salt != nil && c.Passphrase == nil {
167 return ErrMissingPassphrase
168 }
169 if c.Iterations != nil && c.Passphrase == nil {
170 return ErrMissingPassphrase
171 }
172 return nil
173 }
175 // BulkProfileChange represents a single atomic change to many Profiles' mutable data.
176 // It is a subset of a ProfileChange, as it doesn't make sense to mutate some of the
177 // ProfileChange values across many Profiles all at once.
178 type BulkProfileChange struct {
179 Compromised *bool
180 }
182 // Validate checks the BulkProfileChange it is called on
183 // and asserts its internal validity, or lack thereof.
184 // A descriptive error will be returned in the case of an
185 // invalid change.
186 func (b BulkProfileChange) Validate() error {
187 if b.Compromised == nil {
188 return ErrEmptyChange
189 }
190 return nil
191 }
193 // Login represents a single human-friendly identifier for
194 // a given Profile that can be used to log into that Profile.
195 // Each Profile may only have one Login for each Type.
196 type Login struct {
197 Type string `json:"type,omitempty"`
198 Value string `json:"value,omitempty"`
199 ProfileID uuid.ID `json:"profile_id,omitempty"`
200 Created time.Time `json:"created,omitempty"`
201 LastUsed time.Time `json:"last_used,omitempty"`
202 }
204 type newProfileRequest struct {
205 Username string `json:"username"`
206 Email string `json:"email"`
207 Passphrase string `json:"passphrase"`
208 Name string `json:"name"`
209 }
211 func validateNewProfileRequest(req *newProfileRequest) []requestError {
212 errors := []requestError{}
213 req.Name = strings.TrimSpace(req.Name)
214 req.Email = strings.TrimSpace(req.Email)
215 req.Username = slug.SlugAscii(strings.TrimSpace(req.Username))
216 if len(req.Passphrase) < MinPassphraseLength {
217 errors = append(errors, requestError{
218 Slug: requestErrInsufficient,
219 Field: "/passphrase",
220 })
221 }
222 if len(req.Passphrase) > MaxPassphraseLength {
223 errors = append(errors, requestError{
224 Slug: requestErrOverflow,
225 Field: "/passphrase",
226 })
227 }
228 if len(req.Name) > MaxNameLength {
229 errors = append(errors, requestError{
230 Slug: requestErrOverflow,
231 Field: "/name",
232 })
233 }
234 if len(req.Username) > MaxUsernameLength {
235 errors = append(errors, requestError{
236 Slug: requestErrOverflow,
237 Field: "/username",
238 })
239 }
240 if req.Email == "" {
241 errors = append(errors, requestError{
242 Slug: requestErrMissing,
243 Field: "/email",
244 })
245 }
246 if len(req.Email) > MaxEmailLength {
247 errors = append(errors, requestError{
248 Slug: requestErrOverflow,
249 Field: "/email",
250 })
251 }
252 re := regexp.MustCompile(".+@.+\\..+")
253 if !re.Match([]byte(req.Email)) {
254 errors = append(errors, requestError{
255 Slug: requestErrInvalidFormat,
256 Field: "/email",
257 })
258 }
259 return errors
260 }
262 type profileStore interface {
263 getProfileByID(id uuid.ID) (Profile, error)
264 getProfileByLogin(value string) (Profile, error)
265 saveProfile(profile Profile) error
266 updateProfile(id uuid.ID, change ProfileChange) error
267 updateProfiles(ids []uuid.ID, change BulkProfileChange) error
269 addLogin(login Login) error
270 removeLogin(value string, profile uuid.ID) error
271 recordLoginUse(value string, when time.Time) error
272 listLogins(profile uuid.ID, num, offset int) ([]Login, error)
273 }
275 func (m *memstore) getProfileByID(id uuid.ID) (Profile, error) {
276 m.profileLock.RLock()
277 defer m.profileLock.RUnlock()
278 p, ok := m.profiles[id.String()]
279 if !ok {
280 return Profile{}, ErrProfileNotFound
281 }
282 if p.Deleted {
283 return Profile{}, ErrProfileNotFound
284 }
285 return p, nil
286 }
288 func (m *memstore) getProfileByLogin(value string) (Profile, error) {
289 m.loginLock.RLock()
290 defer m.loginLock.RUnlock()
291 login, ok := m.logins[value]
292 if !ok {
293 return Profile{}, ErrLoginNotFound
294 }
295 m.profileLock.RLock()
296 defer m.profileLock.RUnlock()
297 profile, ok := m.profiles[login.ProfileID.String()]
298 if !ok {
299 return Profile{}, ErrProfileNotFound
300 }
301 if profile.Deleted {
302 return Profile{}, ErrProfileNotFound
303 }
304 return profile, nil
305 }
307 func (m *memstore) saveProfile(profile Profile) error {
308 m.profileLock.Lock()
309 defer m.profileLock.Unlock()
310 _, ok := m.profiles[profile.ID.String()]
311 if ok {
312 return ErrProfileAlreadyExists
313 }
314 m.profiles[profile.ID.String()] = profile
315 return nil
316 }
318 func (m *memstore) updateProfile(id uuid.ID, change ProfileChange) error {
319 m.profileLock.Lock()
320 defer m.profileLock.Unlock()
321 p, ok := m.profiles[id.String()]
322 if !ok {
323 return ErrProfileNotFound
324 }
325 p.ApplyChange(change)
326 m.profiles[id.String()] = p
327 return nil
328 }
330 func (m *memstore) updateProfiles(ids []uuid.ID, change BulkProfileChange) error {
331 m.profileLock.Lock()
332 defer m.profileLock.Unlock()
333 for id, profile := range m.profiles {
334 for _, i := range ids {
335 if id == i.String() {
336 profile.ApplyBulkChange(change)
337 m.profiles[id] = profile
338 break
339 }
340 }
341 }
342 return nil
343 }
345 func (m *memstore) addLogin(login Login) error {
346 m.loginLock.Lock()
347 defer m.loginLock.Unlock()
348 _, ok := m.logins[login.Value]
349 if ok {
350 return ErrLoginAlreadyExists
351 }
352 m.logins[login.Value] = login
353 m.profileLoginLookup[login.ProfileID.String()] = append(m.profileLoginLookup[login.ProfileID.String()], login.Value)
354 return nil
355 }
357 func (m *memstore) removeLogin(value string, profile uuid.ID) error {
358 m.loginLock.Lock()
359 defer m.loginLock.Unlock()
360 l, ok := m.logins[value]
361 if !ok {
362 return ErrLoginNotFound
363 }
364 if !l.ProfileID.Equal(profile) {
365 return ErrLoginNotFound
366 }
367 delete(m.logins, value)
368 pos := -1
369 for p, id := range m.profileLoginLookup[profile.String()] {
370 if id == value {
371 pos = p
372 break
373 }
374 }
375 if pos >= 0 {
376 m.profileLoginLookup[profile.String()] = append(m.profileLoginLookup[profile.String()][:pos], m.profileLoginLookup[profile.String()][pos+1:]...)
377 }
378 return nil
379 }
381 func (m *memstore) recordLoginUse(value string, when time.Time) error {
382 m.loginLock.Lock()
383 defer m.loginLock.Unlock()
384 l, ok := m.logins[value]
385 if !ok {
386 return ErrLoginNotFound
387 }
388 l.LastUsed = when
389 m.logins[value] = l
390 return nil
391 }
393 func (m *memstore) listLogins(profile uuid.ID, num, offset int) ([]Login, error) {
394 m.loginLock.RLock()
395 defer m.loginLock.RUnlock()
396 ids, ok := m.profileLoginLookup[profile.String()]
397 if !ok {
398 return []Login{}, nil
399 }
400 if len(ids) > num+offset {
401 ids = ids[offset : num+offset]
402 } else if len(ids) > offset {
403 ids = ids[offset:]
404 } else {
405 return []Login{}, nil
406 }
407 logins := []Login{}
408 for _, id := range ids {
409 login, ok := m.logins[id]
410 if !ok {
411 continue
412 }
413 logins = append(logins, login)
414 }
415 return logins, nil
416 }
418 // RegisterProfileHandlers adds handlers to the passed router to handle the profile endpoints, like registration and user retrieval.
419 func RegisterProfileHandlers(r *mux.Router, context Context) {
420 r.Handle("/profiles", wrap(context, CreateProfileHandler)).Methods("POST")
421 // BUG(paddy): We need to implement a handler that will return information about a profile or set of profiles.
422 r.Handle("/profiles/{id}", wrap(context, UpdateProfileHandler)).Methods("PATCH")
423 // BUG(paddy): We need to implement a handler that will delete a profile. What happens to clients/tokens/grants/sessions when a profile is deleted?
424 // BUG(paddy): We need to implement a handler that will add a login to a profile.
425 // BUG(paddy): We need to implement a handler that will remove a login from a profile. What happens to sessions created with that login?
426 // BUG(paddy): We need to implement a handler that will list the logins attached to a profile.
427 }
429 // CreateProfileHandler is an HTTP handler for registering new profiles.
430 func CreateProfileHandler(w http.ResponseWriter, r *http.Request, context Context) {
431 scheme, ok := passphraseSchemes[CurPassphraseScheme]
432 if !ok {
433 encode(w, r, http.StatusInternalServerError, actOfGodResponse)
434 return
435 }
436 var req newProfileRequest
437 errors := []requestError{}
438 decoder := json.NewDecoder(r.Body)
439 err := decoder.Decode(&req)
440 if err != nil {
441 encode(w, r, http.StatusBadRequest, invalidFormatResponse)
442 return
443 }
444 errors = append(errors, validateNewProfileRequest(&req)...)
445 if len(errors) > 0 {
446 encode(w, r, http.StatusBadRequest, response{Errors: errors})
447 return
448 }
449 passphrase, salt, err := scheme.create(req.Passphrase, context.config.iterations)
450 if err != nil {
451 encode(w, r, http.StatusInternalServerError, actOfGodResponse)
452 return
453 }
454 profile := Profile{
455 ID: uuid.NewID(),
456 Name: req.Name,
457 Passphrase: string(passphrase),
458 Iterations: context.config.iterations,
459 Salt: string(salt),
460 PassphraseScheme: CurPassphraseScheme,
461 Created: time.Now(),
462 LastSeen: time.Now(),
463 }
464 err = context.SaveProfile(profile)
465 if err != nil {
466 if err == ErrProfileAlreadyExists {
467 encode(w, r, http.StatusBadRequest, response{Errors: []requestError{{Slug: requestErrConflict, Field: "/id"}}})
468 return
469 }
470 encode(w, r, http.StatusInternalServerError, actOfGodResponse)
471 return
472 }
473 logins := []Login{}
474 login := Login{
475 Type: "email",
476 Value: req.Email,
477 Created: profile.Created,
478 LastUsed: profile.Created,
479 ProfileID: profile.ID,
480 }
481 err = context.AddLogin(login)
482 if err != nil {
483 if err == ErrLoginAlreadyExists {
484 encode(w, r, http.StatusBadRequest, response{Errors: []requestError{{Slug: requestErrConflict, Field: "/email"}}})
485 return
486 }
487 encode(w, r, http.StatusInternalServerError, actOfGodResponse)
488 return
489 }
490 logins = append(logins, login)
491 if req.Username != "" {
492 login.Type = "username"
493 login.Value = req.Username
494 err = context.AddLogin(login)
495 if err != nil {
496 if err == ErrLoginAlreadyExists {
497 encode(w, r, http.StatusBadRequest, response{Errors: []requestError{{Slug: requestErrConflict, Field: "/username"}}})
498 return
499 }
500 encode(w, r, http.StatusInternalServerError, actOfGodResponse)
501 return
502 }
503 logins = append(logins, login)
504 }
505 resp := response{
506 Logins: logins,
507 Profiles: []Profile{profile},
508 }
509 encode(w, r, http.StatusCreated, resp)
510 // TODO(paddy): should we kick off the email validation flow?
511 }
513 func UpdateProfileHandler(w http.ResponseWriter, r *http.Request, context Context) {
514 errors := []requestError{}
515 vars := mux.Vars(r)
516 if vars["id"] == "" {
517 errors = append(errors, requestError{Slug: requestErrMissing, Param: "id"})
518 encode(w, r, http.StatusBadRequest, response{Errors: errors})
519 return
520 }
521 id, err := uuid.Parse(vars["id"])
522 if err != nil {
523 errors = append(errors, requestError{Slug: requestErrAccessDenied})
524 encode(w, r, http.StatusBadRequest, response{Errors: errors})
525 return
526 }
527 username, password, ok := r.BasicAuth()
528 if !ok {
529 errors = append(errors, requestError{Slug: requestErrAccessDenied})
530 encode(w, r, http.StatusUnauthorized, response{Errors: errors})
531 return
532 }
533 profile, err := authenticate(username, password, context)
534 if err != nil {
535 if isAuthError(err) {
536 errors = append(errors, requestError{Slug: requestErrAccessDenied})
537 encode(w, r, http.StatusUnauthorized, response{Errors: errors})
538 } else {
539 errors = append(errors, requestError{Slug: requestErrActOfGod})
540 encode(w, r, http.StatusInternalServerError, response{Errors: errors})
541 }
542 return
543 }
544 if !profile.ID.Equal(id) {
545 errors = append(errors, requestError{Slug: requestErrAccessDenied})
546 encode(w, r, http.StatusForbidden, response{Errors: errors})
547 return
548 }
549 var req ProfileChange
550 decoder := json.NewDecoder(r.Body)
551 err = decoder.Decode(&req)
552 if err != nil {
553 encode(w, r, http.StatusBadRequest, invalidFormatResponse)
554 return
555 }
556 req.Iterations = nil
557 req.Salt = nil
558 req.PassphraseScheme = nil
559 req.Compromised = nil // BUG(paddy): Need a way for admins to mark accounts as compromised
560 req.LockedUntil = nil
561 req.LastSeen = nil
562 if req.Passphrase != nil {
563 if len(*req.Passphrase) < MinPassphraseLength {
564 errors = append(errors, requestError{Slug: requestErrInsufficient, Field: "/passphrase"})
565 encode(w, r, http.StatusBadRequest, response{Errors: errors})
566 return
567 }
568 if len(*req.Passphrase) > MaxPassphraseLength {
569 errors = append(errors, requestError{Slug: requestErrOverflow, Field: "/passphrase"})
570 encode(w, r, http.StatusBadRequest, response{Errors: errors})
571 return
572 }
573 iterations := context.config.iterations
574 scheme, ok := passphraseSchemes[CurPassphraseScheme]
575 if !ok {
576 encode(w, r, http.StatusInternalServerError, actOfGodResponse)
577 return
578 }
579 curScheme := CurPassphraseScheme
580 req.PassphraseScheme = &curScheme
581 passphrase, salt, err := scheme.create(*req.Passphrase, iterations)
582 if err != nil {
583 encode(w, r, http.StatusInternalServerError, actOfGodResponse)
584 return
585 }
586 req.Passphrase = &passphrase
587 req.Salt = &salt
588 req.Iterations = &iterations
589 }
590 if req.PassphraseReset != nil {
591 now := time.Now()
592 req.PassphraseResetCreated = &now
593 }
594 err = req.Validate()
595 if err != nil {
596 var status int
597 var resp response
598 switch err {
599 case ErrEmptyChange:
600 resp.Profiles = []Profile{profile}
601 status = http.StatusOK
602 default:
603 errors = append(errors, requestError{Slug: requestErrActOfGod})
604 resp.Errors = errors
605 status = http.StatusInternalServerError
606 }
607 encode(w, r, status, resp)
608 return
609 }
610 err = context.UpdateProfile(id, req)
611 if err != nil {
612 if err == ErrProfileNotFound {
613 errors = append(errors, requestError{Slug: requestErrNotFound})
614 encode(w, r, http.StatusNotFound, response{Errors: errors})
615 return
616 }
617 encode(w, r, http.StatusInternalServerError, actOfGodResponse)
618 return
619 }
620 profile.ApplyChange(req)
621 encode(w, r, http.StatusOK, response{Profiles: []Profile{profile}})
622 return
623 }