Skip to content

Commit

Permalink
Typing fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
kislyuk committed Aug 11, 2024
1 parent 3f9f009 commit 45b93bc
Show file tree
Hide file tree
Showing 6 changed files with 35 additions and 30 deletions.
4 changes: 2 additions & 2 deletions signxml/algorithms.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ class SignatureConstructionMethod(Enum):
class FragmentLookupMixin:
@classmethod
def from_fragment(cls, fragment):
for i in cls: # type: ignore
for i in cls: # type: ignore[attr-defined]
if i.value.endswith("#" + fragment):
return i
else:
Expand All @@ -50,7 +50,7 @@ def _missing_(cls, value):
raise InvalidInput(f"Unrecognized {cls.__name__}: {value}")

def __repr__(self):
return f"{self.__class__.__name__}.{self.name}" # type: ignore
return f"{self.__class__.__name__}.{self.name}" # type: ignore[attr-defined]


class DigestAlgorithm(FragmentLookupMixin, InvalidInputErrorMixin, Enum):
Expand Down
2 changes: 1 addition & 1 deletion signxml/processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ class XMLSignatureProcessor(XMLProcessor):
"urn:oid:1.3.132.0.37": ec.SECT409R1,
"urn:oid:1.3.132.0.38": ec.SECT571K1,
}
known_ecdsa_curve_oids = {ec().name: oid for oid, ec in known_ecdsa_curves.items()} # type: ignore
known_ecdsa_curve_oids = {ec().name: oid for oid, ec in known_ecdsa_curves.items()} # type: ignore[abstract]

excise_empty_xmlns_declarations = False

Expand Down
9 changes: 5 additions & 4 deletions signxml/signer.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ def sign(
if len(cert_chain) == 0:
raise InvalidInput("No PEM-encoded certificates found in string cert input data")
else:
cert_chain = cert # type: ignore
cert_chain = cert # type:ignore[assignment]

input_references = self._preprocess_reference_uri(reference_uri)

Expand Down Expand Up @@ -244,7 +244,7 @@ def sign(
signed_info_node, algorithm=self.c14n_alg, inclusive_ns_prefixes=inclusive_ns_prefixes
)
if self.sign_alg.name.startswith("HMAC_"):
signer = HMAC(key=key, algorithm=digest_algorithm_implementations[self.sign_alg]()) # type: ignore
signer = HMAC(key=key, algorithm=digest_algorithm_implementations[self.sign_alg]()) # type:ignore[arg-type]
signer.update(signed_info_c14n)
signature_value_node.text = b64encode(signer.finalize()).decode()
sig_root.append(signature_value_node)
Expand Down Expand Up @@ -378,14 +378,15 @@ def _unpack(self, data, references: List[SignatureReference]):
return sig_root, doc_root, c14n_inputs, references

def _build_transforms_for_reference(self, *, transforms_node: _Element, reference: SignatureReference):
assert reference.c14n_method is not None
if self.construction_method == SignatureConstructionMethod.enveloped:
SubElement(transforms_node, ds_tag("Transform"), Algorithm=SignatureConstructionMethod.enveloped.value)
SubElement(transforms_node, ds_tag("Transform"), Algorithm=reference.c14n_method.value) # type: ignore
SubElement(transforms_node, ds_tag("Transform"), Algorithm=reference.c14n_method.value)
else:
c14n_xform = SubElement(
transforms_node,
ds_tag("Transform"),
Algorithm=reference.c14n_method.value, # type: ignore
Algorithm=reference.c14n_method.value,
)
if reference.inclusive_ns_prefixes:
SubElement(
Expand Down
8 changes: 4 additions & 4 deletions signxml/util/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,10 +152,10 @@ def bits_to_bytes_unit(num_of_bits):


def strip_pem_header(cert):
try:
return re.search(pem_regexp, ensure_str(cert)).group(1).replace("\r", "") # type: ignore
except Exception:
return ensure_str(cert).replace("\r", "")
search_res = re.search(pem_regexp, ensure_str(cert))
if search_res:
return search_res.group(1).replace("\r", "")
return ensure_str(cert).replace("\r", "")


def add_pem_header(bare_base64_cert):
Expand Down
31 changes: 17 additions & 14 deletions signxml/verifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
SignatureMethod,
digest_algorithm_implementations,
)
from .exceptions import InvalidCertificate, InvalidDigest, InvalidInput, InvalidSignature
from .exceptions import InvalidCertificate, InvalidDigest, InvalidInput, InvalidSignature, SignXMLException
from .processor import XMLSignatureProcessor
from .util import (
X509CertChainVerifier,
Expand Down Expand Up @@ -124,7 +124,8 @@ def _verify_signature_with_pubkey(
signing_certificate: Optional[x509.Certificate] = None,
) -> None:
if der_encoded_key_value is not None:
key = load_der_public_key(b64decode(der_encoded_key_value.text)) # type: ignore
assert der_encoded_key_value.text is not None
key = load_der_public_key(b64decode(der_encoded_key_value.text))
elif signing_certificate is not None:
key = signing_certificate.public_key()
elif key_value is None:
Expand All @@ -140,7 +141,7 @@ def _verify_signature_with_pubkey(
x = bytes_to_long(key_data[: len(key_data) // 2])
y = bytes_to_long(key_data[len(key_data) // 2 :])
curve_class = self.known_ecdsa_curves[named_curve.get("URI")]
ecpn = ec.EllipticCurvePublicNumbers(x=x, y=y, curve=curve_class()) # type: ignore
ecpn = ec.EllipticCurvePublicNumbers(x=x, y=y, curve=curve_class()) # type: ignore[abstract]
key = ecpn.public_key()
elif not isinstance(key, ec.EllipticCurvePublicKey):
raise InvalidInput("DER encoded key value does not match specified signature algorithm")
Expand All @@ -154,7 +155,7 @@ def _verify_signature_with_pubkey(
g = self._get_long(dsa_key_value, "G", require=False)
y = self._get_long(dsa_key_value, "Y")
dsapn = dsa.DSAPublicNumbers(y=y, parameter_numbers=dsa.DSAParameterNumbers(p=p, q=q, g=g))
key = dsapn.public_key() # type: ignore
key = dsapn.public_key()
elif not isinstance(key, dsa.DSAPublicKey):
raise InvalidInput("DER encoded key value does not match specified signature algorithm")
# TODO: supply meaningful key_size_bits for signature length assertion
Expand Down Expand Up @@ -505,7 +506,9 @@ def validate_schema(self, signature):
return
except Exception as e:
last_exception = e
raise last_exception # type: ignore
if last_exception is not None:
raise last_exception
raise SignXMLException("Invalid state")

def _check_key_value_matches_cert_public_key(self, key_value, public_key, signature_alg: SignatureMethod):
if signature_alg.name.startswith("ECDSA_") and isinstance(public_key, ec.EllipticCurvePublicKey):
Expand All @@ -529,9 +532,9 @@ def _check_key_value_matches_cert_public_key(self, key_value, public_key, signat
q = self._get_long(dsa_key_value, "Q")
g = self._get_long(dsa_key_value, "G", require=False)

pubk_p = public_key.public_numbers().p
pubk_q = public_key.public_numbers().q
pubk_g = public_key.public_numbers().g
pubk_p = public_key.public_numbers().parameter_numbers.p
pubk_q = public_key.public_numbers().parameter_numbers.q
pubk_g = public_key.public_numbers().parameter_numbers.g

return p == pubk_p and q == pubk_q and g == pubk_g

Expand Down Expand Up @@ -571,13 +574,13 @@ def _check_der_key_value_matches_cert_public_key(self, der_encoded_key_value, pu
and isinstance(der_public_key, dsa.DSAPublicKey)
and isinstance(public_key, dsa.DSAPublicKey)
):
p = der_public_key.public_numbers().parameter_numbers().p # type: ignore
q = der_public_key.public_numbers().parameter_numbers().q # type: ignore
g = der_public_key.public_numbers().parameter_numbers().g # type: ignore
p = der_public_key.public_numbers().parameter_numbers.p
q = der_public_key.public_numbers().parameter_numbers.q
g = der_public_key.public_numbers().parameter_numbers.g

pubk_p = public_key.public_numbers().p
pubk_q = public_key.public_numbers().q
pubk_g = public_key.public_numbers().g
pubk_p = public_key.public_numbers().parameter_numbers.p
pubk_q = public_key.public_numbers().parameter_numbers.q
pubk_g = public_key.public_numbers().parameter_numbers.g

return p == pubk_p and q == pubk_q and g == pubk_g

Expand Down
11 changes: 6 additions & 5 deletions signxml/xades/xades.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ def __init__(
self.namespaces.update(xades=namespaces.xades)

@wraps(XMLSigner.sign)
def sign(self, data, always_add_key_value: bool = True, **kwargs) -> _Element: # type: ignore
def sign(self, data, always_add_key_value: bool = True, **kwargs) -> _Element: # type: ignore[override]
return super().sign(data=data, always_add_key_value=always_add_key_value, **kwargs)

def _get_token(self, length=4):
Expand Down Expand Up @@ -195,7 +195,8 @@ def add_signing_certificate(self, signed_signature_properties, sig_root, signing
signing_cert_v2 = SubElement(
signed_signature_properties, xades_tag("SigningCertificateV2"), nsmap=self.namespaces
)
for cert in signing_settings.cert_chain: # type: ignore
assert signing_settings.cert_chain is not None
for cert in signing_settings.cert_chain:
if isinstance(cert, x509.Certificate):
loaded_cert = cert
else:
Expand Down Expand Up @@ -333,7 +334,7 @@ def _verify_signed_properties(self, verify_result):
)
return self._find(verify_result.signed_xml, "xades:SignedSignatureProperties")

def verify( # type: ignore
def verify( # type: ignore[override]
self,
data,
*,
Expand Down Expand Up @@ -367,12 +368,12 @@ def verify( # type: ignore
if verify_result.signed_xml is None:
continue
if verify_result.signed_xml.tag == xades_tag("SignedProperties"):
verify_results[i] = XAdESVerifyResult( # type: ignore
verify_results[i] = XAdESVerifyResult( # type: ignore[misc]
*astuple(verify_result), signed_properties=self._verify_signed_properties(verify_result)
)
break
else:
raise InvalidInput("Expected to find a xades:SignedProperties element")

# TODO: assert all mandatory signed properties are set
return verify_results # type: ignore
return verify_results # type: ignore[return-value]

0 comments on commit 45b93bc

Please sign in to comment.