Skip to content

Commit 046670b

Browse files
Apply Black
1 parent a7fe48e commit 046670b

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

44 files changed

+2954
-2134
lines changed

Diff for: .github/workflows/lint.yml

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
name: Lint
2+
3+
on: ["push", "pull_request"]
4+
5+
jobs:
6+
lint:
7+
runs-on: ubuntu-latest
8+
steps:
9+
- uses: actions/checkout@v2
10+
- uses: actions/setup-python@v2
11+
- run: pip install isort black
12+
- name: Check import order
13+
run: isort --profile black --line-length 80 --check pyhanko_certvalidator tests
14+
- name: Run Black
15+
run: black -S --line-length 80 --check pyhanko_certvalidator tests

Diff for: pyhanko_certvalidator/__init__.py

+35-26
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,23 @@
11
import asyncio
22
import warnings
3-
from typing import Optional, Iterable
3+
from typing import Iterable, Optional
44

55
from asn1crypto import x509
66

7+
from ._types import type_name
78
from .context import ValidationContext
9+
from .errors import InvalidCertificateError, PathBuildingError, ValidationError
810
from .policy_decl import PKIXValidationParams
9-
from .errors import ValidationError, PathBuildingError, InvalidCertificateError
11+
from .util import pretty_message
1012
from .validate import async_validate_path, validate_tls_hostname, validate_usage
1113
from .version import __version__, __version_info__
12-
from .util import pretty_message
13-
from ._types import type_name
14-
1514

1615
__all__ = [
1716
'__version__',
1817
'__version_info__',
1918
'CertificateValidator',
2019
'ValidationContext',
21-
'PKIXValidationParams'
20+
'PKIXValidationParams',
2221
]
2322

2423

@@ -37,11 +36,12 @@ class CertificateValidator:
3736
_params = None
3837

3938
def __init__(
40-
self,
41-
end_entity_cert: x509.Certificate,
42-
intermediate_certs: Optional[Iterable[x509.Certificate]] = None,
43-
validation_context: Optional[ValidationContext] = None,
44-
pkix_params: PKIXValidationParams = None):
39+
self,
40+
end_entity_cert: x509.Certificate,
41+
intermediate_certs: Optional[Iterable[x509.Certificate]] = None,
42+
validation_context: Optional[ValidationContext] = None,
43+
pkix_params: PKIXValidationParams = None,
44+
):
4545
"""
4646
:param end_entity_cert:
4747
An asn1crypto.x509.Certificate object X.509 end-entity
@@ -100,31 +100,37 @@ async def _validate_path(self):
100100
exceptions = []
101101

102102
if self._certificate.hash_algo in self._context.weak_hash_algos:
103-
raise InvalidCertificateError(pretty_message(
104-
'''
103+
raise InvalidCertificateError(
104+
pretty_message(
105+
'''
105106
The X.509 certificate provided has a signature using the weak
106107
hash algorithm %s
107108
''',
108-
self._certificate.hash_algo
109-
))
109+
self._certificate.hash_algo,
110+
)
111+
)
110112

111113
try:
112114
paths = await self._context.path_builder.async_build_paths(
113115
self._certificate
114116
)
115117
except PathBuildingError:
116118
if self._certificate.self_signed in {'yes', 'maybe'}:
117-
raise InvalidCertificateError(pretty_message(
118-
'''
119+
raise InvalidCertificateError(
120+
pretty_message(
121+
'''
119122
The X.509 certificate provided is self-signed - "%s"
120123
''',
121-
self._certificate.subject.human_friendly
122-
))
124+
self._certificate.subject.human_friendly,
125+
)
126+
)
123127
raise
124128

125129
for candidate_path in paths:
126130
try:
127-
await async_validate_path(self._context, candidate_path, self._params)
131+
await async_validate_path(
132+
self._context, candidate_path, self._params
133+
)
128134
self._path = candidate_path
129135
return
130136
except ValidationError as e:
@@ -143,7 +149,9 @@ async def _validate_path(self):
143149

144150
raise exceptions[0]
145151

146-
def validate_usage(self, key_usage, extended_key_usage=None, extended_optional=False):
152+
def validate_usage(
153+
self, key_usage, extended_key_usage=None, extended_optional=False
154+
):
147155
"""
148156
Validates the certificate path and that the certificate is valid for
149157
the key usage and extended key usage purposes specified.
@@ -202,7 +210,7 @@ def validate_usage(self, key_usage, extended_key_usage=None, extended_optional=F
202210
warnings.warn(
203211
"'validate_usage' is deprecated, use "
204212
"'async_validate_usage' instead",
205-
DeprecationWarning
213+
DeprecationWarning,
206214
)
207215

208216
return asyncio.run(
@@ -211,8 +219,9 @@ def validate_usage(self, key_usage, extended_key_usage=None, extended_optional=F
211219
)
212220
)
213221

214-
async def async_validate_usage(self, key_usage, extended_key_usage=None,
215-
extended_optional=False):
222+
async def async_validate_usage(
223+
self, key_usage, extended_key_usage=None, extended_optional=False
224+
):
216225
"""
217226
Validates the certificate path and that the certificate is valid for
218227
the key usage and extended key usage purposes specified.
@@ -271,7 +280,7 @@ async def async_validate_usage(self, key_usage, extended_key_usage=None,
271280
self._certificate,
272281
key_usage,
273282
extended_key_usage,
274-
extended_optional
283+
extended_optional,
275284
)
276285
return self._path
277286

@@ -299,7 +308,7 @@ def validate_tls(self, hostname):
299308

300309
warnings.warn(
301310
"'validate_tls' is deprecated, use 'async_validate_tls' instead",
302-
DeprecationWarning
311+
DeprecationWarning,
303312
)
304313

305314
return asyncio.run(self.async_validate_tls(hostname))

Diff for: pyhanko_certvalidator/_asyncio_compat.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
1+
import asyncio
12
import contextvars
23
import functools
3-
import asyncio
4-
54

65
# Used as an alternative for asyncio.to_thread in python <=3.8
76
# Repurposed from CPython, used under the terms of the PSL

Diff for: pyhanko_certvalidator/_state.py

+11-8
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,13 @@
88

99
@dataclass
1010
class ValProcState:
11-
12-
def __init__(self, *, cert_path_stack: ConsList,
13-
ee_name_override: Optional[str] = None,
14-
is_side_validation: bool = False):
11+
def __init__(
12+
self,
13+
*,
14+
cert_path_stack: ConsList,
15+
ee_name_override: Optional[str] = None,
16+
is_side_validation: bool = False,
17+
):
1518
if cert_path_stack.head is None:
1619
raise ValueError("Empty path stack")
1720
self.index: int = 0
@@ -29,6 +32,7 @@ def path_len(self):
2932
the root doesn't count.
3033
"""
3134
from pyhanko_certvalidator.path import ValidationPath
35+
3236
path = self.cert_path_stack.head
3337
assert isinstance(path, ValidationPath)
3438
return path.pkix_len
@@ -45,6 +49,7 @@ def check_path_verif_recursion(self, ee_cert: x509.Certificate):
4549
which could cause a naive implementation to recurse.
4650
"""
4751
from pyhanko_certvalidator.path import ValidationPath
52+
4853
path: ValidationPath
4954
for path in self.cert_path_stack:
5055
cert = path.get_ee_cert_safe()
@@ -65,14 +70,12 @@ def describe_cert(self, def_interm=False, never_def=False):
6570
result = "certificate"
6671
elif not self.is_ee_cert:
6772
prefix &= def_interm
68-
result = (
69-
f'intermediate certificate {self.index}'
70-
)
73+
result = f'intermediate certificate {self.index}'
7174
elif self.ee_name_override is not None:
7275
result = self.ee_name_override
7376
else:
7477
result = 'end-entity certificate'
7578
if prefix:
7679
return "the " + result
7780
else:
78-
return result
81+
return result

Diff for: pyhanko_certvalidator/asn1_types.py

+13-8
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,30 @@
11
from typing import Optional
22

3-
from asn1crypto import core, x509, cms
3+
from asn1crypto import cms, core, x509
44

55
__all__ = [
6-
'Target', 'TargetCert', 'Targets', 'SequenceOfTargets',
7-
'AttrSpec', 'AAControls'
6+
'Target',
7+
'TargetCert',
8+
'Targets',
9+
'SequenceOfTargets',
10+
'AttrSpec',
11+
'AAControls',
812
]
913

1014

1115
class TargetCert(core.Sequence):
1216
_fields = [
1317
('target_certificate', cms.IssuerSerial),
1418
('target_name', x509.GeneralName, {'optional': True}),
15-
('cert_digest_info', cms.ObjectDigestInfo, {'optional': True})
19+
('cert_digest_info', cms.ObjectDigestInfo, {'optional': True}),
1620
]
1721

1822

1923
class Target(core.Choice):
2024
_alternatives = [
2125
('target_name', x509.GeneralName, {'explicit': 0}),
2226
('target_group', x509.GeneralName, {'explicit': 1}),
23-
('target_cert', TargetCert, {'explicit': 2})
27+
('target_cert', TargetCert, {'explicit': 2}),
2428
]
2529

2630

@@ -42,7 +46,7 @@ class AAControls(core.Sequence):
4246
('path_len_constraint', core.Integer, {'optional': True}),
4347
('permitted_attrs', AttrSpec, {'optional': True, 'implicit': 0}),
4448
('excluded_attrs', AttrSpec, {'optional': True, 'implicit': 1}),
45-
('permit_unspecified', core.Boolean, {'default': True})
49+
('permit_unspecified', core.Boolean, {'default': True}),
4650
]
4751

4852
def accept(self, attr_id: cms.AttCertAttributeType) -> bool:
@@ -60,8 +64,9 @@ def accept(self, attr_id: cms.AttCertAttributeType) -> bool:
6064
return bool(self['permit_unspecified'])
6165

6266
@classmethod
63-
def read_extension_value(cls, cert: x509.Certificate) \
64-
-> Optional['AAControls']:
67+
def read_extension_value(
68+
cls, cert: x509.Certificate
69+
) -> Optional['AAControls']:
6570
# handle AA controls (not natively supported by asn1crypto, so
6671
# not available as an attribute).
6772
try:

Diff for: pyhanko_certvalidator/authority.py

+20-13
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,14 @@
22
from dataclasses import dataclass
33
from typing import Optional
44

5-
from asn1crypto import x509, keys
5+
from asn1crypto import keys, x509
66

77
from .name_trees import process_general_subtrees
88
from .policy_decl import PKIXValidationParams
99

10-
1110
# TODO add support for roots that are limited in time?
1211

12+
1313
@dataclass(frozen=True)
1414
class TrustQualifiers:
1515
"""
@@ -103,8 +103,9 @@ class TrustAnchor:
103103
Equality of trust roots reduces to equality of authorities.
104104
"""
105105

106-
def __init__(self, authority: Authority,
107-
quals: Optional[TrustQualifiers] = None):
106+
def __init__(
107+
self, authority: Authority, quals: Optional[TrustQualifiers] = None
108+
):
108109
self._authority = authority
109110
self._quals = quals
110111

@@ -120,8 +121,10 @@ def trust_qualifiers(self) -> TrustQualifiers:
120121
return self._quals or TrustQualifiers()
121122

122123
def __eq__(self, other):
123-
return isinstance(other, TrustAnchor) \
124-
and other._authority == self._authority
124+
return (
125+
isinstance(other, TrustAnchor)
126+
and other._authority == self._authority
127+
)
125128

126129
def __hash__(self):
127130
return hash(self._authority)
@@ -162,9 +165,9 @@ def derive_quals_from_cert(cert: x509.Certificate) -> TrustQualifiers:
162165
if cert.certificate_policies_value is not None:
163166
ext_found = True
164167
policies_val: x509.CertificatePolicies = cert.certificate_policies_value
165-
acceptable_policies = frozenset([
166-
pol_info['policy_identifier'].dotted for pol_info in policies_val
167-
])
168+
acceptable_policies = frozenset(
169+
[pol_info['policy_identifier'].dotted for pol_info in policies_val]
170+
)
168171

169172
params = None
170173
if ext_found:
@@ -176,7 +179,7 @@ def derive_quals_from_cert(cert: x509.Certificate) -> TrustQualifiers:
176179
# let's assume that they want the policies to be enforced.
177180
initial_explicit_policy=acceptable_policies is not None,
178181
initial_permitted_subtrees=permitted_subtrees,
179-
initial_excluded_subtrees=excluded_subtrees
182+
initial_excluded_subtrees=excluded_subtrees,
180183
)
181184

182185
return TrustQualifiers(
@@ -191,6 +194,7 @@ class AuthorityWithCert(Authority):
191194
:param cert:
192195
The certificate.
193196
"""
197+
194198
def __init__(self, cert: x509.Certificate):
195199
self._cert = cert
196200

@@ -237,9 +241,12 @@ class CertTrustAnchor(TrustAnchor):
237241
content if explicit ones are not provided. Defaults to ``False``.
238242
"""
239243

240-
def __init__(self, cert: x509.Certificate,
241-
quals: Optional[TrustQualifiers] = None,
242-
derive_default_quals_from_cert: bool = False):
244+
def __init__(
245+
self,
246+
cert: x509.Certificate,
247+
quals: Optional[TrustQualifiers] = None,
248+
derive_default_quals_from_cert: bool = False,
249+
):
243250
authority = AuthorityWithCert(cert)
244251
self._cert = cert
245252
super().__init__(authority, quals)

0 commit comments

Comments
 (0)