1use std::collections::HashMap;
9use std::time::Instant;
10
11use a2a_protocol_types::params::{DeletePushConfigParams, GetPushConfigParams};
12use a2a_protocol_types::push::TaskPushNotificationConfig;
13use a2a_protocol_types::task::TaskId;
14
15use crate::error::{ServerError, ServerResult};
16
17use super::RequestHandler;
18use super::helpers::build_call_context;
19
20pub(super) fn unset_proto3_defaults(config: &mut TaskPushNotificationConfig) {
26 super::helpers::unset_if_empty(&mut config.id);
27 super::helpers::unset_if_empty(&mut config.token);
28}
29
30fn require_field(name: &str, value: &str) -> ServerResult<()> {
35 if value.is_empty() {
36 return Err(ServerError::InvalidField {
37 field: name.to_owned(),
38 message: format!("{name} is required"),
39 });
40 }
41 super::ids::refuse_control_chars(value, name)
42}
43
44impl RequestHandler {
45 async fn require_task(&self, task_id: &str) -> ServerResult<()> {
47 let id = TaskId::new(task_id);
48 match self.task_store.get(&id).await? {
49 Some(_) => Ok(()),
50 None => Err(ServerError::TaskNotFound(id)),
51 }
52 }
53
54 pub(super) async fn validate_and_store_push_config(
74 &self,
75 config: TaskPushNotificationConfig,
76 ) -> ServerResult<TaskPushNotificationConfig> {
77 self.ensure_push_supported()?;
80 let Some(ref sender) = self.push_sender else {
81 return Err(ServerError::PushNotSupported);
82 };
83 super::ids::refuse_control_chars_in_push_config(&config)?;
84 if config.url.is_empty() {
90 return Err(ServerError::InvalidField {
91 field: "url".into(),
92 message: "url is required: the webhook to deliver to".into(),
93 });
94 }
95
96 let target_task = TaskId::new(config.task_id.clone().unwrap_or_default());
99 if self.task_store.get(&target_task).await?.is_none() {
100 return Err(ServerError::TaskNotFound(target_task));
101 }
102
103 refuse_an_unservable_config(sender.as_ref(), &config)?;
104
105 let task_key = config.task_id.clone().unwrap_or_default();
110
111 let cap_lock = self.keyed_lock(&format!("push:{task_key}")).await;
124 let _cap_guard = cap_lock.lock().await;
125
126 let existing = self.push_config_store.list(&task_key).await?;
127 let is_update = config
128 .id
129 .as_deref()
130 .is_some_and(|id| existing.iter().any(|c| c.id.as_deref() == Some(id)));
131 if !is_update && existing.len() >= self.limits.max_push_configs_per_task {
132 return Err(ServerError::InvalidParams(format!(
133 "task {task_key} already has the maximum of {} push notification configs",
134 self.limits.max_push_configs_per_task
135 )));
136 }
137
138 if !is_update
154 && let Some(total) = self.push_config_store.count().await?
155 && total >= self.limits.max_total_push_configs
156 {
157 self.metrics
158 .on_refusal(crate::metrics::control::refusal::PUSH_CONFIG_CAP);
159 return Err(ServerError::Overloaded(format!(
160 "server is at the maximum of {} push notification configs; \
161 delete unused configs before creating more",
162 self.limits.max_total_push_configs
163 )));
164 }
165
166 let stored = self.push_config_store.set(config).await?;
167 if is_update {
168 return Ok(stored);
169 }
170
171 let total = self.push_config_store.list(&task_key).await?.len();
186 if total > self.limits.max_push_configs_per_task {
187 if let Some(id) = stored.id.as_deref() {
188 self.push_config_store.delete(&task_key, id).await?;
189 }
190 return Err(ServerError::InvalidParams(format!(
191 "task {task_key} already has the maximum of {} push notification configs",
192 self.limits.max_push_configs_per_task
193 )));
194 }
195 Ok(stored)
196 }
197
198 #[allow(clippy::too_many_lines)]
205 pub async fn on_create_push_config(
206 &self,
207 mut config: TaskPushNotificationConfig,
208 headers: Option<&HashMap<String, String>>,
209 ) -> ServerResult<TaskPushNotificationConfig> {
210 let start = Instant::now();
211 unset_proto3_defaults(&mut config);
212 #[cfg(feature = "tracing")]
213 if let Some(task_id) = config.task_id.as_deref() {
214 crate::rpc_span::record_task(task_id, None);
215 }
216 self.metrics.on_request("CreateTaskPushNotificationConfig");
217
218 let tenant = self
219 .resolve_tenant_counted(
220 start,
221 "CreateTaskPushNotificationConfig",
222 headers,
223 config.tenant.as_deref(),
224 )
225 .await?;
226 let result: ServerResult<_> =
227 crate::store::tenant::TenantContext::scope_request(tenant, async {
228 let mut call_ctx = build_call_context(
229 "CreateTaskPushNotificationConfig",
230 headers,
231 self.inbound_trace_policy,
232 );
233 if let Some(task_id) = config.task_id.as_deref() {
234 call_ctx = call_ctx.with_task_id(task_id);
235 }
236 let mut call = self.interceptors.begin(&call_ctx);
237 let result = async {
238 self.admit(&mut call, &call_ctx).await?;
239 self.ensure_required_extensions(&call_ctx)?;
242 if config.task_id.as_deref().unwrap_or("").is_empty() {
248 return Err(ServerError::InvalidField {
249 field: "taskId".into(),
250 message: "taskId is required for CreateTaskPushNotificationConfig"
251 .into(),
252 });
253 }
254 self.validate_and_store_push_config(config).await
255 }
256 .await;
257 call.finish(result).await
258 })
259 .await
260 .map_err(ServerError::not_retry_safe);
261
262 let elapsed = start.elapsed();
263 match &result {
264 Ok(_) => {
265 self.metrics.on_response("CreateTaskPushNotificationConfig");
266 self.metrics
267 .on_latency("CreateTaskPushNotificationConfig", elapsed);
268 }
269 Err(e) => {
270 self.metrics
271 .on_error("CreateTaskPushNotificationConfig", e.metric_label());
272 self.metrics
273 .on_latency("CreateTaskPushNotificationConfig", elapsed);
274 }
275 }
276 result
277 }
278
279 pub async fn on_get_push_config(
288 &self,
289 params: GetPushConfigParams,
290 headers: Option<&HashMap<String, String>>,
291 ) -> ServerResult<TaskPushNotificationConfig> {
292 let start = Instant::now();
293 #[cfg(feature = "tracing")]
294 crate::rpc_span::record_task(¶ms.task_id, None);
295 self.metrics.on_request("GetTaskPushNotificationConfig");
296
297 let tenant = self
298 .resolve_tenant_counted(
299 start,
300 "GetTaskPushNotificationConfig",
301 headers,
302 params.tenant.as_deref(),
303 )
304 .await?;
305 let result: ServerResult<_> =
306 crate::store::tenant::TenantContext::scope_request(tenant, async {
307 let call_ctx = build_call_context(
308 "GetTaskPushNotificationConfig",
309 headers,
310 self.inbound_trace_policy,
311 )
312 .with_task_id(params.task_id.clone());
313 let mut call = self.interceptors.begin(&call_ctx);
314 let result = async {
315 self.admit(&mut call, &call_ctx).await?;
316 self.ensure_required_extensions(&call_ctx)?;
319 self.ensure_push_supported()?;
324
325 require_field("taskId", ¶ms.task_id)?;
326 require_field("id", ¶ms.id)?;
327 let config = self
330 .push_config_store
331 .get(¶ms.task_id, ¶ms.id)
332 .await?
333 .ok_or_else(|| ServerError::TaskNotFound(TaskId::new(¶ms.task_id)))?;
334
335 Ok(config)
336 }
337 .await;
338 call.finish(result).await
339 })
340 .await;
341
342 let elapsed = start.elapsed();
343 match &result {
344 Ok(_) => {
345 self.metrics.on_response("GetTaskPushNotificationConfig");
346 self.metrics
347 .on_latency("GetTaskPushNotificationConfig", elapsed);
348 }
349 Err(e) => {
350 self.metrics
351 .on_error("GetTaskPushNotificationConfig", e.metric_label());
352 self.metrics
353 .on_latency("GetTaskPushNotificationConfig", elapsed);
354 }
355 }
356 result
357 }
358
359 pub async fn on_list_push_configs(
368 &self,
369 task_id: &str,
370 tenant: Option<&str>,
371 headers: Option<&HashMap<String, String>>,
372 ) -> ServerResult<Vec<TaskPushNotificationConfig>> {
373 let start = Instant::now();
374 #[cfg(feature = "tracing")]
375 crate::rpc_span::record_task(task_id, None);
376 self.metrics.on_request("ListTaskPushNotificationConfigs");
377
378 let tenant_owned = self
379 .resolve_tenant_counted(start, "ListTaskPushNotificationConfigs", headers, tenant)
380 .await?;
381 let result: ServerResult<_> =
382 crate::store::tenant::TenantContext::scope_request(tenant_owned, async {
383 let call_ctx = build_call_context(
384 "ListTaskPushNotificationConfigs",
385 headers,
386 self.inbound_trace_policy,
387 )
388 .with_task_id(task_id);
389 let mut call = self.interceptors.begin(&call_ctx);
390 let result = async {
391 self.admit(&mut call, &call_ctx).await?;
392 self.ensure_required_extensions(&call_ctx)?;
395 self.ensure_push_supported()?;
400 require_field("taskId", task_id)?;
405 self.require_task(task_id).await?;
406 let configs = self.push_config_store.list(task_id).await?;
407 Ok(configs)
408 }
409 .await;
410 call.finish(result).await
411 })
412 .await;
413
414 let elapsed = start.elapsed();
415 match &result {
416 Ok(_) => {
417 self.metrics.on_response("ListTaskPushNotificationConfigs");
418 self.metrics
419 .on_latency("ListTaskPushNotificationConfigs", elapsed);
420 }
421 Err(e) => {
422 self.metrics
423 .on_error("ListTaskPushNotificationConfigs", e.metric_label());
424 self.metrics
425 .on_latency("ListTaskPushNotificationConfigs", elapsed);
426 }
427 }
428 result
429 }
430
431 pub async fn on_delete_push_config(
440 &self,
441 params: DeletePushConfigParams,
442 headers: Option<&HashMap<String, String>>,
443 ) -> ServerResult<()> {
444 let start = Instant::now();
445 #[cfg(feature = "tracing")]
446 crate::rpc_span::record_task(¶ms.task_id, None);
447 self.metrics.on_request("DeleteTaskPushNotificationConfig");
448
449 let tenant = self
450 .resolve_tenant_counted(
451 start,
452 "DeleteTaskPushNotificationConfig",
453 headers,
454 params.tenant.as_deref(),
455 )
456 .await?;
457 let result: ServerResult<_> =
458 crate::store::tenant::TenantContext::scope_request(tenant, async {
459 let call_ctx = build_call_context(
460 "DeleteTaskPushNotificationConfig",
461 headers,
462 self.inbound_trace_policy,
463 )
464 .with_task_id(params.task_id.clone());
465 let mut call = self.interceptors.begin(&call_ctx);
466 let result = async {
467 self.admit(&mut call, &call_ctx).await?;
468 self.ensure_required_extensions(&call_ctx)?;
471 self.ensure_push_supported()?;
476 require_field("taskId", ¶ms.task_id)?;
480 require_field("id", ¶ms.id)?;
481 self.require_task(¶ms.task_id).await?;
482 self.push_config_store
483 .delete(¶ms.task_id, ¶ms.id)
484 .await?;
485 Ok(())
486 }
487 .await;
488 call.finish(result).await
489 })
490 .await;
491
492 let elapsed = start.elapsed();
493 match &result {
494 Ok(()) => {
495 self.metrics.on_response("DeleteTaskPushNotificationConfig");
496 self.metrics
497 .on_latency("DeleteTaskPushNotificationConfig", elapsed);
498 }
499 Err(e) => {
500 self.metrics
501 .on_error("DeleteTaskPushNotificationConfig", e.metric_label());
502 self.metrics
503 .on_latency("DeleteTaskPushNotificationConfig", elapsed);
504 }
505 }
506 result
507 }
508}
509
510fn warn_if_plaintext_credentials(config: &TaskPushNotificationConfig) {
515 if !crate::push::sender::is_https_url(&config.url)
516 && (config.authentication.is_some()
517 || config.token.as_deref().is_some_and(|t| !t.is_empty()))
518 {
519 trace_warn!(
520 webhook = %crate::push::webhook::origin_for_log(&config.url),
521 "push config sends its token or credentials to a plaintext http:// webhook; \
522 spec §13.4 says credentials SHOULD travel only over encrypted connections \
523 (HttpPushSender::https_only refuses such configs)"
524 );
525 }
526}
527
528fn refuse_an_unservable_config(
532 sender: &dyn crate::push::PushSender,
533 config: &TaskPushNotificationConfig,
534) -> ServerResult<()> {
535 if !sender.allows_private_urls() {
547 crate::push::sender::validate_webhook_url(&config.url)?;
548 }
549 if sender.requires_https() && !crate::push::sender::is_https_url(&config.url) {
553 return Err(ServerError::InvalidField {
554 field: "url".into(),
555 message: "push notification URL must be https://: this server's push sender \
556 delivers only to https webhooks"
557 .into(),
558 });
559 }
560 warn_if_plaintext_credentials(config);
561 if !sender.allows_webhook_url(&config.url) {
562 return Err(ServerError::InvalidField {
563 field: "url".into(),
564 message: "push notification URL's host is not in the server's webhook allowlist".into(),
565 });
566 }
567 config.validate().map_err(ServerError::InvalidParams)?;
571 if let Some(auth) = &config.authentication
576 && !auth.scheme.eq_ignore_ascii_case("bearer")
577 && !auth.scheme.eq_ignore_ascii_case("basic")
578 {
579 return Err(ServerError::InvalidField {
580 field: "authentication.scheme".into(),
581 message: format!(
582 "push notification authentication scheme {:?} is not supported; \
583 this server can send Bearer or Basic",
584 auth.scheme
585 ),
586 });
587 }
588 refuse_unsendable_credentials(config)
589}
590
591fn refuse_unsendable_credentials(config: &TaskPushNotificationConfig) -> ServerResult<()> {
595 if config.authentication.as_ref().is_some_and(|auth| {
600 auth.credentials
601 .as_deref()
602 .is_none_or(|c| c.trim().is_empty())
603 }) {
604 return Err(ServerError::InvalidField {
605 field: "authentication.credentials".into(),
606 message: "push notification authentication names a scheme but carries no \
607 credentials; give the credentials, or leave authentication out"
608 .into(),
609 });
610 }
611 let credentials = config
615 .authentication
616 .as_ref()
617 .and_then(|auth| auth.credentials.as_deref());
618 for (field, path, value) in [
619 ("token", "token", config.token.as_deref()),
620 ("credentials", "authentication.credentials", credentials),
621 ] {
622 if value.is_some_and(|v| hyper::header::HeaderValue::from_str(v).is_err()) {
623 return Err(ServerError::InvalidField {
624 field: path.to_owned(),
625 message: format!(
626 "push notification {field} holds a character a header cannot carry \
627 (a control character such as CR or LF)"
628 ),
629 });
630 }
631 }
632 Ok(())
633}
634
635#[cfg(test)]
636mod tests {
637 use super::*;
638 use crate::agent_executor;
639 use crate::builder::RequestHandlerBuilder;
640
641 struct DummyExecutor;
642 agent_executor!(DummyExecutor, |_ctx, _queue| async { Ok(()) });
643
644 fn make_handler() -> RequestHandler {
645 RequestHandlerBuilder::new(DummyExecutor)
646 .without_agent_card()
647 .build()
648 .unwrap()
649 }
650
651 fn make_push_handler() -> RequestHandler {
654 RequestHandlerBuilder::new(DummyExecutor)
655 .without_agent_card()
656 .with_push_sender(NoopSender)
657 .build()
658 .unwrap()
659 }
660
661 fn make_push_config(task_id: &str) -> TaskPushNotificationConfig {
662 TaskPushNotificationConfig::new(
663 task_id.to_owned(),
664 "https://example.com/webhook".to_owned(),
665 )
666 .with_id("cfg-1".to_owned())
667 }
668
669 async fn save_task(handler: &RequestHandler, id: &str) {
672 use a2a_protocol_types::task::{ContextId, Task, TaskId, TaskState, TaskStatus};
673 let task = Task::new(
674 TaskId::new(id),
675 ContextId::new("ctx"),
676 TaskStatus::new(TaskState::Submitted),
677 );
678 handler.task_store.save(&task).await.unwrap();
679 }
680
681 #[derive(Debug)]
686 struct CapTestSender;
687
688 impl crate::push::PushSender for CapTestSender {
689 fn send<'a>(
690 &'a self,
691 _url: &'a str,
692 _event: &'a a2a_protocol_types::events::StreamResponse,
693 _config: &'a TaskPushNotificationConfig,
694 ) -> std::pin::Pin<
695 Box<
696 dyn std::future::Future<Output = a2a_protocol_types::error::A2aResult<()>>
697 + Send
698 + 'a,
699 >,
700 > {
701 Box::pin(async { Ok(()) })
702 }
703 }
704
705 #[derive(Debug, Default)]
713 struct SlowListStore(crate::push::InMemoryPushConfigStore);
714
715 type StoreFuture<'a, T> = std::pin::Pin<
716 Box<dyn std::future::Future<Output = a2a_protocol_types::error::A2aResult<T>> + Send + 'a>,
717 >;
718
719 impl crate::push::PushConfigStore for SlowListStore {
720 fn set(
721 &self,
722 config: TaskPushNotificationConfig,
723 ) -> StoreFuture<'_, TaskPushNotificationConfig> {
724 self.0.set(config)
725 }
726 fn get<'a>(
727 &'a self,
728 task_id: &'a str,
729 id: &'a str,
730 ) -> StoreFuture<'a, Option<TaskPushNotificationConfig>> {
731 self.0.get(task_id, id)
732 }
733 fn list<'a>(
734 &'a self,
735 task_id: &'a str,
736 ) -> StoreFuture<'a, Vec<TaskPushNotificationConfig>> {
737 Box::pin(async move {
738 tokio::time::sleep(std::time::Duration::from_millis(20)).await;
739 self.0.list(task_id).await
740 })
741 }
742 fn delete<'a>(&'a self, task_id: &'a str, id: &'a str) -> StoreFuture<'a, ()> {
743 self.0.delete(task_id, id)
744 }
745 }
746
747 #[tokio::test(flavor = "multi_thread", worker_threads = 8)]
772 async fn concurrent_creates_cannot_exceed_the_per_task_cap() {
773 use std::sync::Arc;
774
775 const CAP: usize = 5;
776 const WRITERS: usize = 32;
777
778 let handler = Arc::new(
779 RequestHandlerBuilder::new(DummyExecutor)
780 .without_agent_card()
781 .with_push_sender(CapTestSender)
782 .with_push_config_store(SlowListStore::default())
783 .with_handler_limits(
784 crate::handler::HandlerLimits::default().with_max_push_configs_per_task(CAP),
785 )
786 .build()
787 .unwrap(),
788 );
789 save_task(&handler, "task-1").await;
790
791 let mut creates = Vec::new();
792 for i in 0..WRITERS {
793 let each = Arc::clone(&handler);
794 creates.push(tokio::spawn(async move {
795 each.on_create_push_config(
796 TaskPushNotificationConfig::new(
797 "task-1".to_owned(),
798 format!("https://example.com/hook/{i}"),
799 )
800 .with_id(format!("cfg-{i}")),
801 None,
802 )
803 .await
804 .is_ok()
805 }));
806 }
807 let mut accepted = 0usize;
808 for create in creates {
809 if create.await.unwrap_or(false) {
810 accepted += 1;
811 }
812 }
813
814 let stored = handler
815 .on_list_push_configs("task-1", None, None)
816 .await
817 .expect("list")
818 .len();
819
820 assert_eq!(
821 stored, CAP,
822 "the store must hold exactly the cap; {WRITERS} concurrent creates stored {stored}"
823 );
824 assert_eq!(
825 accepted, CAP,
826 "and exactly {CAP} callers must have been told they succeeded, not {accepted} — \
827 a caller handed Ok for a config that breaks the cap was lied to"
828 );
829 }
830
831 #[tokio::test]
834 async fn set_push_config_without_sender_returns_push_not_supported() {
835 let handler = make_handler();
836 let config = make_push_config("task-1");
837 let result = handler.on_create_push_config(config, None).await;
838 assert!(
839 matches!(result, Err(crate::error::ServerError::PushNotSupported)),
840 "expected PushNotSupported, got: {result:?}"
841 );
842 }
843
844 #[tokio::test]
848 async fn every_push_op_without_a_sender_returns_push_not_supported() {
849 use a2a_protocol_types::params::{DeletePushConfigParams, GetPushConfigParams};
850
851 let handler = make_handler();
852 save_task(&handler, "task-1").await;
853
854 let get = handler
855 .on_get_push_config(GetPushConfigParams::new("task-1", "cfg-1"), None)
856 .await;
857 assert!(
858 matches!(get, Err(crate::error::ServerError::PushNotSupported)),
859 "get: {get:?}"
860 );
861 let list = handler.on_list_push_configs("task-1", None, None).await;
862 assert!(
863 matches!(list, Err(crate::error::ServerError::PushNotSupported)),
864 "list: {list:?}"
865 );
866 let delete = handler
867 .on_delete_push_config(DeletePushConfigParams::new("task-1", "cfg-1"), None)
868 .await;
869 assert!(
870 matches!(delete, Err(crate::error::ServerError::PushNotSupported)),
871 "delete: {delete:?}"
872 );
873 }
874
875 #[tokio::test]
880 async fn set_push_config_without_task_id_returns_invalid_params() {
881 use crate::push::PushSender;
882 use a2a_protocol_types::events::StreamResponse;
883 use std::future::Future;
884 use std::pin::Pin;
885
886 struct NoopSender;
887 impl PushSender for NoopSender {
888 fn send<'a>(
889 &'a self,
890 _url: &'a str,
891 _event: &'a StreamResponse,
892 _config: &'a TaskPushNotificationConfig,
893 ) -> Pin<Box<dyn Future<Output = a2a_protocol_types::error::A2aResult<()>> + Send + 'a>>
894 {
895 Box::pin(async { Ok(()) })
896 }
897 fn allows_private_urls(&self) -> bool {
898 true
899 }
900 }
901
902 let handler = RequestHandlerBuilder::new(DummyExecutor)
903 .without_agent_card()
904 .with_push_sender(NoopSender)
905 .build()
906 .unwrap();
907
908 let config = TaskPushNotificationConfig::for_url("https://example.com/webhook".to_owned());
909 let result = handler.on_create_push_config(config, None).await;
910 match result {
911 Err(crate::error::ServerError::InvalidField { message: msg, .. }) => {
912 assert!(msg.contains("taskId"), "got: {msg}");
913 }
914 other => panic!("expected InvalidParams for missing taskId, got: {other:?}"),
915 }
916 }
917
918 #[tokio::test]
932 async fn set_push_config_rejects_private_url_under_the_default_sender_policy() {
933 use crate::push::PushSender;
934 use a2a_protocol_types::events::StreamResponse;
935 use std::future::Future;
936 use std::pin::Pin;
937
938 struct DefaultPolicySender;
941 impl PushSender for DefaultPolicySender {
942 fn send<'a>(
943 &'a self,
944 _url: &'a str,
945 _event: &'a StreamResponse,
946 _config: &'a TaskPushNotificationConfig,
947 ) -> Pin<Box<dyn Future<Output = a2a_protocol_types::error::A2aResult<()>> + Send + 'a>>
948 {
949 Box::pin(async { Ok(()) })
950 }
951 }
952
953 let handler = RequestHandlerBuilder::new(DummyExecutor)
954 .without_agent_card()
955 .with_push_sender(DefaultPolicySender)
956 .build()
957 .unwrap();
958 save_task(&handler, "task-ssrf").await;
959
960 let config = TaskPushNotificationConfig::new(
961 "task-ssrf".to_owned(),
962 "http://127.0.0.1:9000/webhook".to_owned(),
963 )
964 .with_id("cfg-ssrf".to_owned());
965
966 match handler.on_create_push_config(config, None).await {
971 Err(e) => {
972 let msg = e.to_string();
973 assert!(
974 msg.contains("private/loopback"),
975 "expected the SSRF rejection, got: {msg}"
976 );
977 }
978 Ok(v) => panic!(
979 "a sender taking the default policy must refuse a loopback webhook URL, got: Ok({v:?})"
980 ),
981 }
982 }
983
984 #[tokio::test]
988 async fn set_push_config_enforces_global_cap() {
989 use crate::push::PushSender;
990 use a2a_protocol_types::events::StreamResponse;
991 use std::future::Future;
992 use std::pin::Pin;
993
994 struct NoopSender;
995 impl PushSender for NoopSender {
996 fn send<'a>(
997 &'a self,
998 _url: &'a str,
999 _event: &'a StreamResponse,
1000 _config: &'a TaskPushNotificationConfig,
1001 ) -> Pin<Box<dyn Future<Output = a2a_protocol_types::error::A2aResult<()>> + Send + 'a>>
1002 {
1003 Box::pin(async { Ok(()) })
1004 }
1005 }
1006
1007 let handler = RequestHandlerBuilder::new(DummyExecutor)
1008 .without_agent_card()
1009 .with_push_sender(NoopSender)
1010 .with_handler_limits(
1011 crate::handler::HandlerLimits::default().with_max_total_push_configs(2),
1012 )
1013 .build()
1014 .unwrap();
1015
1016 for i in 0..2 {
1018 save_task(&handler, &format!("task-{i}")).await;
1019 let cfg = TaskPushNotificationConfig::new(
1020 format!("task-{i}"),
1021 "https://example.com/webhook".to_owned(),
1022 )
1023 .with_id(format!("cfg-{i}"));
1024 handler
1025 .on_create_push_config(cfg, None)
1026 .await
1027 .expect("creates under the global cap should succeed");
1028 }
1029
1030 save_task(&handler, "task-x").await;
1032 let cfg = TaskPushNotificationConfig::new(
1033 "task-x".to_owned(),
1034 "https://example.com/webhook".to_owned(),
1035 )
1036 .with_id("cfg-x".to_owned());
1037 let result = handler.on_create_push_config(cfg, None).await;
1038 assert!(
1039 matches!(result, Err(crate::error::ServerError::Overloaded(_))),
1040 "global push-config cap must reject, got {result:?}"
1041 );
1042 }
1043
1044 #[tokio::test]
1048 async fn set_push_config_update_allowed_at_per_task_cap() {
1049 use crate::push::PushSender;
1050 use a2a_protocol_types::events::StreamResponse;
1051 use std::future::Future;
1052 use std::pin::Pin;
1053
1054 struct NoopSender;
1055 impl PushSender for NoopSender {
1056 fn send<'a>(
1057 &'a self,
1058 _url: &'a str,
1059 _event: &'a StreamResponse,
1060 _config: &'a TaskPushNotificationConfig,
1061 ) -> Pin<Box<dyn Future<Output = a2a_protocol_types::error::A2aResult<()>> + Send + 'a>>
1062 {
1063 Box::pin(async { Ok(()) })
1064 }
1065 }
1066
1067 let handler = RequestHandlerBuilder::new(DummyExecutor)
1069 .without_agent_card()
1070 .with_push_sender(NoopSender)
1071 .with_handler_limits(
1072 crate::handler::HandlerLimits::default().with_max_push_configs_per_task(1),
1073 )
1074 .build()
1075 .unwrap();
1076
1077 save_task(&handler, "task-1").await;
1078 let make = |url: &str| {
1079 TaskPushNotificationConfig::new("task-1".to_owned(), url.to_owned())
1080 .with_id("cfg-1".to_owned())
1081 };
1082
1083 handler
1085 .on_create_push_config(make("https://example.com/a"), None)
1086 .await
1087 .expect("first create should succeed");
1088
1089 handler
1091 .on_create_push_config(make("https://example.com/b"), None)
1092 .await
1093 .expect("updating an existing config at the cap must be allowed");
1094
1095 let mut newcfg = make("https://example.com/c");
1097 newcfg.id = Some("cfg-2".to_owned());
1098 let rejected = handler.on_create_push_config(newcfg, None).await;
1099 assert!(
1100 matches!(rejected, Err(crate::error::ServerError::InvalidParams(_))),
1101 "a new config beyond the per-task cap must be rejected, got {rejected:?}"
1102 );
1103 }
1104
1105 struct NoopSender;
1108 impl crate::push::PushSender for NoopSender {
1109 fn send<'a>(
1110 &'a self,
1111 _url: &'a str,
1112 _event: &'a a2a_protocol_types::events::StreamResponse,
1113 _config: &'a TaskPushNotificationConfig,
1114 ) -> std::pin::Pin<
1115 Box<
1116 dyn std::future::Future<Output = a2a_protocol_types::error::A2aResult<()>>
1117 + Send
1118 + 'a,
1119 >,
1120 > {
1121 Box::pin(async { Ok(()) })
1122 }
1123 fn allows_private_urls(&self) -> bool {
1124 true
1125 }
1126 }
1127
1128 fn card_with(
1130 caps: a2a_protocol_types::agent_card::AgentCapabilities,
1131 ) -> a2a_protocol_types::agent_card::AgentCard {
1132 use a2a_protocol_types::agent_card::{AgentCard, AgentInterface};
1133 AgentCard::new(
1134 "Test Agent",
1135 "1.0.0",
1136 AgentInterface::new("http://localhost:8080", "JSONRPC").with_protocol_version("1.0.0"),
1137 )
1138 .with_description("A test agent")
1139 .with_input_modes(vec!["text/plain"])
1140 .with_output_modes(vec!["text/plain"])
1141 .with_skill(
1142 a2a_protocol_types::AgentSkill::new("test", "Test", "A test skill").with_tags(["test"]),
1143 )
1144 .with_capabilities(caps)
1145 }
1146
1147 #[tokio::test]
1151 async fn set_push_config_rejects_an_empty_or_schemeless_url_when_private_urls_are_allowed() {
1152 let handler = RequestHandlerBuilder::new(DummyExecutor)
1153 .without_agent_card()
1154 .with_push_sender(NoopSender)
1155 .build()
1156 .unwrap();
1157 save_task(&handler, "t-1").await;
1158 for url in ["", "example.com/hook"] {
1159 let mut config = make_push_config("t-1");
1160 config.url = url.to_owned();
1161 let result = handler.on_create_push_config(config, None).await;
1162 let refused = if url.is_empty() {
1166 matches!(&result, Err(crate::error::ServerError::InvalidField { field, .. }) if field == "url")
1167 } else {
1168 matches!(result, Err(crate::error::ServerError::InvalidParams(_)))
1169 };
1170 assert!(
1171 refused,
1172 "url {url:?}: expected InvalidParams, got {result:?}"
1173 );
1174 }
1175 let stored = handler
1176 .on_list_push_configs("t-1", None, None)
1177 .await
1178 .expect("list");
1179 assert!(stored.is_empty(), "nothing may be stored: {stored:?}");
1180 }
1181
1182 #[tokio::test]
1186 async fn set_push_config_refuses_an_auth_scheme_it_cannot_send() {
1187 use a2a_protocol_types::push::AuthenticationInfo;
1188 let handler = RequestHandlerBuilder::new(DummyExecutor)
1189 .without_agent_card()
1190 .with_push_sender(NoopSender)
1191 .build()
1192 .unwrap();
1193 save_task(&handler, "t-1").await;
1194 let with_scheme = |scheme: &str| {
1195 let mut config = make_push_config("t-1");
1196 config.authentication = Some(
1197 AuthenticationInfo::new(scheme.to_owned()).with_credentials("secret".to_owned()),
1198 );
1199 config
1200 };
1201 let refused = handler
1202 .on_create_push_config(with_scheme("Digest"), None)
1203 .await;
1204 assert!(
1205 matches!(&refused, Err(crate::error::ServerError::InvalidField { message: m, .. }) if m.contains("Digest")),
1206 "{refused:?}"
1207 );
1208 let refused = handler.on_create_push_config(with_scheme(""), None).await;
1210 assert!(
1211 matches!(
1212 &refused,
1213 Err(crate::error::ServerError::InvalidField { .. })
1214 ),
1215 "{refused:?}"
1216 );
1217 for scheme in ["Bearer", "basic"] {
1218 handler
1219 .on_create_push_config(with_scheme(scheme), None)
1220 .await
1221 .unwrap_or_else(|e| panic!("{scheme} must be accepted: {e}"));
1222 }
1223 }
1224
1225 #[tokio::test]
1229 async fn empty_required_ids_are_invalid_params() {
1230 let handler = RequestHandlerBuilder::new(DummyExecutor)
1231 .without_agent_card()
1232 .with_push_sender(NoopSender)
1233 .build()
1234 .unwrap();
1235 save_task(&handler, "t-1").await;
1236 let get =
1237 |task_id: &str, id: &str| GetPushConfigParams::new(task_id.to_owned(), id.to_owned());
1238 let del = |task_id: &str, id: &str| {
1239 DeletePushConfigParams::new(task_id.to_owned(), id.to_owned())
1240 };
1241 for (task_id, id) in [("", "cfg-1"), ("t-1", "")] {
1242 let r = handler.on_get_push_config(get(task_id, id), None).await;
1243 assert!(
1244 matches!(r, Err(crate::error::ServerError::InvalidField { .. })),
1245 "get {task_id:?}/{id:?}: {r:?}"
1246 );
1247 let r = handler.on_delete_push_config(del(task_id, id), None).await;
1248 assert!(
1249 matches!(r, Err(crate::error::ServerError::InvalidField { .. })),
1250 "delete {task_id:?}/{id:?}: {r:?}"
1251 );
1252 }
1253 let r = handler.on_list_push_configs("", None, None).await;
1254 assert!(
1255 matches!(r, Err(crate::error::ServerError::InvalidField { .. })),
1256 "list: {r:?}"
1257 );
1258 }
1259
1260 #[tokio::test]
1263 async fn set_push_config_refuses_a_host_outside_the_allowlist() {
1264 let handler = RequestHandlerBuilder::new(DummyExecutor)
1265 .without_agent_card()
1266 .with_push_sender(
1267 crate::push::HttpPushSender::new().with_allowed_hosts(["hooks.example.com"]),
1268 )
1269 .build()
1270 .unwrap();
1271 save_task(&handler, "t-1").await;
1272 let mut config = make_push_config("t-1");
1273 config.url = "https://other.example.com/hook".into();
1274 let refused = handler.on_create_push_config(config, None).await;
1275 assert!(
1276 matches!(&refused, Err(crate::error::ServerError::InvalidField { message: m, .. }) if m.contains("allowlist")),
1277 "{refused:?}"
1278 );
1279 let mut config = make_push_config("t-1");
1280 config.url = "https://hooks.example.com/hook".into();
1281 handler
1282 .on_create_push_config(config, None)
1283 .await
1284 .expect("a listed host is accepted");
1285 }
1286
1287 #[tokio::test]
1290 async fn set_push_config_refuses_http_when_the_sender_is_https_only() {
1291 let handler = RequestHandlerBuilder::new(DummyExecutor)
1292 .without_agent_card()
1293 .with_push_sender(crate::push::HttpPushSender::new().https_only())
1294 .build()
1295 .unwrap();
1296 save_task(&handler, "t-1").await;
1297 let mut config = make_push_config("t-1");
1298 config.url = "http://hooks.example.com/hook".into();
1299 let refused = handler.on_create_push_config(config, None).await;
1300 assert!(
1301 matches!(&refused, Err(crate::error::ServerError::InvalidField { message: m, .. }) if m.contains("must be https://")),
1302 "{refused:?}"
1303 );
1304 let mut config = make_push_config("t-1");
1305 config.url = "https://hooks.example.com/hook".into();
1306 handler
1307 .on_create_push_config(config, None)
1308 .await
1309 .expect("an https:// webhook is accepted");
1310 }
1311
1312 #[tokio::test]
1315 async fn set_push_config_accepts_http_from_a_sender_that_does_not_require_https() {
1316 let handler = RequestHandlerBuilder::new(DummyExecutor)
1317 .without_agent_card()
1318 .with_push_sender(NoopSender)
1319 .build()
1320 .unwrap();
1321 save_task(&handler, "t-1").await;
1322 let mut config = make_push_config("t-1");
1323 config.url = "http://hooks.example.com/hook".into();
1324 handler
1325 .on_create_push_config(config, None)
1326 .await
1327 .expect("http:// is accepted unless the sender requires https");
1328 }
1329
1330 #[tokio::test]
1333 async fn set_push_config_for_missing_task_returns_task_not_found() {
1334 let handler = RequestHandlerBuilder::new(DummyExecutor)
1335 .without_agent_card()
1336 .with_push_sender(NoopSender)
1337 .build()
1338 .unwrap();
1339 let config = make_push_config("ghost-task");
1340 let result = handler.on_create_push_config(config, None).await;
1341 assert!(
1342 matches!(result, Err(crate::error::ServerError::TaskNotFound(_))),
1343 "expected TaskNotFound for a config targeting a missing task, got: {result:?}"
1344 );
1345 }
1346
1347 #[tokio::test]
1351 async fn push_ops_rejected_when_card_lacks_capability() {
1352 use a2a_protocol_types::agent_card::AgentCapabilities;
1353 use a2a_protocol_types::params::{DeletePushConfigParams, GetPushConfigParams};
1354
1355 let handler = RequestHandlerBuilder::new(DummyExecutor)
1356 .with_push_sender(NoopSender)
1357 .with_agent_card(card_with(AgentCapabilities::none()))
1358 .build()
1359 .unwrap();
1360
1361 let set = handler
1362 .on_create_push_config(make_push_config("t1"), None)
1363 .await;
1364 assert!(
1365 matches!(set, Err(crate::error::ServerError::PushNotSupported)),
1366 "set must be rejected, got: {set:?}"
1367 );
1368
1369 let get = handler
1370 .on_get_push_config(GetPushConfigParams::new("t1", "cfg-1"), None)
1371 .await;
1372 assert!(
1373 matches!(get, Err(crate::error::ServerError::PushNotSupported)),
1374 "get must be rejected, got: {get:?}"
1375 );
1376
1377 let list = handler.on_list_push_configs("t1", None, None).await;
1378 assert!(
1379 matches!(list, Err(crate::error::ServerError::PushNotSupported)),
1380 "list must be rejected, got: {list:?}"
1381 );
1382
1383 let delete = handler
1384 .on_delete_push_config(DeletePushConfigParams::new("t1", "cfg-1"), None)
1385 .await;
1386 assert!(
1387 matches!(delete, Err(crate::error::ServerError::PushNotSupported)),
1388 "delete must be rejected, got: {delete:?}"
1389 );
1390 }
1391
1392 #[tokio::test]
1395 async fn push_ops_allowed_when_card_has_capability() {
1396 use a2a_protocol_types::agent_card::AgentCapabilities;
1397
1398 let handler = RequestHandlerBuilder::new(DummyExecutor)
1399 .with_push_sender(NoopSender)
1400 .with_agent_card(card_with(
1401 AgentCapabilities::none().with_push_notifications(true),
1402 ))
1403 .build()
1404 .unwrap();
1405 save_task(&handler, "t1").await;
1406
1407 handler
1408 .on_create_push_config(make_push_config("t1"), None)
1409 .await
1410 .expect("set should succeed when push capability is advertised");
1411 let configs = handler
1412 .on_list_push_configs("t1", None, None)
1413 .await
1414 .expect("list should succeed");
1415 assert_eq!(configs.len(), 1, "the created config should be listed");
1416 }
1417
1418 #[tokio::test]
1421 async fn get_push_config_not_found_returns_task_not_found() {
1422 use a2a_protocol_types::params::GetPushConfigParams;
1425
1426 let handler = make_push_handler();
1427 let params = GetPushConfigParams::new("no-task".to_owned(), "no-id".to_owned());
1428 let result = handler.on_get_push_config(params, None).await;
1429 assert!(
1430 matches!(result, Err(crate::error::ServerError::TaskNotFound(_))),
1431 "expected TaskNotFound for missing config, got: {result:?}"
1432 );
1433 }
1434
1435 #[tokio::test]
1440 async fn list_push_configs_for_an_unknown_task_is_task_not_found() {
1441 let handler = make_push_handler();
1442 let result = handler.on_list_push_configs("no-task", None, None).await;
1443 assert!(
1444 matches!(result, Err(crate::error::ServerError::TaskNotFound(_))),
1445 "expected TaskNotFound, got: {result:?}"
1446 );
1447 }
1448
1449 #[tokio::test]
1450 async fn list_push_configs_of_a_task_without_any_is_empty() {
1451 let handler = make_push_handler();
1452 save_task(&handler, "t-empty").await;
1453 let result = handler
1454 .on_list_push_configs("t-empty", None, None)
1455 .await
1456 .expect("a known task lists");
1457 assert!(result.is_empty(), "{result:?}");
1458 }
1459
1460 #[tokio::test]
1465 async fn delete_push_config_nonexistent_returns_ok() {
1466 use a2a_protocol_types::params::DeletePushConfigParams;
1467
1468 let handler = make_push_handler();
1469 save_task(&handler, "t-del").await;
1470 let params = DeletePushConfigParams::new("t-del".to_owned(), "no-id".to_owned());
1471 let result = handler.on_delete_push_config(params, None).await;
1472 assert!(
1473 result.is_ok(),
1474 "deleting a non-existent push config should return Ok, got: {result:?}"
1475 );
1476 }
1477
1478 #[tokio::test]
1480 async fn delete_push_config_of_an_unknown_task_is_task_not_found() {
1481 use a2a_protocol_types::params::DeletePushConfigParams;
1482
1483 let handler = make_push_handler();
1484 let params = DeletePushConfigParams::new("no-task".to_owned(), "no-id".to_owned());
1485 let result = handler.on_delete_push_config(params, None).await;
1486 assert!(
1487 matches!(result, Err(crate::error::ServerError::TaskNotFound(_))),
1488 "expected TaskNotFound, got: {result:?}"
1489 );
1490 }
1491
1492 #[tokio::test]
1495 async fn list_push_configs_error_path_records_metrics() {
1496 use crate::call_context::CallContext;
1499 use crate::interceptor::ServerInterceptor;
1500 use std::future::Future;
1501 use std::pin::Pin;
1502
1503 struct FailInterceptor;
1504 impl ServerInterceptor for FailInterceptor {
1505 fn before<'a>(
1506 &'a self,
1507 _ctx: &'a CallContext,
1508 ) -> Pin<Box<dyn Future<Output = a2a_protocol_types::error::A2aResult<()>> + Send + 'a>>
1509 {
1510 Box::pin(async {
1511 Err(a2a_protocol_types::error::A2aError::internal(
1512 "forced failure",
1513 ))
1514 })
1515 }
1516 fn after<'a>(
1517 &'a self,
1518 _ctx: &'a CallContext,
1519 ) -> Pin<Box<dyn Future<Output = a2a_protocol_types::error::A2aResult<()>> + Send + 'a>>
1520 {
1521 Box::pin(async { Ok(()) })
1522 }
1523 }
1524
1525 let handler = RequestHandlerBuilder::new(DummyExecutor)
1526 .without_agent_card()
1527 .with_interceptor(FailInterceptor)
1528 .with_push_sender(NoopSender)
1529 .build()
1530 .unwrap();
1531
1532 let result = handler.on_list_push_configs("task-1", None, None).await;
1533 assert!(
1534 result.is_err(),
1535 "list_push_configs should fail when interceptor rejects"
1536 );
1537 }
1538
1539 #[tokio::test]
1540 async fn delete_push_config_error_path_records_metrics() {
1541 use crate::call_context::CallContext;
1544 use crate::interceptor::ServerInterceptor;
1545 use a2a_protocol_types::params::DeletePushConfigParams;
1546 use std::future::Future;
1547 use std::pin::Pin;
1548
1549 struct FailInterceptor;
1550 impl ServerInterceptor for FailInterceptor {
1551 fn before<'a>(
1552 &'a self,
1553 _ctx: &'a CallContext,
1554 ) -> Pin<Box<dyn Future<Output = a2a_protocol_types::error::A2aResult<()>> + Send + 'a>>
1555 {
1556 Box::pin(async {
1557 Err(a2a_protocol_types::error::A2aError::internal(
1558 "forced failure",
1559 ))
1560 })
1561 }
1562 fn after<'a>(
1563 &'a self,
1564 _ctx: &'a CallContext,
1565 ) -> Pin<Box<dyn Future<Output = a2a_protocol_types::error::A2aResult<()>> + Send + 'a>>
1566 {
1567 Box::pin(async { Ok(()) })
1568 }
1569 }
1570
1571 let handler = RequestHandlerBuilder::new(DummyExecutor)
1572 .without_agent_card()
1573 .with_interceptor(FailInterceptor)
1574 .build()
1575 .unwrap();
1576
1577 let params = DeletePushConfigParams::new("task-1".to_owned(), "cfg-1".to_owned());
1578 let result = handler.on_delete_push_config(params, None).await;
1579 assert!(
1580 result.is_err(),
1581 "delete_push_config should fail when interceptor rejects"
1582 );
1583 }
1584
1585 #[tokio::test]
1586 async fn set_push_config_error_path_records_metrics() {
1587 let handler = make_handler();
1590 let config = make_push_config("task-err");
1591 let result = handler.on_create_push_config(config, None).await;
1592 assert!(
1593 result.is_err(),
1594 "set_push_config without push sender should hit error metrics path"
1595 );
1596 }
1597
1598 #[tokio::test]
1599 async fn get_push_config_error_path_records_metrics() {
1600 use a2a_protocol_types::params::GetPushConfigParams;
1603
1604 let handler = make_push_handler();
1605 let params = GetPushConfigParams::new("missing-task".to_owned(), "missing-id".to_owned());
1606 let result = handler.on_get_push_config(params, None).await;
1607 assert!(
1608 result.is_err(),
1609 "get_push_config for missing config should hit error metrics path"
1610 );
1611 }
1612}