From 7ab37a049807cb535267e091ec9accd400095451 Mon Sep 17 00:00:00 2001 From: Larry Klosowski Date: Thu, 22 Oct 2026 17:29:35 -0700 Subject: [PATCH 1/7] test(crypto,client,ipfs,learning,release): pin envelope, list, invite, transport and release-gate guards at their entry points (red) The manifest check fails on main: MANIFEST.in includes requirements.txt, which no longer exists. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KGMeatV8UjtCB4CTbWuAv4 --- tests/test_gap_guard_pins.py | 211 ++++++++++++++++++++++++++++ tests/test_release_artifact_pins.py | 181 ++++++++++++++++++++++++ 2 files changed, 392 insertions(+) create mode 100644 tests/test_gap_guard_pins.py create mode 100644 tests/test_release_artifact_pins.py diff --git a/tests/test_gap_guard_pins.py b/tests/test_gap_guard_pins.py new file mode 100644 index 0000000..417a556 --- /dev/null +++ b/tests/test_gap_guard_pins.py @@ -0,0 +1,211 @@ +"""Pins for guards whose removal the rest of the suite did not notice. + +Each test drives the public entry point (``decrypt_data``, ``list_models``, +``verify_model_integrity``, ``ClassroomManager.create``, the client +constructors, ``IPFSClient``) and fails on an assertion if the guard it names +is removed. No network: RPC and HTTP are replaced in-process, and the keys +are fixed throwaway test scalars. +""" +from __future__ import annotations + +import json +from typing import Any + +import pytest + +from citrate_sdk import crypto as crypto_mod +from citrate_sdk._url_security import InsecureTransportError +from citrate_sdk.client import CitrateClient +from citrate_sdk.crypto import KeyManager, verify_model_integrity +from citrate_sdk.errors import CitrateError +from citrate_sdk.ipfs import IPFSClient +from citrate_sdk.learning import ClassroomManager + +SENDER_PK = "0x" + "11" * 32 +RECIPIENT_PK = "0x" + "22" * 32 + + +def _envelope() -> tuple[KeyManager, str]: + sender = KeyManager(SENDER_PK) + recipient = KeyManager(RECIPIENT_PK) + env = sender.encrypt_data("payload", recipient.get_public_key()) + return recipient, env + + +# ── envelope scheme and salt checks in decrypt_data ───────────────────────── + +def test_positive_control_v2_envelope_decrypts() -> None: + recipient, env = _envelope() + assert recipient.decrypt_data(env) == "payload" + + +@pytest.mark.parametrize("scheme", ["ecdh-secp256k1-aesgcm-v1", None, "", "ECDH-SECP256K1-AESGCM-V2 "]) +def test_a_well_formed_envelope_under_another_scheme_label_is_refused(scheme: Any) -> None: + """Every other field is a valid V2 envelope, so only the scheme check can + stop this decrypting (an older-scheme or unlabelled envelope must not be read).""" + recipient, env = _envelope() + pkg = json.loads(env) + if scheme is None: + del pkg["scheme"] + else: + pkg["scheme"] = scheme + with pytest.raises(CitrateError, match="unsupported envelope scheme"): + recipient.decrypt_data(json.dumps(pkg)) + + +def test_an_envelope_without_its_kdf_salt_is_refused_by_name() -> None: + recipient, env = _envelope() + pkg = json.loads(env) + del pkg["kdf_salt"] + with pytest.raises(CitrateError, match="missing kdf_salt"): + recipient.decrypt_data(json.dumps(pkg)) + + +# ── verify_model_integrity uses a constant-time compare ───────────────────── + +def test_verify_model_integrity_compares_with_compare_digest(monkeypatch: pytest.MonkeyPatch) -> None: + import hashlib + import hmac + + seen: list[tuple[Any, Any]] = [] + real = hmac.compare_digest + + def spy(a: Any, b: Any) -> bool: + seen.append((a, b)) + return real(a, b) + + monkeypatch.setattr(crypto_mod.hmac, "compare_digest", spy) + data = b"model-bytes" + good = hashlib.sha256(data).hexdigest() + assert verify_model_integrity(data, good) is True + assert verify_model_integrity(data, "0" * 64) is False + assert [b for _, b in seen] == [good, "0" * 64] + + +# ── list_models unwraps the node's {"models": [...]} answer ───────────────── + +def test_list_models_unwraps_the_node_shape(monkeypatch: pytest.MonkeyPatch) -> None: + client = CitrateClient("http://localhost:8545") + rows = [{"model_id": "m1"}, {"model_id": "m2"}] + monkeypatch.setattr(client, "_rpc_call", lambda method, params=None: {"models": rows}) + got = client.list_models(limit=2) + assert got == rows + assert [m["model_id"] for m in got] == ["m1", "m2"] + + +def test_list_models_of_an_empty_node_answer_is_an_empty_list(monkeypatch: pytest.MonkeyPatch) -> None: + client = CitrateClient("http://localhost:8545") + monkeypatch.setattr(client, "_rpc_call", lambda method, params=None: {}) + assert client.list_models() == [] + + +# ── ClassroomManager.create default invite secret is random, not clock-derived ── + +def _classroom() -> ClassroomManager: + def rpc(method: str, params: Any) -> Any: + if method == "eth_chainId": + return hex(40204) + if method == "eth_sendTransaction": + return "0xhash" + raise AssertionError(method) + + return ClassroomManager(rpc, default_account="0x" + "01" * 20, classroom_address="0x" + "02" * 20) + + +def test_default_invite_secret_does_not_depend_on_the_clock(monkeypatch: pytest.MonkeyPatch) -> None: + import time as time_mod + + monkeypatch.setattr(time_mod, "time", lambda: 1_700_000_000.123) + mgr = _classroom() + mgr.create("A", 10) + first = mgr.last_invite_code + mgr.create("B", 10) + second = mgr.last_invite_code + assert first and second and first != second + + +def test_default_invite_secret_comes_from_the_os_csprng(monkeypatch: pytest.MonkeyPatch) -> None: + import citrate_sdk.learning as learning + + monkeypatch.setattr(learning.secrets, "token_bytes", lambda n: b"\x5a" * n) + mgr = _classroom() + mgr.create("A", 10) + assert mgr.last_invite_code == "0x" + "5a" * 32 + + +# ── transport gate: only https/http are accepted, wherever the URL enters ─── + +@pytest.mark.parametrize("url", [ + "ftp://localhost:8545", + "ws://127.0.0.1:8545", + "gopher://localhost:8545", + "file://localhost/etc/passwd", +]) +def test_client_refuses_a_non_http_scheme_even_on_loopback(url: str) -> None: + with pytest.raises(InsecureTransportError, match="is not https or http"): + CitrateClient(url) + + +@pytest.mark.parametrize("url", ["ftp://ipfs.example.com:5001", "wss://ipfs.example.com:5001"]) +def test_insecure_opt_in_does_not_admit_other_schemes(url: str) -> None: + with pytest.raises(InsecureTransportError, match="is not https or http"): + IPFSClient(url, allow_insecure_http=True) + + +# ── every IPFS request carries the client's timeout ───────────────────────── + +class _Resp: + def __init__(self, body: dict[str, Any] | None = None, chunks: list[bytes] | None = None) -> None: + self.status_code = 200 + self._body = body or {} + self._chunks = chunks or [] + self.text = json.dumps(self._body) + + def json(self) -> dict[str, Any]: + return self._body + + def iter_content(self, chunk_size: int = 0) -> Any: + return iter(self._chunks) + + def close(self) -> None: + pass + + +def _recording_client(calls: list[tuple[str, dict[str, Any]]], data: bytes = b"x") -> IPFSClient: + c = IPFSClient("http://localhost:5001", timeout=7.5) + + def post(url: str, **kw: Any) -> _Resp: + calls.append((url.rsplit("/api/v0/", 1)[-1], kw)) + if url.endswith("/add"): + return _Resp({"Hash": "QmTest", "Size": "1"}) + if url.endswith("/files/stat") or url.endswith("/object/stat"): + return _Resp({"Hash": "QmTest", "Size": 1, "CumulativeSize": 1, "Type": "file"}) + if url.endswith("/cat"): + return _Resp(chunks=[data]) + return _Resp({}) + + c.session.post = post # type: ignore[method-assign] + return c + + +def test_upload_and_its_verification_carry_the_timeout() -> None: + calls: list[tuple[str, dict[str, Any]]] = [] + c = _recording_client(calls) + c.upload_bytes(b"model") + assert calls, "upload made no request" + assert calls[0][0] == "add" + for endpoint, kw in calls: + assert kw.get("timeout") == 7.5, f"{endpoint} request sent without the client timeout" + + +def test_download_and_pin_carry_the_timeout() -> None: + import hashlib + + calls: list[tuple[str, dict[str, Any]]] = [] + c = _recording_client(calls, data=b"abc") + c.download_bytes("QmTest", expected_sha256=hashlib.sha256(b"abc").hexdigest()) + c.pin_file("QmTest") + seen = {e for e, _ in calls} + assert {"cat", "pin/add"} <= seen, seen + for endpoint, kw in calls: + assert kw.get("timeout") == 7.5, f"{endpoint} request sent without the client timeout" diff --git a/tests/test_release_artifact_pins.py b/tests/test_release_artifact_pins.py new file mode 100644 index 0000000..436d6c2 --- /dev/null +++ b/tests/test_release_artifact_pins.py @@ -0,0 +1,181 @@ +"""Pins on the non-source artifacts that ship with, or gate, this package. + +Each check reads a file that nothing in the runtime suite otherwise reads: the +shipped examples, the publish workflow, the lockfile and the sdist manifest. +They are text/AST checks on purpose (no network, no YAML dependency), so they +run in the same frozen environment as the rest of the suite. +""" +from __future__ import annotations + +import ast +import pathlib +import re +import sys + +import pytest +from packaging.requirements import Requirement +from packaging.version import Version + +if sys.version_info >= (3, 11): + import tomllib +else: # Python 3.10 (requires-python floor) + import tomli as tomllib + +ROOT = pathlib.Path(__file__).resolve().parent.parent +EXAMPLES = sorted((ROOT / "examples").glob("*.py")) +WORKFLOWS = ROOT / ".github" / "workflows" + + +# --------------------------------------------------------------------------- +# Shipped examples: the code integrators copy. +# --------------------------------------------------------------------------- + +def _calls(path: pathlib.Path) -> list[ast.Call]: + tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) + return [n for n in ast.walk(tree) if isinstance(n, ast.Call)] + + +def _attr_name(call: ast.Call) -> str | None: + f = call.func + if isinstance(f, ast.Attribute): + return f.attr + if isinstance(f, ast.Name): + return f.id + return None + + +def test_examples_are_present_and_parse() -> None: + assert EXAMPLES, "examples/ is empty; the pins below would pass vacuously" + for path in EXAMPLES: + ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) + + +@pytest.mark.parametrize("path", EXAMPLES, ids=lambda p: p.name) +def test_examples_never_call_the_disabled_purchase_path(path: pathlib.Path) -> None: + names = [_attr_name(c) for c in _calls(path)] + assert "purchase_model_access" not in names, ( + f"{path.name} calls purchase_model_access, which has no on-chain route and refuses" + ) + + +@pytest.mark.parametrize("path", EXAMPLES, ids=lambda p: p.name) +def test_example_encrypted_calls_name_a_recipient_key(path: pathlib.Path) -> None: + for call in _calls(path): + name = _attr_name(call) + kw = {k.arg: k.value for k in call.keywords if k.arg} + if name == "inference": + enc = kw.get("encrypted") + if isinstance(enc, ast.Constant) and enc.value is True: + assert "recipient_public_key" in kw, ( + f"{path.name}:{call.lineno} encrypted inference without recipient_public_key" + ) + if name == "encrypt_data": + assert len(call.args) >= 2 or "recipient_public_key" in kw, ( + f"{path.name}:{call.lineno} encrypt_data without a recipient key" + ) + + +@pytest.mark.parametrize("path", EXAMPLES, ids=lambda p: p.name) +def test_examples_do_not_hand_a_generated_key_string_to_a_client(path: pathlib.Path) -> None: + """`CitrateClient(private_key=KeyManager().get_private_key())` is the + round-trip the examples must not model; keys come from the environment.""" + for call in _calls(path): + if _attr_name(call) != "CitrateClient": + continue + for k in call.keywords: + if k.arg == "private_key" and isinstance(k.value, ast.Call): + assert _attr_name(k.value) != "get_private_key", ( + f"{path.name}:{call.lineno} builds a client from get_private_key()" + ) + + +# --------------------------------------------------------------------------- +# Publish workflow: the release gate. +# --------------------------------------------------------------------------- + +def _jobs(text: str) -> dict[str, str]: + """Split a workflow's `jobs:` block into {job_name: body} by indentation.""" + body = text.split("\njobs:\n", 1)[1] + out: dict[str, str] = {} + cur: str | None = None + for line in body.splitlines(): + m = re.match(r"^ ([A-Za-z0-9_-]+):\s*$", line) + if m: + cur = m.group(1) + out[cur] = "" + elif cur is not None and (line.startswith(" ") or not line.strip()): + out[cur] += line + "\n" + elif line.strip(): + break + return out + + +@pytest.fixture(scope="module") +def publish() -> str: + return (WORKFLOWS / "publish.yml").read_text(encoding="utf-8") + + +def test_publish_workflow_chains_test_build_publish(publish: str) -> None: + jobs = _jobs(publish) + assert {"test", "build", "publish"} <= set(jobs), sorted(jobs) + assert re.search(r"^ needs: test\s*$", jobs["build"], re.M), "build must need test" + assert re.search(r"^ needs: build\s*$", jobs["publish"], re.M), "publish must need build" + + +def test_publish_test_job_runs_the_suite_blocking(publish: str) -> None: + test_job = _jobs(publish)["test"] + assert re.search(r"run: uv run --frozen pytest\b", test_job), "test job must run pytest" + assert "continue-on-error" not in publish + assert "|| true" not in publish + + +def test_publish_uses_trusted_publishing_not_a_token(publish: str) -> None: + job = _jobs(publish)["publish"] + assert re.search(r"id-token: write", job) + assert "pypa/gh-action-pypi-publish@" in job + assert not re.search(r"^\s*(password|api[-_]token)\s*:", publish, re.M | re.I) + assert "secrets.PYPI" not in publish + + +def test_manual_publish_is_main_only_and_version_checked(publish: str) -> None: + job = _jobs(publish)["publish"] + assert "github.ref == 'refs/heads/main'" in job + assert "inputs.publish_version != ''" in job + assert "Built version matches the requested version" in job + + +@pytest.mark.parametrize("wf", sorted(WORKFLOWS.glob("*.yml")), ids=lambda p: p.name) +def test_every_action_reference_is_pinned_to_a_commit(wf: pathlib.Path) -> None: + refs = re.findall(r"^\s*-?\s*uses:\s*(\S+)", wf.read_text(encoding="utf-8"), re.M) + assert refs, f"{wf.name} has no uses: lines" + for ref in refs: + if ref.startswith("./"): + continue + assert re.search(r"@[0-9a-f]{40}$", ref), f"{wf.name}: {ref} is not pinned to a commit SHA" + + +# --------------------------------------------------------------------------- +# Lockfile and sdist manifest. +# --------------------------------------------------------------------------- + +def _locked_version(name: str) -> Version: + text = (ROOT / "uv.lock").read_text(encoding="utf-8") + m = re.search(r'^\[\[package\]\]\nname = "' + re.escape(name) + r'"\nversion = "([^"]+)"', text, re.M) + assert m, f"{name} not in uv.lock" + return Version(m.group(1)) + + +def test_locked_cryptography_satisfies_the_declared_range() -> None: + with (ROOT / "pyproject.toml").open("rb") as fh: + deps = tomllib.load(fh)["project"]["dependencies"] + req = next(Requirement(d) for d in deps if Requirement(d).name == "cryptography") + locked = _locked_version("cryptography") + assert req.specifier.contains(locked), f"uv.lock pins cryptography {locked}, pyproject wants {req.specifier}" + + +def test_manifest_includes_only_files_that_exist() -> None: + for line in (ROOT / "MANIFEST.in").read_text(encoding="utf-8").splitlines(): + parts = line.split() + if parts and parts[0] == "include": + for name in parts[1:]: + assert (ROOT / name).exists(), f"MANIFEST.in includes missing file {name}" From caa45260ebde7c661b87921ee1a097cc5fe5dd29 Mon Sep 17 00:00:00 2001 From: Larry Klosowski Date: Thu, 22 Oct 2026 17:29:35 -0700 Subject: [PATCH 2/7] chore(sdist): drop the MANIFEST.in include of the removed requirements.txt pyproject.toml is the single dependency declaration. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KGMeatV8UjtCB4CTbWuAv4 --- MANIFEST.in | 1 - 1 file changed, 1 deletion(-) diff --git a/MANIFEST.in b/MANIFEST.in index 93abf6e..b603db1 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,7 +1,6 @@ include README.md include LICENSE include CHANGELOG.md -include requirements.txt include pyproject.toml recursive-include citrate_sdk *.py *.pyi recursive-include citrate_sdk py.typed From 07f8636b40133726f221adcf65acc76c638041e6 Mon Sep 17 00:00:00 2001 From: Larry Klosowski Date: Thu, 22 Oct 2026 17:49:35 -0700 Subject: [PATCH 3/7] test: widen the type-ignore on the recorded session.post (mypy) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KGMeatV8UjtCB4CTbWuAv4 --- tests/test_gap_guard_pins.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_gap_guard_pins.py b/tests/test_gap_guard_pins.py index 417a556..9c97673 100644 --- a/tests/test_gap_guard_pins.py +++ b/tests/test_gap_guard_pins.py @@ -184,7 +184,7 @@ def post(url: str, **kw: Any) -> _Resp: return _Resp(chunks=[data]) return _Resp({}) - c.session.post = post # type: ignore[method-assign] + c.session.post = post # type: ignore[method-assign,assignment] return c From ee718c532ec32e71d9339558eb86cc8db4afa6c2 Mon Sep 17 00:00:00 2001 From: Larry Klosowski Date: Sat, 28 Nov 2026 13:02:59 -0800 Subject: [PATCH 4/7] test: turn off the genesis guard in the classroom invite pin fixture main now checks block 0 before a pinned send; this fake RPC serves no block 0, and the guard has its own pins in test_r1006_network_guard.py. Signed-off-by: Larry Klosowski Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01FPJzHJptQTtnapM2Jio6AY --- tests/test_gap_guard_pins.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/tests/test_gap_guard_pins.py b/tests/test_gap_guard_pins.py index 9c97673..33b6e5e 100644 --- a/tests/test_gap_guard_pins.py +++ b/tests/test_gap_guard_pins.py @@ -109,7 +109,14 @@ def rpc(method: str, params: Any) -> Any: return "0xhash" raise AssertionError(method) - return ClassroomManager(rpc, default_account="0x" + "01" * 20, classroom_address="0x" + "02" * 20) + # This fake RPC serves no block 0; the genesis guard has its own pins in + # test_r1006_network_guard.py, so it is off here. + return ClassroomManager( + rpc, + default_account="0x" + "01" * 20, + classroom_address="0x" + "02" * 20, + expected_genesis_hash=None, + ) def test_default_invite_secret_does_not_depend_on_the_clock(monkeypatch: pytest.MonkeyPatch) -> None: From 74858a6dd6abb563cb144bf654b6bdc4e21f5e12 Mon Sep 17 00:00:00 2001 From: Larry Klosowski Date: Sat, 28 Nov 2026 17:36:11 -0800 Subject: [PATCH 5/7] test: parse workflows, bind encrypted-call arguments, run examples for key leaks Tightens the release-artifact and IPFS pins after review found checks that passed with the guard they name removed: - Examples: a new run of each example's main() with the client replaced fails if, without CITRATE_PRIVATE_KEY, it builds a signing client or writes any 32-byte hex secret to stdout/stderr (and if it echoes an env key). Examples may not call get_private_key() at all. Red here on examples/basic_usage.py, which generates a key and prints it. - Encrypted calls bind positional and keyword arguments to the public signatures and reject an absent or literal-None recipient. - publish.yml is parsed as YAML. The publish job's if: is evaluated over a context table against the policy (release, or manual from main with a version); the version-check step must run on every manual publish before the upload, and its script is executed against matching and mismatched dist/ fixtures. The pytest step and the test/build jobs may not be conditional or continue-on-error. - Workflow discovery covers *.yml and *.yaml; uses: pins are read from the parsed job and step mappings (quoted and flow-style included). - The upload test requires add then object/stat, with the CID add returned. Adds pyyaml and types-pyyaml to the dev extra (uv.lock updated). Signed-off-by: Larry Klosowski Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01FPJzHNqGLdTVoFzde3Sxbw --- pyproject.toml | 4 + tests/test_gap_guard_pins.py | 16 +- tests/test_release_artifact_pins.py | 569 ++++++++++++++++++++++++---- uv.lock | 13 + 4 files changed, 521 insertions(+), 81 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 11f7c77..f2219f8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -90,6 +90,10 @@ dev = [ # PYSEC-2026-3447, which fails the blocking pip-audit step. Pull the fixed release # into the dev env explicitly rather than ignoring the advisory. "setuptools>=83", + # tests/test_release_artifact_pins.py parses the workflows as YAML so a + # comment or a reformatted `uses:` cannot satisfy a release-gate check. + "pyyaml>=6.0", + "types-pyyaml>=6.0", ] docs = [ "sphinx>=8.1.3", diff --git a/tests/test_gap_guard_pins.py b/tests/test_gap_guard_pins.py index 33b6e5e..e14ef1c 100644 --- a/tests/test_gap_guard_pins.py +++ b/tests/test_gap_guard_pins.py @@ -178,15 +178,17 @@ def close(self) -> None: pass -def _recording_client(calls: list[tuple[str, dict[str, Any]]], data: bytes = b"x") -> IPFSClient: +def _recording_client( + calls: list[tuple[str, dict[str, Any]]], data: bytes = b"x", cid: str = "QmTest" +) -> IPFSClient: c = IPFSClient("http://localhost:5001", timeout=7.5) def post(url: str, **kw: Any) -> _Resp: calls.append((url.rsplit("/api/v0/", 1)[-1], kw)) if url.endswith("/add"): - return _Resp({"Hash": "QmTest", "Size": "1"}) + return _Resp({"Hash": cid, "Size": "1"}) if url.endswith("/files/stat") or url.endswith("/object/stat"): - return _Resp({"Hash": "QmTest", "Size": 1, "CumulativeSize": 1, "Type": "file"}) + return _Resp({"Hash": cid, "Size": 1, "CumulativeSize": 1, "Type": "file"}) if url.endswith("/cat"): return _Resp(chunks=[data]) return _Resp({}) @@ -197,10 +199,10 @@ def post(url: str, **kw: Any) -> _Resp: def test_upload_and_its_verification_carry_the_timeout() -> None: calls: list[tuple[str, dict[str, Any]]] = [] - c = _recording_client(calls) - c.upload_bytes(b"model") - assert calls, "upload made no request" - assert calls[0][0] == "add" + c = _recording_client(calls, cid="QmReturnedByAdd") + assert c.upload_bytes(b"model") == "QmReturnedByAdd" + assert [e for e, _ in calls] == ["add", "object/stat"], "upload must add, then verify with object/stat" + assert calls[1][1].get("params", {}).get("arg") == "QmReturnedByAdd", "stat must verify the CID add returned" for endpoint, kw in calls: assert kw.get("timeout") == 7.5, f"{endpoint} request sent without the client timeout" diff --git a/tests/test_release_artifact_pins.py b/tests/test_release_artifact_pins.py index 436d6c2..b5ecafc 100644 --- a/tests/test_release_artifact_pins.py +++ b/tests/test_release_artifact_pins.py @@ -2,17 +2,26 @@ Each check reads a file that nothing in the runtime suite otherwise reads: the shipped examples, the publish workflow, the lockfile and the sdist manifest. -They are text/AST checks on purpose (no network, no YAML dependency), so they -run in the same frozen environment as the rest of the suite. +Examples are checked through their AST and by running main() with the client +replaced; workflows are parsed as YAML and their gates are evaluated or +executed, so a comment or a renamed-but-hollow step cannot satisfy a check. +No network. """ from __future__ import annotations import ast +import importlib.util +import inspect +import os import pathlib import re +import shutil +import subprocess import sys +from typing import Any import pytest +import yaml from packaging.requirements import Requirement from packaging.version import Version @@ -21,6 +30,9 @@ else: # Python 3.10 (requires-python floor) import tomli as tomllib +from citrate_sdk.client import CitrateClient +from citrate_sdk.crypto import KeyManager + ROOT = pathlib.Path(__file__).resolve().parent.parent EXAMPLES = sorted((ROOT / "examples").glob("*.py")) WORKFLOWS = ROOT / ".github" / "workflows" @@ -30,11 +42,14 @@ # Shipped examples: the code integrators copy. # --------------------------------------------------------------------------- -def _calls(path: pathlib.Path) -> list[ast.Call]: - tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) +def _calls(tree: ast.AST) -> list[ast.Call]: return [n for n in ast.walk(tree) if isinstance(n, ast.Call)] +def _parse(path: pathlib.Path) -> ast.Module: + return ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) + + def _attr_name(call: ast.Call) -> str | None: f = call.func if isinstance(f, ast.Attribute): @@ -47,111 +62,517 @@ def _attr_name(call: ast.Call) -> str | None: def test_examples_are_present_and_parse() -> None: assert EXAMPLES, "examples/ is empty; the pins below would pass vacuously" for path in EXAMPLES: - ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) + _parse(path) @pytest.mark.parametrize("path", EXAMPLES, ids=lambda p: p.name) def test_examples_never_call_the_disabled_purchase_path(path: pathlib.Path) -> None: - names = [_attr_name(c) for c in _calls(path)] + names = [_attr_name(c) for c in _calls(_parse(path))] assert "purchase_model_access" not in names, ( f"{path.name} calls purchase_model_access, which has no on-chain route and refuses" ) +def _params(fn: Any) -> list[inspect.Parameter]: + return [p for p in inspect.signature(fn).parameters.values() if p.name != "self"] + + +# Calls whose payload is encrypted to a recipient, with the public signature +# their arguments bind against. `encrypted` is None when the call always +# encrypts; otherwise it names the flag that turns encryption on. +_ENCRYPTED_CALLS: dict[str, tuple[list[inspect.Parameter], str | None]] = { + "inference": (_params(CitrateClient.inference), "encrypted"), + "encrypt_data": (_params(KeyManager.encrypt_data), None), +} + + +def _is_literal(node: ast.AST | None, value: object) -> bool: + return isinstance(node, ast.Constant) and node.value is value + + +def _encrypted_call_problems(tree: ast.AST, label: str) -> list[str]: + """Bind each encrypted call's positional and keyword arguments to the + public signature; an encrypted call must bind a recipient key that is not + the literal None. Unpackable arguments cannot be verified and are refused.""" + problems: list[str] = [] + for call in _calls(tree): + spec = _ENCRYPTED_CALLS.get(_attr_name(call) or "") + if spec is None: + continue + params, flag = spec + where = f"{label}:{call.lineno} {_attr_name(call)}" + if any(isinstance(a, ast.Starred) for a in call.args) or any(k.arg is None for k in call.keywords): + problems.append(f"{where} uses */** arguments the check cannot bind") + continue + if len(call.args) > len(params): + problems.append(f"{where} passes more positional arguments than the signature takes") + continue + bound: dict[str, ast.AST] = {} + for param, arg in zip(params, call.args, strict=False): + bound[param.name] = arg + for k in call.keywords: + assert k.arg is not None + bound[k.arg] = k.value + if flag is not None: + enc = bound.get(flag) + # Absent or a literal False is a plaintext call; anything else + # (True, a variable, an expression) may encrypt. + if enc is None or _is_literal(enc, False): + continue + recipient = bound.get("recipient_public_key") + if recipient is None or _is_literal(recipient, None): + problems.append(f"{where} encrypts without a recipient_public_key") + return problems + + @pytest.mark.parametrize("path", EXAMPLES, ids=lambda p: p.name) def test_example_encrypted_calls_name_a_recipient_key(path: pathlib.Path) -> None: - for call in _calls(path): - name = _attr_name(call) - kw = {k.arg: k.value for k in call.keywords if k.arg} - if name == "inference": - enc = kw.get("encrypted") - if isinstance(enc, ast.Constant) and enc.value is True: - assert "recipient_public_key" in kw, ( - f"{path.name}:{call.lineno} encrypted inference without recipient_public_key" - ) - if name == "encrypt_data": - assert len(call.args) >= 2 or "recipient_public_key" in kw, ( - f"{path.name}:{call.lineno} encrypt_data without a recipient key" - ) + assert _encrypted_call_problems(_parse(path), path.name) == [] + + +@pytest.mark.parametrize( + "src", + [ + "c.inference('m', {}, True)", + "c.inference('m', {}, True, 10)", + "c.inference('m', {}, encrypted=True)", + "c.inference('m', {}, encrypted=flag)", + "c.inference('m', {}, True, recipient_public_key=None)", + "c.inference('m', {}, encrypted=True, recipient_public_key=None)", + "c.inference('m', {}, True, 10, None)", + "c.inference(*a)", + "c.inference('m', {}, **kw)", + "k.encrypt_data('x')", + "k.encrypt_data('x', None)", + "k.encrypt_data('x', recipient_public_key=None)", + ], +) +def test_encrypted_call_check_refuses_a_missing_recipient(src: str) -> None: + assert _encrypted_call_problems(ast.parse(src), "fixture"), f"check accepted {src!r}" + + +@pytest.mark.parametrize( + "src", + [ + "c.inference('m', {})", + "c.inference('m', {}, False)", + "c.inference('m', {}, True, 10, pk)", + "c.inference('m', {}, encrypted=True, recipient_public_key=pk)", + "k.encrypt_data('x', pk)", + "k.encrypt_data('x', recipient_public_key=pk)", + ], +) +def test_encrypted_call_check_accepts_a_named_recipient(src: str) -> None: + assert _encrypted_call_problems(ast.parse(src), "fixture") == [] @pytest.mark.parametrize("path", EXAMPLES, ids=lambda p: p.name) -def test_examples_do_not_hand_a_generated_key_string_to_a_client(path: pathlib.Path) -> None: - """`CitrateClient(private_key=KeyManager().get_private_key())` is the - round-trip the examples must not model; keys come from the environment.""" - for call in _calls(path): - if _attr_name(call) != "CitrateClient": - continue - for k in call.keywords: - if k.arg == "private_key" and isinstance(k.value, ast.Call): - assert _attr_name(k.value) != "get_private_key", ( - f"{path.name}:{call.lineno} builds a client from get_private_key()" - ) +def test_examples_never_extract_a_private_key(path: pathlib.Path) -> None: + """A raw key string is what gets printed, logged or pasted. Examples take + their signing key from the environment and never pull one out of a + KeyManager, inline or through a variable.""" + for call in _calls(_parse(path)): + assert _attr_name(call) != "get_private_key", ( + f"{path.name}:{call.lineno} extracts a private key with get_private_key()" + ) + + +class _StopExample(BaseException): + """Raised by the stand-in client so an example stops before any network I/O.""" + + +_HEX64 = re.compile(r"(?i)(? list[dict[str, Any]]: + spec = importlib.util.spec_from_file_location(f"_example_{path.stem}", path) + assert spec is not None and spec.loader is not None + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + assert hasattr(mod, "main"), f"{path.name} has no main()" + built: list[dict[str, Any]] = [] + + def fake_client(*args: Any, **kwargs: Any) -> Any: + built.append(kwargs) + raise _StopExample + + monkeypatch.setattr(mod, "CitrateClient", fake_client) + try: + mod.main() + except (_StopExample, SystemExit): + pass + return built + + +@pytest.mark.parametrize("path", EXAMPLES, ids=lambda p: p.name) +def test_examples_never_print_a_private_key( + path: pathlib.Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + """Run each example's main() with the network replaced. Without a key in the + environment it must stop before building a signing client, and no run may + write a 32-byte hex secret (generated or supplied) to stdout or stderr.""" + generated: list[str] = [] + real_get = KeyManager.get_private_key + + def recording_get(self: KeyManager) -> str: + key = real_get(self) + generated.append(key) + return key + + monkeypatch.setattr(KeyManager, "get_private_key", recording_get) + monkeypatch.setenv("CITRATE_RPC_URL", "http://127.0.0.1:1") + for var in ("CITRATE_PRIVATE_KEY", "CITRATE_BUYER_PRIVATE_KEY"): + monkeypatch.delenv(var, raising=False) + + built = _run_example(path, monkeypatch) + out = capsys.readouterr() + text = out.out + out.err + assert not [b for b in built if b.get("private_key")], ( + f"{path.name} built a signing client with no key in the environment" + ) + for key in generated: + assert key.lower().removeprefix("0x") not in text.lower(), f"{path.name} printed a generated private key" + assert not _HEX64.search(text), f"{path.name} printed a 32-byte hex value: {_HEX64.search(text)}" + + for var in ("CITRATE_PRIVATE_KEY", "CITRATE_BUYER_PRIVATE_KEY"): + monkeypatch.setenv(var, _ENV_KEY) + _run_example(path, monkeypatch) + out = capsys.readouterr() + assert _ENV_KEY.removeprefix("0x") not in (out.out + out.err).lower(), ( + f"{path.name} printed the environment private key" + ) # --------------------------------------------------------------------------- -# Publish workflow: the release gate. +# Workflows, parsed as YAML (comments and formatting cannot satisfy a check). # --------------------------------------------------------------------------- -def _jobs(text: str) -> dict[str, str]: - """Split a workflow's `jobs:` block into {job_name: body} by indentation.""" - body = text.split("\njobs:\n", 1)[1] - out: dict[str, str] = {} - cur: str | None = None - for line in body.splitlines(): - m = re.match(r"^ ([A-Za-z0-9_-]+):\s*$", line) - if m: - cur = m.group(1) - out[cur] = "" - elif cur is not None and (line.startswith(" ") or not line.strip()): - out[cur] += line + "\n" - elif line.strip(): +def _workflow_files(directory: pathlib.Path) -> list[pathlib.Path]: + return sorted([*directory.glob("*.yml"), *directory.glob("*.yaml")]) + + +WORKFLOW_FILES = _workflow_files(WORKFLOWS) + + +def _load(text: str) -> dict[str, Any]: + doc = yaml.safe_load(text) + assert isinstance(doc, dict), "workflow is not a mapping" + return doc + + +def _steps(job: dict[str, Any]) -> list[dict[str, Any]]: + steps = job.get("steps") or [] + assert isinstance(steps, list) + return steps + + +def _needs(job: dict[str, Any]) -> list[str]: + needs = job.get("needs", []) + return [needs] if isinstance(needs, str) else list(needs) + + +# A small evaluator for the subset of GitHub expression syntax the publish +# gates use: context paths, string literals, ==, !=, !, &&, || and parentheses. +# Anything else (functions such as always(), other operators) is refused, so a +# gate rewritten into an unrecognised form fails instead of passing. +_TOKEN = re.compile(r"\s*(?:(\|\||&&|==|!=|!|\(|\))|'((?:[^']|'')*)'|([A-Za-z_][A-Za-z0-9_.-]*))") + + +def _tokenize(expr: str) -> list[tuple[str, str]]: + expr = expr.strip() + if expr.startswith("${{") and expr.endswith("}}"): + expr = expr[3:-2] + out: list[tuple[str, str]] = [] + pos = 0 + while pos < len(expr): + if expr[pos:].strip() == "": break + m = _TOKEN.match(expr, pos) + if not m or m.end() == pos: + raise ValueError(f"unsupported expression syntax at {expr[pos:]!r}") + op, lit, ident = m.groups() + if op: + out.append(("op", op)) + elif lit is not None: + out.append(("str", lit.replace("''", "'"))) + else: + out.append(("id", ident)) + pos = m.end() return out +def _evaluate(expr: str, ctx: dict[str, str]) -> bool: + toks = _tokenize(expr) + i = 0 + + def peek() -> tuple[str, str] | None: + return toks[i] if i < len(toks) else None + + def take() -> tuple[str, str]: + nonlocal i + if i >= len(toks): + raise ValueError("unexpected end of expression") + i += 1 + return toks[i - 1] + + def primary() -> Any: + kind, val = take() + if (kind, val) == ("op", "("): + v = or_() + if take() != ("op", ")"): + raise ValueError("unbalanced parentheses") + return v + if (kind, val) == ("op", "!"): + return not truthy(primary()) + if kind == "str": + return val + if kind == "id": + if peek() == ("op", "("): + raise ValueError(f"function {val}() is not allowed in a publish gate") + if val not in ctx: + raise ValueError(f"unknown context {val}") + return ctx[val] + raise ValueError(f"unexpected token {val!r}") + + def truthy(v: Any) -> bool: + return bool(v) + + def cmp() -> Any: + left = primary() + t = peek() + if t in (("op", "=="), ("op", "!=")): + take() + right = primary() + return (left == right) if t[1] == "==" else (left != right) + return left + + def and_() -> Any: + v = cmp() + while peek() == ("op", "&&"): + take() + r = cmp() + v = truthy(v) and truthy(r) + return v + + def or_() -> Any: + v = and_() + while peek() == ("op", "||"): + take() + r = and_() + v = truthy(v) or truthy(r) + return v + + result = or_() + if i != len(toks): + raise ValueError(f"trailing tokens in {expr!r}") + return truthy(result) + + +def _contexts() -> list[dict[str, str]]: + return [ + {"github.event_name": ev, "github.ref": ref, "inputs.publish_version": ver} + for ev in ("release", "workflow_dispatch", "push", "pull_request", "schedule") + for ref in ("refs/heads/main", "refs/heads/feature", "refs/tags/v0.6.2", "refs/heads/main-x") + for ver in ("", "0.6.2") + ] + + +def _should_publish(ctx: dict[str, str]) -> bool: + if ctx["github.event_name"] == "release": + return True + return ( + ctx["github.event_name"] == "workflow_dispatch" + and ctx["github.ref"] == "refs/heads/main" + and ctx["inputs.publish_version"] != "" + ) + + +def _publish_gate_mismatches(expr: Any) -> list[dict[str, str]]: + """Contexts where the publish job's `if:` disagrees with the policy: + a release publishes; a manual run publishes only from main with a version.""" + if not isinstance(expr, str): + return [{"reason": "publish job has no if: condition"}] + return [c for c in _contexts() if _evaluate(expr, c) != _should_publish(c)] + + @pytest.fixture(scope="module") -def publish() -> str: - return (WORKFLOWS / "publish.yml").read_text(encoding="utf-8") +def publish() -> dict[str, Any]: + return _load((WORKFLOWS / "publish.yml").read_text(encoding="utf-8")) -def test_publish_workflow_chains_test_build_publish(publish: str) -> None: - jobs = _jobs(publish) +def test_publish_workflow_chains_test_build_publish(publish: dict[str, Any]) -> None: + jobs = publish["jobs"] assert {"test", "build", "publish"} <= set(jobs), sorted(jobs) - assert re.search(r"^ needs: test\s*$", jobs["build"], re.M), "build must need test" - assert re.search(r"^ needs: build\s*$", jobs["publish"], re.M), "publish must need build" - + assert _needs(jobs["build"]) == ["test"], "build must need test" + assert _needs(jobs["publish"]) == ["build"], "publish must need build" + for name in ("test", "build"): + assert "if" not in jobs[name], f"the {name} job must not be conditional" + + +def test_publish_test_job_runs_the_suite_blocking(publish: dict[str, Any]) -> None: + jobs = publish["jobs"] + pytest_steps = [s for s in _steps(jobs["test"]) if re.search(r"\bpytest\b", str(s.get("run", "")))] + assert pytest_steps, "test job must run pytest" + for step in pytest_steps: + assert re.search(r"^uv run --frozen pytest\b", str(step["run"]).strip()), step["run"] + assert "if" not in step, f"pytest step is conditional: if: {step['if']}" + for name, job in jobs.items(): + assert "continue-on-error" not in job, f"job {name} sets continue-on-error" + for step in _steps(job): + assert "continue-on-error" not in step, f"{name}: step {step.get('name')} sets continue-on-error" + assert "|| true" not in str(step.get("run", "")), f"{name}: step {step.get('name')} swallows failure" + + +def test_publish_uses_trusted_publishing_not_a_token(publish: dict[str, Any]) -> None: + job = publish["jobs"]["publish"] + assert job.get("permissions", {}).get("id-token") == "write" + pub = [s for s in _steps(job) if str(s.get("uses", "")).startswith("pypa/gh-action-pypi-publish@")] + assert len(pub) == 1, "publish job must publish exactly once through pypa/gh-action-pypi-publish" + assert not {"password", "api-token", "api_token", "user"} & set(pub[0].get("with") or {}) + text = (WORKFLOWS / "publish.yml").read_text(encoding="utf-8") + assert "secrets.PYPI" not in text + + +def test_manual_publish_is_main_only_with_a_version(publish: dict[str, Any]) -> None: + bad = _publish_gate_mismatches(publish["jobs"]["publish"].get("if")) + assert not bad, f"publish job if: disagrees with the policy for {bad[:3]}" + + +@pytest.mark.parametrize( + "expr", + [ + "github.event_name == 'release' || github.event_name == 'workflow_dispatch'", + "github.event_name == 'release' || (github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main')", + "github.event_name == 'release' || (github.event_name == 'workflow_dispatch' && inputs.publish_version != '')", + "github.event_name == 'release' || github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' || inputs.publish_version != ''", + "always()", + None, + ], +) +def test_publish_gate_check_refuses_a_weakened_gate(expr: str | None) -> None: + try: + bad = _publish_gate_mismatches(expr) + except ValueError: + return + assert bad, f"gate check accepted {expr!r}" + + +def _dist_name() -> str: + with (ROOT / "pyproject.toml").open("rb") as fh: + return re.sub(r"[-_.]+", "_", tomllib.load(fh)["project"]["name"]).lower() + + +def _run_version_check(script: str, want: str, artifacts: list[str], tmp: pathlib.Path) -> int: + work = tmp / f"run{len(list(tmp.iterdir()))}" + (work / "dist").mkdir(parents=True) + for name in artifacts: + (work / "dist" / name).write_bytes(b"") + bash = shutil.which("bash") + assert bash, "bash is required to exercise the version-check step" + env = {"PATH": os.environ.get("PATH", ""), "WANT": want} + proc = subprocess.run( + [bash, "--noprofile", "--norc", "-eo", "pipefail", "-c", script], + cwd=work, env=env, capture_output=True, text=True, timeout=30, + ) + return proc.returncode + + +def test_manual_publish_checks_the_built_artifacts_first(publish: dict[str, Any], tmp_path: pathlib.Path) -> None: + """The version-check step runs on every manual publish, before the upload, + and its script rejects any artifact that is not the requested version.""" + job = publish["jobs"]["publish"] + steps = _steps(job) + pub_idx = next(i for i, s in enumerate(steps) if str(s.get("uses", "")).startswith("pypa/gh-action-pypi-publish@")) + checks = [(i, s) for i, s in enumerate(steps) if s.get("name") == "Built version matches the requested version"] + assert len(checks) == 1, "publish job must have exactly one version-check step" + idx, step = checks[0] + assert idx < pub_idx, "version check must run before the PyPI upload" + assert "continue-on-error" not in step + for ctx in _contexts(): + if ctx["github.event_name"] == "workflow_dispatch" and _evaluate(job["if"], ctx): + assert "if" not in step or _evaluate(step["if"], ctx), f"version check skipped for {ctx}" + assert re.fullmatch(r"\$\{\{\s*inputs\.publish_version\s*\}\}", str((step.get("env") or {}).get("WANT", ""))), ( + "WANT must be the requested publish_version" + ) -def test_publish_test_job_runs_the_suite_blocking(publish: str) -> None: - test_job = _jobs(publish)["test"] - assert re.search(r"run: uv run --frozen pytest\b", test_job), "test job must run pytest" - assert "continue-on-error" not in publish - assert "|| true" not in publish + script = str(step["run"]) + pkg = _dist_name() + good = [f"{pkg}-0.6.2-py3-none-any.whl", f"{pkg}-0.6.2.tar.gz"] + assert _run_version_check(script, "0.6.2", good, tmp_path) == 0, "matching artifacts were rejected" + for artifacts in ( + [f"{pkg}-0.6.1-py3-none-any.whl", f"{pkg}-0.6.1.tar.gz"], + [f"{pkg}-0.6.2-py3-none-any.whl", f"{pkg}-0.6.1.tar.gz"], + [f"{pkg}-0.6.2-py3-none-any.whl", "other-0.6.2.tar.gz"], + [f"{pkg}-0.6.20-py3-none-any.whl"], + [], + ): + assert _run_version_check(script, "0.6.2", artifacts, tmp_path) != 0, f"accepted {artifacts} for 0.6.2" + + +_PINNED = re.compile(r"^[^@\s]+@[0-9a-f]{40}$") + + +def _unpinned_uses(doc: dict[str, Any]) -> list[str]: + """Every job-level (reusable workflow) and step-level `uses:` that is not a + local path and not pinned to a full commit SHA.""" + refs: list[Any] = [] + for job in (doc.get("jobs") or {}).values(): + if "uses" in job: + refs.append(job["uses"]) + refs.extend(s["uses"] for s in _steps(job) if isinstance(s, dict) and "uses" in s) + bad = [] + for ref in refs: + if not isinstance(ref, str): + bad.append(repr(ref)) + elif ref.startswith("./"): + continue + elif ref.startswith("docker://"): + if not re.search(r"@sha256:[0-9a-f]{64}$", ref): + bad.append(ref) + elif not _PINNED.match(ref): + bad.append(ref) + return bad -def test_publish_uses_trusted_publishing_not_a_token(publish: str) -> None: - job = _jobs(publish)["publish"] - assert re.search(r"id-token: write", job) - assert "pypa/gh-action-pypi-publish@" in job - assert not re.search(r"^\s*(password|api[-_]token)\s*:", publish, re.M | re.I) - assert "secrets.PYPI" not in publish +def _uses_count(doc: dict[str, Any]) -> int: + n = 0 + for job in (doc.get("jobs") or {}).values(): + n += "uses" in job + n += sum(1 for s in _steps(job) if isinstance(s, dict) and "uses" in s) + return n -def test_manual_publish_is_main_only_and_version_checked(publish: str) -> None: - job = _jobs(publish)["publish"] - assert "github.ref == 'refs/heads/main'" in job - assert "inputs.publish_version != ''" in job - assert "Built version matches the requested version" in job +def test_workflow_discovery_includes_both_extensions(tmp_path: pathlib.Path) -> None: + for name in ("a.yml", "b.yaml", "c.txt"): + (tmp_path / name).write_text("") + assert [p.name for p in _workflow_files(tmp_path)] == ["a.yml", "b.yaml"] + assert WORKFLOW_FILES, "no workflows found" -@pytest.mark.parametrize("wf", sorted(WORKFLOWS.glob("*.yml")), ids=lambda p: p.name) +@pytest.mark.parametrize("wf", WORKFLOW_FILES, ids=lambda p: p.name) def test_every_action_reference_is_pinned_to_a_commit(wf: pathlib.Path) -> None: - refs = re.findall(r"^\s*-?\s*uses:\s*(\S+)", wf.read_text(encoding="utf-8"), re.M) - assert refs, f"{wf.name} has no uses: lines" - for ref in refs: - if ref.startswith("./"): - continue - assert re.search(r"@[0-9a-f]{40}$", ref), f"{wf.name}: {ref} is not pinned to a commit SHA" + doc = _load(wf.read_text(encoding="utf-8")) + assert _uses_count(doc), f"{wf.name} has no uses: entries" + assert _unpinned_uses(doc) == [], f"{wf.name}: not pinned to a commit SHA" + + +_SHA = "11d5960a326750d5838078e36cf38b85af677262" + + +@pytest.mark.parametrize( + "text", + [ + f"jobs:\n a:\n steps:\n - uses: actions/checkout@{_SHA}\n - uses: 'actions/setup-python@v5'\n", + f'jobs:\n a:\n steps:\n - uses: actions/checkout@{_SHA}\n - "uses": "actions/setup-python@v5"\n', + f"jobs:\n a:\n steps: [{{uses: actions/checkout@{_SHA}}}, {{uses: actions/cache@v4}}]\n", + f"jobs:\n a:\n steps:\n - {{name: x, uses: actions/cache@main}}\n - uses: actions/checkout@{_SHA}\n", + "jobs:\n a:\n uses: org/repo/.github/workflows/x.yml@main\n", + "jobs:\n a:\n steps:\n - uses: docker://alpine:3\n", + ], +) +def test_pin_check_parses_quoted_and_flow_style_uses(text: str) -> None: + assert _unpinned_uses(_load(text)), f"pin check accepted:\n{text}" # --------------------------------------------------------------------------- diff --git a/uv.lock b/uv.lock index bd1ca46..daff0f8 100644 --- a/uv.lock +++ b/uv.lock @@ -614,9 +614,11 @@ dev = [ { name = "mypy" }, { name = "pytest" }, { name = "pytest-asyncio" }, + { name = "pyyaml" }, { name = "ruff" }, { name = "setuptools" }, { name = "tomli" }, + { name = "types-pyyaml" }, ] docs = [ { name = "myst-parser", version = "4.0.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, @@ -643,6 +645,7 @@ requires-dist = [ { name = "numpy", specifier = "~=2.0" }, { name = "pytest", marker = "extra == 'dev'", specifier = ">=7.0" }, { name = "pytest-asyncio", marker = "extra == 'dev'", specifier = ">=0.21" }, + { name = "pyyaml", marker = "extra == 'dev'", specifier = ">=6.0" }, { name = "requests", specifier = "~=2.33" }, { name = "ruff", marker = "extra == 'dev'", specifier = ">=0.1.0" }, { name = "setuptools", marker = "extra == 'dev'", specifier = ">=83" }, @@ -650,6 +653,7 @@ requires-dist = [ { name = "sphinx-autodoc-typehints", marker = "extra == 'docs'", specifier = ">=1.20" }, { name = "sphinx-rtd-theme", marker = "extra == 'docs'", specifier = ">=1.0" }, { name = "tomli", marker = "extra == 'dev'", specifier = ">=2.0" }, + { name = "types-pyyaml", marker = "extra == 'dev'", specifier = ">=6.0" }, { name = "typing-extensions", specifier = "~=4.0" }, { name = "urllib3", specifier = ">=2.0,<3" }, { name = "web3", specifier = "~=7.15" }, @@ -4061,6 +4065,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/fb/12/5911ae3eeec47800503a238d971e51722ccea5feb8569b735184d5fcdbc0/toolz-1.1.0-py3-none-any.whl", hash = "sha256:15ccc861ac51c53696de0a5d6d4607f99c210739caf987b5d2054f3efed429d8", size = 58093, upload-time = "2025-10-17T04:03:20.435Z" }, ] +[[package]] +name = "types-pyyaml" +version = "6.0.12.20261122" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/3d/fe/e4d32b089d06f3b5d2f3f1909b1cb450ce2e18ea6e2c1863d2b29ad0090e/types_pyyaml-6.0.12.20261122.tar.gz", hash = "sha256:7fa577c893a1db255cbb02320884ffcb97b7a219fe515bec6c5f15d5d3af41ed", size = 19093, upload-time = "2026-11-22T08:57:28.481Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/4c/71/8dc5553ca25c3a4799ce789f8300d2c3933d427585222c431c77450ed60d/types_pyyaml-6.0.12.20261122-py3-none-any.whl", hash = "sha256:689fbbe883b60471166dede9dba6ac0dbdbcf0ea98062d7ec195430f5bbdb009", size = 21356, upload-time = "2026-11-22T08:57:27.509Z" }, +] + [[package]] name = "types-requests" version = "2.33.0.20260402" From 3b4944aad4e0c8f6e4f45993bec84804f6dd7691 Mon Sep 17 00:00:00 2001 From: Larry Klosowski Date: Sat, 28 Nov 2026 17:36:11 -0800 Subject: [PATCH 6/7] fix(examples): basic_usage never generates or prints a private key Without CITRATE_PRIVATE_KEY the example generated a key, printed it to stdout and signed with it. It now stops with the same message as encrypted_inference.py. The README notes the key comes from the environment. Turns test_examples_never_print_a_private_key and test_examples_never_extract_a_private_key green. Signed-off-by: Larry Klosowski Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01FPJzHNqGLdTVoFzde3Sxbw --- README.md | 4 +++- examples/basic_usage.py | 12 +++++------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 6cc11a0..3015bbf 100644 --- a/README.md +++ b/README.md @@ -120,7 +120,9 @@ Point the SDK at a local Citrate stack on one machine instead of the public test ```python gw = GatewayClient(api_key="cgk_...", base_url="http://localhost:8080") ``` -4. **End-to-end check** — run the basic example against your local node: +4. **End-to-end check** — run the basic example against your local node. It signs with + the key in `CITRATE_PRIVATE_KEY` (a funded devnet account) and exits without one; it + never generates or prints a private key: ```bash CITRATE_RPC_URL=http://localhost:8545 python examples/basic_usage.py ``` diff --git a/examples/basic_usage.py b/examples/basic_usage.py index 9ad1255..6b4fb04 100644 --- a/examples/basic_usage.py +++ b/examples/basic_usage.py @@ -14,7 +14,6 @@ from pathlib import Path from citrate_sdk import AccessType, CitrateClient, ModelConfig, ModelType -from citrate_sdk.crypto import KeyManager def main() -> None: @@ -24,13 +23,12 @@ def main() -> None: RPC_URL = os.getenv("CITRATE_RPC_URL", "http://localhost:8545") PRIVATE_KEY = os.getenv("CITRATE_PRIVATE_KEY") + # The signing key comes from the environment only. The example never + # generates, prints or logs a private key: anything written to stdout ends + # up in terminal scrollback, CI logs and pasted bug reports. if not PRIVATE_KEY: - print("Generating new private key...") - key_manager = KeyManager() - PRIVATE_KEY = key_manager.get_private_key() - print(f"Address: {key_manager.get_address()}") - print(f"Private Key: {PRIVATE_KEY}") - print("Save this private key to use again!") + print("Please set CITRATE_PRIVATE_KEY environment variable") + return # Connect to Citrate print(f"Connecting to Citrate at {RPC_URL}...") From 4c9df907556abb380586d549c2d932e9efdadd76 Mon Sep 17 00:00:00 2001 From: Larry Klosowski Date: Sat, 28 Nov 2026 17:54:28 -0800 Subject: [PATCH 7/7] test: pin every use of the env key, capture fd output and logs, whole-suite pytest From the independent review of 3b4944a: - The runtime key test stops at client construction, so a print of the env key after it went unseen. A new AST check requires every read of a name bound from a *PRIVATE_KEY* env var to be a truth test or the private_key= of CitrateClient; fixtures pin print, logging, slicing and a pass-through call. - The runtime test now reads capfd (fd 1/2, so os.write is seen) and caplog, and its docstring says what it covers. - The pytest step may only add verbosity flags (-q, -v, -ra), so --co, -k or a path cannot narrow the release gate. Signed-off-by: Larry Klosowski Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01FPJzHNqGLdTVoFzde3Sxbw --- tests/test_release_artifact_pins.py | 87 ++++++++++++++++++++++++++--- 1 file changed, 78 insertions(+), 9 deletions(-) diff --git a/tests/test_release_artifact_pins.py b/tests/test_release_artifact_pins.py index b5ecafc..2134a41 100644 --- a/tests/test_release_artifact_pins.py +++ b/tests/test_release_artifact_pins.py @@ -12,6 +12,7 @@ import ast import importlib.util import inspect +import logging import os import pathlib import re @@ -177,6 +178,62 @@ def test_examples_never_extract_a_private_key(path: pathlib.Path) -> None: ) +def _env_key_names(tree: ast.AST) -> set[str]: + """Names bound from an environment variable whose name contains PRIVATE_KEY.""" + names: set[str] = set() + for node in ast.walk(tree): + if isinstance(node, ast.Assign) and isinstance(node.value, ast.Call): + call = node.value + src = ast.unparse(call.func) + if src in ("os.getenv", "os.environ.get") and call.args: + arg = call.args[0] + if isinstance(arg, ast.Constant) and "PRIVATE_KEY" in str(arg.value): + names |= {t.id for t in node.targets if isinstance(t, ast.Name)} + return names + + +def _env_key_misuses(tree: ast.AST, label: str) -> list[str]: + """Every read of an env private-key name must be either a truth test + (`if not KEY`, `if not (A and B)`) or the private_key= of CitrateClient.""" + names = _env_key_names(tree) + allowed: set[int] = set() + for node in ast.walk(tree): + if isinstance(node, ast.If | ast.While): + test = node.test + if isinstance(test, ast.UnaryOp) and isinstance(test.op, ast.Not): + test = test.operand + parts = test.values if isinstance(test, ast.BoolOp) else [test] + allowed |= {id(x) for x in parts if isinstance(x, ast.Name)} + if isinstance(node, ast.Call) and _attr_name(node) == "CitrateClient": + allowed |= {id(k.value) for k in node.keywords + if k.arg == "private_key" and isinstance(k.value, ast.Name)} + return [ + f"{label}:{n.lineno} uses {n.id} outside the client constructor" + for n in ast.walk(tree) + if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Load) and n.id in names and id(n) not in allowed + ] + + +@pytest.mark.parametrize("path", EXAMPLES, ids=lambda p: p.name) +def test_examples_use_the_env_key_only_to_build_a_client(path: pathlib.Path) -> None: + assert _env_key_misuses(_parse(path), path.name) == [] + + +@pytest.mark.parametrize( + "src", + [ + "K = os.getenv('CITRATE_PRIVATE_KEY')\nc = CitrateClient(private_key=K)\nprint(K)", + "K = os.environ.get('CITRATE_PRIVATE_KEY')\nlogging.info('key %s', K)", + "K = os.getenv('CITRATE_PRIVATE_KEY')\nc = CitrateClient(private_key=K)\nprint(f'{K[:10]}')", + "K = os.getenv('CITRATE_BUYER_PRIVATE_KEY')\nsave(K)", + ], +) +def test_env_key_check_refuses_other_uses(src: str) -> None: + tree = ast.parse(src) + assert _env_key_names(tree), "fixture binds no env key" + assert _env_key_misuses(tree, "fixture"), f"check accepted {src!r}" + + class _StopExample(BaseException): """Raised by the stand-in client so an example stops before any network I/O.""" @@ -207,11 +264,18 @@ def fake_client(*args: Any, **kwargs: Any) -> Any: @pytest.mark.parametrize("path", EXAMPLES, ids=lambda p: p.name) def test_examples_never_print_a_private_key( - path: pathlib.Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] + path: pathlib.Path, + monkeypatch: pytest.MonkeyPatch, + capfd: pytest.CaptureFixture[str], + caplog: pytest.LogCaptureFixture, ) -> None: - """Run each example's main() with the network replaced. Without a key in the - environment it must stop before building a signing client, and no run may - write a 32-byte hex secret (generated or supplied) to stdout or stderr.""" + """Run each example's main() up to the point it builds a client (the stand-in + client stops it there; later uses of the key are pinned statically by + test_examples_use_the_env_key_only_to_build_a_client). Without a key in the + environment it must stop before building a signing client, and up to that + point no 32-byte hex secret, generated or supplied, may reach stdout, stderr + (file-descriptor level) or a log record.""" + caplog.set_level(logging.DEBUG) generated: list[str] = [] real_get = KeyManager.get_private_key @@ -226,8 +290,8 @@ def recording_get(self: KeyManager) -> str: monkeypatch.delenv(var, raising=False) built = _run_example(path, monkeypatch) - out = capsys.readouterr() - text = out.out + out.err + out = capfd.readouterr() + text = out.out + out.err + caplog.text assert not [b for b in built if b.get("private_key")], ( f"{path.name} built a signing client with no key in the environment" ) @@ -237,9 +301,10 @@ def recording_get(self: KeyManager) -> str: for var in ("CITRATE_PRIVATE_KEY", "CITRATE_BUYER_PRIVATE_KEY"): monkeypatch.setenv(var, _ENV_KEY) + caplog.clear() _run_example(path, monkeypatch) - out = capsys.readouterr() - assert _ENV_KEY.removeprefix("0x") not in (out.out + out.err).lower(), ( + out = capfd.readouterr() + assert _ENV_KEY.removeprefix("0x") not in (out.out + out.err + caplog.text).lower(), ( f"{path.name} printed the environment private key" ) @@ -415,7 +480,11 @@ def test_publish_test_job_runs_the_suite_blocking(publish: dict[str, Any]) -> No pytest_steps = [s for s in _steps(jobs["test"]) if re.search(r"\bpytest\b", str(s.get("run", "")))] assert pytest_steps, "test job must run pytest" for step in pytest_steps: - assert re.search(r"^uv run --frozen pytest\b", str(step["run"]).strip()), step["run"] + # The whole suite: only output-verbosity flags, no selection (`-k`, a path, + # `--co`) that would let the gate pass without running every test. + cmd = str(step["run"]).strip().split() + assert cmd[:4] == ["uv", "run", "--frozen", "pytest"], step["run"] + assert set(cmd[4:]) <= {"-q", "-v", "-ra"}, f"pytest step narrows the run: {step['run']}" assert "if" not in step, f"pytest step is conditional: if: {step['if']}" for name, job in jobs.items(): assert "continue-on-error" not in job, f"job {name} sets continue-on-error"