Go SDK (v2)
Install
Section titled “Install”Package: github.com/identities-ai/ratify-protocol/v2. API documentation: pkg.go.dev.
- The
/v2module keeps the v1 API next to the v2 API, so v1 verification stays available in the same build. - Every v2 call that can block takes a
context.Context; cancellation follows SPEC-v2 §6.11. - Released decisions have unexported fields;
ReleaseV2Decisionis the only constructor.
Part B stores
Section titled “Part B stores”Production verifiers implement the claim store, rate reservations, receipt publisher,
independent checkpoint, and journal store durably. The in-memory implementations in
github.com/identities-ai/ratify-protocol/v2/v2reference (every type ends in TestOnly) are for tests only. See Deployment profiles.
Quickstart
Section titled “Quickstart”Delegate, present, verify, and release: Go quickstart (development only).
Examples
Section titled “Examples”Signed status
Section titled “Signed status”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.
// 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// package v2reference. A production verifier supplies durable Part B stores,// an anchored journal store and an independent checkpoint (SPEC-v2 §7).//// Run from the repository root: go run ./examples/v2/go/signed_statuspackage main
import ( "context" "fmt" "os"
ratify "github.com/identities-ai/ratify-protocol/v2" "github.com/identities-ai/ratify-protocol/v2/v2reference")
const ( start = int64(1800000000) namespace = "signed-status" epoch = int64(1) logID = "00000000000000000000000000000002" certID = "status-demo-cert-1")
func main() { if err := run(); err != nil { fmt.Fprintln(os.Stderr, "error:", err) os.Exit(1) }}
func run() error { ctx := context.Background() fmt.Println("Ratify Protocol v2 signed status") fmt.Println("development only: in-memory reference stores")
rootPub, rootPriv, err := ratify.GenerateHybridKeypair() if err != nil { return err } agentPub, agentPriv, err := ratify.GenerateHybridKeypair() if err != nil { return err } statusPub, statusPriv, err := ratify.GenerateHybridKeypair() if err != nil { return err } verifierPub, verifierPriv, err := ratify.GenerateHybridKeypair() if err != nil { return err } rootID, _ := ratify.KeyIDV2(rootPub) agentID, _ := ratify.KeyIDV2(agentPub) verifierID, _ := ratify.KeyIDV2(verifierPub)
cert, err := ratify.SignDelegationCertV2(&ratify.DelegationCertV2{ Version: 2, CertID: certID, IssuerID: rootID, IssuerPubKey: rootPub, SubjectID: agentID, SubjectPubKey: agentPub, Scope: []string{"data:read"}, Constraints: []ratify.ConstraintV2{}, IssuedAt: start, ExpiresAt: start + 86400, }, rootPriv) if err != nil { return err } fmt.Printf("delegation: %s scope=data:read\n", certID)
// 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, err := v2reference.NewJournalStore() if err != nil { return err } for _, r := range []struct { role string pub ratify.HybridPublicKey }{{"issuer", rootPub}, {"delegation", agentPub}, {"verifier", verifierPub}} { if _, err := ratify.RecordSecurityKeyRoleV2(ctx, journal, r.role, r.pub); err != nil { return err } } if _, err := ratify.ConfigureStatusKeyEpochV2(ctx, journal, rootID, 1, statusPub); err != nil { return err } fmt.Println("journal: key roles recorded; status key configured for the root at epoch 1")
// Role separation: the root key can never sign status for itself. _, err = ratify.NewV2StatusPublisherWithKey(ctx, journal, rootPub, rootPriv, 3600) fmt.Printf("publisher with the root key as status key: refused (%s)\n", ratify.V2ErrorClassOf(err))
publisher, err := ratify.NewV2StatusPublisherWithKey(ctx, journal, rootPub, statusPriv, 3600) if err != nil { return err } policy := ratify.RevocationStatusPolicyV2{MaxListLifetimeSeconds: 3600, MaxStatusAgeSeconds: 3600, ClockSkewSeconds: 5}
// Genesis: sequence 1, nothing revoked. The caller persists the returned // state before publishing the signed list. genesis, err := publisher.Genesis(ctx, start) if err != nil { return err } genesisWire, err := ratify.EncodeRevocationListV2(genesis.List) if err != nil { return err } fmt.Printf("publisher: genesis list sequence %d\n", genesis.List.Sequence) if _, err := ratify.ApplyRevocationListToJournalV2(ctx, journal, genesis.List, rootID, 1, statusPub, policy, start); err != nil { return err } status, err := ratify.RevocationStatusFromJournalV2(ctx, journal, rootID, certID, 1, statusPub, policy, start) if err != nil { return err } fmt.Printf("journal: ingested list sequence %d; %s is %s\n", genesis.List.Sequence, certID, status.Status)
store, err := v2reference.NewStore(start, 30, logID, verifierPriv) if err != nil { return err } issuance := v2reference.NewTestOnlyChallengeIssuanceStore() evidence := []ratify.V2StatusEvidenceObject{{ObjectType: 3, Wire: genesisWire}}
// verifyAndRelease runs one complete live verification at the store's // current time and returns the released decision. verifyAndRelease := func(label string) error { challenge, err := ratify.V2ChallengeIssuer{Clock: store, Store: issuance}.IssueChallengeV2(ctx, ratify.V2ChallengeIssueRequest{ VerifierNamespace: namespace, ReplayEpoch: epoch, VerifierID: verifierID, LifetimeSeconds: 120, ExpectedAgentID: agentID, ExpectedAgentPublicKey: &agentPub, }) if err != nil { return err } bundle, err := ratify.SignProofBundleV2(&ratify.ProofBundleV2{ Version: 2, VerifierID: verifierID, AgentID: agentID, AgentPubKey: agentPub, Delegations: []ratify.DelegationCertV2{*cert}, Challenge: challenge.Value, ChallengeAt: challenge.IssuedAt, }, agentPriv) if err != nil { return err } wire, err := ratify.EncodeProofBundleV2(bundle) if err != nil { return err } expected, err := ratify.LoadExpectedChallengeV2(ctx, issuance, namespace, epoch, bundle.Challenge) if err != nil { return err } contextPolicy, err := ratify.NewV2ContextPolicy("example.signed-status/v1", false, nil, nil) if err != nil { return err } outcome, err := ratify.VerifyProofBundleV2(ctx, ratify.V2VerifyRequest{ Bundle: wire, Expected: expected, ContextPolicy: contextPolicy, RequiredScope: "data:read", VerifierNamespace: namespace, ReplayEpoch: epoch, VerifierID: verifierID, Now: store.Now(), MaxChallengeAgeSeconds: 300, FutureSkewSeconds: 5, TZDBVersion: ratify.TZDBVersionV2, StatusKeys: map[string]ratify.V2StatusKeyConfig{rootID: {Epoch: 1, Key: statusPub}}, StatusPolicy: policy, }, ratify.V2VerifyCallbacks{ ClaimStore: store, Trust: func(_ context.Context, chain []ratify.DelegationCertV2) (ratify.V2TrustResolution, error) { if chain[len(chain)-1].IssuerID == rootID { return ratify.V2TrustResolution{Outcome: ratify.V2TrustTrusted, RootKey: rootPub}, nil } return ratify.V2TrustResolution{Outcome: ratify.V2TrustUntrusted}, nil }, // 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. StatusEvidence: func(context.Context, ratify.V2StatusEvidenceRequest) (ratify.V2StatusEvidenceBatch, error) { return ratify.V2StatusEvidenceBatch{Objects: evidence}, nil }, StatusJournal: journal, }) if err != nil { return err } if outcome.Stage != ratify.V2StageCommitted { return fmt.Errorf("verify stopped at %s: %v", outcome.Stage, outcome.Error) } receiptWire, err := store.PublishV2Receipt(ctx, outcome.Committed.ClaimID(), outcome.Committed.ReceiptBody()) if err != nil { return err } result := ratify.ReleaseV2Decision(ctx, outcome.Committed, receiptWire, ratify.V2ReleaseConfig{ VerifierPublicKey: verifierPub, LogID: logID, ClaimStore: store, Checkpoint: store, }) if result.Status != ratify.V2ReleaseReleased { return fmt.Errorf("release %s: %s", result.Status, result.Reason) } receipt, err := result.Decision.Receipt() if err != nil { return err } fmt.Printf("%s: decision=%s reason=%s status_assessment=%s allowed=%t\n", label, result.Decision.Decision(), result.Decision.Reason(), receipt.StatusAssessment, result.Decision.Allowed(ctx, store)) return nil }
store.SetTime(start + 5) if err := verifyAndRelease("verify before revocation"); err != nil { return err }
// Revoke: a push with the newly revoked ID and the cumulative list, both // at sequence 2. revoked, err := publisher.Revoke(ctx, genesis.State, []string{certID}, start+10) if err != nil { return err } pushWire, err := ratify.EncodeRevocationPushV2(revoked.Push) if err != nil { return err } listWire, err := ratify.EncodeRevocationListV2(revoked.List) if err != nil { return err } fmt.Printf("publisher: revoked %s (push sequence %d, list sequence %d)\n", certID, revoked.Push.Sequence, revoked.List.Sequence) if _, err := ratify.ApplyRevocationPushToJournalV2(ctx, journal, revoked.Push, rootID, 1, statusPub, policy, start+10); err != nil { return err } status, err = ratify.RevocationStatusFromJournalV2(ctx, journal, rootID, certID, 1, statusPub, policy, start+10) if err != nil { return err } fmt.Printf("journal: ingested push sequence %d; %s is %s\n", revoked.Push.Sequence, certID, status.Status)
evidence = []ratify.V2StatusEvidenceObject{{ObjectType: 5, Wire: pushWire}, {ObjectType: 3, Wire: listWire}} store.SetTime(start + 15) return verifyAndRelease("verify after revocation")}Source: examples/v2/go/signed_status at commit 5ca7585c2c1d, SHA-256 checked at build time.
Custom scope and evaluator profile
Section titled “Custom scope and evaluator profile”An exact custom: required scope and a registered evaluator profile.
See Delegation and constraints.
// 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// package v2reference. A production verifier supplies durable Part B stores// and an independent checkpoint (SPEC-v2 §7).//// Run from the repository root: go run ./examples/v2/go/custom_scopepackage main
import ( "context" "fmt" "os" "time"
ratify "github.com/identities-ai/ratify-protocol/v2" "github.com/identities-ai/ratify-protocol/v2/v2reference")
const ( start = int64(1800000000) namespace = "custom-scope" epoch = int64(1) logID = "00000000000000000000000000000003" customScope = "custom:acme:deploy")
func main() { if err := run(); err != nil { fmt.Fprintln(os.Stderr, "error:", err) os.Exit(1) }}
func run() error { ctx := context.Background() fmt.Println("Ratify Protocol v2 custom scope and max_count profile") fmt.Println("development only: in-memory reference stores")
rootPub, rootPriv, err := ratify.GenerateHybridKeypair() if err != nil { return err } agentPub, agentPriv, err := ratify.GenerateHybridKeypair() if err != nil { return err } statusPub, statusPriv, err := ratify.GenerateHybridKeypair() if err != nil { return err } verifierPub, verifierPriv, err := ratify.GenerateHybridKeypair() if err != nil { return err } rootID, _ := ratify.KeyIDV2(rootPub) agentID, _ := ratify.KeyIDV2(agentPub) verifierID, _ := ratify.KeyIDV2(verifierPub)
template := ratify.DelegationCertV2{ Version: 2, CertID: "custom-scope-cert-1", IssuerID: rootID, IssuerPubKey: rootPub, SubjectID: agentID, SubjectPubKey: agentPub, IssuedAt: start, ExpiresAt: start + 86400, }
// A custom scope is one exact name. Wildcards are invalid. wildcard := template wildcard.Scope, wildcard.Constraints = []string{"custom:*"}, []ratify.ConstraintV2{} _, err = ratify.SignDelegationCertV2(&wildcard, rootPriv) fmt.Printf("issue scope custom:*: refused (%s)\n", ratify.V2ErrorClassOf(err))
// The certificate carries an extension constraint. Only a verifier that // registered the max_count/v1 profile for this type can evaluate it. template.Scope = []string{customScope} template.Constraints = []ratify.ConstraintV2{{ Type: ratify.ConstraintMaxCountV2, Params: map[string]any{"counter": "nodes", "max": int64(5)}, }} cert, err := ratify.SignDelegationCertV2(&template, rootPriv) if err != nil { return err } fmt.Printf("delegation: scope=%s constraint=%s(counter=nodes, max=5)\n", customScope, ratify.ConstraintMaxCountV2)
maxCount := ratify.StandardMaxCountEvaluatorV2() digest, err := ratify.ConstraintProfileDigestV2(maxCount.Descriptor) if err != nil { return err } fmt.Printf("profile: %s digest=%s\n", ratify.ProfileMaxCountV2, digest) registry, err := ratify.NewConstraintEvaluatorRegistryV2(time.Second, maxCount) if err != nil { return err }
journal, err := v2reference.NewJournalStore() if err != nil { return err } if _, err := ratify.RecordSecurityKeyRoleV2(ctx, journal, "issuer", rootPub); err != nil { return err } if _, err := ratify.ConfigureStatusKeyEpochV2(ctx, journal, rootID, 1, statusPub); err != nil { return err } publisher, err := ratify.NewV2StatusPublisherWithKey(ctx, journal, rootPub, statusPriv, 3600) if err != nil { return err } genesis, err := publisher.Genesis(ctx, start) if err != nil { return err } statusWire, err := ratify.EncodeRevocationListV2(genesis.List) if err != nil { return err }
store, err := v2reference.NewStore(start, 30, logID, verifierPriv) if err != nil { return err } issuance := v2reference.NewTestOnlyChallengeIssuanceStore()
// attempt verifies one request for `nodes` nodes and releases the result. attempt := func(label string, nodes int64, evaluators *ratify.ConstraintEvaluatorRegistryV2) error { store.SetTime(store.Now() + 1) challenge, err := ratify.V2ChallengeIssuer{Clock: store, Store: issuance}.IssueChallengeV2(ctx, ratify.V2ChallengeIssueRequest{ VerifierNamespace: namespace, ReplayEpoch: epoch, VerifierID: verifierID, LifetimeSeconds: 120, ExpectedAgentID: agentID, ExpectedAgentPublicKey: &agentPub, }) if err != nil { return err } bundle, err := ratify.SignProofBundleV2(&ratify.ProofBundleV2{ Version: 2, VerifierID: verifierID, AgentID: agentID, AgentPubKey: agentPub, Delegations: []ratify.DelegationCertV2{*cert}, Challenge: challenge.Value, ChallengeAt: challenge.IssuedAt, }, agentPriv) if err != nil { return err } wire, err := ratify.EncodeProofBundleV2(bundle) if err != nil { return err } expected, err := ratify.LoadExpectedChallengeV2(ctx, issuance, namespace, epoch, bundle.Challenge) if err != nil { return err } contextPolicy, err := ratify.NewV2ContextPolicy("example.custom-scope/v1", false, nil, nil) if err != nil { return err } outcome, err := ratify.VerifyProofBundleV2(ctx, ratify.V2VerifyRequest{ Bundle: wire, Expected: expected, ContextPolicy: contextPolicy, RequiredScope: customScope, VerifierNamespace: namespace, ReplayEpoch: epoch, VerifierID: verifierID, Now: store.Now(), MaxChallengeAgeSeconds: 300, FutureSkewSeconds: 5, TZDBVersion: ratify.TZDBVersionV2, // The requested quantity comes from the authenticated request, // never from the proof. Context: ratify.ConstraintContextV2{ExtensionCounts: map[string]int64{"nodes": nodes}}, ConstraintEvaluators: evaluators, StatusKeys: map[string]ratify.V2StatusKeyConfig{rootID: {Epoch: 1, Key: statusPub}}, StatusPolicy: ratify.RevocationStatusPolicyV2{MaxListLifetimeSeconds: 3600, MaxStatusAgeSeconds: 3600, ClockSkewSeconds: 5}, }, ratify.V2VerifyCallbacks{ ClaimStore: store, Trust: func(_ context.Context, chain []ratify.DelegationCertV2) (ratify.V2TrustResolution, error) { if chain[len(chain)-1].IssuerID == rootID { return ratify.V2TrustResolution{Outcome: ratify.V2TrustTrusted, RootKey: rootPub}, nil } return ratify.V2TrustResolution{Outcome: ratify.V2TrustUntrusted}, nil }, StatusEvidence: func(context.Context, ratify.V2StatusEvidenceRequest) (ratify.V2StatusEvidenceBatch, error) { return ratify.V2StatusEvidenceBatch{Objects: []ratify.V2StatusEvidenceObject{{ObjectType: 3, Wire: statusWire}}}, nil }, StatusJournal: journal, }) if err != nil { return err } if outcome.Stage != ratify.V2StageCommitted { return fmt.Errorf("verify stopped at %s: %v", outcome.Stage, outcome.Error) } receiptWire, err := store.PublishV2Receipt(ctx, outcome.Committed.ClaimID(), outcome.Committed.ReceiptBody()) if err != nil { return err } result := ratify.ReleaseV2Decision(ctx, outcome.Committed, receiptWire, ratify.V2ReleaseConfig{ VerifierPublicKey: verifierPub, LogID: logID, ClaimStore: store, Checkpoint: store, }) if result.Status != ratify.V2ReleaseReleased { return fmt.Errorf("release %s: %s", result.Status, result.Reason) } receipt, err := result.Decision.Receipt() if err != nil { return err } fmt.Printf("%s: decision=%s reason=%s allowed=%t\n", label, result.Decision.Decision(), result.Decision.Reason(), result.Decision.Allowed(ctx, store)) for _, ref := range receipt.ConstraintEvaluators { fmt.Printf(" receipt constraint_evaluators: %s %s\n", ref.Type, ref.ProfileDigest) } return nil }
if err := attempt("request nodes=3", 3, registry); err != nil { return err } if err := attempt("request nodes=8", 8, registry); err != nil { return err } return attempt("request nodes=3 without the profile registered", 3, nil)}Source: examples/v2/go/custom_scope at commit 5ca7585c2c1d, SHA-256 checked at build time.
External signer
Section titled “External signer”Signing through a key held outside the SDK, with verify-before-use. See Typed signing and key IDs.
// 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.//// Run from the repository root: go run ./examples/v2/go/external_signerpackage main
import ( "bytes" "context" "crypto/ed25519" "crypto/rand" "fmt" "os"
"github.com/cloudflare/circl/sign/mldsa/mldsa65" ratify "github.com/identities-ai/ratify-protocol/v2")
const start = int64(1800000000)
// provider is 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.type provider struct { name string pub ratify.HybridPublicKey ed ed25519.PrivateKey ml *mldsa65.PrivateKey log []string}
func newProvider(name string) (*provider, error) { edPub, edPriv, err := ed25519.GenerateKey(rand.Reader) if err != nil { return nil, err } mlPub, mlPriv, err := mldsa65.GenerateKey(rand.Reader) if err != nil { return nil, err } mlBytes, err := mlPub.MarshalBinary() if err != nil { return nil, err } return &provider{name: name, pub: ratify.HybridPublicKey{Ed25519: edPub, MLDSA65: mlBytes}, ed: edPriv, ml: mlPriv}, nil}
func (p *provider) PublicKeyV2() ratify.HybridPublicKey { return p.pub }
func (p *provider) ModeV2() ratify.SignerModeV2 { return ratify.SignerModeDirectV2 }
func (p *provider) SignV2(ctx context.Context, req ratify.SignRequestV2) (ratify.HybridSignature, error) { // A provider refuses any request for a key it does not hold. if !bytes.Equal(req.PublicKey.Ed25519, p.pub.Ed25519) || !bytes.Equal(req.PublicKey.MLDSA65, p.pub.MLDSA65) { return ratify.HybridSignature{}, fmt.Errorf("%s: request names a key this provider does not hold", p.name) } p.log = append(p.log, fmt.Sprintf("%s signed: mode=direct message=%d bytes context=%s", p.name, len(req.Message), req.MLDSAContext)) ml := make([]byte, mldsa65.SignatureSize) if err := mldsa65.SignTo(p.ml, req.Message, req.MLDSAContext, true, ml); err != nil { return ratify.HybridSignature{}, err } return ratify.HybridSignature{Ed25519: ed25519.Sign(p.ed, req.Message), MLDSA65: ml}, nil}
func main() { if err := run(); err != nil { fmt.Fprintln(os.Stderr, "error:", err) os.Exit(1) }}
func run() error { ctx := context.Background() fmt.Println("Ratify Protocol v2 external signer")
issuer, err := newProvider("issuer provider") if err != nil { return err } agent, err := newProvider("agent provider") if err != nil { return err } verifierPub, _, err := ratify.GenerateHybridKeypair() if err != nil { return err } issuerID, _ := ratify.KeyIDV2(issuer.pub) agentID, _ := ratify.KeyIDV2(agent.pub) verifierID, _ := ratify.KeyIDV2(verifierPub)
cert, err := ratify.SignDelegationCertV2WithSigner(ctx, &ratify.DelegationCertV2{ Version: 2, CertID: "external-signer-cert-1", IssuerID: issuerID, IssuerPubKey: issuer.pub, SubjectID: agentID, SubjectPubKey: agent.pub, Scope: []string{"files:read"}, Constraints: []ratify.ConstraintV2{}, IssuedAt: start, ExpiresAt: start + 86400, }, issuer) if err != nil { return err } fmt.Println(issuer.log[0]) fmt.Printf("delegation: signature verified by the SDK (%v)\n", ratify.VerifyDelegationCertV2Signature(cert) == nil)
challenge := bytes.Repeat([]byte{0x42}, 32) unsigned := ratify.ProofBundleV2{ Version: 2, VerifierID: verifierID, AgentID: agentID, AgentPubKey: agent.pub, Delegations: []ratify.DelegationCertV2{*cert}, Challenge: challenge, ChallengeAt: start, } bundle, err := ratify.SignProofBundleV2WithSigner(ctx, &unsigned, agent) if err != nil { return err } fmt.Println(agent.log[0]) fmt.Printf("proof bundle: signatures verified by the SDK (%v)\n", ratify.VerifyProofBundleV2Signatures(bundle) == nil)
// A faulty provider returns an ML-DSA-65 signature from a different key. // The SDK verifies before use, so nothing is signed. _, wrong, err := mldsa65.GenerateKey(rand.Reader) if err != nil { return err } agent.ml = wrong _, err = ratify.SignProofBundleV2WithSigner(ctx, &unsigned, agent) fmt.Printf("faulty provider: refused (%s)\n", ratify.V2ErrorClassOf(err)) return nil}Source: examples/v2/go/external_signer at commit 5ca7585c2c1d, SHA-256 checked at build time.
Conformance
Section titled “Conformance”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.
