mirror of
https://github.com/mjl-/mox.git
synced 2025-07-10 07:54:40 +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:
@ -2,6 +2,7 @@ package webmail
|
||||
|
||||
import (
|
||||
"context"
|
||||
cryptorand "crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
@ -43,13 +44,16 @@ import (
|
||||
"github.com/mjl-/mox/smtp"
|
||||
"github.com/mjl-/mox/smtpclient"
|
||||
"github.com/mjl-/mox/store"
|
||||
"github.com/mjl-/mox/webauth"
|
||||
)
|
||||
|
||||
//go:embed api.json
|
||||
var webmailapiJSON []byte
|
||||
|
||||
type Webmail struct {
|
||||
maxMessageSize int64 // From listener.
|
||||
maxMessageSize int64 // From listener.
|
||||
cookiePath string // From listener.
|
||||
isForwarded bool // From listener, whether we look at X-Forwarded-* headers.
|
||||
}
|
||||
|
||||
func mustParseAPI(api string, buf []byte) (doc sherpadoc.Section) {
|
||||
@ -64,8 +68,8 @@ var webmailDoc = mustParseAPI("webmail", webmailapiJSON)
|
||||
|
||||
var sherpaHandlerOpts *sherpa.HandlerOpts
|
||||
|
||||
func makeSherpaHandler(maxMessageSize int64) (http.Handler, error) {
|
||||
return sherpa.NewHandler("/api/", moxvar.Version, Webmail{maxMessageSize}, &webmailDoc, sherpaHandlerOpts)
|
||||
func makeSherpaHandler(maxMessageSize int64, cookiePath string, isForwarded bool) (http.Handler, error) {
|
||||
return sherpa.NewHandler("/api/", moxvar.Version, Webmail{maxMessageSize, cookiePath, isForwarded}, &webmailDoc, sherpaHandlerOpts)
|
||||
}
|
||||
|
||||
func init() {
|
||||
@ -74,20 +78,59 @@ func init() {
|
||||
pkglog.Fatalx("creating sherpa prometheus collector", err)
|
||||
}
|
||||
|
||||
sherpaHandlerOpts = &sherpa.HandlerOpts{Collector: collector, AdjustFunctionNames: "none"}
|
||||
sherpaHandlerOpts = &sherpa.HandlerOpts{Collector: collector, AdjustFunctionNames: "none", NoCORS: true}
|
||||
// Just to validate.
|
||||
_, err = makeSherpaHandler(0)
|
||||
_, err = makeSherpaHandler(0, "", false)
|
||||
if err != nil {
|
||||
pkglog.Fatalx("sherpa handler", err)
|
||||
}
|
||||
}
|
||||
|
||||
// LoginPrep returns a login token, and also sets it as cookie. Both must be
|
||||
// present in the call to Login.
|
||||
func (w Webmail) LoginPrep(ctx context.Context) string {
|
||||
log := pkglog.WithContext(ctx)
|
||||
reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
|
||||
|
||||
var data [8]byte
|
||||
_, err := cryptorand.Read(data[:])
|
||||
xcheckf(ctx, err, "generate token")
|
||||
loginToken := base64.RawURLEncoding.EncodeToString(data[:])
|
||||
|
||||
webauth.LoginPrep(ctx, log, "webmail", w.cookiePath, w.isForwarded, reqInfo.Response, reqInfo.Request, loginToken)
|
||||
|
||||
return loginToken
|
||||
}
|
||||
|
||||
// Login returns a session token for the credentials, or fails with error code
|
||||
// "user:badLogin". Call LoginPrep to get a loginToken.
|
||||
func (w Webmail) Login(ctx context.Context, loginToken, username, password string) store.CSRFToken {
|
||||
log := pkglog.WithContext(ctx)
|
||||
reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
|
||||
|
||||
csrfToken, err := webauth.Login(ctx, log, webauth.Accounts, "webmail", w.cookiePath, w.isForwarded, reqInfo.Response, reqInfo.Request, loginToken, username, password)
|
||||
if _, ok := err.(*sherpa.Error); ok {
|
||||
panic(err)
|
||||
}
|
||||
xcheckf(ctx, err, "login")
|
||||
return csrfToken
|
||||
}
|
||||
|
||||
// Logout invalidates the session token.
|
||||
func (w Webmail) Logout(ctx context.Context) {
|
||||
log := pkglog.WithContext(ctx)
|
||||
reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
|
||||
|
||||
err := webauth.Logout(ctx, log, webauth.Accounts, "webmail", w.cookiePath, w.isForwarded, reqInfo.Response, reqInfo.Request, reqInfo.AccountName, reqInfo.SessionToken)
|
||||
xcheckf(ctx, err, "logout")
|
||||
}
|
||||
|
||||
// Token returns a token to use for an SSE connection. A token can only be used for
|
||||
// a single SSE connection. Tokens are stored in memory for a maximum of 1 minute,
|
||||
// with at most 10 unused tokens (the most recently created) per account.
|
||||
func (Webmail) Token(ctx context.Context) string {
|
||||
reqInfo := ctx.Value(requestInfoCtxKey).(requestInfo)
|
||||
return sseTokens.xgenerate(ctx, reqInfo.AccountName, reqInfo.LoginAddress)
|
||||
return sseTokens.xgenerate(ctx, reqInfo.AccountName, reqInfo.LoginAddress, reqInfo.SessionToken)
|
||||
}
|
||||
|
||||
// Requests sends a new request for an open SSE connection. Any currently active
|
||||
|
Reference in New Issue
Block a user