Debian Codegraph @

crypto/attachment/attachments_test.go

raw
1 package attachment
2
3 import (
4 "encoding/base64"
5 "encoding/json"
6 "testing"
7
8 "github.com/stretchr/testify/assert"
9 )
10
11 const helloWorldCiphertext = ":6\xc7O1yR\x06\xe8\xcf]"
12 const helloWorldRawFile = `{
13 "v": "v2",
14 "key": {
15 "kty": "oct",
16 "alg": "A256CTR",
17 "ext": true,
18 "k": "35XNdmWKOpn6UYS82Y83wEY8LagwQZHX2X0kAFW7sdg",
19 "key_ops": [
20 "encrypt",
21 "decrypt"
22 ]
23 },
24 "iv": "DOtPz8bC3qgAAAAAAAAAAA",
25 "hashes": {
26 "sha256": "rO+040ZhUxbpbmIS9GUuMSen4NPKFxMzqOUJeemM8mk"
27 }
28 }`
29 const random32Bytes = "\x85\xb4\x16/\xcaO\x1d\xe6\x7f\x95\xeb\xdb+g\x11\xb1\x81\x1a\xafY\x00\x1dq!h{\x81F\xaa\xd7A\x00"
30
31 func parseHelloWorld() *EncryptedFile {
32 file := &EncryptedFile{}
33 _ = json.Unmarshal([]byte(helloWorldRawFile), file)
34 return file
35 }
36
37 func TestDecryptHelloWorld(t *testing.T) {
38 file := parseHelloWorld()
39 data := []byte(helloWorldCiphertext)
40 err := file.DecryptInPlace(data)
41 assert.NoError(t, err, "failed to decrypt file")
42 assert.Equal(t, "hello world", string(data), "unexpected decrypt output")
43 }
44
45 func TestEncryptHelloWorld(t *testing.T) {
46 file := parseHelloWorld()
47 data := []byte("hello world")
48 file.EncryptInPlace(data)
49 assert.Equal(t, helloWorldCiphertext, string(data), "unexpected encrypt output")
50 }
51
52 func TestUnsupportedVersion(t *testing.T) {
53 file := parseHelloWorld()
54 file.Version = "foo"
55 err := file.DecryptInPlace([]byte(helloWorldCiphertext))
56 assert.ErrorIs(t, err, UnsupportedVersion)
57 }
58
59 func TestUnsupportedAlgorithm(t *testing.T) {
60 file := parseHelloWorld()
61 file.Key.Algorithm = "bar"
62 err := file.DecryptInPlace([]byte(helloWorldCiphertext))
63 assert.ErrorIs(t, err, UnsupportedAlgorithm)
64 }
65
66 func TestHashMismatch(t *testing.T) {
67 file := parseHelloWorld()
68 file.Hashes.SHA256 = base64.RawStdEncoding.EncodeToString([]byte(random32Bytes))
69 err := file.DecryptInPlace([]byte(helloWorldCiphertext))
70 assert.ErrorIs(t, err, HashMismatch)
71 }
72
73 func TestTooLongHash(t *testing.T) {
74 file := parseHelloWorld()
75 file.Hashes.SHA256 = "TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVlciBhZGlwaXNjaW5nIGVsaXQuIFNlZCBwb3N1ZXJlIGludGVyZHVtIHNlbS4gUXVpc3F1ZSBsaWd1bGEgZXJvcyB1bGxhbWNvcnBlciBxdWlzLCBsYWNpbmlhIHF1aXMgZmFjaWxpc2lzIHNlZCBzYXBpZW4uCg"
76 err := file.DecryptInPlace([]byte(helloWorldCiphertext))
77 assert.ErrorIs(t, err, InvalidHash)
78 }
79
80 func TestTooShortHash(t *testing.T) {
81 file := parseHelloWorld()
82 file.Hashes.SHA256 = "5/Gy1JftyyQ"
83 err := file.DecryptInPlace([]byte(helloWorldCiphertext))
84 assert.ErrorIs(t, err, InvalidHash)
85 }