mox/webmail/eventwriter.go
Mechiel Lukkien 0f8bf2f220
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
2024-01-05 10:48:42 +01:00

185 lines
4.6 KiB
Go

package webmail
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io"
mathrand "math/rand"
"net/http"
"runtime/debug"
"sync"
"time"
"golang.org/x/exp/slog"
"github.com/mjl-/mox/metrics"
"github.com/mjl-/mox/mlog"
"github.com/mjl-/mox/store"
)
type eventWriter struct {
out writeFlusher
waitMin, waitMax time.Duration
// If connection is closed, the goroutine doing delayed writes must abort.
sync.Mutex
closed bool
// Before writing an event, we check if session is still valid. If not, we send a
// fatal error instead.
accountName string
sessionToken store.SessionToken
wrote bool // To be reset by user, set on write.
events chan struct {
name string // E.g. "start" for EventStart.
v any // Written as JSON.
when time.Time // For delaying.
} // Will only be set when waitMin or waitMax is > 0. Closed on connection shutdown.
errors chan error // If we have an events channel, we read errors and abort for them.
}
func newEventWriter(out writeFlusher, waitMin, waitMax time.Duration, accountName string, sessionToken store.SessionToken) *eventWriter {
return &eventWriter{out: out, waitMin: waitMin, waitMax: waitMax, accountName: accountName, sessionToken: sessionToken}
}
// close shuts down the events channel, causing the goroutine (if created) to
// stop.
func (ew *eventWriter) close() {
if ew.events != nil {
close(ew.events)
}
ew.Lock()
defer ew.Unlock()
ew.closed = true
}
// Write an event to the connection, e.g. "start" with value v, written as
// JSON. This directly writes the event, no more delay.
func (ew *eventWriter) write(name string, v any) error {
bw := bufio.NewWriter(ew.out)
if _, err := fmt.Fprintf(bw, "event: %s\ndata: ", name); err != nil {
return err
} else if err := json.NewEncoder(bw).Encode(v); err != nil {
return err
} else if _, err := fmt.Fprint(bw, "\n"); err != nil {
return err
} else if err := bw.Flush(); err != nil {
return err
}
return ew.out.Flush()
}
// For random wait between min and max delay.
var waitGen = mathrand.New(mathrand.NewSource(time.Now().UnixNano()))
// Schedule an event for writing to the connection. If events get a delay, this
// function still returns immediately.
func (ew *eventWriter) xsendEvent(ctx context.Context, log mlog.Log, name string, v any) {
if name != "fatalErr" {
if _, err := store.SessionUse(ctx, log, ew.accountName, ew.sessionToken, ""); err != nil {
ew.xsendEvent(ctx, log, "fatalErr", "session no longer valid")
return
}
}
if (ew.waitMin > 0 || ew.waitMax > 0) && ew.events == nil {
// First write on a connection with delay.
ew.events = make(chan struct {
name string
v any
when time.Time
}, 100)
ew.errors = make(chan error)
go func() {
defer func() {
x := recover() // Should not happen, but don't take program down if it does.
if x != nil {
log.WithContext(ctx).Error("writeEvent panic", slog.Any("err", x))
debug.PrintStack()
metrics.PanicInc(metrics.Webmailsendevent)
}
}()
for {
ev, ok := <-ew.events
if !ok {
return
}
d := time.Until(ev.when)
if d > 0 {
time.Sleep(d)
}
ew.Lock()
if ew.closed {
ew.Unlock()
return
}
err := ew.write(ev.name, ev.v)
ew.Unlock()
if err != nil {
ew.errors <- err
return
}
}
}()
}
// Check for previous write error before continuing.
if ew.errors != nil {
select {
case err := <-ew.errors:
panic(ioErr{err})
default:
break
}
}
// If we have an events channel, we have a goroutine that write the events, delayed.
if ew.events != nil {
wait := ew.waitMin + time.Duration(waitGen.Intn(1000))*(ew.waitMax-ew.waitMin)/1000
when := time.Now().Add(wait)
ew.events <- struct {
name string
v any
when time.Time
}{name, v, when}
} else {
err := ew.write(name, v)
if err != nil {
panic(ioErr{err})
}
}
ew.wrote = true
}
// writeFlusher is a writer and flusher. We need to flush after writing an
// Event. Both to flush pending gzip data to the http response, and the http
// response to the client.
type writeFlusher interface {
io.Writer
Flush() error
}
// nopFlusher is a standin for writeFlusher if gzip is not used.
type nopFlusher struct {
io.Writer
}
func (f nopFlusher) Flush() error {
return nil
}
// httpFlusher wraps Flush for a writeFlusher with a call to an http.Flusher.
type httpFlusher struct {
writeFlusher
f http.Flusher
}
// Flush flushes the underlying writeFlusher, and calls Flush on the http.Flusher
// (which doesn't return an error).
func (f httpFlusher) Flush() error {
err := f.writeFlusher.Flush()
f.f.Flush()
return err
}