Skip to content

Commit

Permalink
update python annotations to 3.9
Browse files Browse the repository at this point in the history
Signed-off-by: NicholasTanz <[email protected]>
  • Loading branch information
NicholasTanz committed Oct 20, 2024
1 parent 26f794b commit 873c8e0
Show file tree
Hide file tree
Showing 17 changed files with 79 additions and 77 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ classifiers = [
"Topic :: Security",
"Topic :: Software Development",
]
requires-python = "~=3.8"
requires-python = "~=3.9"
dynamic = ["version"]

[project.urls]
Expand Down
8 changes: 4 additions & 4 deletions securesystemslib/_gpg/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
import os
import shlex
import subprocess
from typing import List, Optional
from typing import Optional

log = logging.getLogger(__name__)

Expand Down Expand Up @@ -72,7 +72,7 @@ def have_gpg() -> bool:
return bool(gpg_command())


def gpg_version_command() -> List[str]:
def gpg_version_command() -> list[str]:
"""Returns the command to get the current GPG version."""
return shlex.split(f"{gpg_command()} --version")

Expand All @@ -84,14 +84,14 @@ def gpg_version_command() -> List[str]:
)


def gpg_sign_command(keyarg: str, homearg: str) -> List[str]:
def gpg_sign_command(keyarg: str, homearg: str) -> list[str]:
"""Returns the command to use GPG to sign STDIN."""
return shlex.split(
f"{gpg_command()} --detach-sign --digest-algo SHA256 {keyarg} {homearg}"
)


def gpg_export_pubkey_command(homearg: str, keyid: str) -> List[str]:
def gpg_export_pubkey_command(homearg: str, keyid: str) -> list[str]:
"""Returns the GPG command to export a public key."""
return shlex.split(f"{gpg_command()} {homearg} --export {keyid}")

Expand Down
6 changes: 3 additions & 3 deletions securesystemslib/dsse.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Dead Simple Signing Envelope"""

import logging
from typing import Any, Dict, List
from typing import Any

from securesystemslib import exceptions
from securesystemslib._internal.utils import b64dec, b64enc
Expand All @@ -24,7 +24,7 @@ def __init__(
self,
payload: bytes,
payload_type: str,
signatures: Dict[str, Signature],
signatures: dict[str, Signature],
):
self.payload = payload
self.payload_type = payload_type
Expand Down Expand Up @@ -112,7 +112,7 @@ def sign(self, signer: Signer) -> Signature:

return signature

def verify(self, keys: List[Key], threshold: int) -> Dict[str, Key]:
def verify(self, keys: list[Key], threshold: int) -> dict[str, Key]:
"""Verify the payload with the provided Keys.
Arguments:
Expand Down
6 changes: 3 additions & 3 deletions securesystemslib/signer/_aws_signer.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Signer implementation for AWS Key Management Service"""

import logging
from typing import List, Optional, Tuple
from typing import Optional
from urllib import parse

from securesystemslib.exceptions import (
Expand Down Expand Up @@ -101,7 +101,7 @@ def from_priv_key_uri(
return cls(uri.path, public_key)

@classmethod
def _get_default_scheme(cls, supported_by_key: List[str]) -> Optional[str]:
def _get_default_scheme(cls, supported_by_key: list[str]) -> Optional[str]:
# Iterate over supported AWS algorithms, pick the **first** that is also
# supported by the key, and return the related securesystemslib scheme.
for scheme, algo in cls.aws_algos.items():
Expand All @@ -120,7 +120,7 @@ def _get_keytype_for_scheme(scheme: str) -> str:
@classmethod
def import_(
cls, aws_key_id: str, local_scheme: Optional[str] = None
) -> Tuple[str, Key]:
) -> tuple[str, Key]:
"""Loads a key and signer details from AWS KMS.
Returns the private key uri and the public key. This method should only
Expand Down
6 changes: 3 additions & 3 deletions securesystemslib/signer/_azure_signer.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Signer implementation for Azure Key Vault"""

import logging
from typing import Optional, Tuple
from typing import Optional
from urllib import parse

import securesystemslib.hash as sslib_hash
Expand Down Expand Up @@ -165,7 +165,7 @@ def _get_hash_algorithm(public_key: "Key") -> str:
raise UnsupportedKeyType("Unsupported curve supplied by key")

@staticmethod
def _get_keytype_and_scheme(crv: str) -> Tuple[str, str]:
def _get_keytype_and_scheme(crv: str) -> tuple[str, str]:
if crv == KeyCurveName.p_256:
return "ecdsa", "ecdsa-sha2-nistp256"
if crv == KeyCurveName.p_384:
Expand All @@ -191,7 +191,7 @@ def from_priv_key_uri(
return cls(az_key_uri, public_key)

@classmethod
def import_(cls, az_vault_name: str, az_key_name: str) -> Tuple[str, Key]:
def import_(cls, az_vault_name: str, az_key_name: str) -> tuple[str, Key]:
"""Load key and signer details from KMS
Returns the private key uri and the public key. This method should only
Expand Down
6 changes: 3 additions & 3 deletions securesystemslib/signer/_gcp_signer.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Signer implementation for Google Cloud KMS"""

import logging
from typing import Optional, Tuple
from typing import Optional
from urllib import parse

import securesystemslib.hash as sslib_hash
Expand Down Expand Up @@ -83,7 +83,7 @@ def from_priv_key_uri(
return cls(uri.path, public_key)

@classmethod
def import_(cls, gcp_keyid: str) -> Tuple[str, Key]:
def import_(cls, gcp_keyid: str) -> tuple[str, Key]:
"""Load key and signer details from KMS
Returns the private key uri and the public key. This method should only
Expand All @@ -109,7 +109,7 @@ def import_(cls, gcp_keyid: str) -> Tuple[str, Key]:
return f"{cls.SCHEME}:{gcp_keyid}", public_key

@staticmethod
def _get_keytype_and_scheme(algorithm: int) -> Tuple[str, str]:
def _get_keytype_and_scheme(algorithm: int) -> tuple[str, str]:
"""Return keytype and scheme for the KMS algorithm enum"""
keytypes_and_schemes = {
CryptoKeyVersion.CryptoKeyVersionAlgorithm.EC_SIGN_P256_SHA256: (
Expand Down
16 changes: 8 additions & 8 deletions securesystemslib/signer/_gpg_signer.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Signer implementation for OpenPGP"""

import logging
from typing import Any, Dict, Optional, Tuple
from typing import Any, Optional
from urllib import parse

from securesystemslib import exceptions
Expand Down Expand Up @@ -32,11 +32,11 @@ class GPGKey(Key):
"""

@classmethod
def from_dict(cls, keyid: str, key_dict: Dict[str, Any]) -> "GPGKey":
def from_dict(cls, keyid: str, key_dict: dict[str, Any]) -> "GPGKey":
keytype, scheme, keyval = cls._from_dict(key_dict)
return cls(keyid, keytype, scheme, keyval, key_dict)

def to_dict(self) -> Dict:
def to_dict(self) -> dict:
return self._to_dict()

def verify_signature(self, signature: Signature, data: bytes) -> None:
Expand Down Expand Up @@ -113,20 +113,20 @@ def from_priv_key_uri(
return cls(public_key, homedir)

@staticmethod
def _sig_to_legacy_dict(sig: Signature) -> Dict:
def _sig_to_legacy_dict(sig: Signature) -> dict:
"""Helper to convert Signature to internal gpg signature dict format."""
sig_dict = sig.to_dict()
sig_dict["signature"] = sig_dict.pop("sig")
return sig_dict

@staticmethod
def _sig_from_legacy_dict(sig_dict: Dict) -> Signature:
def _sig_from_legacy_dict(sig_dict: dict) -> Signature:
"""Helper to convert internal gpg signature format to Signature."""
sig_dict["sig"] = sig_dict.pop("signature")
return Signature.from_dict(sig_dict)

@staticmethod
def _key_to_legacy_dict(key: GPGKey) -> Dict[str, Any]:
def _key_to_legacy_dict(key: GPGKey) -> dict[str, Any]:
"""Returns legacy dictionary representation of self."""
return {
"keyid": key.keyid,
Expand All @@ -137,7 +137,7 @@ def _key_to_legacy_dict(key: GPGKey) -> Dict[str, Any]:
}

@staticmethod
def _key_from_legacy_dict(key_dict: Dict[str, Any]) -> GPGKey:
def _key_from_legacy_dict(key_dict: dict[str, Any]) -> GPGKey:
"""Create GPGKey from legacy dictionary representation."""
keyid = key_dict["keyid"]
keytype = key_dict["type"]
Expand All @@ -147,7 +147,7 @@ def _key_from_legacy_dict(key_dict: Dict[str, Any]) -> GPGKey:
return GPGKey(keyid, keytype, scheme, keyval)

@classmethod
def import_(cls, keyid: str, homedir: Optional[str] = None) -> Tuple[str, Key]:
def import_(cls, keyid: str, homedir: Optional[str] = None) -> tuple[str, Key]:
"""Load key and signer details from GnuPG keyring.
NOTE: Information about the key validity (expiration, revocation, etc.)
Expand Down
19 changes: 10 additions & 9 deletions securesystemslib/signer/_hsm_signer.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@
"""

import binascii
from collections.abc import Iterator
from contextlib import contextmanager
from typing import Dict, Iterator, List, Optional, Tuple
from typing import Optional
from urllib import parse

from securesystemslib.exceptions import UnsupportedLibraryError
Expand Down Expand Up @@ -125,7 +126,7 @@ def pin_handler(secret: str) -> str:
def __init__(
self,
hsm_keyid: int,
token_filter: Dict[str, str],
token_filter: dict[str, str],
public_key: Key,
pin_handler: SecretsHandler,
):
Expand All @@ -151,13 +152,13 @@ def public_key(self) -> Key:
return self._public_key

@staticmethod
def _find_pkcs_slot(filters: Dict[str, str]) -> int:
def _find_pkcs_slot(filters: dict[str, str]) -> int:
"""Return the PKCS slot with initialized token that matches filter
Raises ValueError if more or less than 1 PKCS slot is found.
"""
lib = PYKCS11LIB()
slots: List[int] = []
slots: list[int] = []
for slot in lib.getSlotList(tokenPresent=True):
tokeninfo = lib.getTokenInfo(slot)
if not tokeninfo.flags & PyKCS11.CKF_TOKEN_INITIALIZED:
Expand All @@ -183,7 +184,7 @@ def _find_pkcs_slot(filters: Dict[str, str]) -> int:

@staticmethod
@contextmanager
def _get_session(filters: Dict[str, str]) -> Iterator["PyKCS11.Session"]:
def _get_session(filters: dict[str, str]) -> Iterator["PyKCS11.Session"]:
"""Context manager to handle a HSM session.
The cryptographic token is selected by filtering by token info fields.
Expand Down Expand Up @@ -226,7 +227,7 @@ def _find_key(
@classmethod
def _find_key_values(
cls, session: "PyKCS11.Session", keyid: int
) -> Tuple["ECDomainParameters", bytes]:
) -> tuple["ECDomainParameters", bytes]:
"""Find ecdsa public key values on HSM."""
key = cls._find_key(session, keyid)
params, point = session.getAttributeValue(
Expand All @@ -235,7 +236,7 @@ def _find_key_values(
return ECDomainParameters.load(bytes(params)), bytes(point)

@classmethod
def _build_token_filter(cls) -> Dict[str, str]:
def _build_token_filter(cls) -> dict[str, str]:
"""Builds a token filter for the found cryptographic token.
The filter will include 'label' if one is found on token.
Expand All @@ -261,8 +262,8 @@ def _build_token_filter(cls) -> Dict[str, str]:
def import_(
cls,
hsm_keyid: Optional[int] = None,
token_filter: Optional[Dict[str, str]] = None,
) -> Tuple[str, SSlibKey]:
token_filter: Optional[dict[str, str]] = None,
) -> tuple[str, SSlibKey]:
"""Import public key and signer details from HSM.
Either only one cryptographic token must be present when importing or a
Expand Down
28 changes: 14 additions & 14 deletions securesystemslib/signer/_key.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import logging
from abc import ABCMeta, abstractmethod
from typing import Any, Dict, Optional, Tuple, Type, cast
from typing import Any, Optional, cast

from securesystemslib._vendor.ed25519.ed25519 import (
SignatureMismatch,
Expand Down Expand Up @@ -59,7 +59,7 @@

# NOTE Key dispatch table is defined here so it's usable by Key,
# but is populated in __init__.py (and can be appended by users).
KEY_FOR_TYPE_AND_SCHEME: Dict[Tuple[str, str], Type] = {}
KEY_FOR_TYPE_AND_SCHEME: dict[tuple[str, str], type] = {}
"""Key dispatch table for ``Key.from_dict()``
See ``securesystemslib.signer.KEY_FOR_TYPE_AND_SCHEME`` for default key types
Expand Down Expand Up @@ -93,8 +93,8 @@ def __init__(
keyid: str,
keytype: str,
scheme: str,
keyval: Dict[str, Any],
unrecognized_fields: Optional[Dict[str, Any]] = None,
keyval: dict[str, Any],
unrecognized_fields: Optional[dict[str, Any]] = None,
):
if not all(
isinstance(at, str) for at in [keyid, keytype, scheme]
Expand Down Expand Up @@ -124,7 +124,7 @@ def __eq__(self, other: Any) -> bool:

@classmethod
@abstractmethod
def from_dict(cls, keyid: str, key_dict: Dict[str, Any]) -> "Key":
def from_dict(cls, keyid: str, key_dict: dict[str, Any]) -> "Key":
"""Creates ``Key`` object from a serialization dict
Key implementations must override this factory constructor that is used
Expand All @@ -145,17 +145,17 @@ def from_dict(cls, keyid: str, key_dict: Dict[str, Any]) -> "Key":
# NOTE: Explicitly not checking the keytype and scheme types to allow
# intoto to use (None,None) to lookup GPGKey, see issue #450
key_impl = KEY_FOR_TYPE_AND_SCHEME[(keytype, scheme)] # type: ignore
return key_impl.from_dict(keyid, key_dict)
return key_impl.from_dict(keyid, key_dict) # type: ignore

@abstractmethod
def to_dict(self) -> Dict[str, Any]:
def to_dict(self) -> dict[str, Any]:
"""Returns a serialization dict.
Key implementations must override this serialization helper.
"""
raise NotImplementedError

def _to_dict(self) -> Dict[str, Any]:
def _to_dict(self) -> dict[str, Any]:
"""Serialization helper to add base Key fields to a dict.
Key implementations may call this in their to_dict, which they must
Expand All @@ -169,7 +169,7 @@ def _to_dict(self) -> Dict[str, Any]:
}

@staticmethod
def _from_dict(key_dict: Dict[str, Any]) -> Tuple[str, str, Dict[str, Any]]:
def _from_dict(key_dict: dict[str, Any]) -> tuple[str, str, dict[str, Any]]:
"""Deserialization helper to pop base Key fields off the dict.
Key implementations may call this in their from_dict, in order to parse
Expand Down Expand Up @@ -206,21 +206,21 @@ def __init__(
keyid: str,
keytype: str,
scheme: str,
keyval: Dict[str, Any],
unrecognized_fields: Optional[Dict[str, Any]] = None,
keyval: dict[str, Any],
unrecognized_fields: Optional[dict[str, Any]] = None,
):
if "public" not in keyval or not isinstance(keyval["public"], str):
raise ValueError(f"public key string required for scheme {scheme}")
super().__init__(keyid, keytype, scheme, keyval, unrecognized_fields)

@classmethod
def from_dict(cls, keyid: str, key_dict: Dict[str, Any]) -> "SSlibKey":
def from_dict(cls, keyid: str, key_dict: dict[str, Any]) -> "SSlibKey":
keytype, scheme, keyval = cls._from_dict(key_dict)

# All fields left in the key_dict are unrecognized.
return cls(keyid, keytype, scheme, keyval, key_dict)

def to_dict(self) -> Dict[str, Any]:
def to_dict(self) -> dict[str, Any]:
return self._to_dict()

def _crypto_key(self) -> "PublicKeyTypes":
Expand All @@ -229,7 +229,7 @@ def _crypto_key(self) -> "PublicKeyTypes":
return load_pem_public_key(public_bytes)

@staticmethod
def _from_crypto(public_key: "PublicKeyTypes") -> Tuple[str, str, str]:
def _from_crypto(public_key: "PublicKeyTypes") -> tuple[str, str, str]:
"""Return tuple of keytype, default scheme and serialized public key
value for the passed public key.
Expand Down
Loading

0 comments on commit 873c8e0

Please sign in to comment.