Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,23 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [0.4.0] - 2026-07-30

### Added

- **Old-key-endorsed ActionReceipt rotation verification.** `verify_chain()`
accepts a pinned root, signed recorder session, and rotation
endorsements. It verifies each endorsement under the retiring key, binds it
to the exact prior sequence and tail hash, and authorizes the successor key.
Missing, altered, duplicate, cross-session, replayed, boundary-mismatched,
unknown-field, duplicate-key, and trailing-token endorsements fail closed.
- **Rotation endorsement API and CLI.** `load_rotation_endorsement()` and
`verify_rotation_endorsement()` expose strict standalone verification. The
CLI accepts repeatable `--rotation-endorsement FILE` plus `--session-id`.
- **Go-generated rotation conformance fixtures.** Python verifies the same
rotated chain and endorsement consumed by the Go, TypeScript, and Rust
implementations.

## [0.3.0] - 2026-07-24

### Fixed
Expand Down
30 changes: 30 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,12 +78,42 @@ consistency check in Go's `receipt.VerifyChain`.
`verify()` or `verify_evidence()`; v2 chain verification is reserved for a
follow-up release once the cross-version chain-linking rules are specified.

For an ActionReceipt v1 chain that rotated signing keys, pin the original root
and supply one old-key-signed endorsement for each rotation boundary:

```python
import pipelock_verify

endorsement = pipelock_verify.load_rotation_endorsement(
"receipt-rotation-2026-07-30.json"
)
chain = pipelock_verify.verify_chain(
"evidence-proxy.jsonl",
public_key_hex="4655a7e605c12ebb00a46037881c33c5bca5eb74b45a02e8e7261a7ff5a21678",
session_id="proxy",
rotation_endorsements=[endorsement],
)
```

The endorsement is verified under the retiring key and bound to the exact
prior sequence, tail hash, recorder session, and successor key. Missing,
altered, duplicate, replayed, cross-session, and unused endorsements fail
closed.

`session_id` must match `recorder_session` in every signed `session_open`, and
the root segment must contain one. A chain without that signed session binding
cannot be verified with endorsements.

### CLI

```bash
python -m pipelock_verify receipt.json
python -m pipelock_verify evidence.jsonl
python -m pipelock_verify evidence.jsonl --key 70b991eb77816fc4...
python -m pipelock_verify evidence.jsonl \
--key 4655a7e605c12ebb00a46037881c33c5bca5eb74b45a02e8e7261a7ff5a21678 \
--session-id proxy \
--rotation-endorsement receipt-rotation-2026-07-30.json
```

Exit codes match `pipelock verify-receipt`: 0 on success, 1 on failure.
Expand Down
10 changes: 9 additions & 1 deletion pipelock_verify/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,11 @@
evidence_receipt_hash,
verify_evidence,
)
from ._rotation import (
RotationEndorsement,
load_rotation_endorsement,
verify_rotation_endorsement,
)
from ._verify import (
ChainResult,
InvalidReceiptError,
Expand All @@ -60,7 +65,7 @@
verify_chain,
)

__version__ = "0.3.0"
__version__ = "0.4.0"

__all__ = [
"PAYLOAD_AUTHORITY",
Expand All @@ -71,12 +76,15 @@
"DirectoryKey",
"EvidenceVerifyResult",
"InvalidReceiptError",
"RotationEndorsement",
"VerifyResult",
"__version__",
"evidence_receipt_hash",
"fetch_directory",
"load_rotation_endorsement",
"parse_directory",
"verify",
"verify_chain",
"verify_evidence",
"verify_rotation_endorsement",
]
31 changes: 30 additions & 1 deletion pipelock_verify/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
from pathlib import Path

from . import __version__
from ._common import InvalidReceiptError
from ._rotation import load_rotation_endorsement
from ._verify import ChainResult, VerifyResult, verify, verify_chain


Expand Down Expand Up @@ -97,6 +99,19 @@ def main(argv: Sequence[str] | None = None) -> int:
default="auto",
help="force single or chain mode; default auto-detects from file suffix",
)
parser.add_argument(
"--session-id",
default="proxy",
help="signed recorder session for rotation endorsements; default proxy",
)
parser.add_argument(
"--rotation-endorsement",
action="append",
default=None,
type=Path,
metavar="FILE",
help="old-key-signed rotation endorsement; repeat for each rotation boundary",
)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
parser.add_argument(
"--version",
action="version",
Expand All @@ -113,7 +128,21 @@ def main(argv: Sequence[str] | None = None) -> int:
mode = args.mode if args.mode != "auto" else _detect_mode(path)

if mode == "chain":
chain_result = verify_chain(path, args.public_key_hex)
try:
endorsements = [
load_rotation_endorsement(endorsement_path)
for endorsement_path in (args.rotation_endorsement or [])
]
except (InvalidReceiptError, UnicodeDecodeError) as exc:
print(f"CHAIN BROKEN: {path}")
print(f" Error: {exc}")
return 1
chain_result = verify_chain(
path,
args.public_key_hex,
session_id=args.session_id,
rotation_endorsements=endorsements,
)
# Empty files are rejected at the CLI layer to match the Go CLI's
# behavior (internal/cli/signing/receipt.go returns an error when
# the extracted receipt list is empty). The library function keeps
Expand Down
223 changes: 223 additions & 0 deletions pipelock_verify/_rotation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,223 @@
"""Old-key-signed receipt rotation endorsement verification."""

from __future__ import annotations

import hashlib
import json
import re
from dataclasses import dataclass
from pathlib import Path
from typing import Any

from cryptography.exceptions import InvalidSignature, UnsupportedAlgorithm
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey

from ._common import InvalidReceiptError, _is_valid_rfc3339, loads_no_duplicate_keys

_VERSION = 1
_DOMAIN = b"pipelock-rotation-endorsement-v1\x00"
_SIGNATURE_PREFIX = "ed25519:"
_MAX_BYTES = 64 << 10
_FIELDS = frozenset(
{
"version",
"session_id",
"prior_signer_key",
"prior_final_seq",
"prior_tail_hash",
"new_signer_key",
"rotated_at",
"endorsement",
}
)
_LOWER_HEX_32 = re.compile(r"^[0-9a-f]{64}$")
_ED25519_SIGNATURE = re.compile(r"^ed25519:[0-9a-fA-F]{128}$")
_CANONICAL_UTC = re.compile(
r"^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}"
r"(?:\.[0-9]{0,8}[1-9])?Z$"
)


@dataclass(frozen=True)
class RotationEndorsement:
"""A retiring receipt key's authorization of its successor."""

version: int
session_id: str
prior_signer_key: str
prior_final_seq: int
prior_tail_hash: str
new_signer_key: str
rotated_at: str
endorsement: str


def _normalize_go_string(value: str) -> str:
"""Replace lone UTF-16 surrogates as Go encoding/json does."""
out: list[str] = []
index = 0
while index < len(value):
code = ord(value[index])
if 0xD800 <= code <= 0xDBFF:
if index + 1 < len(value) and 0xDC00 <= ord(value[index + 1]) <= 0xDFFF:
high = code - 0xD800
low = ord(value[index + 1]) - 0xDC00
out.append(chr(0x10000 + high * 0x400 + low))
index += 2
continue
out.append("\ufffd")
elif 0xDC00 <= code <= 0xDFFF:
out.append("\ufffd")
else:
out.append(value[index])
index += 1
return "".join(out)


def _require_string(value: Any, field: str) -> str:
if not isinstance(value, str) or not value:
raise InvalidReceiptError(f"rotation endorsement {field} is invalid")
return _normalize_go_string(value)


def _require_hex(value: Any, field: str) -> str:
text = _require_string(value, field)
if _LOWER_HEX_32.fullmatch(text) is None:
raise InvalidReceiptError(f"rotation endorsement {field} is invalid")
return text


def _decode(value: dict[str, Any]) -> RotationEndorsement:
if any(not isinstance(name, str) for name in value):
raise InvalidReceiptError("rotation endorsement field names must be strings")
unknown = set(value) - _FIELDS
if unknown:
raise InvalidReceiptError(
f"rotation endorsement contains unknown field {sorted(unknown)[0]}"
)
missing = _FIELDS - set(value)
if missing:
raise InvalidReceiptError(
f"rotation endorsement is missing required field {sorted(missing)[0]}"
)
version = value["version"]
if isinstance(version, bool) or not isinstance(version, int) or version != _VERSION:
raise InvalidReceiptError(f"unsupported rotation endorsement version {version!r}")
prior_final_seq = value["prior_final_seq"]
if (
isinstance(prior_final_seq, bool)
or not isinstance(prior_final_seq, int)
or not 0 <= prior_final_seq <= 2**64 - 1
):
raise InvalidReceiptError("rotation endorsement prior_final_seq is invalid")
session_id = _require_string(value["session_id"], "session_id")
if not session_id.strip():
raise InvalidReceiptError("rotation endorsement session_id is empty")
prior_key = _require_hex(value["prior_signer_key"], "prior_signer_key")
new_key = _require_hex(value["new_signer_key"], "new_signer_key")
if prior_key == new_key:
raise InvalidReceiptError("rotation endorsement successor key must differ from prior key")
rotated_at = _require_string(value["rotated_at"], "rotated_at")
if _CANONICAL_UTC.fullmatch(rotated_at) is None or not _is_valid_rfc3339(rotated_at):
raise InvalidReceiptError(
"rotation endorsement rotated_at must be canonical UTC RFC3339Nano"
)
return RotationEndorsement(
version=_VERSION,
session_id=session_id,
prior_signer_key=prior_key,
prior_final_seq=prior_final_seq,
prior_tail_hash=_require_hex(value["prior_tail_hash"], "prior_tail_hash"),
new_signer_key=new_key,
rotated_at=rotated_at,
endorsement=_require_string(value["endorsement"], "signature"),
)


def _canonical_bytes(endorsement: RotationEndorsement) -> bytes:
ordered = {
"version": endorsement.version,
"session_id": endorsement.session_id,
"prior_signer_key": endorsement.prior_signer_key,
"prior_final_seq": endorsement.prior_final_seq,
"prior_tail_hash": endorsement.prior_tail_hash,
"new_signer_key": endorsement.new_signer_key,
"rotated_at": endorsement.rotated_at,
}
encoded = json.dumps(
ordered,
ensure_ascii=False,
separators=(",", ":"),
)
encoded = (
encoded.replace("&", "\\u0026")
.replace("<", "\\u003c")
.replace(">", "\\u003e")
.replace("\u2028", "\\u2028")
.replace("\u2029", "\\u2029")
)
return encoded.encode()


def verify_rotation_endorsement(
source: RotationEndorsement | dict[str, Any] | str | bytes,
) -> RotationEndorsement:
"""Strictly parse and verify one rotation endorsement."""
if isinstance(source, RotationEndorsement):
endorsement = _decode(vars(source))
else:
if isinstance(source, bytes):
if len(source) > _MAX_BYTES:
raise InvalidReceiptError(f"rotation endorsement exceeds {_MAX_BYTES} bytes")
try:
text = source.decode("utf-8")
parsed = loads_no_duplicate_keys(text)
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
raise InvalidReceiptError(f"unmarshal rotation endorsement: {exc}") from exc
elif isinstance(source, str):
try:
source_size = len(source.encode())
except UnicodeEncodeError as exc:
raise InvalidReceiptError(f"unmarshal rotation endorsement: {exc}") from exc
if source_size > _MAX_BYTES:
raise InvalidReceiptError(f"rotation endorsement exceeds {_MAX_BYTES} bytes")
try:
parsed = loads_no_duplicate_keys(source)
except json.JSONDecodeError as exc:
raise InvalidReceiptError(f"unmarshal rotation endorsement: {exc}") from exc
elif isinstance(source, dict):
parsed = source
else:
raise InvalidReceiptError("rotation endorsement must be a JSON object")
if not isinstance(parsed, dict):
raise InvalidReceiptError("rotation endorsement must be a JSON object")
endorsement = _decode(parsed)
if _ED25519_SIGNATURE.fullmatch(endorsement.endorsement) is None:
raise InvalidReceiptError("invalid endorsement signature")
try:
signature = bytes.fromhex(endorsement.endorsement[len(_SIGNATURE_PREFIX) :])
except ValueError as exc:
raise InvalidReceiptError("invalid endorsement signature") from exc
if len(signature) != 64:
raise InvalidReceiptError("invalid endorsement signature")
digest = hashlib.sha256(_DOMAIN + _canonical_bytes(endorsement)).digest()
try:
public_key = Ed25519PublicKey.from_public_bytes(bytes.fromhex(endorsement.prior_signer_key))
except (ValueError, UnsupportedAlgorithm) as exc:
raise InvalidReceiptError("rotation endorsement signer key is invalid") from exc
try:
public_key.verify(signature, digest)
except InvalidSignature as exc:
raise InvalidReceiptError("rotation endorsement signature verification failed") from exc
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
return endorsement


def load_rotation_endorsement(path: str | Path) -> RotationEndorsement:
"""Read and verify one bounded endorsement file."""
file = Path(path)
try:
with file.open("rb") as handle:
data = handle.read(_MAX_BYTES + 1)
except OSError as exc:
raise InvalidReceiptError(f"read rotation endorsement: {exc}") from exc
return verify_rotation_endorsement(data)
Loading
Loading