aboutsummaryrefslogtreecommitdiff
path: root/mail_test.go
blob: c9170f6557e097f5a7959908ff0b57f82b2d1983 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
package main

import (
	"bytes"
	"io"
	"log"
	"net/http"
	"net/http/httptest"
	"net/url"
	"os"
	"strings"
	"sync"
	"testing"
)

// recorder is a Mailer that remembers instead of sending.
type recorder struct {
	mu   sync.Mutex
	sent []Message
	fail bool
}

func (m *recorder) Send(msg Message) error {
	m.mu.Lock()
	defer m.mu.Unlock()
	if m.fail {
		return io.ErrUnexpectedEOF
	}
	m.sent = append(m.sent, msg)
	return nil
}

func (m *recorder) messages() []Message {
	m.mu.Lock()
	defer m.mu.Unlock()
	return append([]Message(nil), m.sent...)
}

func TestSpoolDrainsOldestFirst(t *testing.T) {
	dir := t.TempDir()
	driver := &recorder{}
	spool := &Mail{dir: dir, driver: driver, wake: make(chan struct{}, 1)}

	for _, to := range []string{"one@example.com", "two@example.com", "three@example.com"} {
		spool.Enqueue(Message{To: to, Subject: "hello", Body: "body"})
	}
	if entries, _ := os.ReadDir(dir); len(entries) != 3 {
		t.Fatalf("expected three spooled messages, got %d", len(entries))
	}
	if spool.drainOnce() {
		t.Fatal("draining reported a failure")
	}
	sent := driver.messages()
	if len(sent) != 3 || sent[0].To != "one@example.com" || sent[2].To != "three@example.com" {
		t.Errorf("sent out of order: %v", sent)
	}
	if entries, _ := os.ReadDir(dir); len(entries) != 0 {
		t.Errorf("the spool still holds %d messages", len(entries))
	}
	// A message with no recipient is not a message.
	spool.Enqueue(Message{Subject: "nobody"})
	if entries, _ := os.ReadDir(dir); len(entries) != 0 {
		t.Error("a message with no recipient was spooled")
	}
}

// The line that says a message was dropped has to name it without carrying it:
// the body of one of these is a capability.
func TestSpoolGivesUpLoudly(t *testing.T) {
	dir := t.TempDir()
	spool := &Mail{dir: dir, driver: &recorder{fail: true}, wake: make(chan struct{}, 1)}
	spool.Enqueue(Message{To: "one@example.com", Subject: "set a new password",
		Body: "https://forge.example/set-password?name=bob&t=the-capability\n"})

	var buf bytes.Buffer
	old := log.Writer()
	log.SetOutput(&buf)
	for i := 0; i < mailAttempts; i++ {
		if !spool.drainOnce() {
			log.SetOutput(old)
			t.Fatalf("attempt %d: a failing driver reported success", i)
		}
	}
	log.SetOutput(old)

	if entries, _ := os.ReadDir(dir); len(entries) != 0 {
		t.Errorf("a message that will never send is still queued after %d attempts", mailAttempts)
	}
	for _, want := range []string{"giving up", "set a new password", "one@example.com"} {
		if !strings.Contains(buf.String(), want) {
			t.Errorf("the log does not say %q:\n%s", want, buf.String())
		}
	}
	if strings.Contains(buf.String(), "the-capability") {
		t.Errorf("a one time link reached the log:\n%s", buf.String())
	}
}

// The none driver is off: the log names what was not sent and never carries
// it, since the body of one of these is a capability.
func TestNoneDriverNamesWhatItDrops(t *testing.T) {
	if _, ok := newMail(&Config{Mail: MailConfig{Driver: "log"}}, t.TempDir()).driver.(logMailer); !ok {
		t.Error("the log driver is not the one that logs")
	}
	if _, ok := newMail(defaultConfig(), t.TempDir()).driver.(dropMailer); !ok {
		t.Error("the default driver sends somewhere")
	}

	var buf bytes.Buffer
	old := log.Writer()
	log.SetOutput(&buf)
	err := dropMailer{}.Send(Message{To: "bob@example.com", Subject: "set a new password",
		Body: "https://forge.example/set-password?name=bob&t=the-capability\n"})
	log.SetOutput(old)
	if err != nil {
		t.Fatal(err)
	}
	for _, want := range []string{"set a new password", "bob@example.com"} {
		if !strings.Contains(buf.String(), want) {
			t.Errorf("the log does not say %q:\n%s", want, buf.String())
		}
	}
	if strings.Contains(buf.String(), "the-capability") {
		t.Errorf("a one time link reached the log:\n%s", buf.String())
	}
}

func TestMailgunDriver(t *testing.T) {
	var got url.Values
	var user, key string
	var ok bool
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		user, key, ok = r.BasicAuth()
		r.ParseForm()
		got = r.PostForm
		if r.URL.Path != "/v3/mg.example.com/messages" {
			t.Errorf("posted to %s", r.URL.Path)
		}
	}))
	defer srv.Close()

	driver := &mailgunMailer{
		from: "git-forge <forge@example.com>", base: srv.URL + "/v3", domain: "mg.example.com",
		key: "secret", list: "https://git.example.com/settings", client: srv.Client(),
	}
	err := driver.Send(Message{To: "bob@example.com", Subject: "hello", Body: "body", Unsubscribe: true})
	if err != nil {
		t.Fatal(err)
	}
	if !ok || user != "api" || key != "secret" {
		t.Errorf("basic auth was %q %q %v", user, key, ok)
	}
	for field, want := range map[string]string{
		"from": "git-forge <forge@example.com>", "to": "bob@example.com",
		"subject": "hello", "text": "body",
		"h:List-Unsubscribe": "<https://git.example.com/settings>",
	} {
		if got.Get(field) != want {
			t.Errorf("%s was %q, wanted %q", field, got.Get(field), want)
		}
	}

	// A message that ignores the toggle carries no unsubscribe header.
	if err := driver.Send(Message{To: "bob@example.com", Subject: "hello", Body: "body"}); err != nil {
		t.Fatal(err)
	}
	if got.Has("h:List-Unsubscribe") {
		t.Error("a notice about the account itself carried List-Unsubscribe")
	}
}

func TestIssueNotifiesGranteesOnly(t *testing.T) {
	f := testForge(t)
	driver := &recorder{}
	f.mail.driver = driver
	addUser(t, f, "alice", "hunter2hunter2")
	addUser(t, f, "bob", "hunter2hunter2")
	addUser(t, f, "carol", "hunter2hunter2")
	confirm(t, f, "alice", "alice@example.com", true)
	confirm(t, f, "bob", "bob@example.com", true)
	confirm(t, f, "carol", "carol@example.com", false) // notify off
	addRepo(t, f, "notes", Repo{
		Visibility: visPublic, Issues: featUsers, Wiki: featDisabled,
		Grants: map[string]string{"alice": grantWrite, "bob": grantRead, "carol": grantRead},
	})

	h := f.routes()
	session := signIn(t, f, h, "alice")
	form := url.Values{"csrf": {f.csrf(withCookies("/", session))}, "title": {"A bug"}, "body": {"Details."}}
	if code := post(h, "/notes/issues", form, session).Code; code != http.StatusSeeOther {
		t.Fatalf("opening an issue: status %d", code)
	}
	f.mail.drainOnce()

	sent := driver.messages()
	if len(sent) != 1 {
		t.Fatalf("expected one message, got %v", sent)
	}
	if sent[0].To != "bob@example.com" {
		t.Errorf("mailed %s: alice caused it and carol has notifications off", sent[0].To)
	}
	if !sent[0].Unsubscribe {
		t.Error("an activity message did not carry the unsubscribe flag")
	}
	if !strings.Contains(sent[0].Body, "/notes/issues/1") {
		t.Errorf("the message does not link to the issue: %q", sent[0].Body)
	}
}

// An address receives nothing until a link sent to it has been followed, and
// changing it again unproves it and spends the link sent to the old one.
func TestAddressIsProvedByALink(t *testing.T) {
	f := testForge(t)
	driver := &recorder{}
	f.mail.driver = driver
	addUser(t, f, "bob", "hunter2hunter2")
	h := f.routes()
	session := signIn(t, f, h, "bob")
	token := f.csrf(withCookies("/", session))

	set := func(email string) {
		t.Helper()
		w := post(h, "/settings/email", url.Values{
			"csrf": {token}, "email": {email}, "notify": {"yes"}}, session)
		if w.Code != http.StatusOK {
			t.Fatalf("setting %q: status %d", email, w.Code)
		}
		f.mail.drainOnce()
	}

	set("bob@example.com")
	if u, _ := f.store.User("bob"); u.EmailConfirmed {
		t.Fatal("an address was confirmed without the link being followed")
	}
	sent := driver.messages()
	if len(sent) != 1 || sent[0].To != "bob@example.com" {
		t.Fatalf("expected one message to the address, got %v", sent)
	}
	link := between(sent[0].Body, f.cfg.BaseURL, "\n")
	if !strings.HasPrefix(link, "/confirm-email?") {
		t.Fatalf("no confirmation link in %q", sent[0].Body)
	}
	if code := get(h, link, session).Code; code != http.StatusOK {
		t.Fatalf("following the link: status %d", code)
	}
	if u, _ := f.store.User("bob"); !u.EmailConfirmed {
		t.Error("the address is still unconfirmed after the link was followed")
	}

	set("other@example.com")
	if u, _ := f.store.User("bob"); u.EmailConfirmed {
		t.Error("a changed address kept the old one's confirmation")
	}
	if code := get(h, link, session).Code; code != http.StatusNotFound {
		t.Errorf("the link to the old address still works: status %d", code)
	}
}

// The one unauthenticated path that sends a capability. The answer is the same
// either way, or the form is a list of which names are taken.
func TestResetTellsNobodyWhichAccountsExist(t *testing.T) {
	f := testForge(t)
	driver := &recorder{}
	f.mail.driver = driver
	addUser(t, f, "bob", "hunter2hunter2")
	confirm(t, f, "bob", "bob@example.com", true)
	h := f.routes()

	ask := func(name string) string {
		t.Helper()
		w := post(h, "/reset", url.Values{
			"csrf": {f.csrf(withCookies("/", nil))}, "name": {name}}, nil)
		if w.Code != http.StatusOK {
			t.Fatalf("asking for %q: status %d", name, w.Code)
		}
		f.mail.drainOnce()
		return w.Body.String()
	}

	const same = "if that account exists"
	if page := ask("bob"); !strings.Contains(page, same) {
		t.Error("the answer for an account that exists does not carry the notice")
	}
	sent := driver.messages()
	if len(sent) != 1 || sent[0].To != "bob@example.com" {
		t.Fatalf("no link went to the account: %v", sent)
	}
	if page := ask("nobody"); !strings.Contains(page, same) {
		t.Error("the answer for an account that does not exist reads differently")
	}
	if n := len(driver.messages()); n != 1 {
		t.Errorf("a reset for an account that does not exist sent mail: %d", n)
	}

	// And the link it did send sets a password once.
	link := between(sent[0].Body, f.cfg.BaseURL, "\n")
	page := get(h, link, nil)
	if page.Code != http.StatusOK {
		t.Fatalf("following the link: status %d", page.Code)
	}
	body := page.Body.String()
	form := url.Values{
		"csrf":    {f.csrf(withCookies("/", nil))},
		"name":    {between(body, `name="name" value="`, `"`)},
		"expires": {between(body, `name="expires" value="`, `"`)},
		"t":       {between(body, `name="t" value="`, `"`)},
		"new":     {"opensesame1"}, "again": {"opensesame1"},
	}
	if w := post(h, "/set-password", form, nil); w.Code != http.StatusSeeOther {
		t.Fatalf("setting the password: status %d", w.Code)
	}
	if u, _ := f.store.User("bob"); !passwordOK(u.Password, "opensesame1") {
		t.Error("the new password was not stored")
	}
	if w := post(h, "/set-password", form, nil); w.Code != http.StatusNotFound {
		t.Errorf("the link worked twice: status %d", w.Code)
	}
}

func confirm(t *testing.T, f *Forge, name, email string, notify bool) {
	t.Helper()
	err := f.store.UpdateUsers("users: address", f.store.forgeAuthor(), func(m map[string]User) error {
		u := m[name]
		u.Email, u.EmailConfirmed, u.Notify = email, true, notify
		m[name] = u
		return nil
	})
	if err != nil {
		t.Fatal(err)
	}
}