File: backend.go

package info (click to toggle)
golang-github-henrybear327-go-proton-api 1.0.0-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,088 kB
  • sloc: sh: 55; makefile: 26
file content (618 lines) | stat: -rw-r--r-- 14,190 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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
package backend

import (
	"fmt"
	"net/mail"
	"sync"
	"time"

	"github.com/ProtonMail/gluon/rfc822"
	"github.com/ProtonMail/go-srp"
	"github.com/ProtonMail/gopenpgp/v2/crypto"
	"github.com/bradenaw/juniper/xslices"
	"github.com/google/uuid"
	"github.com/henrybear327/go-proton-api"
	"golang.org/x/exp/maps"
	"golang.org/x/exp/slices"
)

type Backend struct {
	domain string

	accounts map[string]*account
	accLock  sync.RWMutex

	attachments map[string]*attachment
	attLock     sync.Mutex

	attData     map[string][]byte
	attDataLock sync.Mutex

	messages map[string]*message
	msgLock  sync.Mutex

	labels  map[string]*label
	lblLock sync.Mutex

	updates            map[ID]update
	updatesLock        sync.RWMutex
	maxUpdatesPerEvent int

	srp     map[string]*srp.Server
	srpLock sync.Mutex

	authLife    time.Duration
	enableDedup bool
}

func New(authLife time.Duration, domain string, enableDedup bool) *Backend {
	return &Backend{
		domain:             domain,
		accounts:           make(map[string]*account),
		attachments:        make(map[string]*attachment),
		attData:            make(map[string][]byte),
		messages:           make(map[string]*message),
		labels:             make(map[string]*label),
		updates:            make(map[ID]update),
		maxUpdatesPerEvent: 0,
		srp:                make(map[string]*srp.Server),
		authLife:           authLife,
		enableDedup:        enableDedup,
	}
}

func (b *Backend) SetAuthLife(authLife time.Duration) {
	b.authLife = authLife
}

func (b *Backend) SetMaxUpdatesPerEvent(max int) {
	b.maxUpdatesPerEvent = max
}

func (b *Backend) CreateUser(username string, password []byte) (string, error) {
	b.accLock.Lock()
	defer b.accLock.Unlock()

	salt, err := crypto.RandomToken(16)
	if err != nil {
		return "", err
	}

	passphrase, err := hashPassword(password, salt)
	if err != nil {
		return "", err
	}

	srpAuth, err := srp.NewAuthForVerifier(password, modulus, salt)
	if err != nil {
		return "", err
	}

	verifier, err := srpAuth.GenerateVerifier(2048)
	if err != nil {
		return "", err
	}

	armKey, err := GenerateKey(username, username, passphrase, "rsa", 2048)
	if err != nil {
		return "", err
	}

	userID := uuid.NewString()

	b.accounts[userID] = newAccount(userID, username, armKey, salt, verifier)

	return userID, nil
}

func (b *Backend) RemoveUser(userID string) error {
	b.accLock.Lock()
	defer b.accLock.Unlock()

	user, ok := b.accounts[userID]
	if !ok {
		return fmt.Errorf("user %s does not exist", userID)
	}

	for _, labelID := range user.labelIDs {
		delete(b.labels, labelID)
	}

	for _, messageID := range user.messageIDs {
		for _, attID := range b.messages[messageID].attIDs {
			if xslices.CountFunc(maps.Values(b.attachments), func(att *attachment) bool {
				return att.attDataID == b.attachments[attID].attDataID
			}) == 1 {
				delete(b.attData, b.attachments[attID].attDataID)
			}

			delete(b.attachments, attID)
		}

		delete(b.messages, messageID)
	}

	delete(b.accounts, userID)

	return nil
}

func (b *Backend) RefreshUser(userID string, refresh proton.RefreshFlag) error {
	return b.withAcc(userID, func(acc *account) error {
		updateID, err := b.newUpdate(&userRefreshed{refresh: refresh})
		if err != nil {
			return err
		}

		if refresh == proton.RefreshAll {
			acc.updateIDs = []ID{updateID}
		} else {
			acc.updateIDs = append(acc.updateIDs, updateID)
		}

		return nil
	})
}

func (b *Backend) CreateUserKey(userID string, password []byte) error {
	b.accLock.Lock()
	defer b.accLock.Unlock()

	user, ok := b.accounts[userID]
	if !ok {
		return fmt.Errorf("user %s does not exist", userID)
	}

	salt, err := crypto.RandomToken(16)
	if err != nil {
		return err
	}

	passphrase, err := hashPassword(password, salt)
	if err != nil {
		return err
	}

	armKey, err := GenerateKey(user.username, user.username, passphrase, "rsa", 2048)
	if err != nil {
		return err
	}

	user.keys = append(user.keys, key{keyID: uuid.NewString(), key: armKey})

	return nil
}

func (b *Backend) RemoveUserKey(userID, keyID string) error {
	b.accLock.Lock()
	defer b.accLock.Unlock()

	user, ok := b.accounts[userID]
	if !ok {
		return fmt.Errorf("user %s does not exist", userID)
	}

	idx := xslices.IndexFunc(user.keys, func(key key) bool {
		return key.keyID == keyID
	})

	if idx == -1 {
		return fmt.Errorf("key %s does not exist", keyID)
	}

	user.keys = append(user.keys[:idx], user.keys[idx+1:]...)

	return nil
}

func (b *Backend) CreateAddress(userID, email string, password []byte, withKey bool, status proton.AddressStatus, addrType proton.AddressType) (string, error) {
	return b.createAddress(userID, email, password, withKey, status, addrType, false)
}

func (b *Backend) CreateAddressAsUpdate(userID, email string, password []byte, withKey bool, status proton.AddressStatus, addrType proton.AddressType) (string, error) {
	return b.createAddress(userID, email, password, withKey, status, addrType, true)
}

func (b *Backend) createAddress(userID, email string, password []byte, withKey bool, status proton.AddressStatus, addrType proton.AddressType, issueUpdateInsteadOfCreate bool) (string, error) {
	return withAcc(b, userID, func(acc *account) (string, error) {
		var keys []key

		if withKey {
			token, err := crypto.RandomToken(32)
			if err != nil {
				return "", err
			}

			armKey, err := GenerateKey(acc.username, email, token, "rsa", 2048)
			if err != nil {
				return "", err
			}

			passphrase, err := hashPassword([]byte(password), acc.salt)
			if err != nil {
				return "", err
			}

			userKR, err := acc.keys[0].unlock(passphrase)
			if err != nil {
				return "", err
			}

			encToken, sigToken, err := encryptWithSignature(userKR, token)
			if err != nil {
				return "", err
			}

			keys = append(keys, key{
				keyID: uuid.NewString(),
				key:   armKey,
				tok:   encToken,
				sig:   sigToken,
			})
		}

		addressID := uuid.NewString()

		acc.addresses[addressID] = &address{
			addrID:   addressID,
			email:    email,
			order:    len(acc.addresses) + 1,
			status:   status,
			addrType: addrType,
			keys:     keys,
		}

		var update update
		if issueUpdateInsteadOfCreate {
			update = &addressUpdated{addressID: addressID}
		} else {
			update = &addressCreated{addressID: addressID}
		}

		updateID, err := b.newUpdate(update)
		if err != nil {
			return "", err
		}

		acc.updateIDs = append(acc.updateIDs, updateID)

		return addressID, nil
	})
}

func (b *Backend) ChangeAddressType(userID, addrId string, addrType proton.AddressType) error {
	return b.withAcc(userID, func(acc *account) error {
		for _, addr := range acc.addresses {
			if addr.addrID == addrId {
				addr.addrType = addrType
				return nil
			}
		}
		return fmt.Errorf("no addrID matching %s for user %s", addrId, userID)
	})
}

func (b *Backend) CreateAddressKey(userID, addrID string, password []byte) error {
	return b.withAcc(userID, func(acc *account) error {
		token, err := crypto.RandomToken(32)
		if err != nil {
			return err
		}

		armKey, err := GenerateKey(acc.username, acc.addresses[addrID].email, token, "rsa", 2048)
		if err != nil {
			return err
		}

		passphrase, err := hashPassword([]byte(password), acc.salt)
		if err != nil {
			return err
		}

		userKR, err := acc.keys[0].unlock(passphrase)
		if err != nil {
			return err
		}

		encToken, sigToken, err := encryptWithSignature(userKR, token)
		if err != nil {
			return err
		}

		acc.addresses[addrID].keys = append(acc.addresses[addrID].keys, key{
			keyID: uuid.NewString(),
			key:   armKey,
			tok:   encToken,
			sig:   sigToken,
		})

		updateID, err := b.newUpdate(&addressUpdated{addressID: addrID})
		if err != nil {
			return err
		}

		acc.updateIDs = append(acc.updateIDs, updateID)

		return nil
	})
}

func (b *Backend) RemoveAddress(userID, addrID string) error {
	return b.withAcc(userID, func(acc *account) error {
		if _, ok := acc.addresses[addrID]; !ok {
			return fmt.Errorf("address %s not found", addrID)
		}

		delete(acc.addresses, addrID)

		updateID, err := b.newUpdate(&addressDeleted{addressID: addrID})
		if err != nil {
			return err
		}

		acc.updateIDs = append(acc.updateIDs, updateID)

		return nil
	})
}

func (b *Backend) RemoveAddressKey(userID, addrID, keyID string) error {
	return b.withAcc(userID, func(acc *account) error {
		idx := xslices.IndexFunc(acc.addresses[addrID].keys, func(key key) bool {
			return key.keyID == keyID
		})

		if idx < 0 {
			return fmt.Errorf("key %s not found", keyID)
		}

		acc.addresses[addrID].keys = append(acc.addresses[addrID].keys[:idx], acc.addresses[addrID].keys[idx+1:]...)

		updateID, err := b.newUpdate(&addressUpdated{addressID: addrID})
		if err != nil {
			return err
		}

		acc.updateIDs = append(acc.updateIDs, updateID)

		return nil
	})
}

// TODO: Implement this when we support subscriptions in the test server.
func (b *Backend) CreateSubscription(userID, planID string) error {
	return nil
}

func (b *Backend) CreateMessage(
	userID, addrID string,
	subject string,
	sender *mail.Address,
	toList, ccList, bccList, replytos []*mail.Address,
	armBody string,
	mimeType rfc822.MIMEType,
	flags proton.MessageFlag,
	date time.Time,
	unread, starred bool,
) (string, error) {
	return withAcc(b, userID, func(acc *account) (string, error) {
		return withMessages(b, func(messages map[string]*message) (string, error) {
			msg := newMessage(addrID, subject, sender, toList, ccList, bccList, replytos, armBody, mimeType, "", date)

			msg.flags |= flags
			msg.unread = unread
			msg.starred = starred

			addrListEqual := func(l1 []*mail.Address, l2 []*mail.Address) bool {
				s1 := xslices.Map(l1, func(addr *mail.Address) string {
					return addr.Address
				})
				s2 := xslices.Map(l2, func(addr *mail.Address) string {
					return addr.Address
				})

				return slices.Equal(s1, s2)
			}

			var foundDuplicate bool

			if b.enableDedup {
				for _, m := range messages {
					if m.addrID != msg.addrID {
						continue
					}

					toEqual := addrListEqual(m.toList, msg.toList)
					bccEqual := addrListEqual(m.bccList, msg.bccList)
					ccEqual := addrListEqual(m.ccList, msg.ccList)

					if m.sender.Address == msg.sender.Address &&
						toEqual &&
						bccEqual &&
						ccEqual &&
						m.subject == msg.subject {
						msg.messageID = m.messageID
						foundDuplicate = true
						break
					}
				}
			}

			if !foundDuplicate {
				messages[msg.messageID] = msg

				updateID, err := b.newUpdate(&messageCreated{messageID: msg.messageID})
				if err != nil {
					return "", err
				}

				acc.messageIDs = append(acc.messageIDs, msg.messageID)
				acc.updateIDs = append(acc.updateIDs, updateID)
			}

			return msg.messageID, nil
		})
	})
}

func (b *Backend) Encrypt(userID, addrID, decBody string) (string, error) {
	return withAcc(b, userID, func(acc *account) (string, error) {
		pubKey, err := acc.addresses[addrID].keys[0].getPubKey()
		if err != nil {
			return "", err
		}

		kr, err := crypto.NewKeyRing(pubKey)
		if err != nil {
			return "", err
		}

		enc, err := kr.Encrypt(crypto.NewPlainMessageFromString(decBody), nil)
		if err != nil {
			return "", err
		}

		return enc.GetArmored()
	})
}

func (b *Backend) withAcc(userID string, fn func(acc *account) error) error {
	b.accLock.RLock()
	defer b.accLock.RUnlock()

	acc, ok := b.accounts[userID]
	if !ok {
		return fmt.Errorf("account %s not found", userID)
	}

	return fn(acc)
}

func (b *Backend) withAccEmail(email string, fn func(acc *account) error) error {
	b.accLock.RLock()
	defer b.accLock.RUnlock()

	for _, acc := range b.accounts {
		for _, addr := range acc.addresses {
			if addr.email == email {
				return fn(acc)
			}
		}
	}

	return fmt.Errorf("account %s not found", email)
}

func withAcc[T any](b *Backend, userID string, fn func(acc *account) (T, error)) (T, error) {
	b.accLock.RLock()
	defer b.accLock.RUnlock()

	for _, acc := range b.accounts {
		if acc.userID == userID {
			return fn(acc)
		}
	}

	return *new(T), fmt.Errorf("account not found")
}

func withAccName[T any](b *Backend, username string, fn func(acc *account) (T, error)) (T, error) {
	b.accLock.RLock()
	defer b.accLock.RUnlock()

	for _, acc := range b.accounts {
		if acc.username == username {
			return fn(acc)
		}
	}

	return *new(T), fmt.Errorf("account not found")
}

func withAccEmail[T any](b *Backend, email string, fn func(acc *account) (T, error)) (T, error) {
	b.accLock.RLock()
	defer b.accLock.RUnlock()

	for _, acc := range b.accounts {
		if _, ok := acc.getAddr(email); ok {
			return fn(acc)
		}
	}

	return *new(T), fmt.Errorf("account not found")
}

func withAccAuth[T any](b *Backend, authUID, authAcc string, fn func(acc *account) (T, error)) (T, error) {
	b.accLock.Lock()
	defer b.accLock.Unlock()

	for _, acc := range b.accounts {
		acc.authLock.Lock()
		defer acc.authLock.Unlock()

		val, ok := acc.auth[authUID]
		if !ok {
			continue
		}

		if time.Since(val.creation) > b.authLife {
			acc.auth[authUID] = auth{ref: val.ref, creation: val.creation}
		} else if val.acc == authAcc {
			return fn(acc)
		}
	}

	return *new(T), fmt.Errorf("account not found")
}

func (b *Backend) withMessages(fn func(map[string]*message) error) error {
	b.msgLock.Lock()
	defer b.msgLock.Unlock()

	return fn(b.messages)
}

func withMessages[T any](b *Backend, fn func(map[string]*message) (T, error)) (T, error) {
	b.msgLock.Lock()
	defer b.msgLock.Unlock()

	return fn(b.messages)
}

func withAtts[T any](b *Backend, fn func(map[string]*attachment) (T, error)) (T, error) {
	b.attLock.Lock()
	defer b.attLock.Unlock()

	return fn(b.attachments)
}

func (b *Backend) withLabels(fn func(map[string]*label) error) error {
	b.lblLock.Lock()
	defer b.lblLock.Unlock()

	return fn(b.labels)
}

func withLabels[T any](b *Backend, fn func(map[string]*label) (T, error)) (T, error) {
	b.lblLock.Lock()
	defer b.lblLock.Unlock()

	return fn(b.labels)
}

func (b *Backend) newUpdate(event update) (ID, error) {
	return withUpdates(b, func(updates map[ID]update) (ID, error) {
		updateID := ID(len(updates))

		updates[updateID] = event

		return updateID, nil
	})
}

func withUpdates[T any](b *Backend, fn func(map[ID]update) (T, error)) (T, error) {
	b.updatesLock.Lock()
	defer b.updatesLock.Unlock()

	return fn(b.updates)
}