ratify_protocol/v2/reference/
approval_ledger.rs1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum ApprovalErrorTestOnly {
33 NotReleased,
35 ActionMismatch,
37 RootMismatch,
39 SlotFilled,
41 Reused,
43 Incomplete,
45 Expired,
47 AlreadyExecuted,
49 SetInvalid,
51 SetUnknown,
53 SetAlreadyExists,
55 InvalidSlot,
57}
58
59impl ApprovalErrorTestOnly {
60 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#[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 pub request_hash: Vec<u8>,
100 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 recorded: BTreeMap<String, String>,
124}
125
126#[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 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 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 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 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}