~bfiedler/go-threema

ref: e1e2805e7fd6220db28ac9665b3c4c63f608f754 go-threema/client/client.go -rw-r--r-- 14.8 KiB
e1e2805e — Ben Fiedler Note that clients are safe for concurrent use 1 year, 8 months ago
                                                                                
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
619
620
621
622
623
624
625
626
627
628
// This package provides a client for sending messages via Threema.Gateway.
package client

import (
	"bytes"
	"encoding/hex"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"net/url"
	"regexp"
	"strconv"
	"strings"
	"sync"
	"time"
)

type (
	ThreemaID = string

	PublicKey  = [32]byte
	PrivateKey = [32]byte
	SharedKey  = [32]byte
	Nonce      = [24]byte
	BlobID     = [16]byte
	MessageID  = [8]byte
)

const (
	DefaultThreemaGatewayURL = "https://msgapi.threema.ch"
	MaxTextMessageBytes      = 3500

	maxCacheEntryAge    = 24 * time.Hour
	maxImageSizeInBytes = 10 * 1000 * 1000
	maxBlobSizeInBytes  = 100 * 1000 * 1000
)

var (
	// Caller errors
	ErrInvalidPhoneNumber = errors.New("invalid phone number, must consist of at most 15 digits")
	ErrIDLength           = errors.New("id must be exactly 8 bytes long")

	ErrImageTooLarge = errors.New("image too large")

	// API errors
	ErrInvalidRequest = errors.New("invalid recipient or identity not set up for chosen mode (simple/e2e)")
	ErrMissingBlob    = errors.New("missing parameters or blob is empty")
	ErrCredentials    = errors.New("wrong id or secret for API")
	ErrOutOfCredits   = errors.New("out of credits")
	ErrNotFound       = errors.New("id not found")
	ErrMessageTooLong = errors.New("message too long")
	ErrBlobTooLarge   = errors.New("blob too large")
	ErrTemporary      = errors.New("temporary API failure")
	ErrUnknown        = errors.New("unknown API error")

	phoneNumberInverted = regexp.MustCompile("[^0-9]+")
)

type Client interface {
	ID() string

	// Fetches the remaining credits for the ID associated with the Client.
	GetRemainingCredits() (int, error)

	LookupIDByPhoneHash(phoneNumber string) (ThreemaID, error)
	LookupIDByEmailHash(address string) (ThreemaID, error)

	SendTextMessage(id ThreemaID, apiSecret string) error
	SendTextMessageToPhone(phone string, apiSecret string) error
	SendTextMessageToEmail(address string, apiSecret string) error
}

// Contains functionality used by both clients
type client struct {
	gatewayUrl string

	id        ThreemaID
	apiSecret string

	httpClient *http.Client

	emailHasher *hasher
	phoneHasher *hasher
}

// A simple client has no private key. It can only send text messages, which
// are encrypted using a key held by Threema.
//
// It is safe for concurrent use by multiple goroutines.
type SimpleClient struct {
	client
}

// An E2EClient has a private key to sign and encrypt messages with.
//
// It automatically caches ID->PubKey lookups as adivsed in the Threema.Gateway
// documentation.
//
// It is safe for concurrent use by multiple goroutines.
type E2EClient struct {
	client

	encrypter

	cacheMu        *sync.RWMutex
	publicKeyCache map[ThreemaID]cacheEntry
}

type cacheEntry struct {
	pubKey      PublicKey
	lastUpdated time.Time
}

func newClient(id ThreemaID, apiSecret string) (*client, error) {
	if len(id) != 8 {
		return nil, ErrIDLength
	}

	return &client{
		gatewayUrl: DefaultThreemaGatewayURL,

		id:        id,
		apiSecret: apiSecret,

		httpClient: http.DefaultClient,

		emailHasher: newEmailHasher(),
		phoneHasher: newPhoneHasher(),
	}, nil
}

func NewSimpleClient(id ThreemaID, apiSecret string) (*SimpleClient, error) {
	c, err := newClient(id, apiSecret)

	return &SimpleClient{
		client: *c,
	}, err
}

func NewE2EClient(id ThreemaID, apiSecret string, privateKey PrivateKey) (*E2EClient, error) {
	c, err := newClient(id, apiSecret)

	return &E2EClient{
		client:    *c,
		encrypter: encrypter{privateKey},

		cacheMu:        &sync.RWMutex{},
		publicKeyCache: make(map[ThreemaID]cacheEntry),
	}, err
}

// Returns the client's ID
func (c *client) ID() string {
	return c.id
}

// Returns the client's hex-encoded public key.
func (c *E2EClient) PublicKey() PublicKey {
	return computePublicKey(c.privateKey)
}

// Set the base URL for the Threema.Gateway server
func (c *client) SetGatewayURL(url string) {
	c.gatewayUrl = url
}

// Set the http.Client to be used
func (c *client) SetHTTPClient(httpClient *http.Client) {
	c.httpClient = httpClient
}

func (c *client) GetRemainingCredits() (int, error) {
	path := "/credits" + c.defaultQuery()
	resp, err := c.httpClient.Get(c.gatewayUrl + path)
	if err != nil {
		return 0, err
	}
	defer resp.Body.Close()

	switch resp.StatusCode {
	case http.StatusOK: // 200
		// intentionally left blank
	case http.StatusUnauthorized: // 401
		return 0, ErrCredentials
	case http.StatusInternalServerError: // 500
		return 0, ErrTemporary
	default:
		return 0, ErrUnknown
	}

	credits, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return 0, err
	}

	return strconv.Atoi(string(credits))
}

// Looks up the Threema ID of the given phone number by hash.
// Phone number must be passed in E.164 format.
// It will be normalized and hashed as neceassary
//
// Returns ErrNotFound if the given phone number is unknown.
func (c *client) LookupIDByPhoneHash(phoneNumber string) (ThreemaID, error) {
	phoneNumber, valid := normalizePhoneNumber(phoneNumber)
	if !valid {
		return "", ErrInvalidPhoneNumber
	}

	hash, err := c.phoneHasher.hash(phoneNumber)
	if err != nil {
		return "", err
	}

	path := fmt.Sprintf("/lookup/phone_hash/%s", hex.EncodeToString(hash)) + c.defaultQuery()
	resp, err := c.httpClient.Get(c.gatewayUrl + path)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	err = decodeLookupResponse(resp)
	if err != nil {
		return "", err
	}

	id, err := ioutil.ReadAll(resp.Body)
	return string(id), err
}

// Looks up the Threema ID of the given e-mail address by its hash. The e-mail
// must be passed in plaintext, it will be normalized and hashed as necessary.
//
// Returns ErrNotFound if the given address is unknown.
func (c *client) LookupIDByEmailHash(address string) (ThreemaID, error) {
	hash, err := c.emailHasher.hash(address)
	if err != nil {
		return "", err
	}

	path := fmt.Sprintf("/lookup/email_hash/%s", hex.EncodeToString(hash)) + c.defaultQuery()
	resp, err := c.httpClient.Get(c.gatewayUrl + path)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	err = decodeLookupResponse(resp)
	if err != nil {
		return "", err
	}

	id, err := ioutil.ReadAll(resp.Body)
	return string(id), err
}

// Looks up the public key associated with the corresponding ID.
//
// Updates the client's cache on successful lookup.
func (c *E2EClient) LookupPublicKeyByID(requestedID ThreemaID) (PublicKey, error) {
	var pubKey PublicKey

	if len(requestedID) != 8 {
		return pubKey, ErrIDLength
	}

	c.cacheMu.RLock()
	entry, ok := c.publicKeyCache[requestedID]
	c.cacheMu.RUnlock()
	if ok && time.Now().Sub(entry.lastUpdated) <= maxCacheEntryAge {
		return entry.pubKey, nil
	}

	path := fmt.Sprintf("/pubkeys/%s", url.QueryEscape(requestedID)) + c.defaultQuery()
	resp, err := c.httpClient.Get(c.gatewayUrl + path)
	if err != nil {
		return pubKey, err
	}
	defer resp.Body.Close()

	err = decodeLookupResponse(resp)
	if err != nil {
		return pubKey, err
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return pubKey, err
	}

	_, err = hex.Decode(pubKey[:], body)
	if err != nil {
		return pubKey, err
	}

	c.cacheMu.Lock()
	c.publicKeyCache[requestedID] = cacheEntry{pubKey, time.Now()}
	c.cacheMu.Unlock()

	return pubKey, nil
}

// Returns the capabilities of the given ID. As of 01/2021, there are
// five supported capabilities:
//   * text
//   * image
//   * video
//   * audio
//   * file
func (c *client) GetCapabilities(id ThreemaID) ([]string, error) {
	if len(id) != 8 {
		return nil, ErrIDLength
	}

	path := fmt.Sprintf("/capabilities/%s", url.QueryEscape(id)) + c.defaultQuery()
	resp, err := c.httpClient.Get(c.gatewayUrl + path)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	err = decodeLookupResponse(resp)
	if err != nil {
		return nil, err
	}

	body, err := ioutil.ReadAll(resp.Body)
	return strings.Split(string(body), ","), err
}

// Send a message to the given Threema ID.
//
// The message is sent in plaintext and encrypted at the Threema servers.
func (c *SimpleClient) SendTextMessage(to ThreemaID, msg string) error {
	if len(to) != 8 {
		return ErrIDLength
	}

	form := url.Values{}
	form.Add("from", c.id)
	form.Add("to", to)
	form.Add("text", msg)
	form.Add("secret", c.apiSecret)

	resp, err := c.httpClient.PostForm(c.gatewayUrl+"/send_simple", form)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	return decodeSendResponse(resp)
}

// Send a message to the given phone number, passed in E.164 format.
//
// The message is sent in plaintext and encrypted at the Threema servers.
func (c *SimpleClient) SendTextMessageToPhone(phone string, msg string) error {
	phone, valid := normalizePhoneNumber(phone)
	if !valid {
		return ErrInvalidPhoneNumber
	}

	form := url.Values{}
	form.Add("from", c.id)
	form.Add("phone", phone)
	form.Add("text", msg)
	form.Add("secret", c.apiSecret)

	resp, err := c.httpClient.PostForm(c.gatewayUrl+"/send_simple", form)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	return decodeSendResponse(resp)
}

// Send a message to account associated with the given email address.
//
// The message is sent in plaintext and encrypted at the Threema servers.
func (c *SimpleClient) SendTextMessageToEmail(address string, msg string) error {
	form := url.Values{}
	form.Add("from", c.id)
	form.Add("email", address)
	form.Add("text", msg)
	form.Add("secret", c.apiSecret)

	resp, err := c.httpClient.PostForm(c.gatewayUrl+"/send_simple", form)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	return decodeSendResponse(resp)
}

// Send a text message to the given Threema ID.
//
// The public key of the recipient is cached for up to `maxCacheEntryAge`, so
// multiple invocations of SendTextMessage re-use existing public keys.
//
// The message is encrypted before sending.
func (c *E2EClient) SendTextMessage(to ThreemaID, msg string) error {
	return c.sendMessage(to, &TextMessage{msg})
}

// Send a text message to the account associated with the given phone number, passed
// in E.164 format.
//
// Phone->ID translations are not cached, so specifying recipients by Threema
// ID is preferred.
//
// The message is encrypted before sending.
func (c *E2EClient) SendTextMessageToPhone(phone string, msg string) error {
	id, err := c.LookupIDByPhoneHash(phone)
	if err != nil {
		return err
	}

	return c.SendTextMessage(id, msg)
}

// Send a text message to account associated with the given email address.
//
// E-Mail->ID translations are not cached, so specifying recipients by Threema
// ID is preferred.
//
// The message is encrypted before sending.
func (c *E2EClient) SendTextMessageToEmail(address string, msg string) error {
	id, err := c.LookupIDByEmailHash(address)
	if err != nil {
		return err
	}

	return c.SendTextMessage(id, msg)
}

// Send an image to the given Threema ID.
//
// Costs 2 credits (1 to upload image, 1 to send message)
//
// Allowed file types (list not exhaustive)
//   * JPEG
//   * PNG
func (c *E2EClient) SendImage(to ThreemaID, image io.Reader) error {
	r := io.LimitReader(image, maxImageSizeInBytes)
	data, err := ioutil.ReadAll(r)
	if err != nil {
		return err
	}
	if len(data) == maxImageSizeInBytes {
		return ErrImageTooLarge
	}

	pubKey, err := c.LookupPublicKeyByID(to)
	if err != nil {
		return err
	}

	encryptedData, nonce, err := c.encryptBytes(pubKey, data)
	if err != nil {
		return err
	}

	blobID, err := c.uploadBlob(encryptedData)
	if err != nil {
		return err
	}

	msg := &ImageMessage{
		BlobID: *blobID,
		Size:   uint32(len(data)),
		Nonce:  nonce,
	}
	return c.sendMessage(to, msg)
}

// Send a message to the given Threema ID.
//
// The public key of the recipient is cached for up to `maxCacheEntryAge`, so
// multiple invocations of SendTextMessage re-use existing public keys.
//
// The message is encrypted before sending.
func (c *E2EClient) sendMessage(to ThreemaID, msg Message) error {
	if len(to) != 8 {
		return ErrIDLength
	}

	pubKey, err := c.LookupPublicKeyByID(to)
	if err != nil {
		return err
	}

	box, nonce, err := c.encryptMessage(pubKey, msg)
	if err != nil {
		return err
	}

	form := url.Values{}
	form.Add("from", c.id)
	form.Add("to", to)
	form.Add("nonce", hex.EncodeToString(nonce[:]))
	form.Add("box", hex.EncodeToString(box))
	form.Add("secret", c.apiSecret)

	resp, err := c.httpClient.PostForm(c.gatewayUrl+"/send_e2e", form)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	return decodeSendResponse(resp)
}

// Uploades a blob (<= 50MB) to the Threema servers
//
// Costs one credit.
func (c *E2EClient) uploadBlob(blob []byte) (*BlobID, error) {
	if len(blob) >= maxBlobSizeInBytes {
		return nil, ErrBlobTooLarge
	}

	var b bytes.Buffer
	w := multipart.NewWriter(&b)
	fw, err := w.CreateFormField("blob")
	if err != nil {
		return nil, err
	}

	_, err = fw.Write(blob)
	if err != nil {
		return nil, err
	}

	err = w.Close()
	if err != nil {
		return nil, err
	}

	path := "/upload_blob" + c.defaultQuery()
	req, err := http.NewRequest(http.MethodPost, c.gatewayUrl+path, &b)
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", w.FormDataContentType())

	resp, err := c.httpClient.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	switch resp.StatusCode {
	case http.StatusOK: // 200
		// intentionally left blank
	case http.StatusBadRequest: // 400
		return nil, ErrMissingBlob
	case http.StatusUnauthorized: // 401
		return nil, ErrCredentials
	case http.StatusPaymentRequired: // 402
		return nil, ErrOutOfCredits
	case http.StatusRequestEntityTooLarge: // 413
		return nil, ErrBlobTooLarge
	case http.StatusInternalServerError: // 500
		return nil, ErrTemporary
	default:
		return nil, ErrUnknown
	}

	hexBlobID, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	return decodeBlobID(string(hexBlobID))
}

func (c *client) defaultQuery() string {
	q := url.Values{}
	q.Add("from", c.id)
	q.Add("secret", c.apiSecret)
	return "?" + q.Encode()
}

func decodeLookupResponse(resp *http.Response) error {
	switch resp.StatusCode {
	case http.StatusOK: // 200
		return nil
	case http.StatusUnauthorized: // 401
		return ErrCredentials
	case http.StatusNotFound: // 404
		return ErrNotFound
	case http.StatusInternalServerError: // 500
		return ErrTemporary
	default:
		return ErrUnknown
	}
}

func decodeSendResponse(resp *http.Response) error {
	switch resp.StatusCode {
	case http.StatusOK: // 200
		return nil
	case http.StatusBadRequest: // 400
		return ErrInvalidRequest
	case http.StatusUnauthorized: // 401
		return ErrCredentials
	case http.StatusPaymentRequired: // 402
		return ErrOutOfCredits
	case http.StatusRequestEntityTooLarge: // 413
		return ErrMessageTooLong
	case http.StatusInternalServerError: // 500
		return ErrTemporary
	default:
		return ErrUnknown
	}
}

// Normalized the phone number by stripping all non-numeric characters and
// checking whether the resulting number is at most 15 digits long, as
// specified by ITU-T Recommendation E.164: https://en.wikipedia.org/wiki/E.164
func normalizePhoneNumber(phoneNumber string) (string, bool) {
	normalized := phoneNumberInverted.ReplaceAllString(phoneNumber, "")
	return normalized, len(normalized) > 0 && len(normalized) <= 15
}