Skip to content
You are reading the Ratify Protocol v2 beta documentation. Protocol v1 remains available at the site root.

Python SDK (v2)

Terminal window
# One distribution for both lines: import ratify_protocol.v2 for v2; ratify_protocol stays v1.
# The protocol-v2 extra installs the v2 signing backend.
pip install "ratify-protocol[protocol-v2]==2.0.0b2"

Package: ratify-protocol 2.x with the protocol-v2 extra, module ratify_protocol.v2. API documentation: the docstrings of the ratify_protocol.v2 modules.

  • One distribution carries both lines: ratify_protocol is the unchanged v1 API and ratify_protocol.v2 is v2. import ratify_protocol never loads v2.
  • Signing runs only in the native backend ratify-protocol-native-v2, which the protocol-v2 extra installs and which is versioned in lockstep with the package. Without it, every signer raises ImportError; verification falls back to a slower pure-Python verifier.
  • time_window constraints fail closed unless the pinned tzdata release is installed; the extra installs it.
  • An unpinned pip install ratify-protocol resolves to the v2 beta, because every published version is a prerelease. v1 users who want to stay on the v1 version pin ratify-protocol<2.
  • v2 calls that reach stores, providers, or signers take a context_v2.Context as their first argument.

Production verifiers implement the claim store, rate reservations, receipt publisher, independent checkpoint, and journal store durably. The in-memory implementations in ratify_protocol.v2.v2reference (every type ends in TestOnly) are for tests only. See Deployment profiles.

Delegate, present, verify, and release: Python quickstart (development only).

An issuer’s status publisher signs revocation lists and pushes under a separate status key; the verifier applies them to its journal. See Status from signed evidence.

examples/v2/python/signed_status.py
"""Ratify Protocol v2 signed status: a status publisher under a separate
status key, journal ingestion, and a revocation that turns a later
verification into deny.
DEVELOPMENT ONLY. This program uses the in-memory reference stores from
ratify_protocol.v2.v2reference. A production verifier supplies durable Part B
stores, an anchored journal store and an independent checkpoint (SPEC-v2 §7).
Run: python examples/v2/python/signed_status.py
"""
from ratify_protocol.v2 import background, error_class_of, key_id_v2
from ratify_protocol.v2.challenge_issuance_v2 import V2ChallengeIssuer, V2ChallengeIssueRequest, load_expected_challenge_v2
from ratify_protocol.v2.constraints_v2 import TZDB_VERSION_V2
from ratify_protocol.v2.context_policy_v2 import new_v2_context_policy
from ratify_protocol.v2.protocol_v2 import (
DelegationCertV2,
ProofBundleV2,
encode_proof_bundle_v2,
encode_revocation_list_v2,
encode_revocation_push_v2,
sign_delegation_cert_v2,
sign_proof_bundle_v2,
)
from ratify_protocol.v2.release_v2 import V2_RELEASE_RELEASED, V2ReleaseConfig, release_v2_decision
from ratify_protocol.v2.security_journal_v2 import (
apply_revocation_list_to_journal_v2,
apply_revocation_push_to_journal_v2,
configure_status_key_epoch_v2,
record_security_key_role_v2,
revocation_status_from_journal_v2,
)
from ratify_protocol.v2.signing_v2 import generate_keypair_v2
from ratify_protocol.v2.status_batch_v2 import V2StatusEvidenceBatch, V2StatusEvidenceObject
from ratify_protocol.v2.status_provenance_v2 import V2StatusKeyConfig
from ratify_protocol.v2.status_publisher_v2 import new_v2_status_publisher_with_key
from ratify_protocol.v2.status_state_v2 import RevocationStatusPolicyV2
from ratify_protocol.v2.v2reference.challenges import TestOnlyChallengeIssuanceStore
from ratify_protocol.v2.v2reference.journal import new_journal_store
from ratify_protocol.v2.v2reference.store import Store
from ratify_protocol.v2.verify_v2 import (
V2_STAGE_COMMITTED,
V2TrustResolution,
V2VerifyCallbacks,
V2VerifyRequest,
verify_proof_bundle_v2,
)
START = 1800000000
NAMESPACE = "signed-status"
EPOCH = 1
LOG_ID = "00000000000000000000000000000002"
CERT_ID = "status-demo-cert-1"
def b(value: bool) -> str:
return "true" if value else "false"
def main() -> None:
ctx = background()
print("Ratify Protocol v2 signed status")
print("development only: in-memory reference stores")
root_pub, root_priv = generate_keypair_v2()
agent_pub, agent_priv = generate_keypair_v2()
status_pub, status_priv = generate_keypair_v2()
verifier_pub, verifier_priv = generate_keypair_v2()
root_id, agent_id, verifier_id = key_id_v2(root_pub), key_id_v2(agent_pub), key_id_v2(verifier_pub)
cert = sign_delegation_cert_v2(DelegationCertV2(
version=2, cert_id=CERT_ID,
issuer_id=root_id, issuer_pub_key=root_pub, subject_id=agent_id, subject_pub_key=agent_pub,
scope=["data:read"], constraints=[], issued_at=START, expires_at=START + 86400,
), root_priv)
print(f"delegation: {CERT_ID} scope=data:read")
# The journal is the verifier's anchored record of key roles, status-key
# epochs and accepted status. Roles are recorded once, when the
# deployment authenticates its trust configuration.
journal = new_journal_store()
for role, pub in (("issuer", root_pub), ("delegation", agent_pub), ("verifier", verifier_pub)):
record_security_key_role_v2(ctx, journal, role, pub)
configure_status_key_epoch_v2(ctx, journal, root_id, 1, status_pub)
print("journal: key roles recorded; status key configured for the root at epoch 1")
# Role separation: the root key can never sign status for itself.
try:
new_v2_status_publisher_with_key(ctx, journal, root_pub, root_priv, 3600)
refused = ""
except Exception as exc: # noqa: BLE001 - the example prints the error class
refused = error_class_of(exc)
print(f"publisher with the root key as status key: refused ({refused})")
publisher = new_v2_status_publisher_with_key(ctx, journal, root_pub, status_priv, 3600)
policy = RevocationStatusPolicyV2(max_list_lifetime_seconds=3600, max_status_age_seconds=3600, clock_skew_seconds=5)
# Genesis: sequence 1, nothing revoked. The caller persists the returned
# state before publishing the signed list.
genesis = publisher.genesis(ctx, START)
genesis_wire = encode_revocation_list_v2(genesis.list)
print(f"publisher: genesis list sequence {genesis.list.sequence}")
apply_revocation_list_to_journal_v2(ctx, journal, genesis.list, root_id, 1, status_pub, policy, START)
status = revocation_status_from_journal_v2(ctx, journal, root_id, CERT_ID, 1, status_pub, policy, START)
print(f"journal: ingested list sequence {genesis.list.sequence}; {CERT_ID} is {status.status}")
store = Store(START, 30, LOG_ID, verifier_priv)
issuance = TestOnlyChallengeIssuanceStore()
evidence = [V2StatusEvidenceObject(object_type=3, wire=genesis_wire)]
def trust(_ctx, chain):
if chain[-1].issuer_id == root_id:
return V2TrustResolution(outcome="trusted", root_key=root_pub)
return V2TrustResolution(outcome="untrusted")
# The provider returns signed objects only; the verifier checks each
# signature against the configured status key and applies it to the
# journal before it derives a status.
def status_evidence(_ctx, _req):
return V2StatusEvidenceBatch(objects=evidence)
def verify_and_release(label: str) -> None:
"""One complete live verification at the store's current time."""
challenge = V2ChallengeIssuer(clock=store, store=issuance).issue_challenge_v2(ctx, V2ChallengeIssueRequest(
verifier_namespace=NAMESPACE, replay_epoch=EPOCH, verifier_id=verifier_id,
lifetime_seconds=120, expected_agent_id=agent_id, expected_agent_public_key=agent_pub,
))
bundle = sign_proof_bundle_v2(ProofBundleV2(
version=2, verifier_id=verifier_id, agent_id=agent_id, agent_pub_key=agent_pub,
delegations=[cert], challenge=challenge.value, challenge_at=challenge.issued_at,
delegation_digest=b"", challenge_sig=None, # computed by sign_proof_bundle_v2
), agent_priv)
expected = load_expected_challenge_v2(ctx, issuance, NAMESPACE, EPOCH, bundle.challenge)
outcome = verify_proof_bundle_v2(ctx, V2VerifyRequest(
bundle=encode_proof_bundle_v2(bundle), expected=expected,
context_policy=new_v2_context_policy("example.signed-status/v1", False, [], None),
required_scope="data:read", verifier_namespace=NAMESPACE, replay_epoch=EPOCH, verifier_id=verifier_id, now=store.now(),
max_challenge_age_seconds=300, future_skew_seconds=5, tzdb_version=TZDB_VERSION_V2,
status_keys={root_id: V2StatusKeyConfig(epoch=1, key=status_pub)}, status_policy=policy,
), V2VerifyCallbacks(claim_store=store, trust=trust, status_evidence=status_evidence, status_journal=journal))
if outcome.stage != V2_STAGE_COMMITTED:
raise SystemExit(f"verify stopped at {outcome.stage}: {outcome.error}")
receipt_wire = store.publish_v2_receipt(ctx, outcome.committed.claim_id(), outcome.committed.receipt_body())
result = release_v2_decision(ctx, outcome.committed, receipt_wire, V2ReleaseConfig(
verifier_public_key=verifier_pub, log_id=LOG_ID, claim_store=store, checkpoint=store,
))
if result.status != V2_RELEASE_RELEASED:
raise SystemExit(f"release {result.status}: {result.reason}")
d = result.decision
receipt = d.receipt()
print(f"{label}: decision={d.decision()} reason={d.reason()} "
f"status_assessment={receipt.status_assessment} allowed={b(d.allowed(ctx, store))}")
store.set_time(START + 5)
verify_and_release("verify before revocation")
# Revoke: a push with the newly revoked ID and the cumulative list, both
# at sequence 2.
revoked = publisher.revoke(ctx, genesis.state, [CERT_ID], START + 10)
push_wire = encode_revocation_push_v2(revoked.push)
list_wire = encode_revocation_list_v2(revoked.list)
print(f"publisher: revoked {CERT_ID} (push sequence {revoked.push.sequence}, list sequence {revoked.list.sequence})")
apply_revocation_push_to_journal_v2(ctx, journal, revoked.push, root_id, 1, status_pub, policy, START + 10)
status = revocation_status_from_journal_v2(ctx, journal, root_id, CERT_ID, 1, status_pub, policy, START + 10)
print(f"journal: ingested push sequence {revoked.push.sequence}; {CERT_ID} is {status.status}")
evidence = [V2StatusEvidenceObject(object_type=5, wire=push_wire), V2StatusEvidenceObject(object_type=3, wire=list_wire)]
store.set_time(START + 15)
verify_and_release("verify after revocation")
if __name__ == "__main__":
main()

Source: examples/v2/python/signed_status at commit 5ca7585c2c1d, SHA-256 checked at build time.

An exact custom: required scope and a registered evaluator profile. See Delegation and constraints.

examples/v2/python/custom_scope.py
"""Ratify Protocol v2 custom scope and the standard max_count evaluator
profile (com.ratifyprotocol.max_count/v1).
DEVELOPMENT ONLY. This program uses the in-memory reference stores from
ratify_protocol.v2.v2reference. A production verifier supplies durable Part B
stores and an independent checkpoint (SPEC-v2 §7).
Run: python examples/v2/python/custom_scope.py
"""
from dataclasses import replace
from ratify_protocol.v2 import background, error_class_of, key_id_v2
from ratify_protocol.v2.challenge_issuance_v2 import V2ChallengeIssuer, V2ChallengeIssueRequest, load_expected_challenge_v2
from ratify_protocol.v2.constraint_evaluator_v2 import (
CONSTRAINT_MAX_COUNT_V2,
PROFILE_MAX_COUNT_V2,
constraint_profile_digest_v2,
new_constraint_evaluator_registry_v2,
standard_max_count_evaluator_v2,
)
from ratify_protocol.v2.constraints_v2 import TZDB_VERSION_V2, ConstraintContextV2, ConstraintV2
from ratify_protocol.v2.context_policy_v2 import new_v2_context_policy
from ratify_protocol.v2.protocol_v2 import (
DelegationCertV2,
ProofBundleV2,
encode_proof_bundle_v2,
encode_revocation_list_v2,
sign_delegation_cert_v2,
sign_proof_bundle_v2,
)
from ratify_protocol.v2.release_v2 import V2_RELEASE_RELEASED, V2ReleaseConfig, release_v2_decision
from ratify_protocol.v2.security_journal_v2 import configure_status_key_epoch_v2, record_security_key_role_v2
from ratify_protocol.v2.signing_v2 import generate_keypair_v2
from ratify_protocol.v2.status_batch_v2 import V2StatusEvidenceBatch, V2StatusEvidenceObject
from ratify_protocol.v2.status_provenance_v2 import V2StatusKeyConfig
from ratify_protocol.v2.status_publisher_v2 import new_v2_status_publisher_with_key
from ratify_protocol.v2.status_state_v2 import RevocationStatusPolicyV2
from ratify_protocol.v2.v2reference.challenges import TestOnlyChallengeIssuanceStore
from ratify_protocol.v2.v2reference.journal import new_journal_store
from ratify_protocol.v2.v2reference.store import Store
from ratify_protocol.v2.verify_v2 import (
V2_STAGE_COMMITTED,
V2TrustResolution,
V2VerifyCallbacks,
V2VerifyRequest,
verify_proof_bundle_v2,
)
START = 1800000000
NAMESPACE = "custom-scope"
EPOCH = 1
LOG_ID = "00000000000000000000000000000003"
CUSTOM_SCOPE = "custom:acme:deploy"
def b(value: bool) -> str:
return "true" if value else "false"
def main() -> None:
ctx = background()
print("Ratify Protocol v2 custom scope and max_count profile")
print("development only: in-memory reference stores")
root_pub, root_priv = generate_keypair_v2()
agent_pub, agent_priv = generate_keypair_v2()
status_pub, status_priv = generate_keypair_v2()
verifier_pub, verifier_priv = generate_keypair_v2()
root_id, agent_id, verifier_id = key_id_v2(root_pub), key_id_v2(agent_pub), key_id_v2(verifier_pub)
template = DelegationCertV2(
version=2, cert_id="custom-scope-cert-1",
issuer_id=root_id, issuer_pub_key=root_pub, subject_id=agent_id, subject_pub_key=agent_pub,
scope=[], constraints=[], issued_at=START, expires_at=START + 86400,
)
# A custom scope is one exact name. Wildcards are invalid.
try:
sign_delegation_cert_v2(replace(template, scope=["custom:*"]), root_priv)
refused = ""
except Exception as exc: # noqa: BLE001 - the example prints the error class
refused = error_class_of(exc)
print(f"issue scope custom:*: refused ({refused})")
# The certificate carries an extension constraint. Only a verifier that
# registered the max_count/v1 profile for this type can evaluate it.
cert = sign_delegation_cert_v2(replace(
template, scope=[CUSTOM_SCOPE],
constraints=[ConstraintV2(type=CONSTRAINT_MAX_COUNT_V2, params={"counter": "nodes", "max": 5})],
), root_priv)
print(f"delegation: scope={CUSTOM_SCOPE} constraint={CONSTRAINT_MAX_COUNT_V2}(counter=nodes, max=5)")
max_count = standard_max_count_evaluator_v2()
digest = constraint_profile_digest_v2(max_count.descriptor)
print(f"profile: {PROFILE_MAX_COUNT_V2} digest={digest}")
registry = new_constraint_evaluator_registry_v2(1.0, max_count)
journal = new_journal_store()
record_security_key_role_v2(ctx, journal, "issuer", root_pub)
configure_status_key_epoch_v2(ctx, journal, root_id, 1, status_pub)
publisher = new_v2_status_publisher_with_key(ctx, journal, root_pub, status_priv, 3600)
status_wire = encode_revocation_list_v2(publisher.genesis(ctx, START).list)
store = Store(START, 30, LOG_ID, verifier_priv)
issuance = TestOnlyChallengeIssuanceStore()
def trust(_ctx, chain):
if chain[-1].issuer_id == root_id:
return V2TrustResolution(outcome="trusted", root_key=root_pub)
return V2TrustResolution(outcome="untrusted")
def status_evidence(_ctx, _req):
return V2StatusEvidenceBatch(objects=[V2StatusEvidenceObject(object_type=3, wire=status_wire)])
def attempt(label: str, nodes: int, evaluators) -> None:
"""Verify one request for `nodes` nodes and release the result."""
store.set_time(store.now() + 1)
challenge = V2ChallengeIssuer(clock=store, store=issuance).issue_challenge_v2(ctx, V2ChallengeIssueRequest(
verifier_namespace=NAMESPACE, replay_epoch=EPOCH, verifier_id=verifier_id,
lifetime_seconds=120, expected_agent_id=agent_id, expected_agent_public_key=agent_pub,
))
bundle = sign_proof_bundle_v2(ProofBundleV2(
version=2, verifier_id=verifier_id, agent_id=agent_id, agent_pub_key=agent_pub,
delegations=[cert], challenge=challenge.value, challenge_at=challenge.issued_at,
delegation_digest=b"", challenge_sig=None, # computed by sign_proof_bundle_v2
), agent_priv)
expected = load_expected_challenge_v2(ctx, issuance, NAMESPACE, EPOCH, bundle.challenge)
outcome = verify_proof_bundle_v2(ctx, V2VerifyRequest(
bundle=encode_proof_bundle_v2(bundle), expected=expected,
context_policy=new_v2_context_policy("example.custom-scope/v1", False, [], None),
required_scope=CUSTOM_SCOPE, verifier_namespace=NAMESPACE, replay_epoch=EPOCH, verifier_id=verifier_id, now=store.now(),
max_challenge_age_seconds=300, future_skew_seconds=5, tzdb_version=TZDB_VERSION_V2,
# The requested quantity comes from the authenticated request,
# never from the proof.
context=ConstraintContextV2(extension_counts={"nodes": nodes}),
constraint_evaluators=evaluators,
status_keys={root_id: V2StatusKeyConfig(epoch=1, key=status_pub)},
status_policy=RevocationStatusPolicyV2(max_list_lifetime_seconds=3600, max_status_age_seconds=3600, clock_skew_seconds=5),
), V2VerifyCallbacks(claim_store=store, trust=trust, status_evidence=status_evidence, status_journal=journal))
if outcome.stage != V2_STAGE_COMMITTED:
raise SystemExit(f"verify stopped at {outcome.stage}: {outcome.error}")
receipt_wire = store.publish_v2_receipt(ctx, outcome.committed.claim_id(), outcome.committed.receipt_body())
result = release_v2_decision(ctx, outcome.committed, receipt_wire, V2ReleaseConfig(
verifier_public_key=verifier_pub, log_id=LOG_ID, claim_store=store, checkpoint=store,
))
if result.status != V2_RELEASE_RELEASED:
raise SystemExit(f"release {result.status}: {result.reason}")
d = result.decision
print(f"{label}: decision={d.decision()} reason={d.reason()} allowed={b(d.allowed(ctx, store))}")
for ref in d.receipt().constraint_evaluators or []:
print(f" receipt constraint_evaluators: {ref.type} {ref.profile_digest}")
attempt("request nodes=3", 3, registry)
attempt("request nodes=8", 8, registry)
attempt("request nodes=3 without the profile registered", 3, None)
if __name__ == "__main__":
main()

Source: examples/v2/python/custom_scope at commit 5ca7585c2c1d, SHA-256 checked at build time.

Signing through a key held outside the SDK, with verify-before-use. See Typed signing and key IDs.

examples/v2/python/external_signer.py
"""Ratify Protocol v2 external signer: a signing provider holds the private
key; the SDK prepares each typed statement and verifies every returned
signature before using it.
The provider here is an in-process stand-in for a remote signing service.
The interface makes no claim about any particular KMS or HSM.
The stand-in needs an Ed25519 and ML-DSA-65 (FIPS 204, with a context string)
signing primitive. The SDK's runtime dependencies expose none publicly, so
this example borrows the key type of the ratify-protocol-native-v2
extension. A real provider uses its own signing service instead.
Run: python examples/v2/python/external_signer.py
"""
import os
import ratify_protocol_native_v2 as native
from ratify_protocol.v2 import HybridPublicKey, HybridSignature, SignerModeV2, background, error_class_of, key_id_v2
from ratify_protocol.v2.protocol_v2 import (
DelegationCertV2,
ProofBundleV2,
sign_delegation_cert_v2_with_signer,
sign_proof_bundle_v2_with_signer,
verify_delegation_cert_v2_signature,
verify_proof_bundle_v2_signatures,
)
from ratify_protocol.v2.signing_v2 import generate_keypair_v2
START = 1800000000
def new_key():
return native.HybridSigningKey.from_seeds(os.urandom(32), os.urandom(32))
class Provider:
"""A signing service. Its private key never leaves it. It signs in direct
mode: Ed25519 over the 77-byte message M and ML-DSA-65 over M with the
SDK-chosen context string. Implements the SignerV2 protocol."""
def __init__(self, name: str):
self.name = name
self.key = new_key()
self.ml_key = self.key # the key used for ML-DSA-65; differs only for a faulty provider
ed, ml = self.key.public_key()
self.pub = HybridPublicKey(ed25519=bytes(ed), ml_dsa_65=bytes(ml))
self.log = []
def public_key_v2(self) -> HybridPublicKey:
return self.pub
def mode_v2(self) -> SignerModeV2:
return SignerModeV2.DIRECT
def sign_v2(self, ctx, req) -> HybridSignature:
# A provider refuses any request for a key it does not hold.
if bytes(req.public_key.ed25519) != self.pub.ed25519 or bytes(req.public_key.ml_dsa_65) != self.pub.ml_dsa_65:
raise ValueError(f"{self.name}: request names a key this provider does not hold")
self.log.append(f"{self.name} signed: mode=direct message={len(req.message)} bytes "
f"context={req.mldsa_context.decode('ascii')}")
ed_sig, _ = self.key._sign(req.message, req.mldsa_context)
_, ml_sig = self.ml_key._sign(req.message, req.mldsa_context)
return HybridSignature(ed25519=bytes(ed_sig), ml_dsa_65=bytes(ml_sig))
def verified(check, obj) -> str:
try:
check(obj)
return "true"
except Exception: # noqa: BLE001
return "false"
def main() -> None:
ctx = background()
print("Ratify Protocol v2 external signer")
issuer = Provider("issuer provider")
agent = Provider("agent provider")
verifier_pub, _ = generate_keypair_v2()
issuer_id, agent_id, verifier_id = key_id_v2(issuer.pub), key_id_v2(agent.pub), key_id_v2(verifier_pub)
cert = sign_delegation_cert_v2_with_signer(ctx, DelegationCertV2(
version=2, cert_id="external-signer-cert-1",
issuer_id=issuer_id, issuer_pub_key=issuer.pub, subject_id=agent_id, subject_pub_key=agent.pub,
scope=["files:read"], constraints=[], issued_at=START, expires_at=START + 86400,
), issuer)
print(issuer.log[0])
print(f"delegation: signature verified by the SDK ({verified(verify_delegation_cert_v2_signature, cert)})")
unsigned = ProofBundleV2(
version=2, verifier_id=verifier_id, agent_id=agent_id, agent_pub_key=agent.pub,
delegations=[cert], challenge=bytes([0x42]) * 32, challenge_at=START,
delegation_digest=b"", challenge_sig=None, # computed by the signing function
)
bundle = sign_proof_bundle_v2_with_signer(ctx, unsigned, agent)
print(agent.log[0])
print(f"proof bundle: signatures verified by the SDK ({verified(verify_proof_bundle_v2_signatures, bundle)})")
# A faulty provider returns an ML-DSA-65 signature from a different key.
# The SDK verifies before use, so nothing is signed.
agent.ml_key = new_key()
try:
sign_proof_bundle_v2_with_signer(ctx, unsigned, agent)
refused = ""
except Exception as exc: # noqa: BLE001 - the example prints the error class
refused = error_class_of(exc)
print(f"faulty provider: refused ({refused})")
if __name__ == "__main__":
main()

Source: examples/v2/python/external_signer at commit 5ca7585c2c1d, SHA-256 checked at build time.

The SDK runs the shared corpus in testvectors/v2. Which files each SDK runs, and the results at the tag, are recorded in the release notes and in docs/V2_REFERENCE_COMPATIBILITY.md.