返回 CodeWhale
ticket.rs
根目录 / crates / engine / src / extension_host / ticket.rs
1 //! Capability tickets: what lets the host ask the core for one specific thing.
2 //!
3 //! A ticket is an opaque id the core mints and keeps a row for. The host can
4 //! only hand it back; what the ticket is good for lives in the row, on the
5 //! Rust side, and [`TicketTable::redeem`] checks every field of it under one
6 //! lock. Today there is one kind, [`TicketKind::Invocation`]: minted for one
7 //! `tool/call` that runs under the turn loop's permission gate, and redeemed
8 //! by `core/call` (`super::core_call`). Other kinds (a process launch, a
9 //! fetch, an MCP grant) join the enum with their first redeemer.
10 //!
11 //! A ticket narrows what a frame may do; it does not isolate plugins that
12 //! share the host process (design section 4.4): a plugin can read the ticket
13 //! of a call made to it, and so can others in the same process. What stops
14 //! that being useful is the row: the owner (its generation and token), the
15 //! tier and the host generation are all checked, so a ticket presented by
16 //! another owner, another tier, a restarted host or for another method is
17 //! refused, and it dies with its invocation, its owner and its host.
18 //!
19 //! Tickets are never persisted, logged or put in a diagnostic: [`Ticket`]'s
20 //! `Debug` is redacted, the table has none, and no refusal quotes one.
21 //!
22 //! A burst of invalid presentations from one host is a protocol violation
23 //! ([`TicketTable::redeem`] reports it; the channel ends the host): a host
24 //! that guesses ids or replays old ones is not honestly confused.
25 //!
26 //! Known limit: ids are 244 random bits from the OS generator (two UUIDv4
27 //! bodies), found by hash lookup rather than compared in constant time; a
28 //! host that can time that lookup already holds the ticket it is probing for
29 //! or none worth having.
30
31 use std::collections::{HashMap, VecDeque};
32 use std::sync::Mutex;
33 use std::time::{Duration, Instant};
34
35 use serde_json::Value;
36
37 use super::tier::{HostCohort, HostTier};
38 use codewhale_config::OwnerRef;
39
40 /// What a ticket is for. A kind says how it is used up, and nothing else; the
41 /// row says the rest.
42 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
43 pub enum TicketKind {
44 /// One `tool/call` running under the turn loop's gate: redeemable by that
45 /// call's `core/call` requests, up to the row's `uses`.
46 Invocation,
47 McpLaunch,
48 McpOperation,
49 Execution,
50 }
51
52 impl TicketKind {
53 /// A single-use ticket is removed when used; a budgeted one stays (at zero
54 /// uses it refuses as exhausted) until it is revoked.
55 fn single_use(self) -> bool {
56 match self {
57 Self::Invocation => false,
58 Self::McpLaunch | Self::McpOperation | Self::Execution => true,
59 }
60 }
61 }
62
63 /// An opaque ticket id. Not `Display`, and `Debug` is redacted.
64 #[derive(Clone, PartialEq, Eq, Hash)]
65 pub struct Ticket(String);
66
67 impl Ticket {
68 /// The id, to send to the host (and nowhere else).
69 #[must_use]
70 pub fn expose(&self) -> &str {
71 &self.0
72 }
73 }
74
75 impl std::fmt::Debug for Ticket {
76 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77 f.write_str("Ticket(..)")
78 }
79 }
80
81 /// What a new ticket is good for.
82 pub struct Grant {
83 pub kind: TicketKind,
84 pub cohort: HostCohort,
85 /// The host process generation that may present it.
86 pub host_generation: u64,
87 pub owner: OwnerRef,
88 /// The protocol method that may redeem it.
89 pub method: &'static str,
90 /// What it names: for an invocation, the `tool/call` id. Compared as
91 /// parsed JSON when a redeemer states one.
92 pub target: Value,
93 pub ttl: Duration,
94 pub uses: u32,
95 }
96
97 impl Grant {
98 #[must_use]
99 pub fn tier(&self) -> HostTier {
100 self.cohort.tier()
101 }
102 }
103
104 struct Row {
105 kind: TicketKind,
106 cohort: HostCohort,
107 host_generation: u64,
108 owner: OwnerRef,
109 method: &'static str,
110 target: Value,
111 expires: Instant,
112 uses_left: u32,
113 }
114
115 /// What the redeemer says it is.
116 pub struct Presented<'a> {
117 pub ticket: &'a str,
118 pub kind: TicketKind,
119 pub cohort: HostCohort,
120 pub host_generation: u64,
121 pub owner: &'a OwnerRef,
122 pub method: &'a str,
123 /// The target the request names, if it names one.
124 pub target: Option<&'a Value>,
125 }
126
127 impl Presented<'_> {
128 #[must_use]
129 pub fn tier(&self) -> HostTier {
130 self.cohort.tier()
131 }
132 }
133
134 /// Why a presentation was refused. Never carries a ticket.
135 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
136 pub enum Refusal {
137 Unknown,
138 Expired,
139 /// A valid ticket whose uses are spent: a limit, not a forgery.
140 Exhausted,
141 WrongKind,
142 WrongTier,
143 WrongCohort,
144 WrongGeneration,
145 WrongOwner,
146 WrongMethod,
147 WrongTarget,
148 Revoked,
149 }
150
151 impl Refusal {
152 /// The words the host is told. Generic on purpose: which field mismatched
153 /// is not an oracle for the host.
154 #[must_use]
155 pub fn describe(self) -> &'static str {
156 match self {
157 Self::Exhausted => "this invocation's core/call limit is used up",
158 Self::Expired => "this invocation's ticket expired",
159 _ => "the ticket is not valid for this request",
160 }
161 }
162 }
163
164 /// A refusal, and whether it makes the host's frames a protocol violation.
165 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
166 pub struct Refused {
167 pub reason: Refusal,
168 /// This refusal tipped the host into a burst of invalid presentations
169 /// ([`INVALID_BURST`] within [`INVALID_WINDOW`]).
170 pub violation: bool,
171 }
172
173 /// This many invalid presentations from one host process within
174 /// [`INVALID_WINDOW`] are a protocol violation.
175 pub const INVALID_BURST: usize = 8;
176 pub const INVALID_WINDOW: Duration = Duration::from_secs(60);
177 pub const REVOKED_GRACE: Duration = Duration::from_secs(10);
178 const MAX_REVOKED: usize = 4096;
179
180 #[derive(Default)]
181 struct State {
182 rows: HashMap<String, Row>,
183 invalid: HashMap<(HostCohort, u64), VecDeque<Instant>>,
184 revoked: VecDeque<(String, Instant)>,
185 }
186
187 impl State {
188 fn note_revoked(&mut self, ids: impl IntoIterator<Item = String>, now: Instant) {
189 self.revoked.extend(ids.into_iter().map(|id| (id, now)));
190 while self.revoked.len() > MAX_REVOKED
191 || self
192 .revoked
193 .front()
194 .is_some_and(|(_, at)| now.saturating_duration_since(*at) >= REVOKED_GRACE)
195 {
196 self.revoked.pop_front();
197 }
198 }
199
200 fn revoked_just_now(&self, ticket: &str, now: Instant) -> bool {
201 self.revoked
202 .iter()
203 .any(|(id, at)| id == ticket && now.saturating_duration_since(*at) < REVOKED_GRACE)
204 }
205
206 fn revoke_where(&mut self, gone: impl Fn(&Row) -> bool) {
207 let ids: Vec<String> = self
208 .rows
209 .iter()
210 .filter(|(_, row)| gone(row))
211 .map(|(id, _)| id.clone())
212 .collect();
213 for id in &ids {
214 self.rows.remove(id);
215 }
216 self.note_revoked(ids, Instant::now());
217 }
218 }
219
220 /// Every live ticket, behind one mutex.
221 #[derive(Default)]
222 pub struct TicketTable {
223 state: Mutex<State>,
224 }
225
226 fn mint_id() -> String {
227 // Two v4 UUIDs: 244 random bits from the OS generator.
228 format!(
229 "cwt.{}{}",
230 uuid::Uuid::new_v4().simple(),
231 uuid::Uuid::new_v4().simple()
232 )
233 }
234
235 impl TicketTable {
236 /// Mint a ticket for `grant`.
237 pub fn mint(&self, grant: Grant) -> Ticket {
238 let id = mint_id();
239 self.state.lock().expect("ticket lock").rows.insert(
240 id.clone(),
241 Row {
242 kind: grant.kind,
243 cohort: grant.cohort,
244 host_generation: grant.host_generation,
245 owner: grant.owner,
246 method: grant.method,
247 target: grant.target,
248 expires: Instant::now() + grant.ttl,
249 uses_left: grant.uses,
250 },
251 );
252 Ticket(id)
253 }
254
255 /// Check `presented` against its row, every field, under one lock, and
256 /// use one of its uses. Returns the row's target. A refusal that is not a
257 /// mere limit counts toward the host's burst.
258 pub fn redeem(&self, presented: &Presented<'_>) -> Result<Value, Refused> {
259 self.redeem_at(presented, Instant::now())
260 }
261
262 fn redeem_at(&self, presented: &Presented<'_>, now: Instant) -> Result<Value, Refused> {
263 let mut state = self.state.lock().expect("ticket lock");
264 let revoked = state.revoked_just_now(presented.ticket, now);
265 let verdict = match state.rows.get_mut(presented.ticket) {
266 None if revoked => Err(Refusal::Revoked),
267 None => Err(Refusal::Unknown),
268 Some(row) => Self::check(row, presented, now).map(|target| {
269 row.uses_left -= 1;
270 (target, row.uses_left == 0 && row.kind.single_use())
271 }),
272 };
273 match verdict {
274 Ok((target, spent)) => {
275 if spent {
276 state.rows.remove(presented.ticket);
277 }
278 Ok(target)
279 }
280 Err(reason) => {
281 let violation = !matches!(reason, Refusal::Exhausted | Refusal::Revoked)
282 && Self::note_invalid(&mut state, presented, now);
283 Err(Refused { reason, violation })
284 }
285 }
286 }
287
288 fn check(row: &Row, presented: &Presented<'_>, now: Instant) -> Result<Value, Refusal> {
289 if row.kind != presented.kind {
290 return Err(Refusal::WrongKind);
291 }
292 if row.cohort != presented.cohort {
293 return Err(Refusal::WrongCohort);
294 }
295 if row.host_generation != presented.host_generation {
296 return Err(Refusal::WrongGeneration);
297 }
298 if row.owner != *presented.owner {
299 return Err(Refusal::WrongOwner);
300 }
301 if row.method != presented.method {
302 return Err(Refusal::WrongMethod);
303 }
304 if presented.target.is_some_and(|target| *target != row.target) {
305 return Err(Refusal::WrongTarget);
306 }
307 if now >= row.expires {
308 return Err(Refusal::Expired);
309 }
310 if row.uses_left == 0 {
311 return Err(Refusal::Exhausted);
312 }
313 Ok(row.target.clone())
314 }
315
316 /// Record one invalid presentation by `presented`'s host; whether that
317 /// made a burst.
318 fn note_invalid(state: &mut State, presented: &Presented<'_>, now: Instant) -> bool {
319 let recent = state
320 .invalid
321 .entry((presented.cohort.clone(), presented.host_generation))
322 .or_default();
323 while recent
324 .front()
325 .is_some_and(|at| now.saturating_duration_since(*at) >= INVALID_WINDOW)
326 {
327 recent.pop_front();
328 }
329 recent.push_back(now);
330 recent.len() >= INVALID_BURST
331 }
332
333 /// Revoke one ticket (its invocation ended). Idempotent.
334 pub fn revoke(&self, ticket: &Ticket) {
335 let mut state = self.state.lock().expect("ticket lock");
336 if state.rows.remove(ticket.expose()).is_some() {
337 state.note_revoked([ticket.expose().to_string()], Instant::now());
338 }
339 }
340
341 /// Revoke every ticket of `plugin_id` (its owner was revoked).
342 pub fn revoke_owner(&self, plugin_id: &str) {
343 self.state
344 .lock()
345 .expect("ticket lock")
346 .revoke_where(|row| row.owner.plugin_id == plugin_id);
347 }
348
349 /// Revoke every ticket of one host process and forget its invalid-burst
350 /// record (the host exited).
351 pub fn revoke_host(&self, cohort: &HostCohort, host_generation: u64) {
352 let mut state = self.state.lock().expect("ticket lock");
353 state
354 .rows
355 .retain(|_, row| !(row.cohort == *cohort && row.host_generation == host_generation));
356 state.invalid.remove(&(cohort.clone(), host_generation));
357 }
358
359 /// How many tickets are live.
360 #[cfg(any(test, feature = "test-support"))]
361 pub fn live(&self) -> usize {
362 self.state.lock().expect("ticket lock").rows.len()
363 }
364 }
365
366 #[cfg(test)]
367 mod tests {
368 use serde_json::json;
369
370 use super::*;
371
372 fn owner(id: &str, token: &str) -> OwnerRef {
373 OwnerRef {
374 plugin_id: id.to_string(),
375 generation: 1,
376 owner_token: token.to_string(),
377 }
378 }
379
380 fn grant(uses: u32) -> Grant {
381 Grant {
382 kind: TicketKind::Invocation,
383 cohort: HostCohort::reviewed(),
384 host_generation: 3,
385 owner: owner("a", "token-a"),
386 method: "core/call",
387 target: json!({"call_id": "c1", "n": 1}),
388 ttl: Duration::from_secs(60),
389 uses,
390 }
391 }
392
393 fn presented<'a>(ticket: &'a Ticket, owner: &'a OwnerRef) -> Presented<'a> {
394 Presented {
395 ticket: ticket.expose(),
396 kind: TicketKind::Invocation,
397 cohort: HostCohort::reviewed(),
398 host_generation: 3,
399 owner,
400 method: "core/call",
401 target: None,
402 }
403 }
404
405 fn refusal_of(table: &TicketTable, presented: &Presented<'_>) -> Refusal {
406 table.redeem(presented).unwrap_err().reason
407 }
408
409 #[test]
410 fn a_ticket_redeems_only_for_exactly_what_it_was_minted_for() {
411 let table = TicketTable::default();
412 let ticket = table.mint(grant(5));
413 let a = owner("a", "token-a");
414 assert_eq!(
415 table.redeem(&presented(&ticket, &a)).unwrap(),
416 json!({"call_id": "c1", "n": 1})
417 );
418
419 // Every field is checked: owner (plugin, token, generation), tier,
420 // host generation, method; and a stated target, as parsed JSON.
421 let mut other_token = a.clone();
422 other_token.owner_token = "token-x".to_string();
423 let mut other_generation = a.clone();
424 other_generation.generation = 2;
425 let b = owner("b", "token-a");
426 for (owner, expected) in [
427 (&other_token, Refusal::WrongOwner),
428 (&other_generation, Refusal::WrongOwner),
429 (&b, Refusal::WrongOwner),
430 ] {
431 assert_eq!(refusal_of(&table, &presented(&ticket, owner)), expected);
432 }
433 let mut wrong_tier = presented(&ticket, &a);
434 wrong_tier.cohort = HostCohort::BUILTIN;
435 assert_eq!(refusal_of(&table, &wrong_tier), Refusal::WrongCohort);
436 let mut wrong_generation = presented(&ticket, &a);
437 wrong_generation.host_generation = 4;
438 assert_eq!(
439 refusal_of(&table, &wrong_generation),
440 Refusal::WrongGeneration
441 );
442 let mut wrong_method = presented(&ticket, &a);
443 wrong_method.method = "registry/register";
444 assert_eq!(refusal_of(&table, &wrong_method), Refusal::WrongMethod);
445 let other_target = json!({"call_id": "c2", "n": 1});
446 let mut wrong_target = presented(&ticket, &a);
447 wrong_target.target = Some(&other_target);
448 assert_eq!(refusal_of(&table, &wrong_target), Refusal::WrongTarget);
449 // Parsed JSON, not bytes: key order does not matter.
450 let same_target: Value = serde_json::from_str(r#"{"n": 1, "call_id": "c1"}"#).unwrap();
451 let mut right_target = presented(&ticket, &a);
452 right_target.target = Some(&same_target);
453 assert!(table.redeem(&right_target).is_ok());
454 // Unknown.
455 let unknown = Ticket("cwt.nope".to_string());
456 assert_eq!(
457 refusal_of(&table, &presented(&unknown, &a)),
458 Refusal::Unknown
459 );
460 }
461
462 #[test]
463 fn a_ticket_expires_and_runs_out_of_uses() {
464 let table = TicketTable::default();
465 let ticket = table.mint(grant(2));
466 let a = owner("a", "token-a");
467 let now = Instant::now();
468 assert!(table.redeem_at(&presented(&ticket, &a), now).is_ok());
469 assert!(table.redeem_at(&presented(&ticket, &a), now).is_ok());
470 // Used up: a limit, which is not counted as a forgery.
471 let refused = table.redeem_at(&presented(&ticket, &a), now).unwrap_err();
472 assert_eq!(
473 refused,
474 Refused {
475 reason: Refusal::Exhausted,
476 violation: false
477 }
478 );
479 // Expired: checked against the clock.
480 let fresh = table.mint(grant(5));
481 let later = now + Duration::from_secs(61);
482 let refused = table.redeem_at(&presented(&fresh, &a), later).unwrap_err();
483 assert_eq!(refused.reason, Refusal::Expired);
484 assert!(table.redeem_at(&presented(&fresh, &a), now).is_ok());
485 }
486
487 #[test]
488 fn a_burst_of_invalid_presentations_from_one_host_is_a_violation_and_only_that_host() {
489 let table = TicketTable::default();
490 let a = owner("a", "token-a");
491 let guess = Ticket("cwt.guess".to_string());
492 let now = Instant::now();
493 for count in 1..=INVALID_BURST {
494 let refused = table.redeem_at(&presented(&guess, &a), now).unwrap_err();
495 assert_eq!(
496 refused.violation,
497 count >= INVALID_BURST,
498 "presentation {count}"
499 );
500 }
501 // Another host process is counted on its own.
502 let mut elsewhere = presented(&guess, &a);
503 elsewhere.host_generation = 4;
504 assert!(!table.redeem_at(&elsewhere, now).unwrap_err().violation);
505 // The window: old presentations stop counting.
506 let table = TicketTable::default();
507 for _ in 0..INVALID_BURST - 1 {
508 let _ = table.redeem_at(&presented(&guess, &a), now);
509 }
510 let later = now + INVALID_WINDOW;
511 assert!(
512 !table
513 .redeem_at(&presented(&guess, &a), later)
514 .unwrap_err()
515 .violation
516 );
517 // Exhausting a valid ticket never counts toward a burst.
518 let table = TicketTable::default();
519 let ticket = table.mint(grant(1));
520 assert!(table.redeem_at(&presented(&ticket, &a), now).is_ok());
521 for _ in 0..INVALID_BURST * 2 {
522 let refused = table.redeem_at(&presented(&ticket, &a), now).unwrap_err();
523 assert!(!refused.violation);
524 }
525 }
526
527 #[test]
528 fn a_ticket_revoked_a_moment_ago_does_not_end_the_host() {
529 let table = TicketTable::default();
530 let a = owner("a", "token-a");
531 let ended = table.mint(grant(5));
532 let withdrawn = table.mint(grant(5));
533 table.revoke(&ended);
534 table.revoke_owner("a");
535 let now = Instant::now();
536 for ticket in [&ended, &withdrawn] {
537 for _ in 0..(INVALID_BURST * 3) {
538 assert_eq!(
539 table.redeem_at(&presented(ticket, &a), now),
540 Err(Refused {
541 reason: Refusal::Revoked,
542 violation: false
543 })
544 );
545 }
546 }
547 assert_eq!(Refusal::Revoked.describe(), Refusal::Unknown.describe());
548 let guess = Ticket("cwt.guess".to_string());
549 let violations = (0..INVALID_BURST)
550 .filter(|_| {
551 table
552 .redeem_at(&presented(&guess, &a), now)
553 .unwrap_err()
554 .violation
555 })
556 .count();
557 assert_eq!(violations, 1, "a guess still counts");
558
559 let fresh = TicketTable::default();
560 let stale = fresh.mint(grant(5));
561 fresh.revoke(&stale);
562 let later = Instant::now() + REVOKED_GRACE;
563 let outcomes: Vec<Refused> = (0..INVALID_BURST)
564 .map(|_| fresh.redeem_at(&presented(&stale, &a), later).unwrap_err())
565 .collect();
566 assert!(
567 outcomes
568 .iter()
569 .all(|refused| refused.reason == Refusal::Unknown)
570 );
571 assert!(
572 outcomes.last().unwrap().violation,
573 "after the grace it is a forgery again"
574 );
575 }
576
577 #[test]
578 fn tickets_are_revoked_with_their_invocation_owner_and_host_and_never_printed() {
579 let table = TicketTable::default();
580 let a = owner("a", "token-a");
581 let by_call = table.mint(grant(5));
582 let by_owner = table.mint(grant(5));
583 let mut other_owner_grant = grant(5);
584 other_owner_grant.owner = owner("b", "token-b");
585 let other_owner = table.mint(other_owner_grant);
586 let mut other_host_grant = grant(5);
587 other_host_grant.host_generation = 9;
588 other_host_grant.owner = owner("c", "token-c");
589 let other_host = table.mint(other_host_grant);
590 assert_eq!(table.live(), 4);
591
592 table.revoke(&by_call);
593 table.revoke(&by_call);
594 assert_eq!(
595 refusal_of(&table, &presented(&by_call, &a)),
596 Refusal::Revoked
597 );
598 table.revoke_owner("a");
599 assert_eq!(
600 refusal_of(&table, &presented(&by_owner, &a)),
601 Refusal::Revoked
602 );
603 assert_eq!(table.live(), 2, "only a's tickets went");
604 table.revoke_host(&HostCohort::reviewed(), 9);
605 assert_eq!(table.live(), 1);
606 let _ = (other_owner, other_host);
607
608 // A ticket's Debug never shows it.
609 let shown = format!("{:?}", Ticket("cwt.secret-id".to_string()));
610 assert!(!shown.contains("secret"), "{shown}");
611 // Two tickets are never the same, and are long random ids.
612 let one = table.mint(grant(1));
613 let two = table.mint(grant(1));
614 assert_ne!(one.expose(), two.expose());
615 assert!(one.expose().len() >= 64);
616 }
617 }
618
618 lines RUST