Do not run the CI workflow on pull requests.
[mailpopbox.git] / pop3 / conn_test.go
1 // mailpopbox
2 // Copyright 2020 Blue Static <https://www.bluestatic.org>
3 // This program is free software licensed under the GNU General Public License,
4 // version 3.0. The full text of the license can be found in LICENSE.txt.
5 // SPDX-License-Identifier: GPL-3.0-only
6
7 package pop3
8
9 import (
10 "fmt"
11 "io"
12 "io/ioutil"
13 "net"
14 "net/textproto"
15 "path/filepath"
16 "reflect"
17 "runtime"
18 "sort"
19 "strings"
20 "testing"
21
22 "go.uber.org/zap"
23 )
24
25 func _fl(depth int) string {
26 _, file, line, _ := runtime.Caller(depth + 1)
27 return fmt.Sprintf("[%s:%d]", filepath.Base(file), line)
28 }
29
30 func ok(t testing.TB, err error) {
31 if err != nil {
32 t.Errorf("%s unexpected error: %v", _fl(1), err)
33 }
34 }
35
36 func responseOK(t testing.TB, conn *textproto.Conn) string {
37 line, err := conn.ReadLine()
38 if err != nil {
39 t.Errorf("%s responseOK: %v", _fl(1), err)
40 }
41 if !strings.HasPrefix(line, "+OK") {
42 t.Errorf("%s expected +OK, got %q", _fl(1), line)
43 }
44 return line
45 }
46
47 func responseERR(t testing.TB, conn *textproto.Conn) string {
48 line, err := conn.ReadLine()
49 if err != nil {
50 t.Errorf("%s responseERR: %v", _fl(1), err)
51 }
52 if !strings.HasPrefix(line, "-ERR") {
53 t.Errorf("%s expected -ERR, got %q", _fl(1), line)
54 }
55 return line
56 }
57
58 func runServer(t *testing.T, po PostOffice) net.Listener {
59 l, err := net.Listen("tcp", "localhost:0")
60 if err != nil {
61 t.Fatal(err)
62 return nil
63 }
64
65 go func() {
66 for {
67 conn, err := l.Accept()
68 if err != nil {
69 return
70 }
71 go AcceptConnection(conn, po, zap.NewNop())
72 }
73 }()
74 return l
75 }
76
77 type testServer struct {
78 user, pass string
79 mb testMailbox
80 }
81
82 func (s *testServer) Name() string {
83 return "Test-Server"
84 }
85
86 func (s *testServer) OpenMailbox(user, pass string) (Mailbox, error) {
87 if s.user == user && s.pass == pass {
88 return &s.mb, nil
89 }
90 return nil, fmt.Errorf("bad username/pass")
91 }
92
93 type testMailbox struct {
94 msgs map[int]*testMessage
95 }
96
97 type MessageList []Message
98
99 func (l MessageList) Len() int {
100 return len(l)
101 }
102 func (l MessageList) Less(i, j int) bool {
103 return l[i].ID() < l[j].ID()
104 }
105 func (l MessageList) Swap(i, j int) {
106 l[i], l[j] = l[j], l[i]
107 }
108
109 func (mb *testMailbox) ListMessages() ([]Message, error) {
110 msgs := make([]Message, 0, len(mb.msgs))
111 for i, _ := range mb.msgs {
112 msgs = append(msgs, mb.msgs[i])
113 }
114 sort.Sort(MessageList(msgs))
115 return msgs, nil
116 }
117
118 func (mb *testMailbox) GetMessage(id int) Message {
119 if msg, ok := mb.msgs[id]; ok {
120 return msg
121 }
122 return nil
123 }
124
125 func (mb *testMailbox) Retrieve(msg Message) (io.ReadCloser, error) {
126 r := strings.NewReader(msg.(*testMessage).body)
127 return ioutil.NopCloser(r), nil
128 }
129
130 func (mb *testMailbox) Delete(msg Message) error {
131 msg.(*testMessage).deleted = true
132 return nil
133 }
134
135 func (mb *testMailbox) Close() error {
136 return nil
137 }
138
139 func (mb *testMailbox) Reset() {
140 for _, msg := range mb.msgs {
141 msg.deleted = false
142 }
143 }
144
145 type testMessage struct {
146 id int
147 size int
148 deleted bool
149 body string
150 }
151
152 func (m *testMessage) UniqueID() string {
153 return fmt.Sprintf("%p", m)
154 }
155
156 func (m *testMessage) ID() int {
157 return m.id
158 }
159 func (m *testMessage) Size() int {
160 return m.size
161 }
162 func (m *testMessage) Deleted() bool {
163 return m.deleted
164 }
165
166 func newTestServer() *testServer {
167 return &testServer{
168 user: "u",
169 pass: "p",
170 mb: testMailbox{
171 msgs: make(map[int]*testMessage),
172 },
173 }
174 }
175
176 // RFC 1939 ยง 10
177 func TestExampleSession(t *testing.T) {
178 s := newTestServer()
179 l := runServer(t, s)
180 defer l.Close()
181
182 s.mb.msgs[1] = &testMessage{1, 120, false, ""}
183 s.mb.msgs[2] = &testMessage{2, 200, false, ""}
184
185 conn, err := textproto.Dial(l.Addr().Network(), l.Addr().String())
186 ok(t, err)
187
188 line := responseOK(t, conn)
189 if !strings.Contains(line, s.Name()) {
190 t.Errorf("POP greeting did not include server name, got %q", line)
191 }
192
193 ok(t, conn.PrintfLine("USER u"))
194 responseOK(t, conn)
195
196 ok(t, conn.PrintfLine("PASS p"))
197 responseOK(t, conn)
198
199 ok(t, conn.PrintfLine("STAT"))
200 if want, got := "+OK 2 320", responseOK(t, conn); want != got {
201 t.Errorf("STAT want %q, got %q", want, got)
202 }
203
204 ok(t, conn.PrintfLine("LIST"))
205 responseOK(t, conn)
206 lines, err := conn.ReadDotLines()
207 ok(t, err)
208 if want, got := 2, len(lines); want != got {
209 t.Errorf("LIST want %d lines, got %d", want, got)
210 }
211 if want, got := "1 120", lines[0]; want != got {
212 t.Errorf("LIST line 0 want %q, got %q", want, got)
213 }
214 if want, got := "2 200", lines[1]; want != got {
215 t.Errorf("LIST line 1 expected %q, got %q", want, got)
216 }
217
218 ok(t, conn.PrintfLine("QUIT"))
219 responseOK(t, conn)
220 }
221
222 type requestResponse struct {
223 command string
224 expecter func(testing.TB, *textproto.Conn) string
225 }
226
227 func expectOKResponse(predicate func(string) bool) func(testing.TB, *textproto.Conn) string {
228 return func(t testing.TB, conn *textproto.Conn) string {
229 line := responseOK(t, conn)
230 if !predicate(line) {
231 t.Errorf("%s Predicate failed, got %q", _fl(1), line)
232 }
233 return line
234 }
235 }
236
237 func clientServerTest(t *testing.T, s *testServer, sequence []requestResponse) {
238 l := runServer(t, s)
239 defer l.Close()
240
241 conn, err := textproto.Dial(l.Addr().Network(), l.Addr().String())
242 ok(t, err)
243
244 responseOK(t, conn)
245
246 for _, pair := range sequence {
247 ok(t, conn.PrintfLine(pair.command))
248 pair.expecter(t, conn)
249 if t.Failed() {
250 t.Logf("command %q", pair.command)
251 }
252 }
253 }
254
255 func TestAuthStates(t *testing.T) {
256 clientServerTest(t, newTestServer(), []requestResponse{
257 {"STAT", responseERR},
258 {"NOOP", responseOK},
259 {"USER bad", responseOK},
260 {"PASS bad", responseERR},
261 {"USER", responseERR},
262 {"USER x", responseOK},
263 {"PASS", responseERR},
264 {"LIST", responseERR},
265 {"USER u", responseOK},
266 {"PASS bad", responseERR},
267 {"STAT", responseERR},
268 {"PASS p", responseOK},
269 {"QUIT", responseOK},
270 })
271 }
272
273 func TestDeleted(t *testing.T) {
274 s := newTestServer()
275 s.mb.msgs[1] = &testMessage{1, 999, false, ""}
276 s.mb.msgs[2] = &testMessage{2, 10, false, ""}
277
278 clientServerTest(t, s, []requestResponse{
279 {"USER u", responseOK},
280 {"PASS p", responseOK},
281 {"STAT", expectOKResponse(func(s string) bool {
282 return s == "+OK 2 1009"
283 })},
284 {"DELE 1", responseOK},
285 {"RETR 1", responseERR},
286 {"DELE 1", responseERR},
287 {"STAT", expectOKResponse(func(s string) bool {
288 return s == "+OK 1 10"
289 })},
290 {"RSET", responseOK},
291 {"STAT", expectOKResponse(func(s string) bool {
292 return s == "+OK 2 1009"
293 })},
294 {"QUIT", responseOK},
295 })
296 }
297
298 func TestCaseSensitivty(t *testing.T) {
299 s := newTestServer()
300 s.mb.msgs[999] = &testMessage{999, 1, false, "a"}
301
302 clientServerTest(t, s, []requestResponse{
303 {"user u", responseOK},
304 {"PasS p", responseOK},
305 {"sTaT", responseOK},
306 {"retr 1", responseERR},
307 {"dele 999", responseOK},
308 {"QUIT", responseOK},
309 })
310 }
311
312 func TestRetr(t *testing.T) {
313 s := newTestServer()
314 s.mb.msgs[1] = &testMessage{1, 5, false, "hello"}
315 s.mb.msgs[2] = &testMessage{2, 69, false, "this\r\nis a\r\n.\r\ntest"}
316
317 clientServerTest(t, s, []requestResponse{
318 {"USER u", responseOK},
319 {"PASS p", responseOK},
320 {"STAT", responseOK},
321 {"RETR 1", func(t testing.TB, tp *textproto.Conn) string {
322 responseOK(t, tp)
323 if t.Failed() {
324 return ""
325 }
326
327 resp, err := tp.ReadDotLines()
328 if err != nil {
329 t.Error(err)
330 return ""
331 }
332
333 want := []string{"hello"}
334 if !reflect.DeepEqual(resp, want) {
335 t.Errorf("Want %v, got %v", want, resp)
336 }
337
338 return ""
339 }},
340 {"RETR 2", func(t testing.TB, tp *textproto.Conn) string {
341 responseOK(t, tp)
342 if t.Failed() {
343 return ""
344 }
345
346 resp, err := tp.ReadDotLines()
347 if err != nil {
348 t.Error(err)
349 return ""
350 }
351
352 want := []string{"this", "is a", ".", "test"}
353 if !reflect.DeepEqual(resp, want) {
354 t.Errorf("Want %v, got %v", want, resp)
355 }
356
357 return ""
358 }},
359 {"QUIT", responseOK},
360 })
361 }
362
363 func TestUidl(t *testing.T) {
364 s := newTestServer()
365 s.mb.msgs[1] = &testMessage{1, 3, false, "abc"}
366 s.mb.msgs[2] = &testMessage{2, 1, true, "Z"}
367 s.mb.msgs[3] = &testMessage{3, 4, false, "test"}
368
369 clientServerTest(t, s, []requestResponse{
370 {"USER u", responseOK},
371 {"PASS p", responseOK},
372 {"UIDL", func(t testing.TB, tp *textproto.Conn) string {
373 responseOK(t, tp)
374 if t.Failed() {
375 return ""
376 }
377
378 resp, err := tp.ReadDotLines()
379 if err != nil {
380 t.Error(err)
381 return ""
382 }
383
384 want := []string{
385 fmt.Sprintf("1 %p", s.mb.msgs[1]),
386 fmt.Sprintf("3 %p", s.mb.msgs[3]),
387 }
388 if !reflect.DeepEqual(resp, want) {
389 t.Errorf("Want %v, got %v", want, resp)
390 }
391
392 return ""
393 }},
394 {"QUIT", responseOK},
395 })
396 }
397
398 func TestDele(t *testing.T) {
399 s := newTestServer()
400 s.mb.msgs[1] = &testMessage{1, 3, false, "abc"}
401 s.mb.msgs[2] = &testMessage{2, 1, false, "d"}
402
403 clientServerTest(t, s, []requestResponse{
404 {"USER u", responseOK},
405 {"PASS p", responseOK},
406 {"STAT", expectOKResponse(func(s string) bool {
407 return s == "+OK 2 4"
408 })},
409 {"DELE 1", responseOK},
410 {"STAT", expectOKResponse(func(s string) bool {
411 return s == "+OK 1 1"
412 })},
413 {"RSET", responseOK},
414 {"STAT", expectOKResponse(func(s string) bool {
415 return s == "+OK 2 4"
416 })},
417 {"QUIT", responseOK},
418 })
419
420 if s.mb.msgs[1].Deleted() || s.mb.msgs[2].Deleted() {
421 t.Errorf("RSET should not delete a message")
422 }
423
424 clientServerTest(t, s, []requestResponse{
425 {"USER u", responseOK},
426 {"PASS p", responseOK},
427 {"STAT", expectOKResponse(func(s string) bool {
428 return s == "+OK 2 4"
429 })},
430 {"DELE 1", responseOK},
431 {"STAT", expectOKResponse(func(s string) bool {
432 return s == "+OK 1 1"
433 })},
434 {"QUIT", responseOK},
435 })
436
437 if !s.mb.msgs[1].Deleted() {
438 t.Errorf("DELE did not work")
439 }
440 if s.mb.msgs[2].Deleted() {
441 t.Errorf("DELE the wrong message")
442 }
443 }
444
445 func TestCapa(t *testing.T) {
446 s := newTestServer()
447
448 capaTest := func(t testing.TB, tp *textproto.Conn) string {
449 responseOK(t, tp)
450 if t.Failed() {
451 return ""
452 }
453
454 resp, err := tp.ReadDotLines()
455 if err != nil {
456 t.Error(err)
457 return ""
458 }
459
460 const (
461 capNeeded = iota
462 capSeen
463 capOK
464 )
465
466 caps := map[string]int{
467 "USER": capNeeded,
468 "UIDL": capNeeded,
469 }
470 for _, line := range resp {
471 if val, ok := caps[line]; ok {
472 if val == capNeeded {
473 caps[line] = capOK
474 } else {
475 t.Errorf("unxpected capa value %q", line)
476 }
477 } else {
478 caps[line] = capSeen
479 }
480 }
481 for c, val := range caps {
482 if val != capOK {
483 t.Errorf("unexpected capa value for %q: %d", c, val)
484 }
485 }
486 return ""
487 }
488
489 clientServerTest(t, s, []requestResponse{
490 {"CAPA", capaTest},
491 {"USER u", responseOK},
492 {"CAPA", capaTest},
493 {"PASS p", responseOK},
494 {"CAPA", capaTest},
495 {"QUIT", responseOK},
496 })
497 }