mirror of
https://github.com/mjl-/mox.git
synced 2025-07-12 13:44: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:
@ -38,25 +38,23 @@ import (
|
||||
"github.com/mjl-/mox/mox-"
|
||||
"github.com/mjl-/mox/moxio"
|
||||
"github.com/mjl-/mox/store"
|
||||
"github.com/mjl-/mox/webaccount"
|
||||
"github.com/mjl-/mox/webauth"
|
||||
)
|
||||
|
||||
func init() {
|
||||
mox.LimitersInit()
|
||||
}
|
||||
|
||||
var pkglog = mlog.New("webmail", nil)
|
||||
|
||||
type ctxKey string
|
||||
|
||||
// We pass the request to the sherpa handler so the TLS info can be used for
|
||||
// the Received header in submitted messages. Most API calls need just the
|
||||
// account name.
|
||||
type ctxKey string
|
||||
|
||||
var requestInfoCtxKey ctxKey = "requestInfo"
|
||||
|
||||
type requestInfo struct {
|
||||
LoginAddress string
|
||||
AccountName string
|
||||
SessionToken store.SessionToken
|
||||
Response http.ResponseWriter
|
||||
Request *http.Request // For Proto and TLS connection state during message submit.
|
||||
}
|
||||
|
||||
@ -171,19 +169,19 @@ func serveContentFallback(log mlog.Log, w http.ResponseWriter, r *http.Request,
|
||||
}
|
||||
|
||||
// Handler returns a handler for the webmail endpoints, customized for the max
|
||||
// message size coming from the listener.
|
||||
func Handler(maxMessageSize int64) func(w http.ResponseWriter, r *http.Request) {
|
||||
sh, err := makeSherpaHandler(maxMessageSize)
|
||||
// message size coming from the listener and cookiePath.
|
||||
func Handler(maxMessageSize int64, cookiePath string, isForwarded bool) func(w http.ResponseWriter, r *http.Request) {
|
||||
sh, err := makeSherpaHandler(maxMessageSize, cookiePath, isForwarded)
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if err != nil {
|
||||
http.Error(w, "500 - internal server error - cannot handle requests", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
handle(sh, w, r)
|
||||
handle(sh, isForwarded, w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func handle(apiHandler http.Handler, w http.ResponseWriter, r *http.Request) {
|
||||
func handle(apiHandler http.Handler, isForwarded bool, w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
log := pkglog.WithContext(ctx).With(slog.String("userauth", ""))
|
||||
|
||||
@ -195,17 +193,6 @@ func handle(apiHandler http.Handler, w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
// HTTP Basic authentication for all requests.
|
||||
loginAddress, accName := webaccount.CheckAuth(ctx, log, "webmail", w, r)
|
||||
if accName == "" {
|
||||
// Error response already sent.
|
||||
return
|
||||
}
|
||||
|
||||
if lw, ok := w.(interface{ AddAttr(a slog.Attr) }); ok {
|
||||
lw.AddAttr(slog.String("authaccount", accName))
|
||||
}
|
||||
|
||||
defer func() {
|
||||
x := recover()
|
||||
if x == nil {
|
||||
@ -230,13 +217,14 @@ func handle(apiHandler http.Handler, w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/":
|
||||
switch r.Method {
|
||||
case "GET", "HEAD":
|
||||
h := w.Header()
|
||||
h.Set("X-Frame-Options", "deny")
|
||||
h.Set("Referrer-Policy", "same-origin")
|
||||
webmailFile.Serve(ctx, log, w, r)
|
||||
default:
|
||||
http.Error(w, "405 - method not allowed - use get", http.StatusMethodNotAllowed)
|
||||
return
|
||||
case "GET", "HEAD":
|
||||
}
|
||||
|
||||
webmailFile.Serve(ctx, log, w, r)
|
||||
return
|
||||
|
||||
case "/msg.js", "/text.js":
|
||||
@ -258,9 +246,27 @@ func handle(apiHandler http.Handler, w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
// API calls.
|
||||
if strings.HasPrefix(r.URL.Path, "/api/") {
|
||||
reqInfo := requestInfo{loginAddress, accName, r}
|
||||
isAPI := strings.HasPrefix(r.URL.Path, "/api/")
|
||||
// Only allow POST for calls, they will not work cross-domain without CORS.
|
||||
if isAPI && r.URL.Path != "/api/" && r.Method != "POST" {
|
||||
http.Error(w, "405 - method not allowed - use post", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
var loginAddress, accName string
|
||||
var sessionToken store.SessionToken
|
||||
// All other URLs, except the login endpoint require some authentication.
|
||||
if r.URL.Path != "/api/LoginPrep" && r.URL.Path != "/api/Login" {
|
||||
var ok bool
|
||||
accName, sessionToken, loginAddress, ok = webauth.Check(ctx, log, webauth.Accounts, "webmail", isForwarded, w, r, isAPI, isAPI, false)
|
||||
if !ok {
|
||||
// Response has been written already.
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if isAPI {
|
||||
reqInfo := requestInfo{loginAddress, accName, sessionToken, w, r}
|
||||
ctx = context.WithValue(ctx, requestInfoCtxKey, reqInfo)
|
||||
apiHandler.ServeHTTP(w, r.WithContext(ctx))
|
||||
return
|
||||
@ -412,7 +418,7 @@ func handle(apiHandler http.Handler, w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
headers(false, false, false)
|
||||
h.Set("Content-Type", "application/zip")
|
||||
h.Set("Cache-Control", "no-cache, max-age=0")
|
||||
h.Set("Cache-Control", "no-store, max-age=0")
|
||||
var subjectSlug string
|
||||
if p.Envelope != nil {
|
||||
s := p.Envelope.Subject
|
||||
@ -537,7 +543,7 @@ func handle(apiHandler http.Handler, w http.ResponseWriter, r *http.Request) {
|
||||
params["charset"] = charset
|
||||
}
|
||||
h.Set("Content-Type", mime.FormatMediaType(ct, params))
|
||||
h.Set("Cache-Control", "no-cache, max-age=0")
|
||||
h.Set("Cache-Control", "no-store, max-age=0")
|
||||
|
||||
_, err := io.Copy(w, &moxio.AtReader{R: msgr})
|
||||
log.Check(err, "writing raw")
|
||||
@ -567,7 +573,7 @@ func handle(apiHandler http.Handler, w http.ResponseWriter, r *http.Request) {
|
||||
allowSelfScript := true
|
||||
headers(sameorigin, loadExternal, allowSelfScript)
|
||||
h.Set("Content-Type", "text/html; charset=utf-8")
|
||||
h.Set("Cache-Control", "no-cache, max-age=0")
|
||||
h.Set("Cache-Control", "no-store, max-age=0")
|
||||
|
||||
path := filepath.FromSlash("webmail/msg.html")
|
||||
fallback := webmailmsgHTML
|
||||
@ -600,7 +606,7 @@ func handle(apiHandler http.Handler, w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
headers(false, false, false)
|
||||
h.Set("Content-Type", "application/javascript; charset=utf-8")
|
||||
h.Set("Cache-Control", "no-cache, max-age=0")
|
||||
h.Set("Cache-Control", "no-store, max-age=0")
|
||||
|
||||
_, err = fmt.Fprintf(w, "window.messageItem = %s;\nwindow.parsedMessage = %s;\n", mijson, pmjson)
|
||||
log.Check(err, "writing parsedmessage.js")
|
||||
@ -632,7 +638,7 @@ func handle(apiHandler http.Handler, w http.ResponseWriter, r *http.Request) {
|
||||
allowSelfScript := true
|
||||
headers(sameorigin, false, allowSelfScript)
|
||||
h.Set("Content-Type", "text/html; charset=utf-8")
|
||||
h.Set("Cache-Control", "no-cache, max-age=0")
|
||||
h.Set("Cache-Control", "no-store, max-age=0")
|
||||
|
||||
// We typically return the embedded file, but during development it's handy to load
|
||||
// from disk.
|
||||
@ -659,7 +665,7 @@ func handle(apiHandler http.Handler, w http.ResponseWriter, r *http.Request) {
|
||||
headers(sameorigin, allowExternal, false)
|
||||
|
||||
h.Set("Content-Type", "text/html; charset=utf-8")
|
||||
h.Set("Cache-Control", "no-cache, max-age=0")
|
||||
h.Set("Cache-Control", "no-store, max-age=0")
|
||||
}
|
||||
|
||||
// todo: skip certain html parts? e.g. with content-disposition: attachment?
|
||||
@ -726,7 +732,7 @@ func handle(apiHandler http.Handler, w http.ResponseWriter, r *http.Request) {
|
||||
ct = strings.ToLower(ap.MediaType + "/" + ap.MediaSubType)
|
||||
}
|
||||
h.Set("Content-Type", ct)
|
||||
h.Set("Cache-Control", "no-cache, max-age=0")
|
||||
h.Set("Cache-Control", "no-store, max-age=0")
|
||||
if t[1] == "download" {
|
||||
name := tryDecodeParam(log, ap.ContentTypeParams["name"])
|
||||
if name == "" {
|
||||
|
Reference in New Issue
Block a user