forked from mjl-/mox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi_test.go
433 lines (388 loc) · 18.1 KB
/
api_test.go
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
package webmail
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"runtime/debug"
"testing"
"golang.org/x/exp/slices"
"github.com/mjl-/bstore"
"github.com/mjl-/sherpa"
"github.com/mjl-/mox/dns"
"github.com/mjl-/mox/mlog"
"github.com/mjl-/mox/mox-"
"github.com/mjl-/mox/queue"
"github.com/mjl-/mox/store"
)
func tneedErrorCode(t *testing.T, code string, fn func()) {
t.Helper()
defer func() {
t.Helper()
x := recover()
if x == nil {
debug.PrintStack()
t.Fatalf("expected sherpa user error, saw success")
}
if err, ok := x.(*sherpa.Error); !ok {
debug.PrintStack()
t.Fatalf("expected sherpa error, saw %#v", x)
} else if err.Code != code {
debug.PrintStack()
t.Fatalf("expected sherpa error code %q, saw other sherpa error %#v", code, err)
}
}()
fn()
}
func tneedError(t *testing.T, fn func()) {
tneedErrorCode(t, "user:error", fn)
}
// Test API calls.
// todo: test that the actions make the changes they claim to make. we currently just call the functions and have only limited checks that state changed.
func TestAPI(t *testing.T) {
mox.LimitersInit()
os.RemoveAll("../testdata/webmail/data")
mox.Context = ctxbg
mox.ConfigStaticPath = filepath.FromSlash("../testdata/webmail/mox.conf")
mox.MustLoadConfig(true, false)
defer store.Switchboard()()
log := mlog.New("webmail", nil)
acc, err := store.OpenAccount(log, "mjl")
tcheck(t, err, "open account")
err = acc.SetPassword(log, "test1234")
tcheck(t, err, "set password")
defer func() {
err := acc.Close()
pkglog.Check(err, "closing account")
}()
var zerom store.Message
var (
inboxMinimal = &testmsg{"Inbox", store.Flags{}, nil, msgMinimal, zerom, 0}
inboxText = &testmsg{"Inbox", store.Flags{}, nil, msgText, zerom, 0}
inboxHTML = &testmsg{"Inbox", store.Flags{}, nil, msgHTML, zerom, 0}
inboxAlt = &testmsg{"Inbox", store.Flags{}, nil, msgAlt, zerom, 0}
inboxAltRel = &testmsg{"Inbox", store.Flags{}, nil, msgAltRel, zerom, 0}
inboxAttachments = &testmsg{"Inbox", store.Flags{}, nil, msgAttachments, zerom, 0}
testbox1Alt = &testmsg{"Testbox1", store.Flags{}, nil, msgAlt, zerom, 0}
rejectsMinimal = &testmsg{"Rejects", store.Flags{Junk: true}, nil, msgMinimal, zerom, 0}
)
var testmsgs = []*testmsg{inboxMinimal, inboxText, inboxHTML, inboxAlt, inboxAltRel, inboxAttachments, testbox1Alt, rejectsMinimal}
for _, tm := range testmsgs {
tdeliver(t, acc, tm)
}
api := Webmail{maxMessageSize: 1024 * 1024, cookiePath: "/webmail/"}
// Test login, and rate limiter.
loginReqInfo := requestInfo{"[email protected]", "mjl", "", httptest.NewRecorder(), &http.Request{RemoteAddr: "1.1.1.1:1234"}}
loginctx := context.WithValue(ctxbg, requestInfoCtxKey, loginReqInfo)
// Missing login token.
tneedErrorCode(t, "user:error", func() { api.Login(loginctx, "", "[email protected]", "test1234") })
// Login with loginToken.
loginCookie := &http.Cookie{Name: "webmaillogin"}
loginCookie.Value = api.LoginPrep(loginctx)
loginReqInfo.Request.Header = http.Header{"Cookie": []string{loginCookie.String()}}
testLogin := func(username, password string, expErrCodes ...string) {
t.Helper()
defer func() {
x := recover()
expErr := len(expErrCodes) > 0
if (x != nil) != expErr {
t.Fatalf("got %v, expected codes %v", x, expErrCodes)
}
if x == nil {
return
} else if err, ok := x.(*sherpa.Error); !ok {
t.Fatalf("got %#v, expected at most *sherpa.Error", x)
} else if !slices.Contains(expErrCodes, err.Code) {
t.Fatalf("got error code %q, expected %v", err.Code, expErrCodes)
}
}()
api.Login(loginctx, loginCookie.Value, username, password)
}
testLogin("[email protected]", "test1234")
testLogin("[email protected]", "bad", "user:loginFailed")
testLogin("[email protected]", "test1234", "user:loginFailed")
testLogin("[email protected]", "test1234", "user:loginFailed")
for i := 3; i < 10; i++ {
testLogin("[email protected]", "test1234", "user:loginFailed")
}
// Ensure rate limiter is triggered, also for slow tests.
for i := 0; i < 10; i++ {
testLogin("[email protected]", "test1234", "user:loginFailed", "user:error")
}
testLogin("[email protected]", "test1234", "user:error")
// Context with different IP, for clear rate limit history.
reqInfo := requestInfo{"[email protected]", "mjl", "", nil, &http.Request{RemoteAddr: "127.0.0.1:1234"}}
ctx := context.WithValue(ctxbg, requestInfoCtxKey, reqInfo)
// FlagsAdd
api.FlagsAdd(ctx, []int64{inboxText.ID}, []string{`\seen`, `customlabel`})
api.FlagsAdd(ctx, []int64{inboxText.ID, inboxHTML.ID}, []string{`\seen`, `customlabel`})
api.FlagsAdd(ctx, []int64{inboxText.ID, inboxText.ID}, []string{`\seen`, `customlabel`}) // Same message twice.
api.FlagsAdd(ctx, []int64{inboxText.ID}, []string{`another`})
api.FlagsAdd(ctx, []int64{inboxText.ID}, []string{`another`}) // No change.
api.FlagsAdd(ctx, []int64{inboxText.ID}, []string{}) // Nothing to do.
api.FlagsAdd(ctx, []int64{}, []string{}) // No messages, no flags.
api.FlagsAdd(ctx, []int64{}, []string{`custom`}) // No message, new flag.
api.FlagsAdd(ctx, []int64{inboxText.ID}, []string{`$junk`}) // Trigger retrain.
api.FlagsAdd(ctx, []int64{inboxText.ID}, []string{`$notjunk`}) // Trigger retrain.
api.FlagsAdd(ctx, []int64{inboxText.ID, testbox1Alt.ID}, []string{`$junk`, `$notjunk`}) // Trigger retrain, messages in different mailboxes.
api.FlagsAdd(ctx, []int64{inboxHTML.ID, testbox1Alt.ID}, []string{`\Seen`, `newlabel`}) // Two mailboxes with counts and keywords changed.
tneedError(t, func() { api.FlagsAdd(ctx, []int64{inboxText.ID}, []string{` bad syntax `}) })
tneedError(t, func() { api.FlagsAdd(ctx, []int64{inboxText.ID}, []string{``}) }) // Empty is invalid.
tneedError(t, func() { api.FlagsAdd(ctx, []int64{inboxText.ID}, []string{`\unknownsystem`}) }) // Only predefined system flags.
// FlagsClear, inverse of FlagsAdd.
api.FlagsClear(ctx, []int64{inboxText.ID}, []string{`\seen`, `customlabel`})
api.FlagsClear(ctx, []int64{inboxText.ID, inboxHTML.ID}, []string{`\seen`, `customlabel`})
api.FlagsClear(ctx, []int64{inboxText.ID, inboxText.ID}, []string{`\seen`, `customlabel`}) // Same message twice.
api.FlagsClear(ctx, []int64{inboxText.ID}, []string{`another`})
api.FlagsClear(ctx, []int64{inboxText.ID}, []string{`another`})
api.FlagsClear(ctx, []int64{inboxText.ID}, []string{})
api.FlagsClear(ctx, []int64{}, []string{})
api.FlagsClear(ctx, []int64{}, []string{`custom`})
api.FlagsClear(ctx, []int64{inboxText.ID}, []string{`$junk`})
api.FlagsClear(ctx, []int64{inboxText.ID}, []string{`$notjunk`})
api.FlagsClear(ctx, []int64{inboxText.ID, testbox1Alt.ID}, []string{`$junk`, `$notjunk`})
api.FlagsClear(ctx, []int64{inboxHTML.ID, testbox1Alt.ID}, []string{`\Seen`}) // Two mailboxes with counts changed.
tneedError(t, func() { api.FlagsClear(ctx, []int64{inboxText.ID}, []string{` bad syntax `}) })
tneedError(t, func() { api.FlagsClear(ctx, []int64{inboxText.ID}, []string{``}) })
tneedError(t, func() { api.FlagsClear(ctx, []int64{inboxText.ID}, []string{`\unknownsystem`}) })
// MailboxSetSpecialUse
var inbox, archive, sent, testbox1 store.Mailbox
err = acc.DB.Read(ctx, func(tx *bstore.Tx) error {
get := func(k string, v any) store.Mailbox {
mb, err := bstore.QueryTx[store.Mailbox](tx).FilterEqual(k, v).Get()
tcheck(t, err, "get special-use mailbox")
return mb
}
get("Draft", true)
sent = get("Sent", true)
archive = get("Archive", true)
get("Trash", true)
get("Junk", true)
inbox = get("Name", "Inbox")
testbox1 = get("Name", "Testbox1")
return nil
})
tcheck(t, err, "get mailboxes")
api.MailboxSetSpecialUse(ctx, store.Mailbox{ID: archive.ID, SpecialUse: store.SpecialUse{Draft: true}}) // Already set.
api.MailboxSetSpecialUse(ctx, store.Mailbox{ID: testbox1.ID, SpecialUse: store.SpecialUse{Draft: true}}) // New draft mailbox.
api.MailboxSetSpecialUse(ctx, store.Mailbox{ID: testbox1.ID, SpecialUse: store.SpecialUse{Sent: true}})
api.MailboxSetSpecialUse(ctx, store.Mailbox{ID: testbox1.ID, SpecialUse: store.SpecialUse{Archive: true}})
api.MailboxSetSpecialUse(ctx, store.Mailbox{ID: testbox1.ID, SpecialUse: store.SpecialUse{Trash: true}})
api.MailboxSetSpecialUse(ctx, store.Mailbox{ID: testbox1.ID, SpecialUse: store.SpecialUse{Junk: true}})
api.MailboxSetSpecialUse(ctx, store.Mailbox{ID: testbox1.ID, SpecialUse: store.SpecialUse{}}) // None
api.MailboxSetSpecialUse(ctx, store.Mailbox{ID: testbox1.ID, SpecialUse: store.SpecialUse{Draft: true, Sent: true, Archive: true, Trash: true, Junk: true}}) // All
api.MailboxSetSpecialUse(ctx, store.Mailbox{ID: testbox1.ID, SpecialUse: store.SpecialUse{}}) // None again.
api.MailboxSetSpecialUse(ctx, store.Mailbox{ID: sent.ID, SpecialUse: store.SpecialUse{Sent: true}}) // Sent, for sending mail later.
tneedError(t, func() { api.MailboxSetSpecialUse(ctx, store.Mailbox{ID: 0}) })
// MailboxRename
api.MailboxRename(ctx, testbox1.ID, "Testbox2")
api.MailboxRename(ctx, testbox1.ID, "Test/A/B/Box1")
api.MailboxRename(ctx, testbox1.ID, "Test/A/Box1")
api.MailboxRename(ctx, testbox1.ID, "Testbox1")
tneedError(t, func() { api.MailboxRename(ctx, 0, "BadID") })
tneedError(t, func() { api.MailboxRename(ctx, testbox1.ID, "Testbox1") }) // Already this name.
tneedError(t, func() { api.MailboxRename(ctx, testbox1.ID, "Inbox") }) // Inbox not allowed.
tneedError(t, func() { api.MailboxRename(ctx, inbox.ID, "Binbox") }) // Inbox not allowed.
tneedError(t, func() { api.MailboxRename(ctx, testbox1.ID, "Archive") }) // Exists.
// ParsedMessage
// todo: verify contents
api.ParsedMessage(ctx, inboxMinimal.ID)
api.ParsedMessage(ctx, inboxText.ID)
api.ParsedMessage(ctx, inboxHTML.ID)
api.ParsedMessage(ctx, inboxAlt.ID)
api.ParsedMessage(ctx, inboxAltRel.ID)
api.ParsedMessage(ctx, testbox1Alt.ID)
tneedError(t, func() { api.ParsedMessage(ctx, 0) })
tneedError(t, func() { api.ParsedMessage(ctx, testmsgs[len(testmsgs)-1].ID+1) })
// MailboxDelete
api.MailboxDelete(ctx, testbox1.ID)
testa, err := bstore.QueryDB[store.Mailbox](ctx, acc.DB).FilterEqual("Name", "Test/A").Get()
tcheck(t, err, "get mailbox Test/A")
tneedError(t, func() { api.MailboxDelete(ctx, testa.ID) }) // Test/A/B still exists.
tneedError(t, func() { api.MailboxDelete(ctx, 0) }) // Bad ID.
tneedError(t, func() { api.MailboxDelete(ctx, testbox1.ID) }) // No longer exists.
tneedError(t, func() { api.MailboxDelete(ctx, inbox.ID) }) // Cannot remove inbox.
tneedError(t, func() { api.ParsedMessage(ctx, testbox1Alt.ID) }) // Message was removed and no longer exists.
api.MailboxCreate(ctx, "Testbox1")
testbox1, err = bstore.QueryDB[store.Mailbox](ctx, acc.DB).FilterEqual("Name", "Testbox1").Get()
tcheck(t, err, "get testbox1")
tdeliver(t, acc, testbox1Alt)
// MailboxEmpty
api.MailboxEmpty(ctx, testbox1.ID)
tneedError(t, func() { api.ParsedMessage(ctx, testbox1Alt.ID) }) // Message was removed and no longer exists.
tneedError(t, func() { api.MailboxEmpty(ctx, 0) }) // Bad ID.
// MessageMove
tneedError(t, func() { api.MessageMove(ctx, []int64{testbox1Alt.ID}, inbox.ID) }) // Message was removed (with MailboxEmpty above).
api.MessageMove(ctx, []int64{}, testbox1.ID) // No messages.
tdeliver(t, acc, testbox1Alt)
tneedError(t, func() { api.MessageMove(ctx, []int64{testbox1Alt.ID}, testbox1.ID) }) // Already in destination mailbox.
tneedError(t, func() { api.MessageMove(ctx, []int64{}, 0) }) // Bad ID.
api.MessageMove(ctx, []int64{inboxMinimal.ID, inboxHTML.ID}, testbox1.ID)
api.MessageMove(ctx, []int64{inboxMinimal.ID, inboxHTML.ID, testbox1Alt.ID}, inbox.ID) // From different mailboxes.
api.FlagsAdd(ctx, []int64{inboxMinimal.ID}, []string{`minimallabel`}) // For move.
api.MessageMove(ctx, []int64{inboxMinimal.ID}, testbox1.ID) // Move causes new label for destination mailbox.
api.MessageMove(ctx, []int64{rejectsMinimal.ID}, testbox1.ID) // Move causing readjustment of MailboxOrigID due to Rejects mailbox.
tneedError(t, func() { api.MessageMove(ctx, []int64{testbox1Alt.ID, inboxMinimal.ID}, testbox1.ID) }) // inboxMinimal already in destination.
// Restore.
api.MessageMove(ctx, []int64{inboxMinimal.ID}, inbox.ID)
api.MessageMove(ctx, []int64{testbox1Alt.ID}, testbox1.ID)
// MessageDelete
api.MessageDelete(ctx, []int64{}) // No messages.
api.MessageDelete(ctx, []int64{inboxMinimal.ID, inboxHTML.ID}) // Same mailbox.
api.MessageDelete(ctx, []int64{inboxText.ID, testbox1Alt.ID, inboxAltRel.ID}) // Multiple mailboxes, multiple times.
tneedError(t, func() { api.MessageDelete(ctx, []int64{0}) }) // Bad ID.
tneedError(t, func() { api.MessageDelete(ctx, []int64{testbox1Alt.ID + 999}) }) // Bad ID
tneedError(t, func() { api.MessageDelete(ctx, []int64{testbox1Alt.ID}) }) // Already removed.
tdeliver(t, acc, testbox1Alt)
tdeliver(t, acc, inboxAltRel)
// MessageSubmit
queue.Localserve = true // Deliver directly to us instead attempting actual delivery.
api.MessageSubmit(ctx, SubmitMessage{
From: "[email protected]",
To: []string{"[email protected]", "mjl to2 <[email protected]>"},
Cc: []string{"[email protected]", "mjl cc2 <[email protected]>"},
Bcc: []string{"[email protected]", "mjl bcc2 <[email protected]>"},
Subject: "test email",
TextBody: "this is the content\n\ncheers,\nmox",
ReplyTo: "mjl replyto <[email protected]>",
UserAgent: "moxwebmail/dev",
})
// todo: check delivery of 6 messages to inbox, 1 to sent
// Reply with attachments.
api.MessageSubmit(ctx, SubmitMessage{
From: "[email protected]",
To: []string{"[email protected]"},
Subject: "Re: reply with attachments",
TextBody: "sending you these fake png files",
Attachments: []File{
{
Filename: "test1.png",
DataURI: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUg==",
},
{
Filename: "test1.png",
DataURI: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUg==",
},
},
ResponseMessageID: testbox1Alt.ID,
})
// todo: check answered flag
// Forward with attachments.
api.MessageSubmit(ctx, SubmitMessage{
From: "[email protected]",
To: []string{"[email protected]"},
Subject: "Fwd: the original subject",
TextBody: "look what i got",
Attachments: []File{
{
Filename: "test1.png",
DataURI: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUg==",
},
},
ForwardAttachments: ForwardAttachments{
MessageID: inboxAltRel.ID,
Paths: [][]int{{1, 1}, {1, 1}},
},
IsForward: true,
ResponseMessageID: testbox1Alt.ID,
})
// todo: check forwarded flag, check it has the right attachments.
// Send from utf8 localpart.
api.MessageSubmit(ctx, SubmitMessage{
From: "mø[email protected]",
To: []string{"[email protected]"},
TextBody: "test",
})
// Send to utf8 localpart.
api.MessageSubmit(ctx, SubmitMessage{
From: "[email protected]",
To: []string{"mø[email protected]"},
TextBody: "test",
})
// Send to utf-8 text.
api.MessageSubmit(ctx, SubmitMessage{
From: "[email protected]",
To: []string{"[email protected]"},
Subject: "hi ☺",
TextBody: fmt.Sprintf("%80s", "tést"),
})
// Send without special-use Sent mailbox.
api.MailboxSetSpecialUse(ctx, store.Mailbox{ID: sent.ID, SpecialUse: store.SpecialUse{}})
api.MessageSubmit(ctx, SubmitMessage{
From: "[email protected]",
To: []string{"[email protected]"},
Subject: "hi ☺",
TextBody: fmt.Sprintf("%80s", "tést"),
})
// Message with From-address of another account.
tneedError(t, func() {
api.MessageSubmit(ctx, SubmitMessage{
From: "[email protected]",
To: []string{"[email protected]"},
TextBody: "test",
})
})
// Message with unknown address.
tneedError(t, func() {
api.MessageSubmit(ctx, SubmitMessage{
From: "[email protected]",
To: []string{"[email protected]"},
TextBody: "test",
})
})
// Message without recipient.
tneedError(t, func() {
api.MessageSubmit(ctx, SubmitMessage{
From: "[email protected]",
TextBody: "test",
})
})
api.maxMessageSize = 1
tneedError(t, func() {
api.MessageSubmit(ctx, SubmitMessage{
From: "[email protected]",
To: []string{"[email protected]"},
Subject: "too large",
TextBody: "so many bytes",
})
})
api.maxMessageSize = 1024 * 1024
// Hit recipient limit.
tneedError(t, func() {
accConf, _ := acc.Conf()
for i := 0; i <= accConf.MaxFirstTimeRecipientsPerDay; i++ {
api.MessageSubmit(ctx, SubmitMessage{
From: fmt.Sprintf("user@mox%d.example", i),
TextBody: "test",
})
}
})
// Hit message limit.
tneedError(t, func() {
accConf, _ := acc.Conf()
for i := 0; i <= accConf.MaxOutgoingMessagesPerDay; i++ {
api.MessageSubmit(ctx, SubmitMessage{
From: fmt.Sprintf("user@mox%d.example", i),
TextBody: "test",
})
}
})
l, full := api.CompleteRecipient(ctx, "doesnotexist")
tcompare(t, len(l), 0)
tcompare(t, full, true)
l, full = api.CompleteRecipient(ctx, "cc2")
tcompare(t, l, []string{"mjl cc2 <[email protected]>"})
tcompare(t, full, true)
// RecipientSecurity
resolver := dns.MockResolver{}
rs, err := recipientSecurity(ctx, resolver, "[email protected]")
tcompare(t, err, nil)
tcompare(t, rs, RecipientSecurity{SecurityResultUnknown, SecurityResultNo, SecurityResultNo, SecurityResultNo, SecurityResultUnknown})
err = acc.DB.Insert(ctx, &store.RecipientDomainTLS{Domain: "a.mox.example", STARTTLS: true, RequireTLS: false})
tcheck(t, err, "insert recipient domain tls info")
rs, err = recipientSecurity(ctx, resolver, "[email protected]")
tcompare(t, err, nil)
tcompare(t, rs, RecipientSecurity{SecurityResultYes, SecurityResultNo, SecurityResultNo, SecurityResultNo, SecurityResultNo})
}