Skip to content

Commit 41af76a

Browse files
Apply new ruff rules (sigstore#1319)
Apply ruff rules F822 Undefined name in `__all__` EXE001 Shebang is present but file is not executable PYI019 Use `Self` instead of custom TypeVar PYI030 Multiple literal members in a union PYI036 The first argument in `__exit__` should be annotated with `object` or `type[BaseException] | None` PYI036 The second argument in `__exit__` should be annotated with `object` or `BaseException | None` PYI036 The third argument in `__exit__` should be annotated with `object` or `types.TracebackType | None` SIM102 Use a single `if` statement instead of nested `if` statements SIM103 Return the negated condition directly SIM108 Use binary operator instead of `if`-`else`-block PERF401 Use a list comprehension to create a transformed list UP006 Use `dict` instead of `Dict` for type annotation UP006 Use `list` instead of `List` for type annotation UP007 Use `X | Y` for type annotations UP012 Unnecessary call to `encode` as UTF-8 UP031 Use format specifiers instead of percent format UP034 Avoid extraneous parentheses UP035 Import from `collections.abc` instead FURB110 Replace ternary `if` expression with `or` operator RUF010 Use explicit conversion flag RUF036 `None` not at the end of the type annotation. RUF100 Unused `noqa` directive Signed-off-by: Dimitri Papadopoulos <[email protected]>
1 parent aa8e458 commit 41af76a

File tree

25 files changed

+116
-133
lines changed

25 files changed

+116
-133
lines changed

docs/scripts/gen_ref_pages.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,10 +38,9 @@ def main(args: argparse.Namespace) -> None:
3838
if any(part.startswith("_") for part in module_path.parts):
3939
continue
4040

41-
if args.check:
42-
if not full_doc_path.is_file():
43-
print(f"File {full_doc_path} does not exist.", file=sys.stderr)
44-
sys.exit(1)
41+
if args.check and not full_doc_path.is_file():
42+
print(f"File {full_doc_path} does not exist.", file=sys.stderr)
43+
sys.exit(1)
4544

4645
full_doc_path.parent.mkdir(parents=True, exist_ok=True)
4746
with full_doc_path.open("w") as f:

sigstore/_cli.py

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
import sys
2323
from dataclasses import dataclass
2424
from pathlib import Path
25-
from typing import Any, Dict, NoReturn, Optional, TextIO, Union
25+
from typing import Any, NoReturn, Optional, TextIO, Union
2626

2727
from cryptography.hazmat.primitives.serialization import Encoding
2828
from cryptography.x509 import load_pem_x509_certificate
@@ -98,7 +98,7 @@ class VerificationBundledMaterials:
9898
]
9999

100100
# Map of inputs -> outputs for signing operations
101-
OutputMap: TypeAlias = Dict[Path, SigningOutputs]
101+
OutputMap: TypeAlias = dict[Path, SigningOutputs]
102102

103103

104104
def _fatal(message: str) -> NoReturn:
@@ -200,7 +200,7 @@ def _add_shared_verification_options(group: argparse._ArgumentGroup) -> None:
200200

201201

202202
def _add_shared_oidc_options(
203-
group: Union[argparse._ArgumentGroup, argparse.ArgumentParser],
203+
group: argparse._ArgumentGroup | argparse.ArgumentParser,
204204
) -> None:
205205
"""
206206
Common OIDC options, shared between `sigstore sign` and `sigstore get-identity-token`.
@@ -833,7 +833,7 @@ def _sign(args: argparse.Namespace) -> None:
833833
args.bundle,
834834
)
835835

836-
output_dir = args.output_directory if args.output_directory else file.parent
836+
output_dir = args.output_directory or file.parent
837837
if output_dir.exists() and not output_dir.is_dir():
838838
_invalid_arguments(
839839
args, f"Output directory exists and is not a directory: {output_dir}"
@@ -895,7 +895,7 @@ def _collect_verification_state(
895895
)
896896

897897
# Fail if digest input is not used with `--bundle` or both `--certificate` and `--signature`.
898-
if any((isinstance(x, Hashed) for x in args.files_or_digest)):
898+
if any(isinstance(x, Hashed) for x in args.files_or_digest):
899899
if not args.bundle and not (args.certificate and args.signature):
900900
_invalid_arguments(
901901
args,
@@ -1200,10 +1200,7 @@ def _get_identity(args: argparse.Namespace) -> Optional[IdentityToken]:
12001200
def _fix_bundle(args: argparse.Namespace) -> None:
12011201
# NOTE: We could support `--trusted-root` here in the future,
12021202
# for custom Rekor instances.
1203-
if args.staging:
1204-
rekor = RekorClient.staging()
1205-
else:
1206-
rekor = RekorClient.production()
1203+
rekor = RekorClient.staging() if args.staging else RekorClient.production()
12071204

12081205
raw_bundle = RawBundle().from_json(args.bundle.read_text())
12091206

sigstore/_internal/fulcio/client.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@
2323
import logging
2424
from abc import ABC
2525
from dataclasses import dataclass
26-
from typing import List
2726
from urllib.parse import urljoin
2827

2928
import requests
@@ -55,14 +54,14 @@ class FulcioCertificateSigningResponse:
5554
"""Certificate response"""
5655

5756
cert: Certificate
58-
chain: List[Certificate]
57+
chain: list[Certificate]
5958

6059

6160
@dataclass(frozen=True)
6261
class FulcioTrustBundleResponse:
6362
"""Trust bundle response, containing a list of certificate chains"""
6463

65-
trust_bundle: List[List[Certificate]]
64+
trust_bundle: list[list[Certificate]]
6665

6766

6867
class FulcioClientError(Exception):
@@ -151,9 +150,9 @@ def get(self) -> FulcioTrustBundleResponse:
151150
raise FulcioClientError from http_error
152151

153152
trust_bundle_json = resp.json()
154-
chains: List[List[Certificate]] = []
153+
chains: list[list[Certificate]] = []
155154
for certificate_chain in trust_bundle_json["chains"]:
156-
chain: List[Certificate] = []
155+
chain: list[Certificate] = []
157156
for certificate in certificate_chain["certificates"]:
158157
cert: Certificate = load_pem_x509_certificate(certificate.encode())
159158
chain.append(cert)

sigstore/_internal/merkle.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,6 @@
2727
import hashlib
2828
import struct
2929
import typing
30-
from typing import List, Tuple
3130

3231
from sigstore._utils import HexStr
3332
from sigstore.errors import VerificationError
@@ -40,7 +39,7 @@
4039
_NODE_HASH_PREFIX = 1
4140

4241

43-
def _decomp_inclusion_proof(index: int, size: int) -> Tuple[int, int]:
42+
def _decomp_inclusion_proof(index: int, size: int) -> tuple[int, int]:
4443
"""
4544
Breaks down inclusion proof for a leaf at the specified |index| in a tree of the specified
4645
|size| into 2 components. The splitting point between them is where paths to leaves |index| and
@@ -55,7 +54,7 @@ def _decomp_inclusion_proof(index: int, size: int) -> Tuple[int, int]:
5554
return inner, border
5655

5756

58-
def _chain_inner(seed: bytes, hashes: List[str], log_index: int) -> bytes:
57+
def _chain_inner(seed: bytes, hashes: list[str], log_index: int) -> bytes:
5958
"""
6059
Computes a subtree hash for a node on or below the tree's right border. Assumes |proof| hashes
6160
are ordered from lower levels to upper, and |seed| is the initial subtree/leaf hash on the path
@@ -71,7 +70,7 @@ def _chain_inner(seed: bytes, hashes: List[str], log_index: int) -> bytes:
7170
return seed
7271

7372

74-
def _chain_border_right(seed: bytes, hashes: List[str]) -> bytes:
73+
def _chain_border_right(seed: bytes, hashes: list[str]) -> bytes:
7574
"""
7675
Chains proof hashes along tree borders. This differs from inner chaining because |proof|
7776
contains only left-side subtree hashes.

sigstore/_internal/oidc/oauth.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,8 @@
2626
import threading
2727
import urllib.parse
2828
import uuid
29-
from typing import Any, Dict, List, Optional, cast
29+
from types import TracebackType
30+
from typing import Any, Optional, cast
3031

3132
from id import IdentityError
3233

@@ -97,7 +98,7 @@
9798
</script>
9899
</body>
99100
</html>
100-
""" # noqa: E501
101+
"""
101102

102103

103104
class _OAuthFlow:
@@ -118,7 +119,12 @@ def __enter__(self) -> _OAuthRedirectServer:
118119

119120
return self._server
120121

121-
def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
122+
def __exit__(
123+
self,
124+
exc_type: type[BaseException] | None,
125+
exc_value: BaseException | None,
126+
traceback: TracebackType | None,
127+
) -> None:
122128
self._server.shutdown()
123129
self._server_thread.join()
124130

@@ -200,7 +206,7 @@ def auth_endpoint(self, redirect_uri: str) -> str:
200206
params = self._auth_params(redirect_uri)
201207
return f"{self._issuer.oidc_config.authorization_endpoint}?{urllib.parse.urlencode(params)}"
202208

203-
def _auth_params(self, redirect_uri: str) -> Dict[str, Any]:
209+
def _auth_params(self, redirect_uri: str) -> dict[str, Any]:
204210
return {
205211
"response_type": "code",
206212
"client_id": self._client_id,
@@ -218,7 +224,7 @@ class _OAuthRedirectServer(http.server.HTTPServer):
218224
def __init__(self, client_id: str, client_secret: str, issuer: Issuer) -> None:
219225
super().__init__(("localhost", 0), _OAuthRedirectHandler)
220226
self.oauth_session = _OAuthSession(client_id, client_secret, issuer)
221-
self.auth_response: Optional[Dict[str, List[str]]] = None
227+
self.auth_response: Optional[dict[str, list[str]]] = None
222228
self._is_out_of_band = False
223229

224230
@property

sigstore/_internal/rekor/checkpoint.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@
2323
import struct
2424
import typing
2525
from dataclasses import dataclass
26-
from typing import List
2726

2827
from pydantic import BaseModel, Field, StrictStr
2928

@@ -65,7 +64,7 @@ class LogCheckpoint(BaseModel):
6564
origin: StrictStr
6665
log_size: int
6766
log_hash: StrictStr
68-
other_content: List[str]
67+
other_content: list[str]
6968

7069
@classmethod
7170
def from_text(cls, text: str) -> LogCheckpoint:
@@ -229,5 +228,5 @@ def verify_checkpoint(rekor_keyring: RekorKeyring, entry: LogEntry) -> None:
229228
if checkpoint_hash != root_hash:
230229
raise VerificationError(
231230
"Inclusion proof contains invalid root hash signature: ",
232-
f"expected {str(checkpoint_hash)} got {str(root_hash)}",
231+
f"expected {checkpoint_hash} got {root_hash}",
233232
)

sigstore/_internal/rekor/client.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
import logging
2323
from abc import ABC
2424
from dataclasses import dataclass
25-
from typing import Any, Dict, Optional
25+
from typing import Any, Optional
2626
from urllib.parse import urljoin
2727

2828
import rekor_types
@@ -50,7 +50,7 @@ class RekorLogInfo:
5050
raw_data: dict
5151

5252
@classmethod
53-
def from_response(cls, dict_: Dict[str, Any]) -> RekorLogInfo:
53+
def from_response(cls, dict_: dict[str, Any]) -> RekorLogInfo:
5454
"""
5555
Create a new `RekorLogInfo` from the given API response.
5656
"""

sigstore/_internal/sct.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
import logging
2020
import struct
2121
from datetime import timezone
22-
from typing import List, Optional
22+
from typing import Optional
2323

2424
from cryptography.hazmat.primitives import hashes, serialization
2525
from cryptography.hazmat.primitives.asymmetric import ec, rsa
@@ -115,7 +115,7 @@ def _pack_digitally_signed(
115115
# Assemble a format string with the certificate length baked in and then pack the digitally
116116
# signed data
117117
# fmt: off
118-
pattern = "!BBQH%dsH" % len(signed_entry)
118+
pattern = f"!BBQH{len(signed_entry)}sH"
119119
timestamp = sct.timestamp.replace(tzinfo=timezone.utc)
120120
data = struct.pack(
121121
pattern,
@@ -141,7 +141,7 @@ def _is_preissuer(issuer: Certificate) -> bool:
141141
return ExtendedKeyUsageOID.CERTIFICATE_TRANSPARENCY in ext_key_usage.value
142142

143143

144-
def _get_issuer_cert(chain: List[Certificate]) -> Certificate:
144+
def _get_issuer_cert(chain: list[Certificate]) -> Certificate:
145145
issuer = chain[0]
146146
if _is_preissuer(issuer):
147147
issuer = chain[1]
@@ -184,7 +184,7 @@ def _cert_is_ca(cert: Certificate) -> bool:
184184

185185
def verify_sct(
186186
cert: Certificate,
187-
chain: List[Certificate],
187+
chain: list[Certificate],
188188
ct_keyring: CTKeyring,
189189
) -> None:
190190
"""

sigstore/_internal/trust.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,12 @@
1818

1919
from __future__ import annotations
2020

21+
from collections.abc import Iterable
2122
from dataclasses import dataclass
2223
from datetime import datetime, timezone
2324
from enum import Enum
2425
from pathlib import Path
25-
from typing import ClassVar, Iterable, List, NewType
26+
from typing import ClassVar, NewType
2627

2728
import cryptography.hazmat.primitives.asymmetric.padding as padding
2829
from cryptography.exceptions import InvalidSignature
@@ -159,7 +160,7 @@ class Keyring:
159160
Represents a set of keys, each of which is a potentially valid verifier.
160161
"""
161162

162-
def __init__(self, public_keys: List[_PublicKey] = []):
163+
def __init__(self, public_keys: list[_PublicKey] = []):
163164
"""
164165
Create a new `Keyring`, with `keys` as the initial set of verifying keys.
165166
"""
@@ -182,10 +183,7 @@ def verify(self, *, key_id: KeyID, signature: bytes, data: bytes) -> None:
182183
"""
183184

184185
key = self._keyring.get(key_id)
185-
if key is not None:
186-
candidates = [key]
187-
else:
188-
candidates = list(self._keyring.values())
186+
candidates = [key] if key is not None else list(self._keyring.values())
189187

190188
# Try to verify each candidate key. In the happy case, this will
191189
# be exactly one candidate.

sigstore/_internal/tuf.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ def __init__(self, url: str, offline: bool = False) -> None:
114114
_logger.debug(f"TUF metadata: {self._metadata_dir}")
115115
_logger.debug(f"TUF targets cache: {self._targets_dir}")
116116

117-
self._updater: None | Updater = None
117+
self._updater: Updater | None = None
118118
if offline:
119119
_logger.warning(
120120
"TUF repository is loaded in offline mode; updates will not be performed"

0 commit comments

Comments
 (0)