Skip to main content

ratify_protocol/v2/reference/
approval_ledger.rs

1//! Dual-root composition profile (SPEC-v2 §7.14), TEST ONLY. Mirrors Go
2//! `v2reference/approval_ledger.go`.
3//!
4//! [`ApprovalLedgerTestOnly`] is the application ledger of the profile. An
5//! approval set names one action through its authenticated fields: the
6//! verifier ID, the workspace and session identifiers, the complete agent
7//! key, the required scope, the action's request hash, and two distinct
8//! pinned root keys. The ledger derives the expected session context from
9//! those fields with invocation_id = approval_set_id (SPEC-v2 §2.4); it never
10//! accepts a caller-supplied context. Each root approves through its own
11//! challenge and its own independently released Protocol decision. The
12//! ledger marks the action executable only when both released allows match
13//! the set and are still within their deadlines, lets it execute exactly
14//! once, and refuses to count one released decision toward more than one
15//! approval set. The composite result is application state, not a Protocol
16//! receipt.
17
18use std::collections::BTreeMap;
19use std::fmt;
20use std::sync::{Arc, Mutex};
21
22use crate::types::HybridPublicKey;
23use crate::v2::claim_store::V2AuthoritativeClock;
24use crate::v2::context::V2Context;
25use crate::v2::crypto::key_id_v2;
26use crate::v2::operation_context::{build_session_context_v2, SessionContextV2Inputs};
27use crate::v2::release::V2ReleasedDecision;
28use crate::v2::wire::{bundle_hash_v2, decode_proof_bundle_v2, validate_required_scope_v2};
29
30/// The ledger's refusals (Go `ErrApproval*`).
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum ApprovalErrorTestOnly {
33    /// The approval is not a released allow.
34    NotReleased,
35    /// The approval does not bind this approval set's action.
36    ActionMismatch,
37    /// The approval chain does not end at the slot's pinned root.
38    RootMismatch,
39    /// The slot already holds a different approval.
40    SlotFilled,
41    /// The approval is already recorded in another approval set.
42    Reused,
43    /// The approval set is missing a released approval.
44    Incomplete,
45    /// An approval is past its release deadline.
46    Expired,
47    /// The approval set already executed.
48    AlreadyExecuted,
49    /// The approval set is invalid.
50    SetInvalid,
51    /// The approval set is unknown.
52    SetUnknown,
53    /// The approval set is already open.
54    SetAlreadyExists,
55    /// The slot is not 0 or 1.
56    InvalidSlot,
57}
58
59impl ApprovalErrorTestOnly {
60    /// The spelling the shared vectors use.
61    pub fn as_str(self) -> &'static str {
62        match self {
63            ApprovalErrorTestOnly::NotReleased => "not_released",
64            ApprovalErrorTestOnly::ActionMismatch => "action_mismatch",
65            ApprovalErrorTestOnly::RootMismatch => "root_mismatch",
66            ApprovalErrorTestOnly::SlotFilled => "slot_filled",
67            ApprovalErrorTestOnly::Reused => "approval_reused",
68            ApprovalErrorTestOnly::Incomplete => "incomplete",
69            ApprovalErrorTestOnly::Expired => "expired",
70            ApprovalErrorTestOnly::AlreadyExecuted => "already_executed",
71            ApprovalErrorTestOnly::SetInvalid => "approval_set_invalid",
72            ApprovalErrorTestOnly::SetUnknown => "approval_set_unknown",
73            ApprovalErrorTestOnly::SetAlreadyExists => "approval_set_already_exists",
74            ApprovalErrorTestOnly::InvalidSlot => "invalid_slot",
75        }
76    }
77}
78
79impl fmt::Display for ApprovalErrorTestOnly {
80    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81        write!(f, "v2reference: approval ledger: {}", self.as_str())
82    }
83}
84
85impl std::error::Error for ApprovalErrorTestOnly {}
86
87/// The authenticated approval set an application opens before issuing
88/// either challenge (SPEC-v2 §7.14 step 1). Every field comes from
89/// authenticated application state, never from the presenter.
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub struct ApprovalSetTestOnly {
92    pub approval_set_id: String,
93    pub verifier_id: String,
94    pub workspace_id: String,
95    pub session_id: String,
96    pub agent_public_key: HybridPublicKey,
97    pub required_scope: String,
98    /// The action's 32-byte operation-context hash (§2.4).
99    pub request_hash: Vec<u8>,
100    /// The complete public keys of the two pinned roots, in slot order.
101    pub roots: [HybridPublicKey; 2],
102}
103
104struct ApprovalRecord {
105    claim_id: String,
106    decision: Arc<V2ReleasedDecision>,
107}
108
109struct ApprovalState {
110    set: ApprovalSetTestOnly,
111    agent_id: String,
112    root_ids: [String; 2],
113    session_context: Vec<u8>,
114    approvals: [Option<ApprovalRecord>; 2],
115    executed: bool,
116}
117
118#[derive(Default)]
119struct Ledger {
120    sets: BTreeMap<String, ApprovalState>,
121    /// Each recorded claim ID and the approval set it counts toward, so one
122    /// released decision never counts toward two sets.
123    recorded: BTreeMap<String, String>,
124}
125
126/// The dual-root application ledger. Safe for concurrent use; each
127/// operation is one atomic step under a mutex.
128#[derive(Default)]
129pub struct ApprovalLedgerTestOnly {
130    state: Mutex<Ledger>,
131}
132
133impl fmt::Debug for ApprovalLedgerTestOnly {
134    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135        f.debug_struct("ApprovalLedgerTestOnly").finish_non_exhaustive()
136    }
137}
138
139impl ApprovalLedgerTestOnly {
140    /// An empty ledger.
141    pub fn new() -> Self {
142        Self::default()
143    }
144
145    fn lock(&self) -> std::sync::MutexGuard<'_, Ledger> {
146        self.state.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
147    }
148
149    /// Go `Open`: record an approval set. It derives the agent and root key
150    /// IDs and the expected session context from the set's fields. The two
151    /// root keys must be distinct: one root never counts twice.
152    pub fn open(&self, set: ApprovalSetTestOnly) -> Result<(), ApprovalErrorTestOnly> {
153        use ApprovalErrorTestOnly::*;
154        if set.approval_set_id.is_empty()
155            || set.request_hash.len() != 32
156            || validate_required_scope_v2(&set.required_scope).is_err()
157        {
158            return Err(SetInvalid);
159        }
160        let agent_id = key_id_v2(&set.agent_public_key).map_err(|_| SetInvalid)?;
161        let root_ids = [
162            key_id_v2(&set.roots[0]).map_err(|_| SetInvalid)?,
163            key_id_v2(&set.roots[1]).map_err(|_| SetInvalid)?,
164        ];
165        if root_ids[0] == root_ids[1] {
166            return Err(SetInvalid);
167        }
168        let session_context = build_session_context_v2(&SessionContextV2Inputs {
169            verifier_id: set.verifier_id.clone(),
170            workspace_id: set.workspace_id.clone(),
171            agent_id: agent_id.clone(),
172            session_id: set.session_id.clone(),
173            invocation_id: set.approval_set_id.clone(),
174            request_hash: set.request_hash.clone(),
175        })
176        .map_err(|_| SetInvalid)?;
177        let mut ledger = self.lock();
178        if ledger.sets.contains_key(&set.approval_set_id) {
179            return Err(SetAlreadyExists);
180        }
181        ledger.sets.insert(
182            set.approval_set_id.clone(),
183            ApprovalState {
184                set,
185                agent_id,
186                root_ids,
187                session_context,
188                approvals: [None, None],
189                executed: false,
190            },
191        );
192        Ok(())
193    }
194
195    /// Go `RecordApproval`: bind a released decision and the exact proof
196    /// bundle it verified to slot 0 or 1, and return whether both slots are
197    /// now filled. Checks, in order: a released allow; the receipt's
198    /// bundle_hash equals the bundle's hash; the claim is not already
199    /// recorded in another set; the receipt and bundle name the set's
200    /// verifier and agent (complete key), the receipt names the set's
201    /// required scope, and the bundle's session_context equals the context
202    /// derived from the set; the chain's terminal issuer key equals the
203    /// slot's pinned root key and the receipt's issuer_ids contain that
204    /// root; the slot is empty or holds this claim.
205    pub fn record_approval(
206        &self,
207        set_id: &str,
208        slot: usize,
209        decision: Option<&Arc<V2ReleasedDecision>>,
210        bundle_wire: &[u8],
211    ) -> Result<bool, ApprovalErrorTestOnly> {
212        use ApprovalErrorTestOnly::*;
213        if slot > 1 {
214            return Err(InvalidSlot);
215        }
216        let decision = match decision {
217            Some(d) if d.decision() == "allow" => d,
218            _ => return Err(NotReleased),
219        };
220        let receipt = decision.receipt().map_err(|_| NotReleased)?;
221        let bundle = decode_proof_bundle_v2(bundle_wire).map_err(|_| ActionMismatch)?;
222        match bundle_hash_v2(&bundle) {
223            Ok(hash) if hash == receipt.bundle_hash => {}
224            _ => return Err(ActionMismatch),
225        }
226        let claim_id = decision.claim_id();
227        let mut ledger = self.lock();
228        let ledger = &mut *ledger;
229        let state = ledger.sets.get_mut(set_id).ok_or(SetUnknown)?;
230        if ledger.recorded.get(&claim_id).is_some_and(|owner| owner != set_id) {
231            return Err(Reused);
232        }
233        let set = &state.set;
234        if receipt.verifier_id != set.verifier_id
235            || bundle.verifier_id != set.verifier_id
236            || receipt.agent_id != state.agent_id
237            || bundle.agent_id != state.agent_id
238            || bundle.agent_pub_key != set.agent_public_key
239            || receipt.required_scope != set.required_scope
240            || bundle.session_context.as_deref() != Some(state.session_context.as_slice())
241        {
242            return Err(ActionMismatch);
243        }
244        let root = bundle.delegations.last().ok_or(RootMismatch)?;
245        if root.issuer_id != state.root_ids[slot]
246            || root.issuer_pub_key != set.roots[slot]
247            || !receipt.issuer_ids.contains(&state.root_ids[slot])
248        {
249            return Err(RootMismatch);
250        }
251        match &state.approvals[slot] {
252            Some(current) if current.claim_id != claim_id => return Err(SlotFilled),
253            Some(_) => {}
254            None => {
255                state.approvals[slot] = Some(ApprovalRecord {
256                    claim_id: claim_id.clone(),
257                    decision: Arc::clone(decision),
258                });
259                ledger.recorded.insert(claim_id, set_id.to_string());
260            }
261        }
262        Ok(state.approvals.iter().all(Option::is_some))
263    }
264
265    /// Go `Execute`: atomically check that both approvals are recorded and
266    /// each is still allowed at the receiver's authoritative time, then mark
267    /// the set executed. It succeeds at most once per set.
268    pub fn execute(
269        &self,
270        ctx: &V2Context,
271        set_id: &str,
272        clock: &dyn V2AuthoritativeClock,
273    ) -> Result<(), ApprovalErrorTestOnly> {
274        use ApprovalErrorTestOnly::*;
275        let mut ledger = self.lock();
276        let state = ledger.sets.get_mut(set_id).ok_or(SetUnknown)?;
277        if state.executed {
278            return Err(AlreadyExecuted);
279        }
280        let [Some(first), Some(second)] = &state.approvals else {
281            return Err(Incomplete);
282        };
283        if !first.decision.allowed(ctx, clock) || !second.decision.allowed(ctx, clock) {
284            return Err(Expired);
285        }
286        state.executed = true;
287        Ok(())
288    }
289}