Welcome to mirror list, hosted at ThFree Co, Russian Federation.

messages_test.py « tests « acme - github.com/certbot/certbot.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: cf7e7629a3b6e55000b1a83cee2301b587368761 (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
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
"""Tests for acme.messages."""
from typing import Dict
import unittest
from unittest import mock

import josepy as jose

from acme import challenges
import test_util

CERT = test_util.load_comparable_cert('cert.der')
CSR = test_util.load_comparable_csr('csr.der')
KEY = test_util.load_rsa_private_key('rsa512_key.pem')


class ErrorTest(unittest.TestCase):
    """Tests for acme.messages.Error."""

    def setUp(self):
        from acme.messages import Error, ERROR_PREFIX, Identifier, IDENTIFIER_FQDN
        self.error = Error.with_code('malformed', detail='foo', title='title')
        self.jobj = {
            'detail': 'foo',
            'title': 'some title',
            'type': ERROR_PREFIX + 'malformed',
        }
        self.error_custom = Error(typ='custom', detail='bar')
        self.identifier = Identifier(typ=IDENTIFIER_FQDN, value='example.com')
        self.subproblem = Error.with_code('caa', detail='bar', title='title', identifier=self.identifier)
        self.error_with_subproblems = Error.with_code('malformed', detail='foo', title='title', subproblems=[self.subproblem])
        self.empty_error = Error()

    def test_default_typ(self):
        from acme.messages import Error
        self.assertEqual(Error().typ, 'about:blank')

    def test_from_json_empty(self):
        from acme.messages import Error
        self.assertEqual(Error(), Error.from_json('{}'))

    def test_from_json_hashable(self):
        from acme.messages import Error
        hash(Error.from_json(self.error.to_json()))

    def test_from_json_with_subproblems(self):
        from acme.messages import Error

        parsed_error = Error.from_json(self.error_with_subproblems.to_json())

        self.assertEqual(1, len(parsed_error.subproblems))
        self.assertEqual(self.subproblem, parsed_error.subproblems[0])

    def test_description(self):
        self.assertEqual('The request message was malformed', self.error.description)
        self.assertIsNone(self.error_custom.description)

    def test_code(self):
        from acme.messages import Error
        self.assertEqual('malformed', self.error.code)
        self.assertIsNone(self.error_custom.code)
        self.assertIsNone(Error().code)

    def test_is_acme_error(self):
        from acme.messages import is_acme_error, Error
        self.assertTrue(is_acme_error(self.error))
        self.assertFalse(is_acme_error(self.error_custom))
        self.assertFalse(is_acme_error(Error()))
        self.assertFalse(is_acme_error(self.empty_error))
        self.assertFalse(is_acme_error("must pet all the {dogs|rabbits}"))

    def test_unicode_error(self):
        from acme.messages import Error, is_acme_error
        arabic_error = Error.with_code(
            'malformed', detail=u'\u0639\u062f\u0627\u0644\u0629', title='title')
        self.assertTrue(is_acme_error(arabic_error))

    def test_with_code(self):
        from acme.messages import Error, is_acme_error
        self.assertTrue(is_acme_error(Error.with_code('badCSR')))
        self.assertRaises(ValueError, Error.with_code, 'not an ACME error code')

    def test_str(self):
        self.assertEqual(
            str(self.error),
            u"{0.typ} :: {0.description} :: {0.detail} :: {0.title}"
            .format(self.error))
        self.assertEqual(
            str(self.error_with_subproblems),
            (u"{0.typ} :: {0.description} :: {0.detail} :: {0.title}\n"+
            u"Problem for {1.identifier.value}: {1.typ} :: {1.description} :: {1.detail} :: {1.title}").format(
        self.error_with_subproblems, self.subproblem))

class ConstantTest(unittest.TestCase):
    """Tests for acme.messages._Constant."""

    def setUp(self):
        from acme.messages import _Constant

        class MockConstant(_Constant):  # pylint: disable=missing-docstring
            POSSIBLE_NAMES: Dict = {}

        self.MockConstant = MockConstant  # pylint: disable=invalid-name
        self.const_a = MockConstant('a')
        self.const_b = MockConstant('b')

    def test_to_partial_json(self):
        self.assertEqual('a', self.const_a.to_partial_json())
        self.assertEqual('b', self.const_b.to_partial_json())

    def test_from_json(self):
        self.assertEqual(self.const_a, self.MockConstant.from_json('a'))
        self.assertRaises(
            jose.DeserializationError, self.MockConstant.from_json, 'c')

    def test_from_json_hashable(self):
        hash(self.MockConstant.from_json('a'))

    def test_repr(self):
        self.assertEqual('MockConstant(a)', repr(self.const_a))
        self.assertEqual('MockConstant(b)', repr(self.const_b))

    def test_equality(self):
        const_a_prime = self.MockConstant('a')
        self.assertNotEqual(self.const_a, self.const_b)
        self.assertEqual(self.const_a, const_a_prime)

        self.assertNotEqual(self.const_a, self.const_b)
        self.assertEqual(self.const_a, const_a_prime)


class DirectoryTest(unittest.TestCase):
    """Tests for acme.messages.Directory."""

    def setUp(self):
        from acme.messages import Directory
        self.dir = Directory({
            'new-reg': 'reg',
            mock.MagicMock(resource_type='new-cert'): 'cert',
            'meta': Directory.Meta(
                terms_of_service='https://example.com/acme/terms',
                website='https://www.example.com/',
                caa_identities=['example.com'],
            ),
        })

    def test_init_wrong_key_value_success(self):  # pylint: disable=no-self-use
        from acme.messages import Directory
        Directory({'foo': 'bar'})

    def test_getitem(self):
        self.assertEqual('reg', self.dir['new-reg'])
        from acme.messages import NewRegistration
        self.assertEqual('reg', self.dir[NewRegistration])
        self.assertEqual('reg', self.dir[NewRegistration()])

    def test_getitem_fails_with_key_error(self):
        self.assertRaises(KeyError, self.dir.__getitem__, 'foo')

    def test_getattr(self):
        self.assertEqual('reg', self.dir.new_reg)

    def test_getattr_fails_with_attribute_error(self):
        self.assertRaises(AttributeError, self.dir.__getattr__, 'foo')

    def test_to_json(self):
        self.assertEqual(self.dir.to_json(), {
            'new-reg': 'reg',
            'new-cert': 'cert',
            'meta': {
                'terms-of-service': 'https://example.com/acme/terms',
                'website': 'https://www.example.com/',
                'caaIdentities': ['example.com'],
            },
        })

    def test_from_json_deserialization_unknown_key_success(self):  # pylint: disable=no-self-use
        from acme.messages import Directory
        Directory.from_json({'foo': 'bar'})

    def test_iter_meta(self):
        result = False
        for k in self.dir.meta:
            if k == 'terms_of_service':
                result = self.dir.meta[k] == 'https://example.com/acme/terms'
        self.assertTrue(result)


class ExternalAccountBindingTest(unittest.TestCase):
    def setUp(self):
        from acme.messages import Directory
        self.key = jose.jwk.JWKRSA(key=KEY.public_key())
        self.kid = "kid-for-testing"
        self.hmac_key = "hmac-key-for-testing"
        self.dir = Directory({
            'newAccount': 'http://url/acme/new-account',
        })

    def test_from_data(self):
        from acme.messages import ExternalAccountBinding
        eab = ExternalAccountBinding.from_data(self.key, self.kid, self.hmac_key, self.dir)

        self.assertEqual(len(eab), 3)
        self.assertEqual(sorted(eab.keys()), sorted(['protected', 'payload', 'signature']))


class RegistrationTest(unittest.TestCase):
    """Tests for acme.messages.Registration."""

    def setUp(self):
        key = jose.jwk.JWKRSA(key=KEY.public_key())
        contact = (
            'mailto:admin@foo.com',
            'tel:1234',
        )
        agreement = 'https://letsencrypt.org/terms'

        from acme.messages import Registration
        self.reg = Registration(key=key, contact=contact, agreement=agreement)
        self.reg_none = Registration()

        self.jobj_to = {
            'contact': contact,
            'agreement': agreement,
            'key': key,
        }
        self.jobj_from = self.jobj_to.copy()
        self.jobj_from['key'] = key.to_json()

    def test_from_data(self):
        from acme.messages import Registration
        reg = Registration.from_data(phone='1234', email='admin@foo.com')
        self.assertEqual(reg.contact, (
            'tel:1234',
            'mailto:admin@foo.com',
        ))

    def test_new_registration_from_data_with_eab(self):
        from acme.messages import NewRegistration, ExternalAccountBinding, Directory
        key = jose.jwk.JWKRSA(key=KEY.public_key())
        kid = "kid-for-testing"
        hmac_key = "hmac-key-for-testing"
        directory = Directory({
            'newAccount': 'http://url/acme/new-account',
        })
        eab = ExternalAccountBinding.from_data(key, kid, hmac_key, directory)
        reg = NewRegistration.from_data(email='admin@foo.com', external_account_binding=eab)
        self.assertEqual(reg.contact, (
            'mailto:admin@foo.com',
        ))
        self.assertEqual(sorted(reg.external_account_binding.keys()),
                         sorted(['protected', 'payload', 'signature']))

    def test_phones(self):
        self.assertEqual(('1234',), self.reg.phones)

    def test_emails(self):
        self.assertEqual(('admin@foo.com',), self.reg.emails)

    def test_to_partial_json(self):
        self.assertEqual(self.jobj_to, self.reg.to_partial_json())

    def test_from_json(self):
        from acme.messages import Registration
        self.assertEqual(self.reg, Registration.from_json(self.jobj_from))

    def test_from_json_hashable(self):
        from acme.messages import Registration
        hash(Registration.from_json(self.jobj_from))

    def test_default_not_transmitted(self):
        from acme.messages import NewRegistration
        empty_new_reg = NewRegistration()
        new_reg_with_contact = NewRegistration(contact=())

        self.assertEqual(empty_new_reg.contact, ())
        self.assertEqual(new_reg_with_contact.contact, ())

        self.assertNotIn('contact', empty_new_reg.to_partial_json())
        self.assertNotIn('contact', empty_new_reg.fields_to_partial_json())
        self.assertIn('contact', new_reg_with_contact.to_partial_json())
        self.assertIn('contact', new_reg_with_contact.fields_to_partial_json())


class UpdateRegistrationTest(unittest.TestCase):
    """Tests for acme.messages.UpdateRegistration."""

    def test_empty(self):
        from acme.messages import UpdateRegistration
        jstring = '{"resource": "reg"}'
        self.assertEqual(jstring, UpdateRegistration().json_dumps())
        self.assertEqual(
            UpdateRegistration(), UpdateRegistration.json_loads(jstring))


class RegistrationResourceTest(unittest.TestCase):
    """Tests for acme.messages.RegistrationResource."""

    def setUp(self):
        from acme.messages import RegistrationResource
        self.regr = RegistrationResource(
            body=mock.sentinel.body, uri=mock.sentinel.uri,
            terms_of_service=mock.sentinel.terms_of_service)

    def test_to_partial_json(self):
        self.assertEqual(self.regr.to_json(), {
            'body': mock.sentinel.body,
            'uri': mock.sentinel.uri,
            'terms_of_service': mock.sentinel.terms_of_service,
        })


class ChallengeResourceTest(unittest.TestCase):
    """Tests for acme.messages.ChallengeResource."""

    def test_uri(self):
        from acme.messages import ChallengeResource
        self.assertEqual('http://challb', ChallengeResource(body=mock.MagicMock(
            uri='http://challb'), authzr_uri='http://authz').uri)


class ChallengeBodyTest(unittest.TestCase):
    """Tests for acme.messages.ChallengeBody."""

    def setUp(self):
        self.chall = challenges.DNS(token=jose.b64decode(
            'evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ-PCt92wr-oA'))

        from acme.messages import ChallengeBody
        from acme.messages import Error
        from acme.messages import STATUS_INVALID
        self.status = STATUS_INVALID
        error = Error.with_code('serverInternal', detail='Unable to communicate with DNS server')
        self.challb = ChallengeBody(
            uri='http://challb', chall=self.chall, status=self.status,
            error=error)

        self.jobj_to = {
            'uri': 'http://challb',
            'status': self.status,
            'type': 'dns',
            'token': 'evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ-PCt92wr-oA',
            'error': error,
        }
        self.jobj_from = self.jobj_to.copy()
        self.jobj_from['status'] = 'invalid'
        self.jobj_from['error'] = {
            'type': 'urn:ietf:params:acme:error:serverInternal',
            'detail': 'Unable to communicate with DNS server',
        }

    def test_encode(self):
        self.assertEqual(self.challb.encode('uri'), self.challb.uri)

    def test_to_partial_json(self):
        self.assertEqual(self.jobj_to, self.challb.to_partial_json())

    def test_from_json(self):
        from acme.messages import ChallengeBody
        self.assertEqual(self.challb, ChallengeBody.from_json(self.jobj_from))

    def test_from_json_hashable(self):
        from acme.messages import ChallengeBody
        hash(ChallengeBody.from_json(self.jobj_from))

    def test_proxy(self):
        self.assertEqual(jose.b64decode(
            'evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ-PCt92wr-oA'), self.challb.token)


class AuthorizationTest(unittest.TestCase):
    """Tests for acme.messages.Authorization."""

    def setUp(self):
        from acme.messages import ChallengeBody
        from acme.messages import STATUS_VALID

        self.challbs = (
            ChallengeBody(
                uri='http://challb1', status=STATUS_VALID,
                chall=challenges.HTTP01(token=b'IlirfxKKXAsHtmzK29Pj8A')),
            ChallengeBody(uri='http://challb2', status=STATUS_VALID,
                          chall=challenges.DNS(
                              token=b'DGyRejmCefe7v4NfDGDKfA')),
        )
        combinations = ((0,), (1,))

        from acme.messages import Authorization
        from acme.messages import Identifier
        from acme.messages import IDENTIFIER_FQDN
        identifier = Identifier(typ=IDENTIFIER_FQDN, value='example.com')
        self.authz = Authorization(
            identifier=identifier, combinations=combinations,
            challenges=self.challbs)

        self.jobj_from = {
            'identifier': identifier.to_json(),
            'challenges': [challb.to_json() for challb in self.challbs],
            'combinations': combinations,
        }

    def test_from_json(self):
        from acme.messages import Authorization
        Authorization.from_json(self.jobj_from)

    def test_from_json_hashable(self):
        from acme.messages import Authorization
        hash(Authorization.from_json(self.jobj_from))

    def test_resolved_combinations(self):
        self.assertEqual(self.authz.resolved_combinations, (
            (self.challbs[0],),
            (self.challbs[1],),
        ))


class AuthorizationResourceTest(unittest.TestCase):
    """Tests for acme.messages.AuthorizationResource."""

    def test_json_de_serializable(self):
        from acme.messages import AuthorizationResource
        authzr = AuthorizationResource(
            uri=mock.sentinel.uri,
            body=mock.sentinel.body)
        self.assertIsInstance(authzr, jose.JSONDeSerializable)


class CertificateRequestTest(unittest.TestCase):
    """Tests for acme.messages.CertificateRequest."""

    def setUp(self):
        from acme.messages import CertificateRequest
        self.req = CertificateRequest(csr=CSR)

    def test_json_de_serializable(self):
        self.assertIsInstance(self.req, jose.JSONDeSerializable)
        from acme.messages import CertificateRequest
        self.assertEqual(
            self.req, CertificateRequest.from_json(self.req.to_json()))


class CertificateResourceTest(unittest.TestCase):
    """Tests for acme.messages.CertificateResourceTest."""

    def setUp(self):
        from acme.messages import CertificateResource
        self.certr = CertificateResource(
            body=CERT, uri=mock.sentinel.uri, authzrs=(),
            cert_chain_uri=mock.sentinel.cert_chain_uri)

    def test_json_de_serializable(self):
        self.assertIsInstance(self.certr, jose.JSONDeSerializable)
        from acme.messages import CertificateResource
        self.assertEqual(
            self.certr, CertificateResource.from_json(self.certr.to_json()))


class RevocationTest(unittest.TestCase):
    """Tests for acme.messages.RevocationTest."""

    def setUp(self):
        from acme.messages import Revocation
        self.rev = Revocation(certificate=CERT)

    def test_from_json_hashable(self):
        from acme.messages import Revocation
        hash(Revocation.from_json(self.rev.to_json()))


class OrderResourceTest(unittest.TestCase):
    """Tests for acme.messages.OrderResource."""

    def setUp(self):
        from acme.messages import OrderResource
        self.regr = OrderResource(
            body=mock.sentinel.body, uri=mock.sentinel.uri)

    def test_to_partial_json(self):
        self.assertEqual(self.regr.to_json(), {
            'body': mock.sentinel.body,
            'uri': mock.sentinel.uri,
            'authorizations': None,
        })


class NewOrderTest(unittest.TestCase):
    """Tests for acme.messages.NewOrder."""

    def setUp(self):
        from acme.messages import NewOrder
        self.reg = NewOrder(
            identifiers=mock.sentinel.identifiers)

    def test_to_partial_json(self):
        self.assertEqual(self.reg.to_json(), {
            'identifiers': mock.sentinel.identifiers,
        })


class JWSPayloadRFC8555Compliant(unittest.TestCase):
    """Test for RFC8555 compliance of JWS generated from resources/challenges"""
    def test_message_payload(self):
        from acme.messages import NewAuthorization

        new_order = NewAuthorization()
        new_order.le_acme_version = 2

        jobj = new_order.json_dumps(indent=2).encode()
        # RFC8555 states that JWS bodies must not have a resource field.
        self.assertEqual(jobj, b'{}')


if __name__ == '__main__':
    unittest.main()  # pragma: no cover