File: server_test.go

package info (click to toggle)
golang-github-protonmail-gluon 0.17.0-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 16,020 kB
  • sloc: sh: 55; makefile: 5
file content (424 lines) | stat: -rw-r--r-- 10,920 bytes parent folder | download
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
package tests

import (
	"context"
	"crypto/tls"
	"encoding/hex"
	"fmt"
	"net"
	"path/filepath"
	"testing"
	"time"

	"github.com/ProtonMail/gluon"
	"github.com/ProtonMail/gluon/connector"
	"github.com/ProtonMail/gluon/db"
	"github.com/ProtonMail/gluon/imap"
	"github.com/ProtonMail/gluon/internal/db_impl"
	"github.com/ProtonMail/gluon/internal/hash"
	"github.com/ProtonMail/gluon/limits"
	"github.com/ProtonMail/gluon/logging"
	"github.com/ProtonMail/gluon/reporter"
	"github.com/ProtonMail/gluon/store"
	"github.com/ProtonMail/gluon/version"
	"github.com/bradenaw/juniper/xslices"
	"github.com/emersion/go-imap/client"
	"github.com/google/uuid"
	"github.com/sirupsen/logrus"
	"github.com/stretchr/testify/require"
	"golang.org/x/exp/slices"
)

const defaultPeriod = time.Second

var (
	defaultFlags          = imap.NewFlagSet(imap.FlagSeen, imap.FlagFlagged, imap.FlagDeleted)
	defaultPermanentFlags = imap.NewFlagSet(imap.FlagSeen, imap.FlagFlagged, imap.FlagDeleted)
	defaultAttributes     = imap.NewFlagSet()
)

type credentials struct {
	usernames []string
	password  string
}

var testServerVersionInfo = version.Info{
	Name:       "gluon-test-server",
	Version:    version.Version{Major: 1, Minor: 1, Patch: 1},
	Vendor:     "Proton",
	SupportURL: "",
}

type connectorBuilder interface {
	New(usernames []string, password []byte, period time.Duration, flags, permFlags, attrs imap.FlagSet) Connector
}

type dummyConnectorBuilder struct{}

func (*dummyConnectorBuilder) New(usernames []string, password []byte, period time.Duration, flags, permFlags, attrs imap.FlagSet) Connector {
	return connector.NewDummy(
		usernames,
		password,
		period,
		flags,
		permFlags,
		attrs,
	)
}

type serverOptions struct {
	credentials          []credentials
	delimiter            string
	loginJailTime        time.Duration
	dataDir              string
	databaseDir          string
	idleBulkTime         time.Duration
	storeBuilder         store.Builder
	connectorBuilder     connectorBuilder
	disableParallelism   bool
	imapLimits           limits.IMAP
	reporter             reporter.Reporter
	uidValidityGenerator imap.UIDValidityGenerator
	database             db.ClientInterface
}

func (s *serverOptions) defaultUsername() string {
	return s.credentials[0].usernames[0]
}

func (s *serverOptions) defaultPassword() string {
	return s.credentials[0].password
}

func (s *serverOptions) password(username string) string {
	return s.credentials[xslices.IndexFunc(s.credentials, func(cred credentials) bool {
		return slices.Contains(cred.usernames, username)
	})].password
}

type serverOption interface {
	apply(options *serverOptions)
}

type delimiterServerOption struct {
	delimiter string
}

func (d *delimiterServerOption) apply(options *serverOptions) {
	options.delimiter = d.delimiter
}

type idleBulkTimeOption struct {
	idleBulkTime time.Duration
}

func (d *idleBulkTimeOption) apply(options *serverOptions) {
	options.idleBulkTime = d.idleBulkTime
}

type dataDirOption struct {
	dir string
}

func (opt *dataDirOption) apply(options *serverOptions) {
	options.dataDir = opt.dir
}

type databaseDirOption struct {
	dir string
}

func (opt *databaseDirOption) apply(options *serverOptions) {
	options.databaseDir = opt.dir
}

type credentialsSeverOption struct {
	credentials []credentials
}

func (c *credentialsSeverOption) apply(options *serverOptions) {
	options.credentials = c.credentials
}

type storeBuilderOption struct {
	builder store.Builder
}

func (s *storeBuilderOption) apply(options *serverOptions) {
	options.storeBuilder = s.builder
}

type connectorBuilderOption struct {
	builder connectorBuilder
}

func (c *connectorBuilderOption) apply(options *serverOptions) {
	options.connectorBuilder = c.builder
}

type disableParallelism struct{}

func (disableParallelism) apply(options *serverOptions) {
	options.disableParallelism = true
}

type imapLimits struct {
	limits limits.IMAP
}

func (m imapLimits) apply(options *serverOptions) {
	options.imapLimits = m.limits
}

type reporterOption struct {
	reporter reporter.Reporter
}

func (r reporterOption) apply(options *serverOptions) {
	options.reporter = r.reporter
}

type uidValidityGeneratorOption struct {
	generator imap.UIDValidityGenerator
}

type withDatabaseOption struct {
	database db.ClientInterface
}

func (w withDatabaseOption) apply(options *serverOptions) {
	options.database = w.database
}

func (u uidValidityGeneratorOption) apply(options *serverOptions) {
	options.uidValidityGenerator = u.generator
}

func withIdleBulkTime(idleBulkTime time.Duration) serverOption {
	return &idleBulkTimeOption{idleBulkTime: idleBulkTime}
}

func withDelimiter(delimiter string) serverOption {
	return &delimiterServerOption{delimiter: delimiter}
}

func withDataDir(dir string) serverOption {
	return &dataDirOption{dir: dir}
}

func withCredentials(credentials []credentials) serverOption {
	return &credentialsSeverOption{credentials: credentials}
}

func withStoreBuilder(builder store.Builder) serverOption {
	return &storeBuilderOption{builder: builder}
}

func withConnectorBuilder(builder connectorBuilder) serverOption {
	return &connectorBuilderOption{builder: builder}
}

func withDisableParallelism() serverOption {
	return &disableParallelism{}
}

func withIMAPLimits(limits limits.IMAP) serverOption {
	return &imapLimits{limits: limits}
}

func withReporter(reporter reporter.Reporter) serverOption {
	return &reporterOption{reporter: reporter}
}

func withUIDValidityGenerator(generator imap.UIDValidityGenerator) serverOption {
	return &uidValidityGeneratorOption{generator: generator}
}

func withDatabaseDir(dir string) serverOption {
	return &databaseDirOption{dir: dir}
}

func withDatabase(ci db.ClientInterface) serverOption {
	return &withDatabaseOption{database: ci}
}

func defaultServerOptions(tb testing.TB, modifiers ...serverOption) *serverOptions {
	options := &serverOptions{
		credentials: []credentials{{
			usernames: []string{"user"},
			password:  "pass",
		}},
		delimiter:        "/",
		loginJailTime:    time.Second,
		dataDir:          filepath.Join(tb.TempDir(), "backend", "store"),
		databaseDir:      filepath.Join(tb.TempDir(), "backend", "db"),
		idleBulkTime:     time.Duration(500 * time.Millisecond),
		storeBuilder:     &store.OnDiskStoreBuilder{},
		connectorBuilder: &dummyConnectorBuilder{},
		imapLimits:       limits.DefaultLimits(),
		database:         db_impl.NewSQLiteDB(),
	}

	for _, op := range modifiers {
		op.apply(options)
	}

	return options
}

// runServer initializes and starts the mailserver.
func runServer(tb testing.TB, options *serverOptions, tests func(session *testSession)) {
	loggerIn := logrus.StandardLogger().WriterLevel(logrus.TraceLevel)
	defer loggerIn.Close()

	loggerOut := logrus.StandardLogger().WriterLevel(logrus.TraceLevel)
	defer loggerOut.Close()

	// Create a test reporter to capture reported messages.
	reporter := new(testReporter)

	// Log the (temporary?) directory to store gluon data.
	logrus.Tracef("Gluon Data Dir: %v", options.dataDir)

	gluonOptions := []gluon.Option{
		gluon.WithDataDir(options.dataDir),
		gluon.WithDatabaseDir(options.databaseDir),
		gluon.WithDelimiter(options.delimiter),
		gluon.WithLoginJailTime(options.loginJailTime),
		gluon.WithTLS(&tls.Config{
			Certificates: []tls.Certificate{testCert},
			MinVersion:   tls.VersionTLS13,
		}),
		gluon.WithLogger(
			loggerIn,
			loggerOut,
		),
		gluon.WithVersionInfo(
			testServerVersionInfo.Version.Major,
			testServerVersionInfo.Version.Minor,
			testServerVersionInfo.Version.Patch,
			testServerVersionInfo.Name,
			testServerVersionInfo.Vendor,
			testServerVersionInfo.SupportURL,
		),
		gluon.WithIdleBulkTime(options.idleBulkTime),
		gluon.WithStoreBuilder(options.storeBuilder),
		gluon.WithReporter(reporter),
		gluon.WithIMAPLimits(options.imapLimits),
		gluon.WithDBClient(options.database),
	}

	if options.disableParallelism {
		gluonOptions = append(gluonOptions, gluon.WithDisableParallelism())
	}

	if options.reporter != nil {
		gluonOptions = append(gluonOptions, gluon.WithReporter(options.reporter))
	}

	if options.uidValidityGenerator != nil {
		gluonOptions = append(gluonOptions, gluon.WithUIDValidityGenerator(options.uidValidityGenerator))
	}

	// Create a new gluon server.
	server, err := gluon.New(gluonOptions...)
	require.NoError(tb, err)

	// Watch server events.
	eventCh := server.AddWatcher()

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

	userIDs := make(map[string]string)
	conns := make(map[string]Connector)
	dbPaths := make(map[string]string)

	for _, creds := range options.credentials {
		conn := options.connectorBuilder.New(
			creds.usernames,
			[]byte(creds.password),
			defaultPeriod,
			defaultFlags,
			defaultPermanentFlags,
			defaultAttributes,
		)

		// Force USER ID to be consistent.
		userID := hex.EncodeToString(hash.SHA256([]byte(creds.usernames[0])))

		// Load the user.
		_, err := server.LoadUser(ctx, conn, userID, []byte(creds.password))
		require.NoError(tb, err)

		// Trigger a sync of the user's data.
		require.NoError(tb, conn.Sync(ctx))

		for _, username := range creds.usernames {
			userIDs[username] = userID
		}

		conns[userID] = conn
		dbPaths[userID] = filepath.Join(server.GetDatabasePath(), fmt.Sprintf("%v.db", userID))
	}

	listener, err := net.Listen("tcp", net.JoinHostPort("localhost", "0"))
	require.NoError(tb, err)

	// Start the server.
	require.NoError(tb, server.Serve(ctx, listener))

	// Run the test against the server.
	logging.DoAnnotated(ctx, func(context.Context) {
		tests(newTestSession(tb, listener, server, eventCh, reporter, userIDs, conns, dbPaths, options))
	}, logging.Labels{
		"Action": "Running gluon tests",
	})

	// Flush and remove user before shutdown.
	for userID, conn := range conns {
		conn.Flush()
		require.NoError(tb, server.RemoveUser(ctx, userID, false))
	}

	// Expect the server to shut down successfully when closed.
	require.NoError(tb, server.Close(ctx))
	require.NoError(tb, <-server.GetErrorCh())
	require.NoError(tb, listener.Close())
}

func withConnections(tb testing.TB, s *testSession, connIDs []int, tests func(map[int]*testConnection)) {
	conns := make(map[int]*testConnection)

	for _, connID := range connIDs {
		conns[connID] = s.newConnection()
	}

	tests(conns)

	for _, connection := range conns {
		require.NoError(tb, connection.disconnect())
	}
}

func withClients(tb testing.TB, s *testSession, connIDs []int, tests func(map[int]*client.Client)) {
	clients := make(map[int]*client.Client)

	for _, connID := range connIDs {
		clients[connID] = s.newClient()
	}

	tests(clients)

	for _, client := range clients {
		require.NoError(tb, client.Logout())
	}
}

func withData(s *testSession, username string, tests func(string, imap.MailboxID)) {
	mbox := uuid.NewString()

	mboxID := s.mailboxCreated(username, []string{mbox}, "testdata/dovecot-crlf")

	tests(mbox, mboxID)
}