diff --git a/internal/mailer/mailer.go b/internal/mailer/mailer.go index a65efa05e1..04dc6ff7e2 100644 --- a/internal/mailer/mailer.go +++ b/internal/mailer/mailer.go @@ -61,6 +61,12 @@ type Client interface { ) error } +// Validator is implemented by a Client that checks an address before it +// sends to it. Validate runs that check without sending anything. +type Validator interface { + Validate(ctx context.Context, to string) error +} + type EmailData struct { Token string `json:"token"` TokenHash string `json:"token_hash"` diff --git a/internal/mailer/templatemailer/templatemailer.go b/internal/mailer/templatemailer/templatemailer.go index 72ef42c260..46563b46ea 100644 --- a/internal/mailer/templatemailer/templatemailer.go +++ b/internal/mailer/templatemailer/templatemailer.go @@ -8,6 +8,7 @@ import ( "strings" "github.com/supabase/auth/internal/conf" + "github.com/supabase/auth/internal/mailer" "github.com/supabase/auth/internal/models" ) @@ -281,6 +282,20 @@ func (m *Mailer) EmailChangeMail(r *http.Request, user *models.User, otpNew, otp ctx, cancel := context.WithCancel(r.Context()) defer cancel() + // The mails below are sent concurrently, so when one address fails + // validation the mail to the other one has already gone out, with a link + // that can never be used because the caller does not store the tokens on + // an error. Validate every address before sending to any of them. Mail + // validates each address again, and a client that sends in the background + // is not a Validator: it never returned a validation error to begin with. + if v, ok := m.mc.(mailer.Validator); ok && len(emails) > 1 { + for _, email := range emails { + if err := v.Validate(ctx, email.Address); err != nil { + return err + } + } + } + errors := make(chan error, len(emails)) for _, email := range emails { path, err := getPath( diff --git a/internal/mailer/templatemailer/templatemailer_test.go b/internal/mailer/templatemailer/templatemailer_test.go index 22837005fa..71eb4c3b0e 100644 --- a/internal/mailer/templatemailer/templatemailer_test.go +++ b/internal/mailer/templatemailer/templatemailer_test.go @@ -1,10 +1,20 @@ package templatemailer import ( + "context" + "net/http" + "net/http/httptest" + "net/url" + "sort" + "sync" "testing" + "time" "github.com/stretchr/testify/require" "github.com/supabase/auth/internal/conf" + "github.com/supabase/auth/internal/mailer" + "github.com/supabase/auth/internal/mailer/validateclient" + "github.com/supabase/auth/internal/models" ) func TestTemplateHeaders(t *testing.T) { @@ -62,3 +72,162 @@ func TestTemplateHeaders(t *testing.T) { require.Equal(t, hdrs, tc.exp) } } + +// testMailClient is a mailer.Client that records the addresses it sent to +// and, like the validating client, rejects the addresses in invalid. A +// rejected Mail call waits for another mail to go out (or a second to pass) +// before it returns, so the result does not depend on which of the two email +// change mails is handled first. +type testMailClient struct { + invalid map[string]bool + + mu sync.Mutex + sent []string + sentOne chan struct{} +} + +func newTestMailClient(invalid ...string) *testMailClient { + c := &testMailClient{ + invalid: make(map[string]bool, len(invalid)), + sentOne: make(chan struct{}), + } + for _, addr := range invalid { + c.invalid[addr] = true + } + return c +} + +func (c *testMailClient) Mail( + ctx context.Context, + to string, + subject string, + body string, + headers map[string][]string, + typ string, +) error { + if c.invalid[to] { + select { + case <-c.sentOne: + case <-time.After(time.Second): + } + return validateclient.ErrInvalidEmailDNS + } + + c.mu.Lock() + defer c.mu.Unlock() + if len(c.sent) == 0 { + close(c.sentOne) + } + c.sent = append(c.sent, to) + return nil +} + +func (c *testMailClient) sentTo() []string { + c.mu.Lock() + defer c.mu.Unlock() + sent := append([]string{}, c.sent...) + sort.Strings(sent) + return sent +} + +// validatingTestMailClient is a testMailClient that can also check an +// address without sending to it. +type validatingTestMailClient struct { + *testMailClient +} + +func (c *validatingTestMailClient) Validate(ctx context.Context, to string) error { + if c.invalid[to] { + return validateclient.ErrInvalidEmailDNS + } + return nil +} + +func TestEmailChangeMailValidatesBeforeSending(t *testing.T) { + const ( + currentEmail = "current@outlook.com" + newEmail = "new@outlook.com" + blockedEmail = "someone@example.com" + ) + + cfg := &conf.GlobalConfiguration{ + SiteURL: "https://example.com", + Mailer: conf.MailerConfiguration{ + SecureEmailChangeEnabled: true, + EmailValidationExtended: true, + }, + } + externalURL, err := url.Parse("https://auth.example.com") + require.NoError(t, err) + + send := func(t *testing.T, mc mailer.Client, current, change string) error { + user, err := models.NewUser("", current, "", "authenticated", nil) + require.NoError(t, err) + user.EmailChange = change + + req := httptest.NewRequest(http.MethodPut, "/user", nil) + return New(cfg, mc, NewCache()).EmailChangeMail( + req, user, "111111", "222222", "", externalURL) + } + + cases := []struct { + desc string + current string + change string + invalid string + sent []string + }{ + { + desc: "new address is rejected", + current: currentEmail, + change: blockedEmail, + invalid: blockedEmail, + sent: []string{}, + }, + { + desc: "current address is rejected", + current: blockedEmail, + change: newEmail, + invalid: blockedEmail, + sent: []string{}, + }, + { + desc: "both addresses are accepted", + current: currentEmail, + change: newEmail, + sent: []string{currentEmail, newEmail}, + }, + } + + for _, tc := range cases { + t.Run(tc.desc, func(t *testing.T) { + mc := newTestMailClient() + if tc.invalid != "" { + mc = newTestMailClient(tc.invalid) + } + + err := send(t, &validatingTestMailClient{mc}, tc.current, tc.change) + if tc.invalid != "" { + require.ErrorIs(t, err, validateclient.ErrInvalidEmailDNS) + } else { + require.NoError(t, err) + } + require.Equal(t, tc.sent, mc.sentTo()) + }) + + // The same through the client the server uses: example.com is on + // its list of invalid hosts and outlook.com on its allow list, so + // neither result needs a DNS lookup. + t.Run(tc.desc+" (validateclient)", func(t *testing.T) { + mc := newTestMailClient() + + err := send(t, validateclient.New(cfg, mc), tc.current, tc.change) + if tc.invalid != "" { + require.ErrorIs(t, err, validateclient.ErrInvalidEmailDNS) + } else { + require.NoError(t, err) + } + require.Equal(t, tc.sent, mc.sentTo()) + }) + } +} diff --git a/internal/mailer/validateclient/validateclient.go b/internal/mailer/validateclient/validateclient.go index 652df4fb6d..8cdbc421a1 100644 --- a/internal/mailer/validateclient/validateclient.go +++ b/internal/mailer/validateclient/validateclient.go @@ -158,6 +158,12 @@ func (o *emailValidatorMailClient) Mail( ) } +// Validate implements mailer.Validator interface by running the validation +// Mail runs before it passes a mail along, without sending anything. +func (o *emailValidatorMailClient) Validate(ctx context.Context, to string) error { + return o.ev.Validate(ctx, to) +} + type emailValidator struct { extended bool serviceURL string