File: test_validate.py

package info (click to toggle)
python-pyhanko-certvalidator 0.26.3-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,956 kB
  • sloc: python: 9,254; sh: 47; makefile: 4
file content (843 lines) | stat: -rw-r--r-- 27,102 bytes parent folder | download | duplicates (2)
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
# coding: utf-8

import json
import os
from dataclasses import dataclass, field
from datetime import datetime
from typing import Iterable, List, Optional, Type

import pytest
from asn1crypto import crl, ocsp, x509
from asn1crypto.util import timezone

from pyhanko_certvalidator import PKIXValidationParams
from pyhanko_certvalidator.authority import Authority, CertTrustAnchor
from pyhanko_certvalidator.context import ValidationContext
from pyhanko_certvalidator.errors import (
    CertificateFetchError,
    CRLFetchError,
    InsufficientRevinfoError,
    OCSPFetchError,
    OCSPValidationError,
    PathValidationError,
    RevokedError,
    StaleRevinfoError,
)
from pyhanko_certvalidator.fetchers import (
    CertificateFetcher,
    CRLFetcher,
    FetcherBackend,
    Fetchers,
    OCSPFetcher,
    aiohttp_fetchers,
    requests_fetchers,
)
from pyhanko_certvalidator.ltv.poe import POEManager
from pyhanko_certvalidator.path import QualifiedPolicy, ValidationPath
from pyhanko_certvalidator.policy_decl import (
    DisallowWeakAlgorithmsPolicy,
    NonRevokedStatusAssertion,
)
from pyhanko_certvalidator.registry import (
    CertificateRegistry,
    PathBuilder,
    SimpleTrustManager,
)
from pyhanko_certvalidator.revinfo.manager import RevinfoManager
from pyhanko_certvalidator.validate import async_validate_path, validate_path

from .common import (
    FIXTURES_DIR,
    load_cert_object,
    load_nist_cert,
    load_nist_crl,
    load_openssl_ors,
)
from .constants import TEST_REQUEST_TIMEOUT


class MockOCSPFetcher(OCSPFetcher):
    def fetched_responses(self) -> Iterable[ocsp.OCSPResponse]:
        return ()

    def fetched_responses_for_cert(
        self, cert: x509.Certificate
    ) -> Iterable[ocsp.OCSPResponse]:
        return ()

    async def fetch(self, cert: x509.Certificate, authority: Authority):
        raise OCSPFetchError("No connection")


class MockOCSPFetcherWithValidationError(MockOCSPFetcher):
    async def fetch(self, cert: x509.Certificate, authority: Authority):
        raise OCSPValidationError("Something went wrong")


class MockCRLFetcher(CRLFetcher):
    def fetched_crls_for_cert(
        self, cert: x509.Certificate
    ) -> Iterable[crl.CertificateList]:
        return ()

    def fetched_crls(self) -> Iterable[crl.CertificateList]:
        return ()

    async def fetch(self, cert: x509.Certificate, *, use_deltas=None):
        raise CRLFetchError("No connection")


class MockCertFetcher(CertificateFetcher):
    def fetched_certs(self) -> Iterable[x509.Certificate]:
        return ()

    def fetch_cert_issuers(self, cert):
        return self

    def fetch_crl_issuers(self, certificate_list):
        return self

    def __aiter__(self):
        raise CertificateFetchError("No connection")


class MockFetcherBackend(FetcherBackend):
    def get_fetchers(self) -> Fetchers:
        return Fetchers(
            ocsp_fetcher=MockOCSPFetcher(),
            crl_fetcher=MockCRLFetcher(),
            cert_fetcher=MockCertFetcher(),
        )


class MockFetcherBackendWithValidationError(FetcherBackend):
    def get_fetchers(self) -> Fetchers:
        return Fetchers(
            ocsp_fetcher=MockOCSPFetcherWithValidationError(),
            crl_fetcher=MockCRLFetcher(),
            cert_fetcher=MockCertFetcher(),
        )


ERR_CLASSES = {
    cls.__name__: cls
    for cls in (
        PathValidationError,
        RevokedError,
        InsufficientRevinfoError,
        StaleRevinfoError,
    )
}


@dataclass(frozen=True)
class PKITSTestCaseErrorResult:
    err_class: Type[Exception]
    msg_regex: str


def test_revocation_mode_soft():
    cert = load_cert_object(
        'digicert-ecc-p384-root-g5-revoked-chain-demos-digicert-com.crt'
    )
    ca_certs = [load_cert_object('digicert-root-g5.crt')]
    other_certs = [
        load_cert_object('digicert-g5-ecc-sha384-2021-ca1.crt'),
    ]

    context = ValidationContext(
        trust_roots=ca_certs,
        other_certs=other_certs,
        moment=datetime(2023, 1, 10, tzinfo=timezone.utc),
        allow_fetching=True,
        weak_hash_algos={'md2', 'md5'},
        fetcher_backend=MockFetcherBackend(),
    )
    paths = context.path_builder.build_paths(cert)
    assert 1 == len(paths)
    path = paths[0]
    assert 3 == len(path)

    validate_path(context, path)


def test_revocation_mode_soft_fail():
    cert = load_cert_object(
        'digicert-ecc-p384-root-g5-revoked-chain-demos-digicert-com.crt'
    )
    ca_certs = [load_cert_object('digicert-root-g5.crt')]
    other_certs = [
        load_cert_object('digicert-g5-ecc-sha384-2021-ca1.crt'),
    ]

    context = ValidationContext(
        trust_roots=ca_certs,
        other_certs=other_certs,
        moment=datetime(2023, 1, 10, tzinfo=timezone.utc),
        allow_fetching=True,
        weak_hash_algos={'md2', 'md5'},
        fetcher_backend=MockFetcherBackendWithValidationError(),
    )
    paths = context.path_builder.build_paths(cert)
    path = paths[0]

    with pytest.raises(InsufficientRevinfoError, match="Something went wrong"):
        validate_path(context, path)


@pytest.mark.skip("annoying to maintain; replace with certomancer test")
def test_revocation_mode_hard():
    cert = load_cert_object(
        'digicert-ecc-p384-root-g5-revoked-chain-demos-digicert-com.crt'
    )
    ca_certs = [load_cert_object('digicert-root-g5.crt')]
    other_certs = [
        load_cert_object('digicert-g5-ecc-sha384-2021-ca1.crt'),
    ]

    context = ValidationContext(
        trust_roots=ca_certs,
        other_certs=other_certs,
        allow_fetching=True,
        revocation_mode='hard-fail',
        weak_hash_algos={'md2', 'md5'},
        fetcher_backend=requests_fetchers.RequestsFetcherBackend(
            per_request_timeout=TEST_REQUEST_TIMEOUT
        ),
    )
    paths = context.path_builder.build_paths(cert)
    assert 1 == len(paths)
    path = paths[0]
    assert 3 == len(path)

    expected = (
        '(CRL|OCSP response) indicates the end-entity certificate was '
        'revoked at \\d\\d:\\d\\d:\\d\\d on \\d\\d\\d\\d-\\d\\d-\\d\\d'
        ', due to an unspecified reason'
    )
    with pytest.raises(RevokedError, match=expected):
        validate_path(context, path)


@pytest.mark.skip("annoying to maintain; replace with certomancer test")
@pytest.mark.asyncio
async def test_revocation_mode_hard_async():
    cert = load_cert_object(
        'digicert-ecc-p384-root-g5-revoked-chain-demos-digicert-com.crt'
    )
    ca_certs = [load_cert_object('digicert-root-g5.crt')]
    other_certs = [
        load_cert_object('digicert-g5-ecc-sha384-2021-ca1.crt'),
    ]
    fb = aiohttp_fetchers.AIOHttpFetcherBackend(
        per_request_timeout=TEST_REQUEST_TIMEOUT
    )
    async with fb as fetchers:
        context = ValidationContext(
            trust_roots=ca_certs,
            other_certs=other_certs,
            allow_fetching=True,
            revocation_mode='hard-fail',
            weak_hash_algos={'md2', 'md5'},
            fetchers=fetchers,
        )
        paths = await context.path_builder.async_build_paths(cert)
        assert 1 == len(paths)
        path = paths[0]
        assert 3 == len(path)

        expected = (
            '(CRL|OCSP response) indicates the end-entity certificate was '
            'revoked at \\d\\d:\\d\\d:\\d\\d on \\d\\d\\d\\d-\\d\\d-\\d\\d'
            ', due to an unspecified reason'
        )
        with pytest.raises(RevokedError, match=expected):
            await async_validate_path(context, path)


@pytest.mark.skip("annoying to maintain; replace with certomancer test")
@pytest.mark.asyncio
async def test_revocation_mode_hard_aiohttp_autofetch():
    cert = load_cert_object(
        'digicert-ecc-p384-root-g5-revoked-chain-demos-digicert-com.crt'
    )
    ca_certs = [load_cert_object('digicert-root-g5.crt')]

    fb = aiohttp_fetchers.AIOHttpFetcherBackend(
        per_request_timeout=TEST_REQUEST_TIMEOUT
    )
    async with fb as fetchers:
        context = ValidationContext(
            trust_roots=ca_certs,
            allow_fetching=True,
            revocation_mode='hard-fail',
            weak_hash_algos={'md2', 'md5'},
            fetchers=fetchers,
        )
        paths = await context.path_builder.async_build_paths(cert)
        assert 1 == len(paths)
        path = paths[0]
        assert 3 == len(path)

        expected = (
            '(CRL|OCSP response) indicates the end-entity certificate was '
            'revoked at \\d\\d:\\d\\d:\\d\\d on \\d\\d\\d\\d-\\d\\d-\\d\\d'
            ', due to an unspecified reason'
        )
        with pytest.raises(RevokedError, match=expected):
            await async_validate_path(context, path)


@pytest.mark.skip("annoying to maintain; replace with certomancer test")
@pytest.mark.asyncio
async def test_revocation_mode_hard_requests_autofetch():
    cert = load_cert_object(
        'digicert-ecc-p384-root-g5-revoked-chain-demos-digicert-com.crt'
    )
    ca_certs = [load_cert_object('digicert-root-g5.crt')]

    fb = requests_fetchers.RequestsFetcherBackend(
        per_request_timeout=TEST_REQUEST_TIMEOUT
    )
    async with fb as fetchers:
        context = ValidationContext(
            trust_roots=ca_certs,
            allow_fetching=True,
            revocation_mode='hard-fail',
            weak_hash_algos={'md2', 'md5'},
            fetchers=fetchers,
        )
        paths = await context.path_builder.async_build_paths(cert)
        assert 1 == len(paths)
        path = paths[0]
        assert 3 == len(path)

        expected = (
            '(CRL|OCSP response) indicates the end-entity certificate was '
            'revoked at \\d\\d:\\d\\d:\\d\\d on \\d\\d\\d\\d-\\d\\d-\\d\\d'
            ', due to an unspecified reason'
        )
        with pytest.raises(RevokedError, match=expected):
            await async_validate_path(context, path)


def test_rsassa_pss():
    cert = load_cert_object('testing-ca-pss', 'signer1.cert.pem')
    ca_certs = [load_cert_object('testing-ca-pss', 'root.cert.pem')]
    other_certs = [load_cert_object('testing-ca-pss', 'interm.cert.pem')]
    moment = datetime(2021, 5, 3, tzinfo=timezone.utc)
    context = ValidationContext(
        trust_roots=ca_certs,
        other_certs=other_certs,
        allow_fetching=False,
        moment=moment,
        revocation_mode='soft-fail',
        weak_hash_algos={'md2', 'md5'},
    )
    paths = context.path_builder.build_paths(cert)
    assert 1 == len(paths)
    path = paths[0]
    assert 3 == len(path)
    validate_path(context, path)


def test_rsassa_pss_exclusive():
    cert = load_cert_object('testing-ca-pss-exclusive', 'signer1.cert.pem')
    ca_certs = [load_cert_object('testing-ca-pss-exclusive', 'root.cert.pem')]
    other_certs = [
        load_cert_object('testing-ca-pss-exclusive', 'interm.cert.pem')
    ]
    moment = datetime(2021, 5, 3, tzinfo=timezone.utc)
    context = ValidationContext(
        trust_roots=ca_certs,
        other_certs=other_certs,
        allow_fetching=False,
        moment=moment,
        revocation_mode='soft-fail',
        weak_hash_algos={'md2', 'md5'},
    )
    paths = context.path_builder.build_paths(cert)
    assert 1 == len(paths)
    path = paths[0]
    assert 3 == len(path)
    validate_path(context, path)


def test_ed25519():
    cert = load_cert_object('testing-ca-ed25519', 'signer.cert.pem')
    ca_certs = [load_cert_object('testing-ca-ed25519', 'root.cert.pem')]
    other_certs = [load_cert_object('testing-ca-ed25519', 'interm.cert.pem')]
    context = ValidationContext(
        trust_roots=ca_certs,
        other_certs=other_certs,
        allow_fetching=False,
        revocation_mode='soft-fail',
        weak_hash_algos={'md2', 'md5'},
        moment=datetime(2020, 11, 1, tzinfo=timezone.utc),
    )
    paths = context.path_builder.build_paths(cert)
    assert 1 == len(paths)
    path = paths[0]
    assert 3 == len(path)
    validate_path(context, path)


def test_ed448():
    cert = load_cert_object('testing-ca-ed448', 'signer.cert.pem')
    ca_certs = [load_cert_object('testing-ca-ed448', 'root.cert.pem')]
    other_certs = [load_cert_object('testing-ca-ed448', 'interm.cert.pem')]
    context = ValidationContext(
        trust_roots=ca_certs,
        other_certs=other_certs,
        allow_fetching=False,
        revocation_mode='soft-fail',
        weak_hash_algos={'md2', 'md5'},
        moment=datetime(2020, 11, 1, tzinfo=timezone.utc),
    )
    paths = context.path_builder.build_paths(cert)
    assert 1 == len(paths)
    path = paths[0]
    assert 3 == len(path)
    validate_path(context, path)


def test_assert_no_revinfo_needed_by_fiat():
    cert = load_cert_object('testing-ca-pss', 'signer1.cert.pem')
    ca_certs = [load_cert_object('testing-ca-pss', 'root.cert.pem')]
    other_certs = [load_cert_object('testing-ca-pss', 'interm.cert.pem')]
    moment = datetime(2021, 5, 3, tzinfo=timezone.utc)
    assertion = NonRevokedStatusAssertion(cert.sha256, moment)
    revinfo_manager = RevinfoManager(
        certificate_registry=CertificateRegistry.build(),
        poe_manager=POEManager(),
        crls=(),
        ocsps=(),
        assertions=(assertion,),
    )
    context = ValidationContext(
        trust_roots=ca_certs,
        other_certs=other_certs,
        allow_fetching=False,
        moment=moment,
        revocation_mode='require',  # turn on strict revinfovalidation
        revinfo_manager=revinfo_manager,
    )
    paths = context.path_builder.build_paths(cert)
    assert 1 == len(paths)
    path = paths[0]
    assert 3 == len(path)
    validate_path(context, path)


def test_multitasking_ocsp():
    # regression test for case where the same responder ID (name + key ID)
    # is used in OCSP responses for different issuers in the same chain of
    # trust

    ors_dir = os.path.join(FIXTURES_DIR, 'multitasking-ocsp')
    with open(os.path.join(ors_dir, 'ocsp-resp-alice.der'), 'rb') as ocspin:
        ocsp_resp_alice = ocsp.OCSPResponse.load(ocspin.read())
    with open(os.path.join(ors_dir, 'ocsp-resp-interm.der'), 'rb') as ocspin:
        ocsp_resp_interm = ocsp.OCSPResponse.load(ocspin.read())
    vc = ValidationContext(
        trust_roots=[
            load_cert_object('multitasking-ocsp', 'root.cert.pem'),
        ],
        other_certs=[load_cert_object('multitasking-ocsp', 'interm.cert.pem')],
        revocation_mode='hard-fail',
        allow_fetching=False,
        ocsps=[ocsp_resp_interm, ocsp_resp_alice],
        moment=datetime(2021, 8, 19, 12, 20, 44, tzinfo=timezone.utc),
    )

    cert = load_cert_object('multitasking-ocsp', 'alice.cert.pem')
    paths = vc.path_builder.build_paths(cert)
    assert 1 == len(paths)
    path = paths[0]
    assert 3 == len(path)
    validate_path(vc, path)


@dataclass(frozen=True)
class OCSPTestCase:
    name: str
    roots: List[x509.Certificate]
    cert: x509.Certificate
    ocsps: List[ocsp.OCSPResponse]
    path_len: int
    moment: datetime
    other_certs: List[x509.Certificate] = field(default_factory=list)
    expected_error: Optional[PKITSTestCaseErrorResult] = None

    @classmethod
    def from_json(cls, obj: dict):
        roots = [load_cert_object('openssl-ocsp', obj['root'])]
        kwargs = dict(
            name=obj['name'],
            cert=load_cert_object('openssl-ocsp', obj['cert']),
            path_len=int(obj['path_len']),
            moment=datetime.fromisoformat(obj['moment']),
            roots=roots,
        )
        kwargs['ocsps'] = [
            load_openssl_ors(filename) for filename in obj['ocsps']
        ]
        if 'other_certs' in obj:
            kwargs['other_certs'] = [
                load_cert_object('openssl-ocsp', filename)
                for filename in obj['other_certs']
            ]
        if 'error' in obj:
            kwargs['expected_error'] = PKITSTestCaseErrorResult(
                ERR_CLASSES[obj['error']['class']], obj['error']['msg_regex']
            )

        return OCSPTestCase(**kwargs)


def read_openssl_ocsp_test_params():
    data_path = os.path.join(FIXTURES_DIR, 'openssl-ocsp', 'openssl-ocsp.json')
    with open(data_path, 'r') as inf:
        cases = json.load(inf)
    return [OCSPTestCase.from_json(obj) for obj in cases]


@pytest.mark.parametrize(
    "test_case", read_openssl_ocsp_test_params(), ids=lambda case: case.name
)
def test_openssl_ocsp(test_case: OCSPTestCase):
    context = ValidationContext(
        trust_roots=test_case.roots,
        other_certs=test_case.other_certs,
        moment=test_case.moment,
        ocsps=test_case.ocsps,
        weak_hash_algos={'md2', 'md5'},
    )
    paths = context.path_builder.build_paths(test_case.cert)
    assert 1 == len(paths)
    path = paths[0]
    assert test_case.path_len == len(path)

    err = test_case.expected_error
    if err:
        with pytest.raises(err.err_class, match=err.msg_regex):
            validate_path(context, path)
    else:
        validate_path(context, path)


def parse_pkix_params(obj: dict):
    kwargs = {}
    if 'user_initial_policy_set' in obj:
        kwargs['user_initial_policy_set'] = frozenset(
            obj['user_initial_policy_set']
        )
    kwargs['initial_policy_mapping_inhibit'] = bool(
        obj.get('initial_policy_mapping_inhibit', False)
    )
    kwargs['initial_explicit_policy'] = bool(
        obj.get('initial_explicit_policy', False)
    )
    kwargs['initial_any_policy_inhibit'] = bool(
        obj.get('initial_any_policy_inhibit', False)
    )
    return PKIXValidationParams(**kwargs)


@dataclass(frozen=True)
class CannedTestInfo:
    test_id: int
    test_name: str

    def __str__(self):
        return f"{self.test_id} ({self.test_name})"


@dataclass(frozen=True)
class PKITSTestCase:
    test_info: CannedTestInfo
    cert: x509.Certificate
    roots: List[x509.Certificate]
    crls: List[crl.CertificateList]
    path_len: int
    path: Optional[ValidationPath] = None
    check_revocation: bool = True
    other_certs: List[x509.Certificate] = field(default_factory=list)
    expected_error: Optional[PKITSTestCaseErrorResult] = None
    pkix_params: Optional[PKIXValidationParams] = None

    @classmethod
    def from_json(cls, obj: dict):
        root = load_nist_cert('TrustAnchorRootCertificate.crt')
        crls = [load_nist_crl('TrustAnchorRootCRL.crl')]
        if 'crls' in obj:
            crls.extend(load_nist_crl(crl_path) for crl_path in obj['crls'])
        cert = load_nist_cert(obj['cert'])
        kwargs = dict(
            test_info=CannedTestInfo(
                test_id=int(obj['id']),
                test_name=obj['name'],
            ),
            cert=cert,
            path_len=int(obj['path_len']),
            check_revocation=bool(obj.get('revocation', True)),
            roots=[root],
            crls=crls,
        )

        kwargs['crls'] = crls
        if 'other_certs' in obj:
            kwargs['other_certs'] = [
                load_nist_cert(cert_path) for cert_path in obj['other_certs']
            ]
        if 'path_intermediates' in obj:
            # -> prebuild the path as indicated in the test spec
            kwargs['path'] = ValidationPath(
                trust_anchor=CertTrustAnchor(root),
                interm=(
                    load_nist_cert(cert_path)
                    for cert_path in obj['path_intermediates']
                ),
                leaf=cert,
            )
        if 'params' in obj:
            kwargs['pkix_params'] = parse_pkix_params(obj['params'])
        if 'error' in obj:
            kwargs['expected_error'] = PKITSTestCaseErrorResult(
                ERR_CLASSES[obj['error']['class']], obj['error']['msg_regex']
            )

        return PKITSTestCase(**kwargs)


def read_pkits_test_params():
    data_path = os.path.join(FIXTURES_DIR, 'nist_pkits', 'pkits.json')
    with open(data_path, 'r') as inf:
        cases = json.load(inf)
    return [PKITSTestCase.from_json(obj) for obj in cases]


@pytest.mark.parametrize(
    'test_case', read_pkits_test_params(), ids=lambda case: str(case.test_info)
)
def test_nist_pkits(test_case: PKITSTestCase):
    revocation_mode = "require" if test_case.check_revocation else "hard-fail"

    context = ValidationContext(
        trust_roots=test_case.roots,
        other_certs=test_case.other_certs,
        crls=test_case.crls,
        revocation_mode=revocation_mode,
        # adjust default algo policy to pass NIST tests
        algorithm_usage_policy=DisallowWeakAlgorithmsPolicy(
            weak_hash_algos={'md2', 'md5'}, dsa_key_size_threshold=1024
        ),
    )

    if test_case.path is None:
        paths = context.path_builder.build_paths(test_case.cert)
        assert 1 == len(paths)
        path: ValidationPath = paths[0]
    else:
        path = test_case.path

    assert test_case.path_len == len(path)

    err = test_case.expected_error
    params = test_case.pkix_params
    if err is not None:
        with pytest.raises(err.err_class, match=err.msg_regex):
            validate_path(context, path, parameters=params)
    else:
        validate_path(context, path, parameters=params)

        # sanity check
        if params is not None and params.user_initial_policy_set != {
            'any_policy'
        }:
            qps = path.qualified_policies()
            if qps is not None:
                for pol in qps:
                    assert (
                        pol.user_domain_policy_id
                        in params.user_initial_policy_set
                    )


@dataclass(frozen=True)
class PKITSUserNoticeTestCase:
    test_info: CannedTestInfo
    cert: x509.Certificate
    roots: List[x509.Certificate]
    crls: List[crl.CertificateList]
    notice: str
    other_certs: List[x509.Certificate] = field(default_factory=list)
    pkix_params: Optional[PKIXValidationParams] = None

    @classmethod
    def from_json(cls, obj: dict):
        roots = [load_nist_cert('TrustAnchorRootCertificate.crt')]
        crls = [load_nist_crl('TrustAnchorRootCRL.crl')]
        if 'crls' in obj:
            crls.extend(load_nist_crl(crl_path) for crl_path in obj['crls'])
        kwargs = dict(
            test_info=CannedTestInfo(
                test_id=int(obj['id']),
                test_name=obj['name'],
            ),
            cert=load_nist_cert(obj['cert']),
            roots=roots,
            crls=crls,
            notice=obj['notice'],
        )

        kwargs['crls'] = crls
        if 'other_certs' in obj:
            kwargs['other_certs'] = [
                load_nist_cert(cert_path) for cert_path in obj['other_certs']
            ]
        if 'params' in obj:
            kwargs['pkix_params'] = parse_pkix_params(obj['params'])

        return PKITSUserNoticeTestCase(**kwargs)


def read_pkits_user_notice_test_params():
    data_path = os.path.join(
        FIXTURES_DIR, 'nist_pkits', 'pkits-user-notice.json'
    )
    with open(data_path, 'r') as inf:
        cases = json.load(inf)
    return [PKITSUserNoticeTestCase.from_json(obj) for obj in cases]


@pytest.mark.parametrize(
    'test_case',
    read_pkits_user_notice_test_params(),
    ids=lambda case: str(case.test_info),
)
def test_nist_pkits_user_notice(test_case: PKITSUserNoticeTestCase):
    context = ValidationContext(
        trust_roots=test_case.roots,
        other_certs=test_case.other_certs,
        crls=test_case.crls,
        revocation_mode="require",
        weak_hash_algos={'md2', 'md5'},
    )

    paths = context.path_builder.build_paths(test_case.cert)
    assert 1 == len(paths)
    path: ValidationPath = paths[0]
    validate_path(context, path, parameters=test_case.pkix_params)

    qps = path.qualified_policies()
    assert 1 == len(qps)

    qp: QualifiedPolicy
    (qp,) = qps
    assert 1 == len(qp.qualifiers)
    (qual_obj,) = qp.qualifiers
    assert qual_obj['policy_qualifier_id'].native == 'user_notice'
    assert qual_obj['qualifier']['explicit_text'].native == test_case.notice


def test_408020_cps_pointer_qualifier_test20():
    cert = load_nist_cert('CPSPointerQualifierTest20EE.crt')
    ca_certs = [load_nist_cert('TrustAnchorRootCertificate.crt')]
    other_certs = [load_nist_cert('GoodCACert.crt')]
    crls = [
        load_nist_crl('GoodCACRL.crl'),
        load_nist_crl('TrustAnchorRootCRL.crl'),
    ]

    context = ValidationContext(
        trust_roots=ca_certs,
        other_certs=other_certs,
        crls=crls,
        revocation_mode="require",
        weak_hash_algos={'md2', 'md5'},
    )

    paths = context.path_builder.build_paths(cert)
    assert 1 == len(paths)
    path: ValidationPath = paths[0]
    validate_path(context, path)

    qps = path.qualified_policies()
    assert 1 == len(qps)

    qp: QualifiedPolicy
    (qp,) = qps
    assert 1 == len(qp.qualifiers)
    (qual_obj,) = qp.qualifiers
    assert (
        qual_obj['policy_qualifier_id'].native
        == 'certification_practice_statement'
    )
    assert qual_obj['qualifier'].native == (
        'http://csrc.nist.gov/groups/ST/crypto_apps_infra/csor/'
        'pki_registration.html#PKITest'
    )


class MockRequestsCertificateFetcher(
    requests_fetchers.RequestsCertificateFetcher
):
    def __init__(self, *args, order, **kwargs):
        super().__init__(*args, **kwargs)
        self.order = order

    async def fetch_certs(self, *args, **kwargs) -> Iterable[x509.Certificate]:
        root_ca = load_cert_object('testing-aia', 'brazilian_root_ca_v5')
        middle_ca = load_cert_object('testing-aia', 'ca_brazilian_fro_v4')
        end_ca = load_cert_object('testing-aia', 'ca_serprorfbv5')
        certs = {'root': root_ca, 'middle': middle_ca, 'end': end_ca}

        return [
            certs[self.order[0]],
            certs[self.order[1]],
            certs[self.order[2]],
        ]


@pytest.mark.parametrize(
    'cert_order',
    [
        ('root', 'middle', 'end'),
        ('root', 'end', 'middle'),
        ('middle', 'root', 'end'),
        ('middle', 'end', 'root'),
        ('root', 'end', 'middle'),
        ('root', 'middle', 'end'),
    ],
)
@pytest.mark.asyncio
async def test_building_trust_path_with_pkcs7_in_different_orders(cert_order):
    trust_path = [
        'Autoridade Certificadora Raiz Brasileira v5',
        'AC Secretaria da Receita Federal do Brasil v4',
        'Autoridade Certificadora SERPRORFBv5',
    ]

    serpro_root = load_cert_object('testing-aia', 'brazilian_root_ca_v5')

    trust_manager = SimpleTrustManager.build(
        extra_trust_roots=[serpro_root],
    )
    cert = load_cert_object('testing-aia', 'repositorio.serpro.gov.br')
    registry = CertificateRegistry.build(
        certs=(cert,),
        cert_fetcher=MockRequestsCertificateFetcher(order=cert_order),
    )
    builder = PathBuilder(trust_manager=trust_manager, registry=registry)
    paths = await builder.async_build_paths(end_entity_cert=cert)

    paths_common_name = [
        [
            authority.name.native['common_name']
            for authority in path.iter_authorities()
        ]
        for path in paths
    ]

    assert trust_path in paths_common_name