Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion internal/api/identity.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ func (a *API) DeleteIdentity(w http.ResponseWriter, r *http.Request) error {
// the user before unlinking. Removing an identity may promote another
// identity's email onto the user record.
if config.Mailer.Notifications.IdentityUnlinkedEnabled && recipientEmail != "" {
if err := a.sendIdentityUnlinkedNotification(r, db, user, provider, recipientEmail); err != nil {
if err := a.sendIdentityUnlinkedNotification(a.notificationRequest(r), db, user, provider, recipientEmail); err != nil {
// Log the error but don't fail the unlinking
logrus.WithError(err).Warn("Unable to send identity unlinked notification email")
}
Expand Down
23 changes: 23 additions & 0 deletions internal/api/mail.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package api

import (
"context"
"net/http"
"regexp"
"strings"
Expand Down Expand Up @@ -588,6 +589,28 @@ func (a *API) sendEmailChange(r *http.Request, tx *storage.Connection, u *models
return nil
}

// notificationRequest returns r with a context that expires before the last
// fifth of the request budget (API.MaxRequestDuration). It is meant for
// notification emails sent after the change they report has been committed: a
// slow mail transport must not push the response past the request timeout,
// otherwise the client sees a timeout for a change that already happened and
// a retry fails with a confusing error (see #2888).
//
// The returned context is not cancelled when the caller returns, because the
// mail may still be in flight on a background task (EmailBackgroundSending).
// It ends at its deadline or together with the request.
func (a *API) notificationRequest(r *http.Request) *http.Request {
maxDuration := a.config.API.MaxRequestDuration
deadline, ok := r.Context().Deadline()
if maxDuration <= 0 || !ok {
return r
}

ctx, cancel := context.WithDeadline(r.Context(), deadline.Add(-maxDuration/5))
context.AfterFunc(r.Context(), cancel)
return r.WithContext(ctx)
}

func (a *API) sendPasswordChangedNotification(r *http.Request, tx *storage.Connection, u *models.User) error {
err := a.sendEmail(r, tx, u, sendEmailParams{
emailActionType: mail.PasswordChangedNotification,
Expand Down
42 changes: 42 additions & 0 deletions internal/api/mail_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@ package api

import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"time"

"github.com/gobwas/glob"
"github.com/golang-jwt/jwt/v5"
Expand Down Expand Up @@ -255,3 +257,43 @@ func (ts *MailTestSuite) setURIAllowListMap(uris ...string) {
ts.Config.URIAllowListMap[uri] = g
}
}

func TestNotificationRequest(t *testing.T) {
a := &API{config: &conf.GlobalConfiguration{}}
a.config.API.MaxRequestDuration = 10 * time.Second

t.Run("NoRequestDeadline", func(t *testing.T) {
r := httptest.NewRequest(http.MethodPost, "/", nil)
require.Same(t, r, a.notificationRequest(r))
})

t.Run("LeavesPartOfTheRequestBudget", func(t *testing.T) {
deadline := time.Now().Add(10 * time.Second)
ctx, cancel := context.WithDeadline(context.Background(), deadline)
defer cancel()

r := httptest.NewRequest(http.MethodPost, "/", nil).WithContext(ctx)
got, ok := a.notificationRequest(r).Context().Deadline()
require.True(t, ok)
require.Equal(t, deadline.Add(-2*time.Second), got)
})

t.Run("EndsWithTheRequest", func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
r := httptest.NewRequest(http.MethodPost, "/", nil).WithContext(ctx)
nr := a.notificationRequest(r)
cancel()

<-nr.Context().Done()
require.ErrorIs(t, nr.Context().Err(), context.Canceled)
})

t.Run("NoMaxRequestDuration", func(t *testing.T) {
b := &API{config: &conf.GlobalConfiguration{}}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

r := httptest.NewRequest(http.MethodPost, "/", nil).WithContext(ctx)
require.Same(t, r, b.notificationRequest(r))
})
}
8 changes: 4 additions & 4 deletions internal/api/mfa.go
Original file line number Diff line number Diff line change
Expand Up @@ -743,7 +743,7 @@ func (a *API) verifyTOTPFactor(w http.ResponseWriter, r *http.Request, params *V

// Send MFA factor enrolled notification email if enabled and the factor was just verified
if verified && config.Mailer.Notifications.MFAFactorEnrolledEnabled && user.GetEmail() != "" {
if err := a.sendMFAFactorEnrolledNotification(r, db, user, factor.FactorType); err != nil {
if err := a.sendMFAFactorEnrolledNotification(a.notificationRequest(r), db, user, factor.FactorType); err != nil {
// Log the error but don't fail the verification
logrus.WithError(err).Warn("Unable to send MFA factor enrolled notification email")
}
Expand Down Expand Up @@ -884,7 +884,7 @@ func (a *API) verifyPhoneFactor(w http.ResponseWriter, r *http.Request, params *

// Send MFA factor enrolled notification email if enabled and the factor was just verified
if verified && config.Mailer.Notifications.MFAFactorEnrolledEnabled && user.GetEmail() != "" {
if err := a.sendMFAFactorEnrolledNotification(r, db, user, factor.FactorType); err != nil {
if err := a.sendMFAFactorEnrolledNotification(a.notificationRequest(r), db, user, factor.FactorType); err != nil {
// Log the error but don't fail the verification
logrus.WithError(err).Warn("Unable to send MFA factor enrolled notification email")
}
Expand Down Expand Up @@ -1004,7 +1004,7 @@ func (a *API) verifyWebAuthnFactor(w http.ResponseWriter, r *http.Request, param

// Send MFA factor enrolled notification email if enabled and the factor was just verified
if verified && config.Mailer.Notifications.MFAFactorEnrolledEnabled && user.GetEmail() != "" {
if err := a.sendMFAFactorEnrolledNotification(r, db, user, factor.FactorType); err != nil {
if err := a.sendMFAFactorEnrolledNotification(a.notificationRequest(r), db, user, factor.FactorType); err != nil {
// Log the error but don't fail the verification
logrus.WithError(err).Warn("Unable to send MFA factor enrolled notification email")
}
Expand Down Expand Up @@ -1118,7 +1118,7 @@ func (a *API) UnenrollFactor(w http.ResponseWriter, r *http.Request) error {

// Send MFA factor unenrolled notification email if enabled
if config.Mailer.Notifications.MFAFactorUnenrolledEnabled && user.GetEmail() != "" {
if err := a.sendMFAFactorUnenrolledNotification(r, db, user, factorType); err != nil {
if err := a.sendMFAFactorUnenrolledNotification(a.notificationRequest(r), db, user, factorType); err != nil {
// Log the error but don't fail the unenrollment
logrus.WithError(err).Warn("Unable to send MFA factor unenrolled notification email")
}
Expand Down
48 changes: 48 additions & 0 deletions internal/api/mfa_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1164,3 +1164,51 @@ func (ts *MFATestSuite) TestMFAFactorUnenrolledNotificationDisabled() {
// Assert that MFA factor unenrolled notification email was sent or not based on the config
require.Len(ts.T(), mockMailer.MFAFactorUnenrolledMailCalls, 0, "Expected 0 MFA factor unenrolled notification email(s) to be sent")
}

// stalledNotificationMailer blocks the MFA factor unenrolled notification
// until the request context is done, like a mail transport that stopped
// responding.
type stalledNotificationMailer struct {
mockclient.MockMailer
hadDeadline bool
}

func (m *stalledNotificationMailer) MFAFactorUnenrolledNotificationMail(r *http.Request, user *models.User, factorType string) error {
_, m.hadDeadline = r.Context().Deadline()
<-r.Context().Done()
return r.Context().Err()
}

func (ts *MFATestSuite) TestUnenrollFactorWithStalledNotification() {
maxRequestDuration := ts.Config.API.MaxRequestDuration
notificationEnabled := ts.Config.Mailer.Notifications.MFAFactorUnenrolledEnabled
defer func() {
ts.Config.API.MaxRequestDuration = maxRequestDuration
ts.Config.Mailer.Notifications.MFAFactorUnenrolledEnabled = notificationEnabled
}()
ts.Config.API.MaxRequestDuration = time.Second
ts.Config.Mailer.Notifications.MFAFactorUnenrolledEnabled = true

mailer := &stalledNotificationMailer{}
api := NewAPIWithVersion(ts.Config, ts.API.db, apiTestVersion, WithMailer(mailer))

f := ts.TestUser.Factors[0]
token := ts.generateAAL1Token(ts.TestUser, &ts.TestSession.ID)

w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodDelete, fmt.Sprintf("/factors/%s", f.ID), nil)
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))

start := time.Now()
api.handler.ServeHTTP(w, req)
elapsed := time.Since(start)

// The factor is removed before the notification is sent, so the
// response must report success instead of a request timeout.
require.Equal(ts.T(), http.StatusOK, w.Code, w.Body.String())
require.Less(ts.T(), elapsed, ts.Config.API.MaxRequestDuration)
require.True(ts.T(), mailer.hadDeadline)

_, err := models.FindFactorByFactorID(ts.API.db, f.ID)
require.EqualError(ts.T(), err, models.FactorNotFoundError{}.Error())
}
4 changes: 2 additions & 2 deletions internal/api/recovery_codes.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ func (a *API) RecoveryCodesGenerate(w http.ResponseWriter, r *http.Request) erro
}

if config.Mailer.Notifications.MFAFactorEnrolledEnabled && user.GetEmail() != "" {
if err := a.sendMFAFactorEnrolledNotification(r, db, user, factor.FactorType); err != nil {
if err := a.sendMFAFactorEnrolledNotification(a.notificationRequest(r), db, user, factor.FactorType); err != nil {
logrus.WithError(err).Warn("Unable to send MFA factor enrolled notification email")
}
}
Expand Down Expand Up @@ -498,7 +498,7 @@ func (a *API) RecoveryCodesDelete(w http.ResponseWriter, r *http.Request) error
}

if config.Mailer.Notifications.MFAFactorUnenrolledEnabled && user.GetEmail() != "" {
if err := a.sendMFAFactorUnenrolledNotification(r, db, user, factor.FactorType); err != nil {
if err := a.sendMFAFactorUnenrolledNotification(a.notificationRequest(r), db, user, factor.FactorType); err != nil {
logrus.WithError(err).Warn("Unable to send MFA factor unenrolled notification email")
}
}
Expand Down
14 changes: 12 additions & 2 deletions internal/mailer/mailmeclient/mailmeclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,18 @@ func (m *Client) Mail(
m.Logger.WithFields(fields).Info("mail.send")
}()
}
if err := dial.DialAndSend(mail); err != nil {
// gomail has no way to abort a send in progress, so the caller stops
// waiting when ctx is done. The send itself is not cancelled: the
// goroutine exits once the SMTP exchange ends on its own.
errCh := make(chan error, 1)
go func() {
errCh <- dial.DialAndSend(mail)
}()

select {
case err := <-errCh:
return err
case <-ctx.Done():
return ctx.Err()
}
return nil
}
107 changes: 107 additions & 0 deletions internal/mailer/mailmeclient/mailmeclient_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
package mailmeclient

import (
"context"
"net"
"sync"
"testing"
"time"

"github.com/sirupsen/logrus"
"github.com/stretchr/testify/require"
)

// stalledSMTPServer accepts connections and never sends the SMTP greeting.
func stalledSMTPServer(t *testing.T) int {
t.Helper()

ln, err := net.Listen("tcp", "127.0.0.1:0")
require.NoError(t, err)

var mu sync.Mutex
var conns []net.Conn
go func() {
for {
conn, err := ln.Accept()
if err != nil {
return
}
mu.Lock()
conns = append(conns, conn)
mu.Unlock()
}
}()

t.Cleanup(func() {
ln.Close()
mu.Lock()
defer mu.Unlock()
for _, conn := range conns {
conn.Close()
}
})

return ln.Addr().(*net.TCPAddr).Port
}

func testClient(port int) *Client {
return &Client{
From: "admin@example.com",
Host: "127.0.0.1",
Port: port,
Logger: logrus.StandardLogger(),
}
}

func TestMailReturnsWhenContextIsDone(t *testing.T) {
c := testClient(stalledSMTPServer(t))

ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()

start := time.Now()
err := c.Mail(ctx, "user@example.com", "subject", "body", nil, "test")
require.ErrorIs(t, err, context.DeadlineExceeded)
require.Less(t, time.Since(start), 2*time.Second)
}

func TestMailWithDoneContextStillSends(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
require.NoError(t, err)
t.Cleanup(func() { ln.Close() })

accepted := make(chan struct{})
go func() {
conn, err := ln.Accept()
if err != nil {
return
}
defer conn.Close()
close(accepted)
}()

ctx, cancel := context.WithCancel(context.Background())
cancel()

// The caller does not wait, but the send is still attempted.
err = testClient(ln.Addr().(*net.TCPAddr).Port).Mail(ctx, "user@example.com", "subject", "body", nil, "test")
require.ErrorIs(t, err, context.Canceled)

select {
case <-accepted:
case <-time.After(2 * time.Second):
t.Fatal("the SMTP server was never contacted")
}
}

func TestMailReturnsSendError(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
require.NoError(t, err)
port := ln.Addr().(*net.TCPAddr).Port
require.NoError(t, ln.Close())

err = testClient(port).Mail(context.Background(), "user@example.com", "subject", "body", nil, "test")
require.Error(t, err)
require.NotErrorIs(t, err, context.Canceled)
require.NotErrorIs(t, err, context.DeadlineExceeded)
}