Skip to contentSkip to conversation

Harden local checks

PATCH Applied Tamir Duberstein 2 participants 6 messages Sep 18 – Oct 5

lore
Share & tools
lore
#0 lore raw

v2 cover Harden local checks

The CI and checker setup proposed in v1 is now largely covered by 05c5bbb0b00e ("Add CI helper scripts and stricter type/lint gates"). This revision builds on that work, retaining the remaining typing and cleanup changes and adding a lockfile for reproducible checks.

---
Changes in v2:
- Rebase onto 0.8.0 and drop the superseded CI, Ruff import/format, and
ty setup patches.
- Add uv.lock in a separate first patch, then upgrade Ruff and ty
alongside the corresponding lint and type fixes.
- Adapt the remaining typing changes to the upstream configuration,
removing unknown-type exemptions and precisely typing the key cache.
- Fix Python 3.8 packaging and test-collection failures and add
regression coverage for cache reuse and missing-key validation.
- Retain the dictionary-lookup and unconditional PyNaCl-import cleanups,
adjusted for upstream changes.
- Link to v1: https://patch.msgid.link/[email protected]

---
Tamir Duberstein (4):
Track uv.lock for reproducible checks
Tighten local type and lint checks
Reduce dictionary lookups
Import PyNaCl unconditionally

 .gitignore                             |    1 -
 docs/conf.py                           |    2 +-
 pyproject.toml                         |   20 +-
 src/patatt/__init__.py                 |  373 ++++----
 tests/conftest.py                      |   12 +-
 tests/test_validation.py               |   19 +-
 tests/unit/test_devsig_header.py       |   17 +-
 tests/unit/test_get_config_from_git.py |    2 +
 tests/unit/test_patatt_message.py      |    4 +-
 tests/unit/test_run_command.py         |    5 +-
 uv.lock                                | 1515 ++++++++++++++++++++++++++++++++
 11 files changed, 1753 insertions(+), 217 deletions(-)

---
base-commit: 274198d9d5cc315c9588bf84cc7b53a7261726e4
change-id: 20260419-stronger-type-checking-3702559acba9

Best regards,

Signature · 1 line
Tamir Duberstein <[email protected]>
#2 lore raw

PATCH v2 2/4 Tighten local type and lint checks

Remove pyright's unknown-type exemptions by annotating containers and attestation results. Describe the shared key cache with its concrete value types and narrow cached values at each consumer. Exercise real Ed25519 signing and signed-message validation with reused key material. Keep the public GPGBIN and SSHKBIN variables mutable, and limit private-usage exemptions to tests.

Upgrade the locked Ruff from 0.15.22 to 0.16.8 and ty from 0.0.69 to 0.0.81. Adopt Ruff's expanded default checks alongside the existing additional rules. Defer annotations so modern syntax remains compatible with Python 3.8, simplify literals and string formatting, and make the subprocess return-code policy explicit. Preserve the public RuntimeError for missing non-OpenPGP keys with a narrow exemption and regression test.

Fix the existing Python 3.8 build and test-collection failures. The SPDX license string added by b967423e2b9f ("Use SPDX license identifier in pyproject.toml") requires a setuptools version that cannot run on Python 3.8. Use the compatible license table and require setuptools>=61 for project metadata support. Defer the tuple annotation in the config test added by 721af992b265 ("Fix multi-value config handling in get_config_from_git()") so Python 3.8 can collect the tests.

Assisted-by LLM
---
 docs/conf.py                           |   2 +-
 pyproject.toml                         |  20 +-
 src/patatt/__init__.py                 | 349 +++++++++++++++++----------------
 tests/conftest.py                      |   6 +-
 tests/test_validation.py               |  19 +-
 tests/unit/test_devsig_header.py       |  17 +-
 tests/unit/test_get_config_from_git.py |   2 +
 tests/unit/test_patatt_message.py      |   4 +-
 tests/unit/test_run_command.py         |   5 +-
 uv.lock                                |  76 +++----
 10 files changed, 272 insertions(+), 228 deletions(-)
docs/conf.py +1 -1
index ca8031a..37e6944 100644
@@ -15,7 +15,7 @@ copyright = '2021-2026, Konstantin Ryabitsev'
 author = 'Konstantin Ryabitsev'
 
 # The version info (imported after sys.path is set up above)
-from patatt import __VERSION__  # noqa: E402
+from patatt import __VERSION__
 
 version = __VERSION__
 release = __VERSION__
pyproject.toml +8 -12
index 8d3de79..8e0472f 100644
@@ -1,5 +1,5 @@
 [build-system]
-requires = ["setuptools>=42", "wheel"]
+requires = ["setuptools>=61", "wheel"]
 build-backend = "setuptools.build_meta"
 
 [project]
@@ -9,7 +9,7 @@ description = "A simple library to add cryptographic attestation to patches sent
 authors = [
     {name = "Konstantin Ryabitsev", email = "[email protected]"},
 ]
-license = "MIT-0"
+license = {text = "MIT-0"}
 readme = "README.rst"
 requires-python = ">=3.8"
 keywords = ["git", "patches", "attestation", "email", "workflow"]
@@ -84,17 +84,13 @@ quote-style = "single"
 [tool.pyright]
 typeCheckingMode = "strict"
 
-# Overly strict rules.
+# GPGBIN and SSHKBIN are mutable settings despite their uppercase names.
+# b4 also assigns GPGBIN directly, so its public name must be preserved.
 reportConstantRedefinition = false
-reportUnknownArgumentType = false
-reportUnknownLambdaType = false
-reportUnknownMemberType = false
-reportUnknownVariableType = false
-
-# False positives caused by underscore-prefixed functions used across files.
-# Might be good to clean this up.
-reportPrivateUsage = false
-reportUnusedFunction = false
+
+executionEnvironments = [
+    { root = "tests", reportPrivateUsage = false },
+]
 
 # Configure mypy in strict mode
 [tool.mypy]
src/patatt/__init__.py +185 -164

921 lines not on this page · raw message

tests/conftest.py +4 -2
index a2d2124..2d5c0b6 100644
@@ -1,7 +1,9 @@
+from __future__ import annotations
+
 import base64
 import tempfile
 from pathlib import Path
-from typing import Dict, Generator
+from typing import Generator
 
 import pytest
 
@@ -47,7 +49,7 @@ def patatt_message(sample_email_bytes: bytes) -> PatattMessage:
 
 
 @pytest.fixture
-def sample_ed25519_key_pair() -> Dict[str, bytes]:
+def sample_ed25519_key_pair() -> dict[str, bytes]:
     """Generate a sample ed25519 key pair for testing."""
     try:
         from nacl.signing import SigningKey
tests/test_validation.py +18 -1
index c399f14..13fbae8 100644
@@ -3,7 +3,7 @@ from pathlib import Path
 
 import pytest
 
-from patatt import RES_VALID, validate_message
+from patatt import RES_VALID, PatattMessage, validate_message
 
 
 @pytest.mark.parametrize(
@@ -33,8 +33,25 @@ def test_validate(sample_file: str) -> None:
     valid_signatures = [r for r in results if r[0] == RES_VALID]
     assert valid_signatures, 'Should find at least one valid signature'
 
+    # Reusing cached key material must preserve validation results.
+    assert validate_message(signed_data, [sources_path]) == results
+
     # Print validation details for debugging
     print(f'Found {len(valid_signatures)} valid signatures:')
     for result in valid_signatures:
         _status, _algo, keytype, identity, selector, _errors = result
         print(f'  - {keytype} signature by {identity} ({selector})')
+
+
[email protected]('sample_file', ['ed25519-signed.txt', 'openssh-signed.txt'])
+def test_validate_requires_public_key(sample_file: str) -> None:
+    sample_path = Path(__file__).parent.parent / 'samples' / sample_file
+    message = PatattMessage(sample_path.read_bytes())
+    signature = message.get_sigs()[0]
+    identity = signature.get_field_as_str('i')
+    assert identity is not None, 'Sample signature must identify its signer'
+
+    with pytest.raises(
+        RuntimeError, match='keyinfo must be a string or bytes, not NoneType'
+    ):
+        message.validate(identity, None)
tests/unit/test_devsig_header.py +11 -6
index 7b6e461..7f09b81 100644
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
 import base64
 import hashlib
 from io import BytesIO
@@ -76,7 +78,7 @@ class TestDevsigHeader:
         header = DevsigHeader()
 
         # Parse the sample email to get headers
-        headers = []
+        headers: list[bytes] = []
         with BytesIO(sample_email_bytes) as fh:
             while True:
                 line = fh.readline()
@@ -109,8 +111,11 @@ class TestDevsigHeader:
         with pytest.raises(RuntimeError, match='Must use set_headers first'):
             header.sanity_check()
 
-    # @pytest.mark.skipif(True, reason="Requires actual ed25519 keys")
-    # def test_sign_ed25519(self, sample_ed25519_key_pair: Dict[str, bytes]) -> None:
-    #     """Test signing with ed25519."""
-    #     # This test would require actual keys and more setup
-    #     pass
+    def test_sign_ed25519(self, sample_ed25519_key_pair: dict[str, bytes]) -> None:
+        """Sign and verify with both freshly loaded and cached key data."""
+        for payload in (b'first message', b'second message'):
+            signed, public_key = DevsigHeader._sign_ed25519(
+                payload, sample_ed25519_key_pair['private']
+            )
+            assert public_key == sample_ed25519_key_pair['public']
+            assert DevsigHeader._validate_ed25519(signed, public_key) == payload
tests/unit/test_get_config_from_git.py +2 -0
index 91ce00e..1df239a 100644
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
 from unittest.mock import MagicMock, patch
 
 from patatt import get_config_from_git
tests/unit/test_patatt_message.py +2 -2
index 17d4a30..0511a5d 100644
@@ -1,4 +1,4 @@
-from typing import Tuple
+from __future__ import annotations
 
 import pytest
 
@@ -49,7 +49,7 @@ This is a test body.
         """Test git canonicalization of message."""
 
         # Mock _get_git_mailinfo to avoid actual git command execution
-        def mock_get_git_mailinfo(payload: bytes) -> Tuple[bytes, bytes, bytes]:
+        def mock_get_git_mailinfo(payload: bytes) -> tuple[bytes, bytes, bytes]:
             # Return mock metadata, patch, and info
             metadata = (
                 b'Author: Test User\nEmail: [email protected]\nSubject: Test email\n'
tests/unit/test_run_command.py +3 -2
index f7eb775..13f88c9 100644
@@ -1,6 +1,7 @@
+from __future__ import annotations
+
 import threading
 import time
-from typing import List, Tuple
 
 from patatt import _run_command
 
@@ -26,7 +27,7 @@ def test_run_command_does_not_wait_for_lingering_child() -> None:
     Runs the call in a daemon thread so a regression surfaces as a prompt
     assertion failure at RETURN_DEADLINE rather than hanging the test suite.
     """
-    holder: List[Tuple[int, bytes, bytes]] = []
+    holder: list[tuple[int, bytes, bytes]] = []
 
     def target() -> None:
         holder.append(_run_command(LINGER_CMD))
uv.lock +38 -38

92 lines not on this page · raw message

Signature · 1 line
2.56.0.rc0.682.g1951b10616.frankengit
#1 lore raw

PATCH v2 1/4 Track uv.lock for reproducible checks

In reply to Tamir Duberstein

The development dependencies are unconstrained and uv.lock is ignored, so fresh checkouts can resolve different versions of Ruff and the other local check tools. Track the lockfile and remove its ignore entry to record the resolved dependency versions and hashes. Use Ruff 0.15.22 and ty 0.0.69 for the existing code; upgrade them alongside the corresponding lint and type fixes.

Follow the existing lockfile tracking in b4 ac39c2cc3d1 ("Track uv.lock for reproducible CI") [0], ezgb a047342a231 ("Add ci.sh and ci-matrix.sh CI guard scripts") [1], and liblore 5b64d9b0359 ("Track uv.lock in git") [2].

---
 .gitignore |    1 -
 uv.lock    | 1515 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 1515 insertions(+), 1 deletion(-)
.gitignore +0 -1
index cfa160d..be5ceb1 100644
@@ -4,7 +4,6 @@
 __pycache__
 .venv
 .venv-*
-uv.lock
 .idea
 *.egg-info
 build
uv.lock new file +1515 -0

1,515 lines not on this page · raw message

Signature · 1 line
2.56.0.rc0.682.g1951b10616.frankengit
#3 lore raw

PATCH v2 3/4 Reduce dictionary lookups

In reply to Tamir Duberstein

Use dict.get instead of separate membership checks and lookups when reading XDG_DATA_HOME and cached identity keys.

Assisted-by LLM
---
 src/patatt/__init__.py | 7 +++----
 1 file changed, 3 insertions(+), 4 deletions(-)
src/patatt/__init__.py +3 -4
index d33ff68..7254fcc 100644
@@ -1037,8 +1037,8 @@ def get_data_dir() -> Path:
     Returns:
         Path to $XDG_DATA_HOME/patatt or ~/.local/share/patatt.
     """
-    if 'XDG_DATA_HOME' in os.environ:
-        datahome = Path(os.environ['XDG_DATA_HOME'])
+    if (xdg_data_home := os.environ.get('XDG_DATA_HOME')) is not None:
+        datahome = Path(xdg_data_home)
     else:
         datahome = Path.home() / '.local' / 'share'
     datadir = datahome / 'patatt'
@@ -1454,8 +1454,7 @@ def get_algo_keydata(config: GitConfigType) -> tuple[str, str]:
             f'Identity must be a string, got {type(identity).__name__}'
         )
 
-    if identity in KEYCACHE:
-        cached = KEYCACHE[identity]
+    if (cached := KEYCACHE.get(identity)) is not None:
         assert isinstance(cached, tuple)
         algo, keydata = cached
         assert isinstance(algo, str)
Signature · 1 line
2.56.0.rc0.682.g1951b10616.frankengit
#4 lore raw

PATCH v2 4/4 Import PyNaCl unconditionally

In reply to Tamir Duberstein

PyNaCl is already a required runtime dependency, but missing imports are only reported when signing, verification, or key generation runs.

Import the required symbols at module load time and remove the RuntimeError wrappers and test skip for an unavailable dependency. Incomplete installations then fail when patatt is imported.

Assisted-by LLM
---
 src/patatt/__init__.py | 25 ++++---------------------
 tests/conftest.py      |  6 +-----
 2 files changed, 5 insertions(+), 26 deletions(-)
src/patatt/__init__.py +4 -21
index 7254fcc..6b61a18 100644
@@ -23,10 +23,11 @@ import urllib.parse
 import warnings
 from io import BytesIO
 from pathlib import Path
-from typing import TYPE_CHECKING, Dict, List, Optional, Tuple, Union
+from typing import Dict, List, Optional, Tuple, Union
 
-if TYPE_CHECKING:
-    from nacl.signing import SigningKey
+from nacl.encoding import Base64Encoder
+from nacl.exceptions import BadSignatureError
+from nacl.signing import SigningKey, VerifyKey
 
 GitConfigType = Dict[str, Union[str, List[str]]]
 AttestationResult = Tuple[
@@ -455,12 +456,6 @@ class DevsigHeader:
 
     @staticmethod
     def _sign_ed25519(payload: bytes, privkey: bytes) -> tuple[bytes, bytes]:
-        try:
-            from nacl.encoding import Base64Encoder
-            from nacl.signing import SigningKey
-        except ModuleNotFoundError as ex:
-            raise RuntimeError('This operation requires PyNaCl libraries') from ex
-
         if privkey not in KEYCACHE:
             sk = SigningKey(privkey, encoder=Base64Encoder)
             vk = base64.b64encode(sk.verify_key.encode())
@@ -479,13 +474,6 @@ class DevsigHeader:
 
     @staticmethod
     def _validate_ed25519(sigdata: bytes, pubkey: bytes) -> bytes:
-        try:
-            from nacl.encoding import Base64Encoder
-            from nacl.exceptions import BadSignatureError
-            from nacl.signing import VerifyKey
-        except ModuleNotFoundError as ex:
-            raise RuntimeError('This operation requires PyNaCl libraries') from ex
-
         vk = VerifyKey(pubkey, encoder=Base64Encoder)
         try:
             return vk.verify(sigdata, encoder=Base64Encoder)
@@ -1769,11 +1757,6 @@ def cmd_validate(cmdargs: argparse.Namespace, config: GitConfigType) -> None:
 
 
 def cmd_genkey(cmdargs: argparse.Namespace, config: GitConfigType) -> None:
-    try:
-        from nacl.signing import SigningKey
-    except ModuleNotFoundError as ex:
-        raise RuntimeError('This operation requires PyNaCl libraries') from ex
-
     # Do we have the signingkey defined?
     usercfg = get_config_from_git(r'user\..*')
     if not config.get('identity'):
tests/conftest.py +1 -5
index 2d5c0b6..9e92937 100644
@@ -6,6 +6,7 @@ from pathlib import Path
 from typing import Generator
 
 import pytest
+from nacl.signing import SigningKey
 
 from patatt import DevsigHeader, PatattMessage
 
@@ -51,11 +52,6 @@ def patatt_message(sample_email_bytes: bytes) -> PatattMessage:
 @pytest.fixture
 def sample_ed25519_key_pair() -> dict[str, bytes]:
     """Generate a sample ed25519 key pair for testing."""
-    try:
-        from nacl.signing import SigningKey
-    except ImportError:
-        pytest.skip('PyNaCl not installed, skipping ed25519 tests')
-
     # Generate a key pair
     private_key = SigningKey.generate()
     public_key = private_key.verify_key
Signature · 1 line
2.56.0.rc0.682.g1951b10616.frankengit
#5 lore raw
In reply to Tamir Duberstein
Quoted 8 lines · Tamir Duberstein

Harden local checks

The CI and checker setup proposed in v1 is now largely covered by 05c5bbb0b00e ("Add CI helper scripts and stricter type/lint gates"). This revision builds on that work, retaining the remaining typing and cleanup changes and adding a lockfile for reproducible checks.

[...]

Applied, thanks!

[1/4] Track uv.lock for reproducible checks

      commit: 0e8f52eee99957e82c16c18473be7f309c84caee
[2/4] Tighten local type and lint checks
      commit: 5ba45852765821173e3740110f7562acab2ca8d7
[3/4] Reduce dictionary lookups
      commit: ca8a7d31413149e765cc81d72916d967ffeeb256
[4/4] Import PyNaCl unconditionally
      commit: 6624df4521b8a0cac7bca931594c4ab8f4e2e8e1

Best regards,

Signature · 1 line
Konstantin Ryabitsev <[email protected]>