mirror of
https://github.com/mjl-/mox.git
synced 2025-07-12 14:24:37 +03:00
replace http basic auth for web interfaces with session cookie & csrf-based auth
the http basic auth we had was very simple to reason about, and to implement. but it has a major downside: there is no way to logout, browsers keep sending credentials. ideally, browsers themselves would show a button to stop sending credentials. a related downside: the http auth mechanism doesn't indicate for which server paths the credentials are. another downside: the original password is sent to the server with each request. though sending original passwords to web servers seems to be considered normal. our new approach uses session cookies, along with csrf values when we can. the sessions are server-side managed, automatically extended on each use. this makes it easy to invalidate sessions and keeps the frontend simpler (than with long- vs short-term sessions and refreshing). the cookies are httponly, samesite=strict, scoped to the path of the web interface. cookies are set "secure" when set over https. the cookie is set by a successful call to Login. a call to Logout invalidates a session. changing a password invalidates all sessions for a user, but keeps the session with which the password was changed alive. the csrf value is also random, and associated with the session cookie. the csrf must be sent as header for api calls, or as parameter for direct form posts (where we cannot set a custom header). rest-like calls made directly by the browser, e.g. for images, don't have a csrf protection. the csrf value is returned by the Login api call and stored in localstorage. api calls without credentials return code "user:noAuth", and with bad credentials return "user:badAuth". the api client recognizes this and triggers a login. after a login, all auth-failed api calls are automatically retried. only for "user:badAuth" is an error message displayed in the login form (e.g. session expired). in an ideal world, browsers would take care of most session management. a server would indicate authentication is needed (like http basic auth), and the browsers uses trusted ui to request credentials for the server & path. the browser could use safer mechanism than sending original passwords to the server, such as scram, along with a standard way to create sessions. for now, web developers have to do authentication themselves: from showing the login prompt, ensuring the right session/csrf cookies/localstorage/headers/etc are sent with each request. webauthn is a newer way to do authentication, perhaps we'll implement it in the future. though hardware tokens aren't an attractive option for many users, and it may be overkill as long as we still do old-fashioned authentication in smtp & imap where passwords can be sent to the server. for issue #58
This commit is contained in:
@ -413,10 +413,11 @@ func sseGet(id int64, accountName string) (sse, bool) {
|
||||
// ssetoken is a temporary token that has not yet been used to start an SSE
|
||||
// connection. Created by Token, consumed by a new SSE connection.
|
||||
type ssetoken struct {
|
||||
token string // Uniquely generated.
|
||||
accName string
|
||||
address string // Address used to authenticate in call that created the token.
|
||||
validUntil time.Time
|
||||
token string // Uniquely generated.
|
||||
accName string
|
||||
address string // Address used to authenticate in call that created the token.
|
||||
sessionToken store.SessionToken // SessionToken that created this token, checked before sending updates.
|
||||
validUntil time.Time
|
||||
}
|
||||
|
||||
// ssetokens maintains unused tokens. We have just one, but it's a type so we
|
||||
@ -434,11 +435,11 @@ var sseTokens = ssetokens{
|
||||
|
||||
// xgenerate creates and saves a new token. It ensures no more than 10 tokens
|
||||
// per account exist, removing old ones if needed.
|
||||
func (x *ssetokens) xgenerate(ctx context.Context, accName, address string) string {
|
||||
func (x *ssetokens) xgenerate(ctx context.Context, accName, address string, sessionToken store.SessionToken) string {
|
||||
buf := make([]byte, 16)
|
||||
_, err := cryptrand.Read(buf)
|
||||
xcheckf(ctx, err, "generating token")
|
||||
st := ssetoken{base64.RawURLEncoding.EncodeToString(buf), accName, address, time.Now().Add(time.Minute)}
|
||||
st := ssetoken{base64.RawURLEncoding.EncodeToString(buf), accName, address, sessionToken, time.Now().Add(time.Minute)}
|
||||
|
||||
x.Lock()
|
||||
defer x.Unlock()
|
||||
@ -456,17 +457,17 @@ func (x *ssetokens) xgenerate(ctx context.Context, accName, address string) stri
|
||||
}
|
||||
|
||||
// check verifies a token, and consumes it if valid.
|
||||
func (x *ssetokens) check(token string) (string, string, bool, error) {
|
||||
func (x *ssetokens) check(token string) (string, string, store.SessionToken, bool, error) {
|
||||
x.Lock()
|
||||
defer x.Unlock()
|
||||
|
||||
st, ok := x.tokens[token]
|
||||
if !ok {
|
||||
return "", "", false, nil
|
||||
return "", "", "", false, nil
|
||||
}
|
||||
delete(x.tokens, token)
|
||||
if i := slices.Index(x.accountTokens[st.accName], st); i < 0 {
|
||||
return "", "", false, errors.New("internal error, could not find token in account")
|
||||
return "", "", "", false, errors.New("internal error, could not find token in account")
|
||||
} else {
|
||||
copy(x.accountTokens[st.accName][i:], x.accountTokens[st.accName][i+1:])
|
||||
x.accountTokens[st.accName] = x.accountTokens[st.accName][:len(x.accountTokens[st.accName])-1]
|
||||
@ -475,9 +476,9 @@ func (x *ssetokens) check(token string) (string, string, bool, error) {
|
||||
}
|
||||
}
|
||||
if time.Now().After(st.validUntil) {
|
||||
return "", "", false, nil
|
||||
return "", "", "", false, nil
|
||||
}
|
||||
return st.accName, st.address, true, nil
|
||||
return st.accName, st.address, st.sessionToken, true, nil
|
||||
}
|
||||
|
||||
// ioErr is panicked on i/o errors in serveEvents and handled in a defer.
|
||||
@ -506,7 +507,7 @@ func serveEvents(ctx context.Context, log mlog.Log, w http.ResponseWriter, r *ht
|
||||
http.Error(w, "400 - bad request - missing credentials", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
accName, address, ok, err := sseTokens.check(token)
|
||||
accName, address, sessionToken, ok, err := sseTokens.check(token)
|
||||
if err != nil {
|
||||
http.Error(w, "500 - internal server error - "+err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
@ -515,6 +516,10 @@ func serveEvents(ctx context.Context, log mlog.Log, w http.ResponseWriter, r *ht
|
||||
http.Error(w, "400 - bad request - bad token", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if _, err := store.SessionUse(ctx, log, accName, sessionToken, ""); err != nil {
|
||||
http.Error(w, "400 - bad request - bad session token", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// We can simulate a slow SSE connection. It seems firefox doesn't slow down
|
||||
// incoming responses with its slow-network similation.
|
||||
@ -594,7 +599,7 @@ func serveEvents(ctx context.Context, log mlog.Log, w http.ResponseWriter, r *ht
|
||||
out = httpFlusher{out, flusher}
|
||||
|
||||
// We'll be writing outgoing SSE events through writer.
|
||||
writer = newEventWriter(out, waitMin, waitMax)
|
||||
writer = newEventWriter(out, waitMin, waitMax, accName, sessionToken)
|
||||
defer writer.close()
|
||||
|
||||
// Fetch initial data.
|
||||
|
Reference in New Issue
Block a user