a2a_protocol_client/webhook/
receiver.rs1use std::collections::HashMap;
10use std::sync::{Mutex, PoisonError};
11use std::time::Duration;
12
13use a2a_protocol_types::StreamResponse;
14use a2a_protocol_types::push::TaskPushNotificationConfig;
15use a2a_protocol_types::task::TaskId;
16use tokio::time::Instant;
17
18use super::outcome::{WebhookError, WebhookOutcome, WebhookRejection};
19use super::span::ReceiveSpan;
20use super::state::{Bucket, DedupCache, RateLimit};
21use super::token;
22
23const DEFAULT_DEDUP_ENTRIES: usize = 10_000;
25
26const DEFAULT_DEDUP_TTL: Duration = Duration::from_secs(3600);
29
30#[derive(Debug)]
32struct Registration {
33 task_id: String,
34 config_id: Option<String>,
35 token: String,
36 authentication: Option<(String, String)>,
38 bucket: Option<Bucket>,
39}
40
41impl Registration {
42 fn same_config(&self, task_id: &str, config_id: Option<&str>) -> bool {
43 self.task_id == task_id && self.config_id.as_deref() == config_id
44 }
45}
46
47#[derive(Debug)]
48struct State {
49 by_token: HashMap<[u8; 32], Registration>,
53 dedup: Option<DedupCache>,
54}
55
56#[derive(Debug)]
75pub struct WebhookReceiver {
76 state: Mutex<State>,
77 rate_limit: Option<RateLimit>,
78}
79
80impl Default for WebhookReceiver {
81 fn default() -> Self {
82 Self::new()
83 }
84}
85
86impl WebhookReceiver {
87 #[must_use]
90 pub fn new() -> Self {
91 Self {
92 state: Mutex::new(State {
93 by_token: HashMap::new(),
94 dedup: Some(DedupCache::new(DEFAULT_DEDUP_ENTRIES, DEFAULT_DEDUP_TTL)),
95 }),
96 rate_limit: None,
97 }
98 }
99
100 #[must_use]
105 pub fn with_dedup(mut self, max_entries: usize, ttl: Duration) -> Self {
106 self.state_mut().dedup = Some(DedupCache::new(max_entries, ttl));
107 self
108 }
109
110 #[must_use]
112 pub fn without_dedup(mut self) -> Self {
113 self.state_mut().dedup = None;
114 self
115 }
116
117 #[must_use]
124 pub const fn with_rate_limit(mut self, per_sec: u32, burst: u32) -> Self {
125 self.rate_limit = Some(RateLimit {
126 per_sec,
127 burst: if burst == 0 { 1 } else { burst },
128 });
129 self
130 }
131
132 fn state_mut(&mut self) -> &mut State {
133 self.state.get_mut().unwrap_or_else(PoisonError::into_inner)
134 }
135
136 fn lock(&self) -> std::sync::MutexGuard<'_, State> {
137 self.state.lock().unwrap_or_else(PoisonError::into_inner)
138 }
139
140 pub fn register(&self, config: &TaskPushNotificationConfig) -> Result<(), WebhookError> {
152 let token = config.token.as_deref().ok_or(WebhookError::MissingToken)?;
153 if !token::is_sendable_token(token) {
154 return Err(WebhookError::InvalidToken);
155 }
156 let task_id = config
157 .task_id
158 .as_deref()
159 .filter(|t| !t.is_empty())
160 .ok_or(WebhookError::MissingTaskId)?;
161 let authentication = match &config.authentication {
162 None => None,
163 Some(auth) => Some((
164 auth.scheme.clone(),
165 auth.credentials
166 .clone()
167 .ok_or(WebhookError::MissingCredentials)?,
168 )),
169 };
170 let config_id = config.id.as_deref();
171 let key = token::digest(&[token.as_bytes()]);
172
173 let registration = Registration {
174 task_id: task_id.to_owned(),
175 config_id: config_id.map(str::to_owned),
176 token: token.to_owned(),
177 authentication,
178 bucket: self.rate_limit.map(|l| Bucket::full(l, Instant::now())),
179 };
180 Self::insert(&mut self.lock(), key, registration)
181 }
182
183 fn insert(
186 state: &mut State,
187 key: [u8; 32],
188 registration: Registration,
189 ) -> Result<(), WebhookError> {
190 let (task_id, config_id) = (
191 registration.task_id.as_str(),
192 registration.config_id.as_deref(),
193 );
194 if state
195 .by_token
196 .get(&key)
197 .is_some_and(|r| !r.same_config(task_id, config_id))
198 {
199 return Err(WebhookError::TokenInUse);
200 }
201 state
202 .by_token
203 .retain(|_, r| !r.same_config(task_id, config_id));
204 state.by_token.insert(key, registration);
205 Ok(())
206 }
207
208 pub fn unregister(&self, task_id: &str, config_id: Option<&str>) -> bool {
212 let mut state = self.lock();
213 let before = state.by_token.len();
214 state
215 .by_token
216 .retain(|_, r| !r.same_config(task_id, config_id));
217 state.by_token.len() != before
218 }
219
220 pub fn receive(&self, headers: &hyper::HeaderMap, body: &[u8]) -> WebhookOutcome {
228 let span = ReceiveSpan::open(headers);
229 #[cfg(feature = "tracing")]
230 let _entered = span.span.enter();
231 let outcome = match self.check(headers, body) {
232 Ok(outcome) => outcome,
233 Err(rejection) => {
234 trace_debug!(reason = %rejection, "webhook request rejected");
235 WebhookOutcome::Rejected(rejection)
236 }
237 };
238 span.ended(&outcome);
239 outcome
240 }
241
242 fn check(
243 &self,
244 headers: &hyper::HeaderMap,
245 body: &[u8],
246 ) -> Result<WebhookOutcome, WebhookRejection> {
247 let presented = token::notification_token(headers).ok_or(WebhookRejection::MissingToken)?;
248
249 let (task_id, config_id) = self.authorize(&mut self.lock(), headers, presented)?;
252
253 let event: StreamResponse =
254 serde_json::from_slice(body).map_err(|_| WebhookRejection::MalformedBody)?;
255 if event_task_id(&event) != Some(task_id.as_str()) {
256 return Err(WebhookRejection::TaskMismatch);
257 }
258
259 let dedup_key = token::digest(&[
260 task_id.as_bytes(),
261 config_id.as_deref().unwrap_or_default().as_bytes(),
262 &[u8::from(config_id.is_some())],
263 body,
264 ]);
265 let duplicate = self
266 .lock()
267 .dedup
268 .as_mut()
269 .is_some_and(|cache| cache.seen_before(dedup_key, Instant::now()));
270 let task_id = TaskId::new(task_id);
271 Ok(if duplicate {
272 WebhookOutcome::Duplicate { task_id, config_id }
273 } else {
274 WebhookOutcome::Accepted {
275 task_id,
276 config_id,
277 event: Box::new(event),
278 }
279 })
280 }
281}
282
283impl WebhookReceiver {
284 fn authorize(
287 &self,
288 state: &mut State,
289 headers: &hyper::HeaderMap,
290 presented: &str,
291 ) -> Result<(String, Option<String>), WebhookRejection> {
292 let key = token::digest(&[presented.as_bytes()]);
293 let reg = state
294 .by_token
295 .get_mut(&key)
296 .filter(|r| token::constant_time_eq(r.token.as_bytes(), presented.as_bytes()))
297 .ok_or(WebhookRejection::UnknownToken)?;
298 if let Some((scheme, credentials)) = ®.authentication
299 && !token::authorization_matches(headers, scheme, credentials)
300 {
301 return Err(WebhookRejection::BadAuthorization);
302 }
303 if let (Some(limit), Some(bucket)) = (self.rate_limit, reg.bucket.as_mut())
304 && !bucket.try_take(limit, Instant::now())
305 {
306 return Err(WebhookRejection::RateLimited);
307 }
308 Ok((reg.task_id.clone(), reg.config_id.clone()))
309 }
310}
311
312fn event_task_id(event: &StreamResponse) -> Option<&str> {
315 match event {
316 StreamResponse::Task(task) => Some(task.id.0.as_str()),
317 StreamResponse::StatusUpdate(update) => Some(update.task_id.0.as_str()),
318 StreamResponse::ArtifactUpdate(update) => Some(update.task_id.0.as_str()),
319 StreamResponse::Message(message) => message.task_id.as_ref().map(|t| t.0.as_str()),
320 _ => None,
321 }
322}