aboutsummaryrefslogtreecommitdiffstats
path: root/tests/test_fernet.py
blob: 15071718eef3ea8e276aa0fe492fcbd26fe1f721 (plain)
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
import base64
import calendar
import json
import os

import iso8601

import pytest

import six

from cryptography.fernet import Fernet, InvalidToken


def json_parametrize(keys, fname):
    path = os.path.join(os.path.dirname(__file__), "vectors", "fernet", fname)
    with open(path) as f:
        data = json.load(f)
    return pytest.mark.parametrize(keys, [
        tuple([entry[k] for k in keys])
        for entry in data
    ])


class TestFernet(object):
    @json_parametrize(
        ("secret", "now", "iv", "src", "token"), "generate.json",
    )
    def test_generate(self, secret, now, iv, src, token):
        f = Fernet(base64.urlsafe_b64decode(secret.encode("ascii")))
        actual_token = f._encrypt_from_parts(
            src.encode("ascii"),
            calendar.timegm(iso8601.parse_date(now).utctimetuple()),
            b"".join(map(six.int2byte, iv))
        )
        assert actual_token == token

    @json_parametrize(
        ("secret", "now", "src", "ttl_sec", "token"), "verify.json",
    )
    def test_verify(self, secret, now, src, ttl_sec, token):
        f = Fernet(base64.urlsafe_b64decode(secret.encode("ascii")))
        payload = f.decrypt(
            token.encode("ascii"),
            ttl=ttl_sec,
            current_time=calendar.timegm(iso8601.parse_date(now).utctimetuple())
        )
        assert payload == src

    @json_parametrize(("secret", "token", "now", "ttl_sec"), "invalid.json")
    def test_invalid(self, secret, token, now, ttl_sec):
        f = Fernet(base64.urlsafe_b64decode(secret.encode("ascii")))
        with pytest.raises(InvalidToken):
            f.decrypt(
                token.encode("ascii"),
                ttl=ttl_sec,
                current_time=calendar.timegm(iso8601.parse_date(now).utctimetuple())
            )

    def test_unicode(self):
        f = Fernet(b"\x00" * 32)
        with pytest.raises(TypeError):
            f.encrypt(six.u(""))
        with pytest.raises(TypeError):
            f.decrypt(six.u(""))