Skip to content

Commit

Permalink
Try running an extra ruff rule (#9402)
Browse files Browse the repository at this point in the history
* Try running an extra ruff rule

I think `from __future__ import annotations` means this is fine, even on older Python

* Enable UP007

* Enable UP038
  • Loading branch information
alex authored Aug 11, 2023
1 parent de7d0e4 commit f558199
Show file tree
Hide file tree
Showing 49 changed files with 504 additions and 605 deletions.
3 changes: 1 addition & 2 deletions noxfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
import pathlib
import re
import sys
import typing
import uuid

import nox
Expand Down Expand Up @@ -227,7 +226,7 @@ def rust(session: nox.Session) -> None:

def process_rust_coverage(
session: nox.Session,
rust_binaries: typing.List[str],
rust_binaries: list[str],
prof_raw_location: pathlib.Path,
) -> None:
# Hitting weird issues merging Windows and Linux Rust coverage, so just
Expand Down
4 changes: 1 addition & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -136,9 +136,7 @@ exclude_lines = [
]

[tool.ruff]
# UP006: Minimum Python 3.9
# UP007, UP038: Minimum Python 3.10
ignore = ['N818', 'UP006', 'UP007', 'UP038']
ignore = ['N818']
select = ['E', 'F', 'I', 'N', 'W', 'UP', 'RUF']
line-length = 79

Expand Down
3 changes: 1 addition & 2 deletions src/_cffi_src/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import os
import platform
import sys
import typing

from cffi import FFI

Expand All @@ -21,7 +20,7 @@
def build_ffi_for_binding(
module_name: str,
module_prefix: str,
modules: typing.List[str],
modules: list[str],
):
"""
Modules listed in ``modules`` should have the following attributes:
Expand Down
6 changes: 2 additions & 4 deletions src/cryptography/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,7 @@


class UnsupportedAlgorithm(Exception):
def __init__(
self, message: str, reason: typing.Optional[_Reasons] = None
) -> None:
def __init__(self, message: str, reason: _Reasons | None = None) -> None:
super().__init__(message)
self._reason = reason

Expand All @@ -44,7 +42,7 @@ class InvalidSignature(Exception):

class InternalError(Exception):
def __init__(
self, msg: str, err_code: typing.List[rust_openssl.OpenSSLError]
self, msg: str, err_code: list[rust_openssl.OpenSSLError]
) -> None:
super().__init__(msg)
self.err_code = err_code
Expand Down
24 changes: 9 additions & 15 deletions src/cryptography/fernet.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ class InvalidToken(Exception):
class Fernet:
def __init__(
self,
key: typing.Union[bytes, str],
key: bytes | str,
backend: typing.Any = None,
) -> None:
try:
Expand Down Expand Up @@ -80,9 +80,7 @@ def _encrypt_from_parts(
hmac = h.finalize()
return base64.urlsafe_b64encode(basic_parts + hmac)

def decrypt(
self, token: typing.Union[bytes, str], ttl: typing.Optional[int] = None
) -> bytes:
def decrypt(self, token: bytes | str, ttl: int | None = None) -> bytes:
timestamp, data = Fernet._get_unverified_token_data(token)
if ttl is None:
time_info = None
Expand All @@ -91,7 +89,7 @@ def decrypt(
return self._decrypt_data(data, timestamp, time_info)

def decrypt_at_time(
self, token: typing.Union[bytes, str], ttl: int, current_time: int
self, token: bytes | str, ttl: int, current_time: int
) -> bytes:
if ttl is None:
raise ValueError(
Expand All @@ -100,16 +98,14 @@ def decrypt_at_time(
timestamp, data = Fernet._get_unverified_token_data(token)
return self._decrypt_data(data, timestamp, (ttl, current_time))

def extract_timestamp(self, token: typing.Union[bytes, str]) -> int:
def extract_timestamp(self, token: bytes | str) -> int:
timestamp, data = Fernet._get_unverified_token_data(token)
# Verify the token was not tampered with.
self._verify_signature(data)
return timestamp

@staticmethod
def _get_unverified_token_data(
token: typing.Union[bytes, str]
) -> typing.Tuple[int, bytes]:
def _get_unverified_token_data(token: bytes | str) -> tuple[int, bytes]:
if not isinstance(token, (str, bytes)):
raise TypeError("token must be bytes or str")

Expand Down Expand Up @@ -139,7 +135,7 @@ def _decrypt_data(
self,
data: bytes,
timestamp: int,
time_info: typing.Optional[typing.Tuple[int, int]],
time_info: tuple[int, int] | None,
) -> bytes:
if time_info is not None:
ttl, current_time = time_info
Expand Down Expand Up @@ -186,7 +182,7 @@ def encrypt(self, msg: bytes) -> bytes:
def encrypt_at_time(self, msg: bytes, current_time: int) -> bytes:
return self._fernets[0].encrypt_at_time(msg, current_time)

def rotate(self, msg: typing.Union[bytes, str]) -> bytes:
def rotate(self, msg: bytes | str) -> bytes:
timestamp, data = Fernet._get_unverified_token_data(msg)
for f in self._fernets:
try:
Expand All @@ -200,9 +196,7 @@ def rotate(self, msg: typing.Union[bytes, str]) -> bytes:
iv = os.urandom(16)
return self._fernets[0]._encrypt_from_parts(p, timestamp, iv)

def decrypt(
self, msg: typing.Union[bytes, str], ttl: typing.Optional[int] = None
) -> bytes:
def decrypt(self, msg: bytes | str, ttl: int | None = None) -> bytes:
for f in self._fernets:
try:
return f.decrypt(msg, ttl)
Expand All @@ -211,7 +205,7 @@ def decrypt(
raise InvalidToken

def decrypt_at_time(
self, msg: typing.Union[bytes, str], ttl: int, current_time: int
self, msg: bytes | str, ttl: int, current_time: int
) -> bytes:
for f in self._fernets:
try:
Expand Down
6 changes: 1 addition & 5 deletions src/cryptography/hazmat/_oid.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@

from __future__ import annotations

import typing

from cryptography.hazmat.bindings._rust import (
ObjectIdentifier as ObjectIdentifier,
)
Expand Down Expand Up @@ -124,9 +122,7 @@ class SignatureAlgorithmOID:
GOSTR3410_2012_WITH_3411_2012_512 = ObjectIdentifier("1.2.643.7.1.1.3.3")


_SIG_OIDS_TO_HASH: typing.Dict[
ObjectIdentifier, typing.Optional[hashes.HashAlgorithm]
] = {
_SIG_OIDS_TO_HASH: dict[ObjectIdentifier, hashes.HashAlgorithm | None] = {
SignatureAlgorithmOID.RSA_WITH_MD5: hashes.MD5(),
SignatureAlgorithmOID.RSA_WITH_SHA1: hashes.SHA1(),
SignatureAlgorithmOID._RSA_WITH_SHA1: hashes.SHA1(),
Expand Down
16 changes: 8 additions & 8 deletions src/cryptography/hazmat/backends/openssl/aead.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def _encrypt(
cipher: _AEADTypes,
nonce: bytes,
data: bytes,
associated_data: typing.List[bytes],
associated_data: list[bytes],
tag_length: int,
ctx: typing.Any = None,
) -> bytes:
Expand All @@ -81,7 +81,7 @@ def _decrypt(
cipher: _AEADTypes,
nonce: bytes,
data: bytes,
associated_data: typing.List[bytes],
associated_data: list[bytes],
tag_length: int,
ctx: typing.Any = None,
) -> bytes:
Expand All @@ -99,7 +99,7 @@ def _evp_aead_create_ctx(
backend: Backend,
cipher: _AEADTypes,
key: bytes,
tag_len: typing.Optional[int] = None,
tag_len: int | None = None,
):
aead_cipher = _evp_aead_get_cipher(backend, cipher)
assert aead_cipher is not None
Expand Down Expand Up @@ -132,7 +132,7 @@ def _evp_aead_encrypt(
cipher: _AEADTypes,
nonce: bytes,
data: bytes,
associated_data: typing.List[bytes],
associated_data: list[bytes],
tag_length: int,
ctx: typing.Any,
) -> bytes:
Expand Down Expand Up @@ -173,7 +173,7 @@ def _evp_aead_decrypt(
cipher: _AEADTypes,
nonce: bytes,
data: bytes,
associated_data: typing.List[bytes],
associated_data: list[bytes],
tag_length: int,
ctx: typing.Any,
) -> bytes:
Expand Down Expand Up @@ -269,7 +269,7 @@ def _evp_cipher_aead_setup(
cipher_name: bytes,
key: bytes,
nonce: bytes,
tag: typing.Optional[bytes],
tag: bytes | None,
tag_len: int,
operation: int,
):
Expand Down Expand Up @@ -375,7 +375,7 @@ def _evp_cipher_encrypt(
cipher: _AEADTypes,
nonce: bytes,
data: bytes,
associated_data: typing.List[bytes],
associated_data: list[bytes],
tag_length: int,
ctx: typing.Any = None,
) -> bytes:
Expand Down Expand Up @@ -427,7 +427,7 @@ def _evp_cipher_decrypt(
cipher: _AEADTypes,
nonce: bytes,
data: bytes,
associated_data: typing.List[bytes],
associated_data: list[bytes],
tag_length: int,
ctx: typing.Any = None,
) -> bytes:
Expand Down
42 changes: 21 additions & 21 deletions src/cryptography/hazmat/backends/openssl/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ class Backend:
# disallowed algorithms are still present in OpenSSL. They just error if
# you try to use them. To avoid that we allowlist the algorithms in
# FIPS 140-3. This isn't ideal, but FIPS 140-3 is trash so here we are.
_fips_aead: typing.ClassVar[typing.Set[bytes]] = {
_fips_aead: typing.ClassVar[set[bytes]] = {
b"aes-128-ccm",
b"aes-192-ccm",
b"aes-256-ccm",
Expand Down Expand Up @@ -136,8 +136,8 @@ def __init__(self) -> None:
self._lib = self._binding.lib
self._fips_enabled = rust_openssl.is_fips_enabled()

self._cipher_registry: typing.Dict[
typing.Tuple[typing.Type[CipherAlgorithm], typing.Type[Mode]],
self._cipher_registry: dict[
tuple[type[CipherAlgorithm], type[Mode]],
typing.Callable,
] = {}
self._register_default_ciphers()
Expand All @@ -155,7 +155,7 @@ def __repr__(self) -> str:
def openssl_assert(
self,
ok: bool,
errors: typing.Optional[typing.List[rust_openssl.OpenSSLError]] = None,
errors: list[rust_openssl.OpenSSLError] | None = None,
) -> None:
return binding._openssl_assert(self._lib, ok, errors=errors)

Expand Down Expand Up @@ -327,7 +327,7 @@ def create_symmetric_decryption_ctx(
def pbkdf2_hmac_supported(self, algorithm: hashes.HashAlgorithm) -> bool:
return self.hmac_supported(algorithm)

def _consume_errors(self) -> typing.List[rust_openssl.OpenSSLError]:
def _consume_errors(self) -> list[rust_openssl.OpenSSLError]:
return rust_openssl.capture_error_stack()

def _bn_to_int(self, bn) -> int:
Expand Down Expand Up @@ -685,7 +685,7 @@ def create_cmac_ctx(self, algorithm: BlockCipherAlgorithm) -> _CMACContext:
def load_pem_private_key(
self,
data: bytes,
password: typing.Optional[bytes],
password: bytes | None,
unsafe_skip_rsa_key_validation: bool,
) -> PrivateKeyTypes:
return self._load_key(
Expand Down Expand Up @@ -740,7 +740,7 @@ def load_pem_public_key(self, data: bytes) -> PublicKeyTypes:
def load_der_private_key(
self,
data: bytes,
password: typing.Optional[bytes],
password: bytes | None,
unsafe_skip_rsa_key_validation: bool,
) -> PrivateKeyTypes:
# OpenSSL has a function called d2i_AutoPrivateKey that in theory
Expand Down Expand Up @@ -1173,7 +1173,7 @@ def dh_supported(self) -> bool:
return not self._lib.CRYPTOGRAPHY_IS_BORINGSSL

def dh_parameters_supported(
self, p: int, g: int, q: typing.Optional[int] = None
self, p: int, g: int, q: int | None = None
) -> bool:
try:
rust_openssl.dh.from_parameter_numbers(
Expand Down Expand Up @@ -1247,11 +1247,11 @@ def _zeroed_null_terminated_buf(self, data):
self._zero_data(self._ffi.cast("uint8_t *", buf), data_len)

def load_key_and_certificates_from_pkcs12(
self, data: bytes, password: typing.Optional[bytes]
) -> typing.Tuple[
typing.Optional[PrivateKeyTypes],
typing.Optional[x509.Certificate],
typing.List[x509.Certificate],
self, data: bytes, password: bytes | None
) -> tuple[
PrivateKeyTypes | None,
x509.Certificate | None,
list[x509.Certificate],
]:
pkcs12 = self.load_pkcs12(data, password)
return (
Expand All @@ -1261,7 +1261,7 @@ def load_key_and_certificates_from_pkcs12(
)

def load_pkcs12(
self, data: bytes, password: typing.Optional[bytes]
self, data: bytes, password: bytes | None
) -> PKCS12KeyAndCertificates:
if password is not None:
utils._check_byteslike("password", password)
Expand Down Expand Up @@ -1337,10 +1337,10 @@ def load_pkcs12(

def serialize_key_and_certificates_to_pkcs12(
self,
name: typing.Optional[bytes],
key: typing.Optional[PKCS12PrivateKeyTypes],
cert: typing.Optional[x509.Certificate],
cas: typing.Optional[typing.List[_PKCS12CATypes]],
name: bytes | None,
key: PKCS12PrivateKeyTypes | None,
cert: x509.Certificate | None,
cas: list[_PKCS12CATypes] | None,
encryption_algorithm: serialization.KeySerializationEncryption,
) -> bytes:
password = None
Expand Down Expand Up @@ -1503,7 +1503,7 @@ def pkcs7_supported(self) -> bool:

def load_pem_pkcs7_certificates(
self, data: bytes
) -> typing.List[x509.Certificate]:
) -> list[x509.Certificate]:
utils._check_bytes("data", data)
bio = self._bytes_to_bio(data)
p7 = self._lib.PEM_read_bio_PKCS7(
Expand All @@ -1518,7 +1518,7 @@ def load_pem_pkcs7_certificates(

def load_der_pkcs7_certificates(
self, data: bytes
) -> typing.List[x509.Certificate]:
) -> list[x509.Certificate]:
utils._check_bytes("data", data)
bio = self._bytes_to_bio(data)
p7 = self._lib.d2i_PKCS7_bio(bio.bio, self._ffi.NULL)
Expand All @@ -1529,7 +1529,7 @@ def load_der_pkcs7_certificates(
p7 = self._ffi.gc(p7, self._lib.PKCS7_free)
return self._load_pkcs7_certificates(p7)

def _load_pkcs7_certificates(self, p7) -> typing.List[x509.Certificate]:
def _load_pkcs7_certificates(self, p7) -> list[x509.Certificate]:
nid = self._lib.OBJ_obj2nid(p7.type)
self.openssl_assert(nid != self._lib.NID_undef)
if nid != self._lib.NID_pkcs7_signed:
Expand Down
4 changes: 2 additions & 2 deletions src/cryptography/hazmat/backends/openssl/ciphers.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def __init__(self, backend: Backend, cipher, mode, operation: int) -> None:
self._cipher = cipher
self._mode = mode
self._operation = operation
self._tag: typing.Optional[bytes] = None
self._tag: bytes | None = None

if isinstance(self._cipher, ciphers.BlockCipherAlgorithm):
self._block_size_bytes = self._cipher.block_size // 8
Expand Down Expand Up @@ -277,5 +277,5 @@ def authenticate_additional_data(self, data: bytes) -> None:
self._backend.openssl_assert(res != 0)

@property
def tag(self) -> typing.Optional[bytes]:
def tag(self) -> bytes | None:
return self._tag
Loading

0 comments on commit f558199

Please sign in to comment.