-
Notifications
You must be signed in to change notification settings - Fork 13
/
test_.py
1967 lines (1669 loc) · 90.9 KB
/
test_.py
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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from email.utils import getaddresses, parseaddr
import logging
import re
import sys
from base64 import b64encode
from contextlib import redirect_stdout
from email.message import EmailMessage
from io import StringIO
from os import environ
from pathlib import Path
from subprocess import PIPE, STDOUT, Popen
from tempfile import TemporaryDirectory
from typing import Tuple, Union
from unittest import main, TestCase, mock
from envelope import Envelope
from envelope.address import Address
from envelope.constants import AUTO, PLAIN, HTML
from envelope.parser import Parser
from envelope.smtp_handler import SMTPHandler
from envelope.utils import assure_list, assure_fetched, get_mimetype
logging.basicConfig(stream=sys.stderr, level=logging.WARNING)
GPG_PASSPHRASE = "test"
IDENTITY_1_GPG_FINGERPRINT = "F14F2E8097E0CCDE93C4E871F4A4F26779FA03BB"
IDENTITY_1 = "[email protected]"
IDENTITY_2 = "[email protected]"
IDENTITY_3 = "[email protected]"
GNUPG_HOME = "tests/gpg_ring/"
PGP_MESSAGE = "-----BEGIN PGP MESSAGE-----"
MESSAGE = "dumb message"
environ["GNUPGHOME"] = GNUPG_HOME
class TestAbstract(TestCase):
utf_header = Path("tests/eml/utf-header.eml") # the file has encoded headers
charset = Path("tests/eml/charset.eml") # the file has encoded headers
internationalized = Path("tests/eml/internationalized.eml")
quopri = Path("tests/eml/quopri.eml") # the file has CRLF separators
eml = Path("tests/eml/mail.eml")
text_attachment = "tests/eml/generic.txt"
image_file = Path("tests/eml/image.gif")
group_recipient = Path("tests/eml/group-recipient.eml")
invalid_characters = Path("tests/eml/invalid-characters.eml")
invalid_headers = Path("tests/eml/invalid-headers.eml")
def check_lines(self, o, lines: Union[str, Tuple[str, ...]] = (), longer: Union[int, Tuple[int, int]] = None,
debug=False, not_in: Union[str, Tuple[str, ...]] = (), raises=(), result=None):
""" Converts Envelope objects to str and asserts that lines are present.
:type lines: Assert in. These line/s must be found in the given order.
:type not_in: Assert not in.
:type longer: If int → result must be longer than int. If tuple → result line count must be within tuple range.
"""
if type(lines) is str:
lines = lines,
if type(not_in) is str:
not_in = not_in,
if raises:
self.assertRaises(raises, str, o)
output = None
else:
output = str(o).splitlines()
# any line is not longer than 1000 characters
self.assertFalse(any(line for line in output if len(line) > 999))
if debug:
print(o)
output_tmp = output
last_search = ""
for search in lines:
try:
index = output_tmp.index(search)
except ValueError:
message = f"is in the wrong order (above the line '{last_search}' )" if search in output else "not found"
self.fail(f"Line '{search}' {message} in the output:\n{o}")
output_tmp = output_tmp[index + 1:]
last_search = search
for search in not_in:
self.assertNotIn(search, output)
# result state
if result is not None:
self.assertIs(bool(o), result)
# result line count range
if type(longer) is tuple:
longer, shorter = longer
self.assertLess(len(output), shorter)
if longer:
self.assertGreater(len(output), longer)
cmd = "python3", "-m", "envelope"
def bash(self, *cmd, file: Path = None, piped=None, envelope=True, env=None, debug=False, decode=True):
"""
:param cmd: Any number of commands.
:param file: File piped to the program.
:param piped: Content piped to the program.
:param envelope: Prepend envelope module call before commands.
:param env: dict Modify environment variables.
:param debug: Print debug info.
:param decode: Decode the output by default.
:return:
"""
if envelope:
cmd = self.cmd + cmd
if not file and not piped:
file = self.eml
if debug:
print("Cmd:")
r = [f"{' '.join(cmd)}"]
if file:
r.append(f" < {file}")
elif piped:
r = [f'echo "{piped}" |'] + r
print(" ".join(r))
if env:
env = {**environ.copy(), **env}
p = Popen(cmd, stdout=PIPE, stdin=PIPE, stderr=STDOUT, env=env)
r = p.communicate(input=file.read_bytes() if file else piped.encode("utf-8"))[0]
if decode:
return r.decode().rstrip()
else:
return r
def assertSubset(self, dict_, subset):
""" assertDictContainsSubset alternative """
self.assertEqual(dict_, {**dict_, **subset}) # XX make (dict_, dict_ | subset) as of Python3.9
class TestInternal(TestCase):
def test_assure_list(self):
t = ["one", "two"]
self.assertEqual([], assure_list(None))
self.assertEqual(["test"], assure_list("test"))
self.assertEqual([5], assure_list(5))
self.assertEqual([False], assure_list(False))
self.assertEqual([b"test"], assure_list(b"test"))
self.assertEqual([0, 1, 2], assure_list(x for x in range(3)))
self.assertEqual([0, 1, 2], assure_list([x for x in range(3)]))
self.assertCountEqual([0, 1, 2], assure_list({x for x in range(3)}))
self.assertEqual([0, 1, 2], assure_list({x: "nothing" for x in range(3)}))
self.assertEqual([0, 1, 2], assure_list({x: "nothing" for x in range(3)}.keys()))
self.assertEqual(t, assure_list(tuple(t)))
self.assertCountEqual(t, assure_list(frozenset(t)))
def test_assure_fetched(self):
self.assertEqual(b"test", assure_fetched("test", bytes))
self.assertEqual("test", assure_fetched("test", str))
self.assertEqual(False, assure_fetched(False, str))
self.assertEqual(None, assure_fetched(None, str))
self.assertEqual(b"test", assure_fetched(b"test", bytes))
self.assertEqual("test", assure_fetched(b"test", str))
self.assertEqual("test", assure_fetched(b"test", str))
self.assertEqual("test", assure_fetched(StringIO("test"), str))
self.assertEqual(b"test", assure_fetched(StringIO("test"), bytes))
class TestEnvelope(TestAbstract):
def test_message_generating(self):
self.check_lines(Envelope(MESSAGE)
.subject("my subject")
.send(False),
("Subject: my subject",
MESSAGE,), 10)
def test_1000_split(self):
self.check_lines(Envelope().message("short text").subject("my subject").send(False),
('Content-Type: text/plain; charset="utf-8"',
'Content-Transfer-Encoding: 7bit',
"Subject: my subject",
"short text"), 10)
# this should be no more 7bit but base64 (or quoted-printable which is however not guaranteed)
e = Envelope().message("Longer than thousand chars. " * 1000).subject("my subject").send(False)
self.check_lines(e,
('Content-Type: text/plain; charset="utf-8"',
"Content-Transfer-Encoding: base64",
"Subject: my subject",), 100,
not_in=('Content-Transfer-Encoding: 7bit',)
)
self.assertFalse(any(line for line in str(e).splitlines() if len(line) > 999))
def test_1000_split_html(self):
# the same is valid for HTML alternative too
e = (Envelope()
.message("short text")
.message("<b>html</b>", alternative="html")
.subject("my subject"))
# 7bit both plain and html
self.check_lines(e.send(False),
("Subject: my subject",
'Content-Type: text/plain; charset="utf-8"',
'Content-Transfer-Encoding: 7bit',
"short text",
'Content-Type: text/html; charset="utf-8"',
'Content-Transfer-Encoding: 7bit',
"<b>html</b>"), 10)
# 7bit html, base64 plain
self.check_lines(e.copy().message("Longer than thousand chars. " * 1000).send(False),
("Subject: my subject",
'Content-Type: text/plain; charset="utf-8"',
"Content-Transfer-Encoding: base64",
'Content-Type: text/html; charset="utf-8"',
'Content-Transfer-Encoding: 7bit',
"<b>html</b>"
), 100,
not_in=('short text')
)
# 7bit plain, base64 html
self.check_lines(e.copy().message("Longer than thousand chars. " * 1000, alternative="html").send(False),
("Subject: my subject",
'Content-Type: text/plain; charset="utf-8"',
'Content-Transfer-Encoding: 7bit',
'short text',
'Content-Type: text/html; charset="utf-8"',
"Content-Transfer-Encoding: base64",
), 100,
not_in="<b>html</b>"
)
# base64 both plain and html
self.check_lines(e.copy().message("Longer than thousand chars. " * 1000, alternative="html")
.message("Longer than thousand chars. " * 1000).send(False),
("Subject: my subject",
'Content-Type: text/plain; charset="utf-8"',
"Content-Transfer-Encoding: base64",
'Content-Type: text/html; charset="utf-8"',
"Content-Transfer-Encoding: base64",
), 100,
not_in=('Content-Transfer-Encoding: 7bit',
'short text',
"<b>html</b>")
)
def test_missing_message(self):
self.assertEqual(Envelope().to("hello").preview(), "")
def test_contents_fetching(self):
t = "Small sample text attachment.\n"
with open("tests/eml/generic.txt") as f:
e1 = Envelope(f)
e2 = e1.copy() # stays intact even if copied to another instance
self.assertEqual(e1.message(), t)
self.assertEqual(e2.message(), t)
self.assertEqual(e2.copy().message(), t)
def test_preview(self):
self.check_lines(Envelope(Path("tests/eml/generic.txt")).preview(),
('Content-Type: text/plain; charset="utf-8"',
"Subject: ",
"Small sample text attachment."))
def test_equality(self):
source = {"message": "message", "subject": "hello"}
e1 = Envelope(**source).date(False)
e2 = Envelope(**source).date(False)
self.assertEqual(e1, e2)
self.assertEqual(str(e1), e2)
self.assertEqual(bytes(e1), e2)
s = 'Content-Type: text/plain; charset="utf-8"\nContent-Transfer-Encoding: 7bit' \
'\nMIME-Version: 1.0\nSubject: hello\n\nmessage\n'
b = bytes(s, "utf-8")
self.assertEqual(s, e1)
self.assertEqual(s, str(e1))
self.assertEqual(b, e1)
self.assertEqual(b, bytes(e1))
def test_bcc_ignored(self):
e = Envelope(**{"message": "message", "subject": "hello", "cc": "[email protected]",
"bcc": "[email protected]"})
self.assertIn("[email protected]", e.recipients())
self.check_lines(e, ('Cc: [email protected]',), not_in=('Bcc: [email protected]',))
def test_internal_cache(self):
e = Envelope("message").date(False) # Date might interfere with the Envelope objects equality
e.header("header1", "1")
# create cache under the hood
self.assertFalse(e._result)
# noinspection PyStatementEffect
e.as_message()["header1"]
self.assertTrue(e._result)
# as soon as object changed, cache regenerated
e.header("header2", "1")
e2 = Envelope("message").header("header1", "1").header("header2", "1").date(False)
self.assertEqual("1", e.as_message()["header2"])
self.assertEqual(e2, e)
self.check_lines(e, "header2: 1")
def test_wrong_charset_message(self):
msg = "WARNING:envelope.message:Cannot decode the message correctly, plain alternative bytes are not in Unicode."
b = "ř".encode("cp1250")
e = Envelope(b)
self.check_lines(e, raises=ValueError)
with self.assertLogs('envelope', level='WARNING') as cm:
repr(e)
self.assertEqual(cm.output, [msg])
e.header("Content-Type", "text/plain; charset=cp1250")
e.header("Content-Transfer-Encoding", "base64")
e.message(b64encode(b), alternative=AUTO)
self.assertEqual("ř", e.message())
# Strangely, putting apostrophes around the charset would not work
# e.header("Content-Type", "text/plain;charset='cp1250'")
# e._header["Content-Type"] == "text/plain;")
def test_repr(self):
e = Envelope("hello").to("[email protected]")
self.assertEqual('Envelope(to=[[email protected]], message="hello")', repr(e))
class TestSmime(TestAbstract):
# create a key and its certificate valid for 100 years
# openssl req -newkey rsa:1024 -nodes -x509 -days 36500 -out certificate.pem
smime_key = 'tests/smime/key.pem'
smime_cert = 'tests/smime/cert.pem'
key_cert_together = Path("tests/smime/key-cert-together.pem")
def test_smime_sign(self):
# Message will look that way:
# MIME-Version: 1.0
# Content-Type: multipart/signed; protocol="application/x-pkcs7-signature"; micalg="sha1"; boundary="----DD291FCCF0F9F19D858D1A9200251EA5"
#
# This is an S/MIME signed message
#
# ------DD291FCCF0F9F19D858D1A9200251EA5
#
# dumb message
# ------DD291FCCF0F9F19D858D1A9200251EA5
# Content-Type: application/x-pkcs7-signature; name="smime.p7s"
# Content-Transfer-Encoding: base64
# Content-Disposition: attachment; filename="smime.p7s"
#
# MIIEggYJKoZIhvcNAQcCoIIEczCCBG8CAQExCzAJBgUrDgMCGgUAMAsGCSqGSIb3
# DQEHAaCCAmwwggJoMIIB0aADAgECAhROmwkIH63oarp3NpQqFoKTy1Q3tTANBgkq
# ... other lines changes every time
self.check_lines(Envelope(MESSAGE)
.smime()
.subject("my subject")
.reply_to("[email protected]")
.signature(Path("tests/smime/key.pem"), cert=Path(self.smime_cert))
.send(False),
("Subject: my subject",
"Reply-To: [email protected]",
MESSAGE,
'Content-Disposition: attachment; filename="smime.p7s"',
"MIIEUwYJKoZIhvcNAQcCoIIERDCCBEACAQExDzANBglghkgBZQMEAgEFADALBgkq",), 10)
def test_smime_key_cert_together(self):
self.check_lines(Envelope(MESSAGE)
.smime()
.signature(self.key_cert_together)
.sign(),
('Content-Disposition: attachment; filename="smime.p7s"',
"MIIEUwYJKoZIhvcNAQcCoIIERDCCBEACAQExDzANBglghkgBZQMEAgEFADALBgkq"))
def test_smime_key_cert_together_passphrase(self):
self.check_lines(Envelope(MESSAGE)
.smime()
.signature(Path("tests/smime/key-cert-together-passphrase.pem"), passphrase=GPG_PASSPHRASE)
.sign(),
('Content-Disposition: attachment; filename="smime.p7s"',
"MIIEUwYJKoZIhvcNAQcCoIIERDCCBEACAQExDzANBglghkgBZQMEAgEFADALBgkq"), 10)
def test_smime_encrypt(self):
# Message will look that way:
# MIME-Version: 1.0
# Content-Disposition: attachment; filename="smime.p7m"
# Content-Type: application/x-pkcs7-mime; smime-type=enveloped-data; name="smime.p7m" # note: x- is deprecated and current standard recomends using quotes around smime-type="enveloped-data", without is also accepted
# Content-Transfer-Encoding: base64
#
# MIIBPQYJKoZIhvcNAQcDoIIBLjCCASoCAQAxgfcwgfQCAQAwXTBFMQswCQYDVQQG
# EwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50ZXJuZXQgV2lk
# Z2l0cyBQdHkgTHRkAhROmwkIH63oarp3NpQqFoKTy1Q3tTANBgkqhkiG9w0BAQEF
# AASBgHriGJfbxNVpzDhxnObA6q0xoAuXOgYobG5HxpGi9InmlYoWS6ZkeDTMo70B
# nnXprxG2Q+/0GHJw48R1/B2d4Ln1sYJe5BXl3LVr7QWpwPb+62AZ1TN8793jSic6
# jBl/v6gDTRoEEjnb8RAkyvDJ7d6OOokgFOfCfTAUOBoZhZrqMCsGCSqGSIb3DQEH
# ATAUBggqhkiG9w0DBwQIt4seJLnZZW+ACBRKsu4Go7lm
self.check_lines(Envelope(MESSAGE)
.smime()
.reply_to("[email protected]")
.subject("my message")
.encryption(Path(self.smime_cert))
.send(False),
(
'Content-Type: application/pkcs7-mime; smime-type="enveloped-data"; name="smime.p7m"',
"Subject: my message",
"Reply-To: [email protected]",
"Z2l0cyBQdHkgTHRkAhROmwkIH63oarp3NpQqFoKTy1Q3tTANBgkqhkiG9w0BAQEF",
), 10)
def test_smime_detection(self):
""" We do not explicitly tell that we are using GPG or S/MIME. """
# Implicit GPG
self.check_lines(Envelope(MESSAGE).from_(IDENTITY_2).to(IDENTITY_2)
.encryption(key=Path("tests/gpg_keys/[email protected]")),
result=True)
self.check_lines(Envelope(MESSAGE).from_(IDENTITY_2).to(IDENTITY_2)
.signature(key=Path("tests/gpg_keys/[email protected]"), passphrase=GPG_PASSPHRASE),
result=True)
# Implicit S/MIME
self.check_lines(Envelope(MESSAGE)
.subject("my subject")
.reply_to("[email protected]")
.signature(self.key_cert_together)
.send(False),
("Subject: my subject",
"Reply-To: [email protected]",
MESSAGE,
'Content-Disposition: attachment; filename="smime.p7s"',
"MIIEUwYJKoZIhvcNAQcCoIIERDCCBEACAQExDzANBglghkgBZQMEAgEFADALBgkq",), 10)
self.check_lines(Envelope(MESSAGE)
.subject("my subject")
.reply_to("[email protected]")
.encryption(self.key_cert_together)
.send(False),
(
'Content-Type: application/pkcs7-mime; smime-type="enveloped-data"; name="smime.p7m"',
"Subject: my subject",
"Reply-To: [email protected]",
"Z2l0cyBQdHkgTHRkAhROmwkIH63oarp3NpQqFoKTy1Q3tTANBgkqhkiG9w0BAQEF",
), 10)
def test_multiple_recipients(self):
# output is generated using pyca cryptography
from M2Crypto import SMIME
msg=MESSAGE
def decrypt(key, cert, text):
try:
return Parser(key=key, cert=cert).smime_decrypt(text)
except SMIME.PKCS7_Error:
return False
# encrypt for both keys
output=(Envelope(msg)
.smime()
.reply_to("[email protected]")
.subject("my message")
.encrypt([Path(self.smime_cert), Path("tests/smime/[email protected]")]))
# First key
decrypted_message = decrypt('tests/smime/[email protected]', 'tests/smime/[email protected]', output).decode('utf-8')
result = re.search(msg, decrypted_message)
self.assertTrue(result)
# Second key
decrypted_message = decrypt(self.smime_key,self.smime_cert, output).decode('utf-8')
result = re.search(msg, decrypted_message)
self.assertTrue(result)
# encrypt for single key only
output=(Envelope(msg)
.smime()
.reply_to("[email protected]")
.subject("my message")
.encrypt([Path(self.smime_cert)]))
# Should be false, no search required
decrypted_message = decrypt('tests/smime/[email protected]', 'tests/smime/[email protected]', output)
self.assertFalse(decrypted_message)
decrypted_message = decrypt(self.smime_key,self.smime_cert, output).decode('utf-8')
result = re.search(msg, decrypted_message)
self.assertTrue(result)
def test_smime_decrypt(self):
e=Envelope.load(path="tests/eml/smime_encrypt.eml", key=self.smime_key, cert=self.smime_cert)
self.assertEqual(MESSAGE, e.message())
def test_smime_decrypt_attachments(self):
from M2Crypto import BIO, SMIME
import re
from base64 import b64encode, b64decode
body="an encrypted message with the attachments" # note that the inline image is not referenced in the text
encrypted_envelope=(Envelope(body)
.smime()
.reply_to("[email protected]")
.subject("my message")
.encryption(Path(self.smime_cert))
.attach(path=self.text_attachment)
.attach(self.image_file, inline=True)
.as_message().as_string()
)
key = self.smime_key
cert = self.smime_cert
# # Load private key and cert and decrypt
s = SMIME.SMIME()
s.load_key(key, cert)
p7, data = SMIME.smime_load_pkcs7_bio(BIO.MemoryBuffer(encrypted_envelope.encode('utf-8')))
# body is in decrypted message
decrypted_data = s.decrypt(p7).decode('utf-8')
print(decrypted_data)
self.assertTrue(re.search(body, decrypted_data))
# find number of attachments
attachments = re.findall(r'Content-Disposition: (attachment|inline)', decrypted_data)
self.assertEqual(2, len(attachments))
# find number of inline attachments
inline_attachments = re.findall(r'Content-Disposition: inline', decrypted_data)
self.assertEqual(1, len(inline_attachments))
# find inline attachment
cd_string = 'Content-Disposition: inline'
pos = decrypted_data.index(cd_string)
# get only gif data
data_temp = decrypted_data[pos + len(cd_string):].strip().replace('\n','').replace('\r', '')
data_temp = data_temp[:data_temp.index("==") +2]
base64_content = b64encode(self.image_file.read_bytes()).decode('ascii')
self.assertEqual(base64_content, data_temp)
# find generic.txt attachment
cd_string = 'Content-Disposition: attachment; filename="generic.txt"'
pos = decrypted_data.index(cd_string)
data_temp = decrypted_data[pos:]
d = data_temp.split('\r\n\r\n')[1].strip() + "=="
attachment_content = b64decode(d).decode('utf-8')
with open(self.text_attachment, 'r') as f:
file_content = f.read()
self.assertEqual(attachment_content, file_content)
# XX smime_sign.eml is not used right now.
# Make signature verification possible first.
# def test_smime_sign(self):
# e = Envelope.load(path="tests/eml/smime_sign.eml", key=self.smime_key, cert=self.smime_cert)
# self.assertEqual(MESSAGE, e.message())
def test_smime_key_cert_together(self):
# XX verify signature
e=Envelope.load(path="tests/eml/smime_key_cert_together.eml", key=self.key_cert_together)
self.assertEqual(MESSAGE, e.message())
class TestGPG(TestAbstract):
# Example identity
# no passphrase
# F14F2E8097E0CCDE93C4E871F4A4F26779FA03BB
# Example identity 2
# passphrase: test
# 3C8124A8245618D286CF871E94CE2905DB00CDB7
def test_gpg_sign(self):
# Message will look like this:
# -----BEGIN PGP SIGNED MESSAGE-----
# Hash: SHA512
#
# dumb message
# -----BEGIN PGP SIGNATURE-----
#
# iQGzBAEBCgAdFiEE8U8ugJfgzN6TxOhx9KTyZ3n6A7sFAl3xGeEACgkQ9KTyZ3n6
# A7vJawv/Q8+2F4sK/QlLdiOorXx9yhAG3jM/u4N2lr7H5aXDLPF7woYTHB8Gl5My
# 2+JDSALES0g2JYT6KKpZxHI+0gVEJtT7onsN7k9ye79okzge4wTZqnvf+GQ8xL8F
# ...
# Rvf4X8ZB
# =qCHO
# -----END PGP SIGNATURE-----
self.check_lines(Envelope(MESSAGE)
.gpg(GNUPG_HOME)
.sign(),
(MESSAGE,
'-----BEGIN PGP SIGNATURE-----',
'-----END PGP SIGNATURE-----',), 10)
def test_gpg_auto_sign(self):
# mail from "[email protected]" is in ring
self.check_lines(Envelope(MESSAGE)
.gpg(GNUPG_HOME)
.from_("[email protected]")
.sign("auto"),
(MESSAGE,
'-----BEGIN PGP SIGNATURE-----',
'-----END PGP SIGNATURE-----',), 10)
# mail from "[email protected]" should not be signed
output=str(Envelope(MESSAGE)
.gpg(GNUPG_HOME)
.from_("[email protected]")
.sign("auto")).splitlines()
self.assertNotIn('-----BEGIN PGP SIGNATURE-----', output)
# force-signing without specifying a key nor sending address should produce a message signed with a first-found key
output=str(Envelope(MESSAGE)
.gpg(GNUPG_HOME)
.sign(True)).splitlines()
self.assertIn('-----BEGIN PGP SIGNATURE-----', output)
# force-signing without specifying a key and with sending from an e-mail which is not in the keyring must fail
self.check_lines(Envelope(MESSAGE)
.gpg(GNUPG_HOME)
.from_("[email protected]")
.signature(True), raises=RuntimeError)
def test_gpg_encrypt_message(self):
# Message will look like this:
# -----BEGIN PGP MESSAGE-----
#
# hQGMA9ig68HPFWOpAQv/dsg8GkPJ9g9HKICe/Hi4AAl0AbAfIvAeKGowHhsvb++G
# ...
# s1gZJ8eJEbjGgdtjohAfnr4Qsz1RGwQGcm8DfqzFSnSIUurN21ZYqKjsWpt6s4Dp
# N0g=
# =rK+/
# -----END PGP MESSAGE-----
message=(Envelope(MESSAGE)
.gpg(GNUPG_HOME)
.from_(IDENTITY_1)
.to(IDENTITY_2)
.encrypt())
self.check_lines(message, (PGP_MESSAGE,), 10)
self.assertIn(MESSAGE, self.bash("gpg", "--decrypt", piped=str(message), envelope=False))
def test_gpg_encrypt(self):
# Message will look like this:
# ****************************************************************************************************
# Have not been sent from [email protected] to [email protected]
# Encrypted subject: None
# Encrypted message: b'message'
#
# Subject: Encrypted message
# MIME-Version: 1.0
# Content-Type: multipart/encrypted; protocol="application/pgp-encrypted";
# boundary="===============1001129828818615570=="
# From: [email protected]
# Date: Wed, 11 Dec 2019 17:56:03 +0100
# Message-ID: <157608336314.13303.1097227818284823500@promyka>
#
# --===============1001129828818615570==
# Content-Type: application/pgp-encrypted
#
# Version: 1
# --===============1001129828818615570==
# Content-Type: application/octet-stream; name="encrypted.asc"
# Content-Description: OpenPGP encrypted message
# Content-Disposition: inline; filename="encrypted.asc"
#
# -----BEGIN PGP MESSAGE-----
# ...
# -----END PGP MESSAGE-----
#
# --===============1001129828818615570==--
e=str(Envelope(MESSAGE)
.to(IDENTITY_2)
.gpg(GNUPG_HOME)
.from_(IDENTITY_1)
.subject("dumb subject")
.encryption())
self.check_lines(e,
("Encrypted subject: dumb subject",
"Encrypted message: dumb message",
"Subject: Encrypted message",
'Content-Type: multipart/encrypted; protocol="application/pgp-encrypted";',
"From: [email protected]",
"To: [email protected]",
), 10, not_in='Subject: dumb subject')
lines=e.splitlines()
message="\n".join(lines[lines.index(PGP_MESSAGE):])
self.check_lines(self.bash("gpg", "--decrypt", piped=message, envelope=False),
('Content-Type: multipart/mixed; protected-headers="v1";',
'Subject: dumb subject',
'Content-Type: text/plain; charset="utf-8"',
MESSAGE
))
def test_arbitrary_encrypt(self):
""" Keys to be encrypted with explicitly chosen """
temp=[TemporaryDirectory() for _ in range(4)] # must exist in the scope to preserve the dirs
rings=[t.name for t in temp]
message=MESSAGE
key1_raw=Path("tests/gpg_keys/[email protected]").read_bytes()
key1_armored=Path("tests/gpg_keys/[email protected]").read_text()
_importer=Envelope("just importer")
# helper methods
def decrypt(s, ring, equal=True):
m=self.assertEqual if equal else self.assertNotEqual
m(message, Envelope.load(s, gnupg_home=rings[ring]).message())
def importer(ring, key, passphrase=None):
_importer.gpg(rings[ring]).sign(Path("tests/gpg_keys/" + key), passphrase=passphrase)
# Message encrypted for [email protected] only, not for the sender
e1=str(Envelope(message)
.to(IDENTITY_1)
.gpg(GNUPG_HOME)
.from_(IDENTITY_2)
.subject("dumb subject")
.encryption(IDENTITY_1).as_message())
# message is decipherable only from the keyring the right key is in
self.assertEqual(message, Envelope.load(e1, gnupg_home=(GNUPG_HOME)).message())
decrypt(e1, 0, False)
# importing other key does not help
importer(0, "[email protected]", GPG_PASSPHRASE)
decrypt(e1, 0, False)
# importing the right key does help
importer(0, "[email protected]")
decrypt(e1, 0)
# message encrypted for multiple recipients
e2=str(Envelope(message)
.to(IDENTITY_1)
.gpg(GNUPG_HOME)
.from_(IDENTITY_3)
.encryption([IDENTITY_1, IDENTITY_2])
.as_message())
decrypt(e2, 1, False)
importer(1, "[email protected]", GPG_PASSPHRASE)
decrypt(e2, 1)
importer(2, "[email protected]", GPG_PASSPHRASE)
decrypt(e2, 2)
# message not encrypted for a recipient but for a sender only (for some unknown reason)
e3=str(Envelope(message)
.to(IDENTITY_2)
.gpg(GNUPG_HOME)
.from_(IDENTITY_1)
.encryption([IDENTITY_1, ])
.as_message())
decrypt(e3, 1, False) # ring 1 has "[email protected]"
decrypt(e3, 2) # ring 2 has "[email protected]"
# message encrypted for combination of fingerprints and e-mails
e3=str(Envelope(message)
.to("[email protected], [email protected]")
.gpg(GNUPG_HOME)
.from_(IDENTITY_2)
.encryption([IDENTITY_2, IDENTITY_1_GPG_FINGERPRINT])
.as_message())
decrypt(e3, 0) # ring 0 has both
decrypt(e3, 1) # ring 1 has "[email protected]"
decrypt(e3, 2) # ring 2 has "[email protected]"
decrypt(e3, 3, False) # ring 3 has none
# trying to encrypt with an unknown key while/without specifying decipherers explicitly
# (note that we pass a generator to the .encryption to test if it takes other iterables than a list)
for e in [Envelope(message).encryption(x for x in [IDENTITY_3, IDENTITY_1_GPG_FINGERPRINT]),
Envelope(message).encryption()]:
with self.assertLogs('envelope', level='WARNING') as cm:
self.assertEqual('None', str(e
.to(f"{IDENTITY_3}, {IDENTITY_1}")
.from_(IDENTITY_2)
.gpg(GNUPG_HOME)
.as_message()))
self.assertIn(f'WARNING:envelope.envelope:Key for {IDENTITY_3} seems missing,'
f' see: GNUPGHOME=tests/gpg_ring/ gpg --list-keys', cm.output)
self.assertIn('ERROR:envelope.envelope:Signing/encrypting failed.', cm.output)
self.assertNotIn(f'WARNING:envelope.envelope:Key for {IDENTITY_2} seems missing', cm.output)
# import raw unarmored key in a list ("[email protected]" into ring 1)
# (note that we pass a set to the .encryption to test if it takes other iterables than a list)
e4=Envelope(message).encryption({IDENTITY_2, key1_raw}).to(IDENTITY_3).from_(IDENTITY_2).gpg(
rings[1]).as_message()
decrypt(e4, 1)
decrypt(e4, 2)
# multiple encryption keys in bash
def bash(ring, from_, to, encrypt, valid=True):
contains=PGP_MESSAGE if valid else "Signing/encrypting failed."
self.assertIn(contains, self.bash("--from", from_, "--to", *to, "--encrypt", *encrypt, piped=message,
env={"GNUPGHOME": rings[ring]}))
bash(1, IDENTITY_1, (IDENTITY_2,), ()) # ring 1 has both
bash(1, IDENTITY_1, (IDENTITY_2,), (IDENTITY_2,))
# not specifying the exact encryption identities leads to an error
bash(0, IDENTITY_1, (IDENTITY_2, IDENTITY_3), (), False) # ring 0 has both, but misses ID=3
bash(0, IDENTITY_1, (IDENTITY_2, IDENTITY_3), (IDENTITY_1, IDENTITY_2))
bash(3, IDENTITY_1, (IDENTITY_2,), (), False) # ring 3 has none
bash(3, IDENTITY_1, (IDENTITY_2, IDENTITY_3), (key1_armored,)) # insert ID=1 into ring 3
bash(3, IDENTITY_2, (IDENTITY_1,), (), False) # ID=2 still misses in ring 3
bash(3, IDENTITY_2, (IDENTITY_1,), ("--no-from",)) # --no-sender supress the need for ID=2
def test_arbitrary_encrypt_with_signing(self):
model=(Envelope(MESSAGE)
.to(f"{IDENTITY_3}, {IDENTITY_1}")
.from_(IDENTITY_2)
.gpg(GNUPG_HOME))
def logged(signature, encryption, warning=False):
e=(model.copy().signature(signature).encryption(encryption))
if warning:
with self.assertLogs('envelope', level='WARNING') as cm:
self.assertEqual("", str(e))
self.assertIn(warning, str(cm.output))
else:
self.assertIn(PGP_MESSAGE, str(e))
logged(False, [IDENTITY_3, "invalid"],
f'WARNING:envelope.envelope:Key for {IDENTITY_3},'
' invalid seems missing, see: GNUPGHOME=tests/gpg_ring/ gpg --list-keys')
logged(False, [IDENTITY_1])
logged(IDENTITY_1, [IDENTITY_1])
logged(IDENTITY_3, [IDENTITY_1],
f'WARNING:envelope.envelope:The secret key for {IDENTITY_3} seems to not be used,'
f" check if it is in the keyring: GNUPGHOME=tests/gpg_ring/ gpg --list-secret-keys")
logged(IDENTITY_3, False,
f'WARNING:envelope.envelope:The secret key for {IDENTITY_3} seems to not be used,'
f" check if it is in the keyring: GNUPGHOME=tests/gpg_ring/ gpg --list-secret-keys")
self.assertEqual("", str(model.copy().encrypt(IDENTITY_2, sign=IDENTITY_3)))
self.assertIn(PGP_MESSAGE, str(model.copy().encrypt(IDENTITY_2, sign=IDENTITY_1)))
def test_gpg_auto_encrypt(self):
# mail `from` "[email protected]" is in ring
self.check_lines(Envelope(MESSAGE)
.gpg(GNUPG_HOME)
.from_(IDENTITY_1)
.to(IDENTITY_1)
.encrypt("auto"),
(PGP_MESSAGE,
'-----END PGP MESSAGE-----',), (10, 15), not_in=MESSAGE)
# mail `to` "[email protected]" unknown, must be both signed and encrypted
self.check_lines(Envelope(MESSAGE)
.gpg(GNUPG_HOME)
.from_(IDENTITY_1)
.to(IDENTITY_2)
.signature("auto")
.encrypt("auto"),
(PGP_MESSAGE,
'-----END PGP MESSAGE-----',), 20, not_in=MESSAGE)
# mail `from` "[email protected]" unknown, must not be encrypted
self.check_lines(Envelope(MESSAGE)
.gpg(GNUPG_HOME)
.from_("[email protected]")
.to(IDENTITY_1)
.encrypt("auto"),
(MESSAGE,), (0, 2), not_in=PGP_MESSAGE)
# mail `to` "[email protected]" unknown, must not be encrypted
self.check_lines(Envelope(MESSAGE)
.gpg(GNUPG_HOME)
.from_(IDENTITY_1)
.to("[email protected]")
.encrypt("auto"),
(MESSAGE,), (0, 2), not_in=PGP_MESSAGE)
# force-encrypting without having key must return empty response
self.check_lines(Envelope(MESSAGE)
.gpg(GNUPG_HOME)
.from_(IDENTITY_1)
.to("[email protected]")
.encryption(True), longer=(0, 1), result=False)
def test_gpg_sign_passphrase(self):
self.check_lines(Envelope(MESSAGE)
.to(IDENTITY_2)
.gpg(GNUPG_HOME)
.from_(IDENTITY_1)
.signature("3C8124A8245618D286CF871E94CE2905DB00CDB7", GPG_PASSPHRASE), # passphrase needed
("-----BEGIN PGP SIGNATURE-----",), 10)
def test_auto_import(self):
temp=TemporaryDirectory()
# no signature - empty ring
self.check_lines(Envelope(MESSAGE)
.gpg(temp.name)
.signature(),
raises=RuntimeError)
# import key to the ring
self.check_lines(Envelope(MESSAGE)
.gpg(temp.name)
.sign(Path("tests/gpg_keys/[email protected]")),
(MESSAGE,
'-----BEGIN PGP SIGNATURE-----',
'-----END PGP SIGNATURE-----',), 10)
# key in the ring from last time
self.check_lines(Envelope(MESSAGE)
.gpg(temp.name)
.signature(),
(MESSAGE,
'-----BEGIN PGP SIGNATURE-----',
'-----END PGP SIGNATURE-----',), 10)
# cannot encrypt for identity-2
self.check_lines(Envelope(MESSAGE)
.gpg(temp.name)
.from_(IDENTITY_1)
.to(IDENTITY_2)
.encryption(),
result=False)
# signing should fail since we have not imported key for identity-2
self.check_lines(Envelope(MESSAGE)
.gpg(temp.name)
.from_(IDENTITY_2)
.signature(),
raises=RuntimeError)
# however it should pass when we explicitly use an existing GPG key to be signed with
self.check_lines(Envelope(MESSAGE)
.gpg(temp.name)
.from_(IDENTITY_2)
.signature(IDENTITY_1_GPG_FINGERPRINT),
(MESSAGE,
'-----BEGIN PGP SIGNATURE-----',
'-----END PGP SIGNATURE-----',), 10, result=True)
# import encryption key - no passphrase needed while importing or using public key
self.check_lines(Envelope(MESSAGE)
.gpg(temp.name)
.from_(IDENTITY_1)
.to(IDENTITY_2)
.encryption(Path("tests/gpg_keys/[email protected]")),
result=True)
# signing with an invalid passphrase should fail for identity-2
self.check_lines(Envelope(MESSAGE)
.gpg(temp.name)
.from_(IDENTITY_2)
.signature(passphrase="INVALID PASSPHRASE"),
result=False)
# signing with a valid passphrase should pass
self.check_lines(Envelope(MESSAGE)
.gpg(temp.name)
.from_(IDENTITY_2)
.signature(passphrase=GPG_PASSPHRASE),
result=True)
def test_signed_gpg(self):
# XX we should test signature verification with e._gpg_verify(),
# however .load does not load application/pgp-signature content at the moment
e=Envelope.load(path="tests/eml/test_signed_gpg.eml")
self.assertEqual(MESSAGE, e.message())
def test_encrypted_gpg(self):
e=Envelope.load(path="tests/eml/test_encrypted_gpg.eml")
self.assertEqual("dumb encrypted message", e.message())
def test_encrypted_signed_gpg(self):
e=Envelope.load(path="tests/eml/test_encrypted_signed_gpg.eml")
self.assertEqual("dumb encrypted and signed message", e.message())
def test_encrypted_gpg_subject(self):
body="just a body text"
subject="This is an encrypted subject"
encrypted_subject="Encrypted message"
ref=(Envelope(body)
.gpg(GNUPG_HOME)
.to(IDENTITY_2)
.from_(IDENTITY_1)
.encryption())
encrypted_eml=ref.subject(subject).as_message().as_string()
# subject has been encrypted
self.assertIn("Subject: " + encrypted_subject, encrypted_eml)
self.assertNotIn(subject, encrypted_eml)
# subject has been decrypted
e=Envelope.load(encrypted_eml)
self.assertEqual(body, e.message())
self.assertEqual(subject, e.subject())
# further meddling with the encrypt parameter
def check_decryption(reference, other_subject=encrypted_subject):
encrypted=reference.as_message().as_string()
self.assertIn(other_subject, encrypted)
self.assertNotIn(subject, encrypted)
decrypted=Envelope.load(encrypted).as_message().as_string()