1use crate::HandlerOutput;
27use crate::I18nProjection;
28use jmap_types::{Id, JmapError, State};
29use serde_json::{Value, json};
30
31use crate::backend::{
32 BackendChangesError, ChangesParams, GetObject, JmapBackend, JmapObject, QueryChangesParams,
33 QueryObject, QueryParams,
34};
35use crate::helpers::{
36 MetadataProjection, enforce_max_objects_in_get, extract_account_id, filter_arg, not_found_json,
37 optional_arg, query_anchor_args, serialize_value,
38};
39
40pub const SERVER_FAIL_INTERNAL_DESC: &str = "internal error";
47
48pub fn server_fail_from_backend<E: std::fmt::Display + ?Sized>(_err: &E) -> JmapError {
86 JmapError::server_fail(SERVER_FAIL_INTERNAL_DESC)
87}
88
89pub fn changes_error_from_backend<E: std::error::Error>(err: BackendChangesError<E>) -> JmapError {
101 match err {
102 BackendChangesError::TooManyChanges { .. } => JmapError::cannot_calculate_changes(),
103 other => JmapError::from(other),
104 }
105}
106
107pub fn server_fail_value_from_backend<E: std::fmt::Display + ?Sized>(_err: &E) -> Value {
153 json!({
154 "type": "serverFail",
155 "description": SERVER_FAIL_INTERNAL_DESC,
156 })
157}
158
159pub async fn handle_get<O: GetObject, B: JmapBackend>(
176 backend: &B,
177 caller: &B::CallerCtx,
178 args: Value,
179) -> Result<HandlerOutput, JmapError> {
180 get_impl::<O, B>(backend, caller, args, &[]).await
181}
182
183async fn get_impl<O: GetObject, B: JmapBackend>(
189 backend: &B,
190 caller: &B::CallerCtx,
191 args: Value,
192 using: &[String],
193) -> Result<HandlerOutput, JmapError> {
194 let (account_id, mut args) = extract_account_id(args)?;
195 if !backend
196 .account_exists(caller, &account_id)
197 .await
198 .map_err(|e| server_fail_from_backend(&e))?
199 {
200 return Err(JmapError::account_not_found());
201 }
202 enforce_max_objects_in_get(&args, backend.max_objects_in_get(caller, &account_id))?;
203
204 let i18n = I18nProjection::from_args::<O>(
205 &mut args,
206 using,
207 backend.i18n_info(caller, &account_id).as_ref(),
208 )?;
209
210 let ids: Option<Vec<Id>> = optional_arg(&mut args, "ids", || {
211 JmapError::invalid_arguments("ids must be an Id array")
212 })?;
213
214 let properties: Option<Vec<String>> = optional_arg(&mut args, "properties", || {
215 JmapError::invalid_arguments("properties must be a string array")
216 })?;
217 let backend_properties = i18n.backend_properties(properties.as_deref());
218
219 let ids_slice = ids.as_deref();
220 let (list, not_found) = backend
221 .get_objects::<O>(
222 caller,
223 &account_id,
224 ids_slice,
225 backend_properties.as_deref(),
226 )
227 .await
228 .map_err(|e| server_fail_from_backend(&e))?;
229
230 let state = backend
231 .get_state::<O>(caller, &account_id)
232 .await
233 .map_err(|e| server_fail_from_backend(&e))?;
234
235 let mut list_json = serialize_value(&list)?;
242
243 if let Value::Array(items) = &mut list_json {
244 for item in items {
245 if let Value::Object(map) = item {
246 i18n.apply(map);
249 if let Some(props) = &properties {
257 map.retain(|k, _| k == "id" || props.iter().any(|p| p == k));
258 }
259 }
260 }
261 }
262
263 Ok(HandlerOutput::new(json!({
264 "accountId": account_id.as_ref(),
265 "state": state.as_ref(),
266 "list": list_json,
267 "notFound": not_found_json(¬_found),
268 })))
269}
270
271pub async fn handle_get_with_metadata<O: GetObject, B: JmapBackend>(
301 backend: &B,
302 caller: &B::CallerCtx,
303 mut args: Value,
304 using: &[String],
305) -> Result<HandlerOutput, JmapError> {
306 let info = args
307 .get("accountId")
308 .and_then(Value::as_str)
309 .and_then(|s| Id::new_validated(s).ok())
310 .and_then(|id| backend.metadata_info::<O>(caller, &id));
311 let Some(info) = info else {
312 return get_impl::<O, B>(backend, caller, args, using).await;
313 };
314 let properties: Option<Vec<String>> = match args.get("properties") {
315 None | Some(Value::Null) => None,
316 Some(v) => match serde_json::from_value(v.clone()) {
317 Ok(props) => Some(props),
318 Err(_) => return get_impl::<O, B>(backend, caller, args, using).await,
320 },
321 };
322 let projection = MetadataProjection::new(properties.as_deref(), true, using, Some(&info))?;
323 if let Some(props) = properties {
324 let mut roots: Vec<String> = Vec::with_capacity(props.len());
325 for p in props {
326 let root = match p.split_once('/') {
327 Some((r @ ("metadata" | "privateMetadata"), _)) => r.to_owned(),
328 _ => p,
329 };
330 if !roots.contains(&root) {
331 roots.push(root);
332 }
333 }
334 args["properties"] = json!(roots);
335 }
336 let mut out = get_impl::<O, B>(backend, caller, args, using).await?;
337 if let Some(Value::Array(list)) = out.primary.get_mut("list") {
338 for item in list {
339 let source = item.clone();
340 projection.apply(&source, item);
341 }
342 }
343 Ok(out)
344}
345
346pub async fn handle_changes<O: JmapObject, B: JmapBackend>(
368 backend: &B,
369 caller: &B::CallerCtx,
370 args: Value,
371 using: &[String],
372) -> Result<HandlerOutput, JmapError> {
373 let (account_id, args) = extract_account_id(args)?;
374 if !backend
375 .account_exists(caller, &account_id)
376 .await
377 .map_err(|e| server_fail_from_backend(&e))?
378 {
379 return Err(JmapError::account_not_found());
380 }
381
382 let since_state: State = match args.get("sinceState").and_then(|v| v.as_str()) {
383 Some(s) => State::from(s),
384 None => return Err(JmapError::invalid_arguments("sinceState is required")),
385 };
386
387 let max_changes = crate::parse_max_changes(args.get("maxChanges"))?;
388
389 let uses_metadata = using
390 .iter()
391 .any(|u| u == jmap_metadata_types::JMAP_METADATA_URI);
392 let ignore_metadata_only_changes = !uses_metadata
393 || match args.get("ignoreMetadataOnlyChanges") {
394 None | Some(Value::Null) => false,
395 Some(Value::Bool(b)) => *b,
396 Some(v) => {
397 return Err(JmapError::invalid_arguments(format!(
398 "ignoreMetadataOnlyChanges: expected a boolean, got {}",
399 crate::helpers::json_type_name(v)
400 )));
401 }
402 };
403
404 let result = backend
405 .get_changes::<O>(
406 caller,
407 &account_id,
408 ChangesParams::new(&since_state)
409 .max_changes(max_changes)
410 .ignore_metadata_only_changes(ignore_metadata_only_changes),
411 )
412 .await
413 .map_err(changes_error_from_backend)?;
414 let updated_properties = if result.updated.is_empty() {
415 None
416 } else {
417 result.updated_properties
418 };
419
420 Ok(HandlerOutput::new(json!({
421 "accountId": account_id.as_ref(),
422 "oldState": since_state.as_ref(),
423 "newState": result.new_state.as_ref(),
424 "hasMoreChanges": result.has_more_changes,
425 "updatedProperties": updated_properties,
426 "created": result.created,
429 "updated": result.updated,
430 "destroyed": result.destroyed,
431 })))
432}
433
434pub async fn handle_query<O: QueryObject, B: JmapBackend>(
452 backend: &B,
453 caller: &B::CallerCtx,
454 args: Value,
455) -> Result<HandlerOutput, JmapError> {
456 query_impl::<O, B>(backend, caller, args, &[]).await
457}
458
459pub async fn handle_query_with_i18n<O: QueryObject, B: JmapBackend>(
474 backend: &B,
475 caller: &B::CallerCtx,
476 args: Value,
477 using: &[String],
478) -> Result<HandlerOutput, JmapError> {
479 query_impl::<O, B>(backend, caller, args, using).await
480}
481
482async fn query_impl<O: QueryObject, B: JmapBackend>(
484 backend: &B,
485 caller: &B::CallerCtx,
486 args: Value,
487 using: &[String],
488) -> Result<HandlerOutput, JmapError> {
489 let (account_id, mut args) = extract_account_id(args)?;
490 if !backend
491 .account_exists(caller, &account_id)
492 .await
493 .map_err(|e| server_fail_from_backend(&e))?
494 {
495 return Err(JmapError::account_not_found());
496 }
497
498 let i18n = I18nProjection::from_args::<O>(
501 &mut args,
502 using,
503 backend.i18n_info(caller, &account_id).as_ref(),
504 )?;
505 let language = i18n.language();
506
507 let calculate_total: bool = args
508 .get("calculateTotal")
509 .and_then(|v| v.as_bool())
510 .unwrap_or(false);
511
512 let limit: Option<u64> = match args.get("limit") {
513 None | Some(Value::Null) => None,
514 Some(v) => match v.as_u64() {
515 Some(n) => Some(n),
516 None => {
517 return Err(JmapError::invalid_arguments(format!(
518 "limit: expected a non-negative integer, got {}",
519 crate::helpers::json_type_name(v)
520 )));
521 }
522 },
523 };
524
525 let position: i64 = match args.get("position") {
526 None | Some(Value::Null) => 0,
527 Some(v) => v.as_i64().ok_or_else(|| {
528 JmapError::invalid_arguments(format!(
529 "position: expected an integer, got {}",
530 crate::helpers::json_type_name(v)
531 ))
532 })?,
533 };
534
535 let (anchor, anchor_offset) = query_anchor_args(&args)?;
536
537 let filter: Option<O::Filter> = filter_arg(&mut args)?;
538
539 let sort: Option<Vec<O::Comparator>> = optional_arg(&mut args, "sort", || {
540 JmapError::invalid_arguments("sort must be an array")
541 })?;
542
543 let result = backend
544 .query_objects::<O>(
545 caller,
546 &account_id,
547 QueryParams::new()
548 .filter(filter.as_ref())
549 .sort(sort.as_deref())
550 .limit(limit)
551 .position(position)
552 .anchor(anchor.as_ref())
553 .anchor_offset(anchor_offset)
554 .language(language),
555 )
556 .await
557 .map_err(JmapError::from)?;
558
559 let mut resp = json!({
560 "accountId": account_id.as_ref(),
561 "queryState": crate::localized_query_state(&result.query_state, language).as_ref(),
562 "canCalculateChanges": result.can_calculate_changes,
563 "position": result.position,
564 "ids": result.ids,
567 });
568 if calculate_total && let Some(t) = result.total {
569 resp["total"] = json!(t);
570 }
571
572 Ok(HandlerOutput::new(resp))
573}
574
575pub async fn handle_query_changes<O: QueryObject, B: JmapBackend>(
591 backend: &B,
592 caller: &B::CallerCtx,
593 args: Value,
594) -> Result<HandlerOutput, JmapError> {
595 query_changes_impl::<O, B>(backend, caller, args, &[]).await
596}
597
598pub async fn handle_query_changes_with_i18n<O: QueryObject, B: JmapBackend>(
611 backend: &B,
612 caller: &B::CallerCtx,
613 args: Value,
614 using: &[String],
615) -> Result<HandlerOutput, JmapError> {
616 query_changes_impl::<O, B>(backend, caller, args, using).await
617}
618
619async fn query_changes_impl<O: QueryObject, B: JmapBackend>(
622 backend: &B,
623 caller: &B::CallerCtx,
624 args: Value,
625 using: &[String],
626) -> Result<HandlerOutput, JmapError> {
627 let (account_id, mut args) = extract_account_id(args)?;
628 if !backend
629 .account_exists(caller, &account_id)
630 .await
631 .map_err(|e| server_fail_from_backend(&e))?
632 {
633 return Err(JmapError::account_not_found());
634 }
635
636 let i18n = I18nProjection::from_args::<O>(
639 &mut args,
640 using,
641 backend.i18n_info(caller, &account_id).as_ref(),
642 )?;
643 let language = i18n.language();
644
645 let since_query_state: State = match args.get("sinceQueryState").and_then(|v| v.as_str()) {
646 Some(s) => State::from(s),
647 None => return Err(JmapError::invalid_arguments("sinceQueryState is required")),
648 };
649 let since_query_state = crate::unwrap_query_state(&since_query_state, language)?;
650
651 let max_changes = crate::parse_max_changes(args.get("maxChanges"))?;
652
653 let up_to_id: Option<Id> = match args.get("upToId") {
654 None | Some(Value::Null) => None,
655 Some(Value::String(s)) => Some(Id::from(s.as_str())),
656 Some(_) => {
657 return Err(JmapError::invalid_arguments(
658 "upToId must be a string Id or null",
659 ));
660 }
661 };
662
663 let calculate_total: bool = args
664 .get("calculateTotal")
665 .and_then(|v| v.as_bool())
666 .unwrap_or(false);
667
668 let filter: Option<O::Filter> = filter_arg(&mut args)?;
669
670 let sort: Option<Vec<O::Comparator>> = optional_arg(&mut args, "sort", || {
671 JmapError::invalid_arguments("sort must be an array")
672 })?;
673
674 let result = backend
675 .query_changes::<O>(
676 caller,
677 &account_id,
678 QueryChangesParams::new(&since_query_state)
679 .filter(filter.as_ref())
680 .sort(sort.as_deref())
681 .max_changes(max_changes)
682 .up_to_id(up_to_id.as_ref())
683 .language(language),
684 )
685 .await
686 .map_err(JmapError::from)?;
687
688 let added: Vec<Value> = result
689 .added
690 .iter()
691 .map(|item| {
692 json!({
693 "id": item.id.as_ref(),
694 "index": item.index,
695 })
696 })
697 .collect();
698
699 let mut resp = json!({
700 "accountId": account_id.as_ref(),
701 "oldQueryState": crate::localized_query_state(&result.old_query_state, language).as_ref(),
702 "newQueryState": crate::localized_query_state(&result.new_query_state, language).as_ref(),
703 "removed": result.removed,
705 "added": added,
706 });
707 if calculate_total && let Some(t) = result.total {
708 resp["total"] = json!(t);
709 }
710
711 Ok(HandlerOutput::new(resp))
712}
713
714#[cfg(test)]
715mod tests {
716 use super::*;
717 use crate::{JmapAccounts, JmapReads};
718
719 #[test]
730 fn server_fail_from_backend_drops_display_text() {
731 #[derive(Debug)]
732 struct LeakyError(&'static str);
733 impl std::fmt::Display for LeakyError {
734 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
735 f.write_str(self.0)
736 }
737 }
738 impl std::error::Error for LeakyError {}
739
740 const CANARY: &str = "TOKEN-DO-NOT-LEAK-c0ffee";
741 let err = LeakyError(CANARY);
742
743 let jmap_err = server_fail_from_backend(&err);
744
745 let wire = serde_json::to_value(&jmap_err).expect("JmapError must serialize");
750 let wire_str = wire.to_string();
751 assert!(
752 !wire_str.contains(CANARY),
753 "server_fail_from_backend must not echo backend error Display \
754 onto the wire; got {wire_str}"
755 );
756 assert_eq!(
758 wire["description"], SERVER_FAIL_INTERNAL_DESC,
759 "description must be the static 'internal error' string"
760 );
761 assert_eq!(wire["type"], "serverFail");
762 }
763
764 #[test]
770 fn server_fail_from_backend_accepts_generic_display() {
771 let _ = server_fail_from_backend("a string");
774 let _ = server_fail_from_backend(&"&str".to_owned());
775 let _ = server_fail_from_backend(&42_u64);
776 }
777
778 #[test]
789 fn server_fail_value_from_backend_drops_display_text() {
790 #[derive(Debug)]
791 struct LeakyError(&'static str);
792 impl std::fmt::Display for LeakyError {
793 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
794 f.write_str(self.0)
795 }
796 }
797 impl std::error::Error for LeakyError {}
798
799 const CANARY: &str = "TOKEN-DO-NOT-LEAK-d00d";
800 let err = LeakyError(CANARY);
801
802 let wire = server_fail_value_from_backend(&err);
803
804 let wire_str = wire.to_string();
806 assert!(
807 !wire_str.contains(CANARY),
808 "server_fail_value_from_backend must not echo backend error \
809 Display onto the wire; got {wire_str}"
810 );
811 assert_eq!(wire["type"], "serverFail");
813 assert_eq!(
814 wire["description"], SERVER_FAIL_INTERNAL_DESC,
815 "description must be the static 'internal error' string"
816 );
817 }
818
819 #[test]
825 fn server_fail_value_from_backend_accepts_generic_display() {
826 let _ = server_fail_value_from_backend("a string");
829 let _ = server_fail_value_from_backend(&"owned-String".to_owned());
830 let owned: String = "owned".to_string();
831 let _ = server_fail_value_from_backend(&owned);
832 let _ = server_fail_value_from_backend(&42_u64);
833 }
834
835 use crate::backend::{
840 BackendChangesError, BackendQueryError, ChangesResult, QueryChangesParams,
841 QueryChangesResult, QueryParams,
842 };
843
844 #[derive(serde::Serialize, serde::Deserialize)]
846 struct QueryProbe;
847
848 impl JmapObject for QueryProbe {
849 const TYPE_NAME: &'static str = "QueryProbe";
850 type Property = ();
851 }
852
853 impl QueryObject for QueryProbe {
854 type Filter = Value;
855 type Comparator = Value;
856 }
857
858 #[derive(Debug)]
859 struct LeakyQueryError(&'static str);
860
861 impl std::fmt::Display for LeakyQueryError {
862 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
863 f.write_str(self.0)
864 }
865 }
866
867 impl std::error::Error for LeakyQueryError {}
868
869 enum QueryFailure {
871 Method(JmapError),
873 Internal(&'static str),
876 }
877
878 struct QueryFailBackend(QueryFailure);
881
882 impl JmapAccounts for QueryFailBackend {
883 type Error = LeakyQueryError;
884 type CallerCtx = ();
885
886 async fn account_exists(
887 &self,
888 _caller: &(),
889 _account_id: &Id,
890 ) -> Result<bool, Self::Error> {
891 Ok(true)
892 }
893 }
894
895 impl JmapReads for QueryFailBackend {
896 async fn get_objects<O: GetObject + Send + Sync>(
897 &self,
898 _caller: &(),
899 _account_id: &Id,
900 _ids: Option<&[Id]>,
901 _properties: Option<&[String]>,
902 ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
903 unreachable!("only query_objects is exercised")
904 }
905
906 async fn get_state<O: JmapObject + Send + Sync>(
907 &self,
908 _caller: &(),
909 _account_id: &Id,
910 ) -> Result<State, Self::Error> {
911 unreachable!("only query_objects is exercised")
912 }
913
914 async fn get_changes<O: JmapObject + Send + Sync>(
915 &self,
916 _caller: &(),
917 _account_id: &Id,
918 _params: ChangesParams<'_>,
919 ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
920 unreachable!("only query_objects is exercised")
921 }
922
923 async fn query_objects<O: QueryObject + Send + Sync>(
924 &self,
925 _caller: &(),
926 _account_id: &Id,
927 _params: QueryParams<'_, O>,
928 ) -> Result<crate::backend::QueryResult, BackendQueryError<Self::Error>> {
929 Err(match &self.0 {
930 QueryFailure::Method(e) => BackendQueryError::Method(e.clone()),
931 QueryFailure::Internal(text) => BackendQueryError::Other(LeakyQueryError(text)),
932 })
933 }
934
935 async fn query_changes<O: QueryObject + Send + Sync>(
936 &self,
937 _caller: &(),
938 _account_id: &Id,
939 _params: QueryChangesParams<'_, O>,
940 ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
941 unreachable!("only query_objects is exercised")
942 }
943 }
944
945 async fn query_error_wire(failure: QueryFailure) -> Value {
948 let backend = QueryFailBackend(failure);
949 let args = json!({
950 "accountId": "a1",
951 "filter": { "text": "hello" },
952 "anchor": "m1",
953 });
954 let err = match handle_query::<QueryProbe, _>(&backend, &(), args).await {
955 Ok(HandlerOutput { primary: resp, .. }) => {
956 panic!("query_objects failed but handle_query succeeded: {resp}")
957 }
958 Err(e) => e,
959 };
960 serde_json::to_value(&err).expect("JmapError must serialize")
961 }
962
963 #[tokio::test]
976 async fn handle_query_passes_backend_unsupported_filter_through() {
977 let mut expected = JmapError::unsupported_filter();
978 expected.description = Some("Message/query requires a chatId condition".into());
979
980 let wire = query_error_wire(QueryFailure::Method(expected.clone())).await;
981
982 assert_eq!(
983 wire,
984 serde_json::to_value(&expected).expect("JmapError must serialize"),
985 "backend unsupportedFilter must pass through handle_query unchanged"
986 );
987 }
988
989 #[tokio::test]
998 async fn handle_query_passes_backend_anchor_not_found_through() {
999 let expected = JmapError::anchor_not_found();
1000
1001 let wire = query_error_wire(QueryFailure::Method(expected.clone())).await;
1002
1003 assert_eq!(
1004 wire,
1005 serde_json::to_value(&expected).expect("JmapError must serialize"),
1006 "backend anchorNotFound must pass through handle_query unchanged"
1007 );
1008 }
1009
1010 #[tokio::test]
1015 async fn handle_query_redacts_backend_internal_error() {
1016 const CANARY: &str = "TOKEN-DO-NOT-LEAK-query-5ca1ab1e";
1017
1018 let wire = query_error_wire(QueryFailure::Internal(CANARY)).await;
1019
1020 assert_eq!(wire["type"], "serverFail");
1021 assert_eq!(wire["description"], SERVER_FAIL_INTERNAL_DESC);
1022 assert!(
1023 !wire.to_string().contains(CANARY),
1024 "internal backend error Display must not reach the wire; got {wire}"
1025 );
1026 }
1027
1028 #[derive(serde::Serialize, serde::Deserialize)]
1034 struct GetProbe;
1035
1036 impl JmapObject for GetProbe {
1037 const TYPE_NAME: &'static str = "GetProbe";
1038 type Property = ();
1039 }
1040
1041 impl GetObject for GetProbe {}
1042
1043 struct GetProbeBackend;
1046
1047 impl JmapAccounts for GetProbeBackend {
1048 type Error = LeakyQueryError;
1049 type CallerCtx = ();
1050
1051 async fn account_exists(
1052 &self,
1053 _caller: &(),
1054 _account_id: &Id,
1055 ) -> Result<bool, Self::Error> {
1056 Ok(true)
1057 }
1058 }
1059
1060 impl JmapReads for GetProbeBackend {
1061 async fn get_objects<O: GetObject + Send + Sync>(
1062 &self,
1063 _caller: &(),
1064 _account_id: &Id,
1065 ids: Option<&[Id]>,
1066 _properties: Option<&[String]>,
1067 ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
1068 Ok((vec![], ids.map(<[Id]>::to_vec).unwrap_or_default()))
1069 }
1070
1071 async fn get_state<O: JmapObject + Send + Sync>(
1072 &self,
1073 _caller: &(),
1074 _account_id: &Id,
1075 ) -> Result<State, Self::Error> {
1076 Ok(State::from("s0"))
1077 }
1078
1079 async fn get_changes<O: JmapObject + Send + Sync>(
1080 &self,
1081 _caller: &(),
1082 _account_id: &Id,
1083 _params: ChangesParams<'_>,
1084 ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
1085 unreachable!("only /get is exercised")
1086 }
1087
1088 async fn query_objects<O: QueryObject + Send + Sync>(
1089 &self,
1090 _caller: &(),
1091 _account_id: &Id,
1092 _params: QueryParams<'_, O>,
1093 ) -> Result<crate::backend::QueryResult, BackendQueryError<Self::Error>> {
1094 unreachable!("only /get is exercised")
1095 }
1096
1097 async fn query_changes<O: QueryObject + Send + Sync>(
1098 &self,
1099 _caller: &(),
1100 _account_id: &Id,
1101 _params: QueryChangesParams<'_, O>,
1102 ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
1103 unreachable!("only /get is exercised")
1104 }
1105 }
1106
1107 #[tokio::test]
1122 async fn handle_get_over_max_objects_is_request_too_large() {
1123 let ids: Vec<String> = (0..501).map(|i| format!("id{i}")).collect();
1124 let args = json!({ "accountId": "a1", "ids": ids });
1125
1126 match handle_get::<GetProbe, _>(&GetProbeBackend, &(), args).await {
1127 Ok(HandlerOutput { primary: resp, .. }) => panic!(
1128 "501 ids exceed the maxObjectsInGet cap, but handle_get \
1129 returned a response with {} notFound ids instead of \
1130 requestTooLarge",
1131 resp["notFound"].as_array().map_or(0, Vec::len)
1132 ),
1133 Err(e) => assert_eq!(e.error_type.to_string(), "requestTooLarge"),
1134 }
1135 }
1136
1137 #[tokio::test]
1148 async fn handle_get_null_ids_is_not_counted_against_cap() {
1149 let args = json!({ "accountId": "a1", "ids": null });
1150
1151 let HandlerOutput { primary: resp, .. } =
1152 handle_get::<GetProbe, _>(&GetProbeBackend, &(), args)
1153 .await
1154 .expect("null ids must not be rejected by the maxObjectsInGet cap");
1155 assert_eq!(resp["list"], json!([]));
1156 }
1157
1158 struct FullObjectBackend;
1162
1163 impl JmapAccounts for FullObjectBackend {
1164 type Error = LeakyQueryError;
1165 type CallerCtx = ();
1166
1167 async fn account_exists(
1168 &self,
1169 _caller: &(),
1170 _account_id: &Id,
1171 ) -> Result<bool, Self::Error> {
1172 Ok(true)
1173 }
1174 }
1175
1176 impl JmapReads for FullObjectBackend {
1177 async fn get_objects<O: GetObject + Send + Sync>(
1178 &self,
1179 _caller: &(),
1180 _account_id: &Id,
1181 _ids: Option<&[Id]>,
1182 _properties: Option<&[String]>,
1183 ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
1184 let obj = serde_json::from_value(json!({
1185 "id": "o1", "name": "n", "color": "c"
1186 }))
1187 .expect("fixture must deserialize");
1188 Ok((vec![obj], vec![]))
1189 }
1190
1191 async fn get_state<O: JmapObject + Send + Sync>(
1192 &self,
1193 _caller: &(),
1194 _account_id: &Id,
1195 ) -> Result<State, Self::Error> {
1196 Ok(State::from("s0"))
1197 }
1198
1199 async fn get_changes<O: JmapObject + Send + Sync>(
1200 &self,
1201 _caller: &(),
1202 _account_id: &Id,
1203 _params: ChangesParams<'_>,
1204 ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
1205 unreachable!("only /get is exercised")
1206 }
1207
1208 async fn query_objects<O: QueryObject + Send + Sync>(
1209 &self,
1210 _caller: &(),
1211 _account_id: &Id,
1212 _params: QueryParams<'_, O>,
1213 ) -> Result<crate::backend::QueryResult, BackendQueryError<Self::Error>> {
1214 unreachable!("only /get is exercised")
1215 }
1216
1217 async fn query_changes<O: QueryObject + Send + Sync>(
1218 &self,
1219 _caller: &(),
1220 _account_id: &Id,
1221 _params: QueryChangesParams<'_, O>,
1222 ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
1223 unreachable!("only /get is exercised")
1224 }
1225 }
1226
1227 #[derive(serde::Serialize, serde::Deserialize)]
1229 struct Swatch {
1230 id: String,
1231 name: String,
1232 color: String,
1233 }
1234
1235 impl JmapObject for Swatch {
1236 const TYPE_NAME: &'static str = "Swatch";
1237 type Property = ();
1238 }
1239
1240 impl GetObject for Swatch {}
1241
1242 #[tokio::test]
1249 async fn handle_get_returns_only_requested_properties_and_id() {
1250 let args = json!({ "accountId": "a1", "ids": ["o1"], "properties": ["name"] });
1251
1252 let HandlerOutput { primary: resp, .. } =
1253 handle_get::<Swatch, _>(&FullObjectBackend, &(), args)
1254 .await
1255 .expect("valid /get must succeed");
1256 assert_eq!(resp["list"], json!([{ "id": "o1", "name": "n" }]));
1257 }
1258
1259 #[tokio::test]
1262 async fn handle_get_null_properties_returns_all() {
1263 let args = json!({ "accountId": "a1", "ids": ["o1"], "properties": null });
1264
1265 let HandlerOutput { primary: resp, .. } =
1266 handle_get::<Swatch, _>(&FullObjectBackend, &(), args)
1267 .await
1268 .expect("valid /get must succeed");
1269 assert_eq!(
1270 resp["list"],
1271 json!([{ "id": "o1", "name": "n", "color": "c" }])
1272 );
1273 }
1274
1275 #[derive(Default)]
1279 struct RecordingQueryBackend(std::sync::Mutex<Option<Value>>);
1280
1281 impl RecordingQueryBackend {
1282 fn take(&self) -> Value {
1283 self.0
1284 .lock()
1285 .unwrap()
1286 .take()
1287 .expect("backend query method was not called")
1288 }
1289 }
1290
1291 impl JmapAccounts for RecordingQueryBackend {
1292 type Error = LeakyQueryError;
1293 type CallerCtx = ();
1294
1295 async fn account_exists(
1296 &self,
1297 _caller: &(),
1298 _account_id: &Id,
1299 ) -> Result<bool, Self::Error> {
1300 Ok(true)
1301 }
1302 }
1303
1304 impl JmapReads for RecordingQueryBackend {
1305 async fn get_objects<O: GetObject + Send + Sync>(
1306 &self,
1307 _caller: &(),
1308 _account_id: &Id,
1309 _ids: Option<&[Id]>,
1310 _properties: Option<&[String]>,
1311 ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
1312 unreachable!("only queries are exercised")
1313 }
1314
1315 async fn get_state<O: JmapObject + Send + Sync>(
1316 &self,
1317 _caller: &(),
1318 _account_id: &Id,
1319 ) -> Result<State, Self::Error> {
1320 unreachable!("only queries are exercised")
1321 }
1322
1323 async fn get_changes<O: JmapObject + Send + Sync>(
1324 &self,
1325 _caller: &(),
1326 _account_id: &Id,
1327 _params: ChangesParams<'_>,
1328 ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
1329 unreachable!("only queries are exercised")
1330 }
1331
1332 async fn query_objects<O: QueryObject + Send + Sync>(
1333 &self,
1334 _caller: &(),
1335 _account_id: &Id,
1336 params: QueryParams<'_, O>,
1337 ) -> Result<crate::backend::QueryResult, BackendQueryError<Self::Error>> {
1338 *self.0.lock().unwrap() = Some(json!({
1339 "filter": params.filter.map(|f| serde_json::to_value(f).unwrap()),
1340 "sort": params.sort.map(|s| serde_json::to_value(s).unwrap()),
1341 "limit": params.limit,
1342 "position": params.position,
1343 "anchor": params.anchor,
1344 "anchorOffset": params.anchor_offset,
1345 }));
1346 Ok(crate::backend::QueryResult::new(
1347 vec![],
1348 0,
1349 None,
1350 State::from("q0"),
1351 false,
1352 ))
1353 }
1354
1355 async fn query_changes<O: QueryObject + Send + Sync>(
1356 &self,
1357 _caller: &(),
1358 _account_id: &Id,
1359 params: QueryChangesParams<'_, O>,
1360 ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
1361 *self.0.lock().unwrap() = Some(json!({
1362 "sinceQueryState": params.since_query_state,
1363 "filter": params.filter.map(|f| serde_json::to_value(f).unwrap()),
1364 "sort": params.sort.map(|s| serde_json::to_value(s).unwrap()),
1365 "maxChanges": params.max_changes,
1366 "upToId": params.up_to_id,
1367 "collapseThreads": params.collapse_threads,
1368 }));
1369 Ok(QueryChangesResult::new(
1370 params.since_query_state.clone(),
1371 State::from("q2"),
1372 None,
1373 vec![],
1374 vec![],
1375 ))
1376 }
1377 }
1378
1379 #[tokio::test]
1384 async fn handle_query_passes_every_argument_to_backend() {
1385 let backend = RecordingQueryBackend::default();
1386 let args = json!({
1387 "accountId": "a1",
1388 "filter": {"text": "hello"},
1389 "sort": [{"property": "receivedAt", "isAscending": false}],
1390 "position": 3,
1391 "anchor": "m7",
1392 "anchorOffset": -2,
1393 "limit": 25,
1394 });
1395 handle_query::<QueryProbe, _>(&backend, &(), args)
1396 .await
1397 .expect("query must succeed");
1398 assert_eq!(
1399 backend.take(),
1400 json!({
1401 "filter": {"text": "hello"},
1402 "sort": [{"property": "receivedAt", "isAscending": false}],
1403 "limit": 25,
1404 "position": 3,
1405 "anchor": "m7",
1406 "anchorOffset": -2,
1407 })
1408 );
1409 }
1410
1411 #[tokio::test]
1416 async fn handle_query_omitted_arguments_reach_backend_as_rfc_defaults() {
1417 let backend = RecordingQueryBackend::default();
1418 handle_query::<QueryProbe, _>(&backend, &(), json!({"accountId": "a1"}))
1419 .await
1420 .expect("query must succeed");
1421 assert_eq!(
1422 backend.take(),
1423 json!({
1424 "filter": null,
1425 "sort": null,
1426 "limit": null,
1427 "position": 0,
1428 "anchor": null,
1429 "anchorOffset": 0,
1430 })
1431 );
1432 }
1433
1434 #[tokio::test]
1441 async fn handle_query_changes_passes_every_argument_to_backend() {
1442 let backend = RecordingQueryBackend::default();
1443 let args = json!({
1444 "accountId": "a1",
1445 "filter": {"text": "hello"},
1446 "sort": [{"property": "receivedAt"}],
1447 "sinceQueryState": "q1",
1448 "maxChanges": 10,
1449 "upToId": "m9",
1450 });
1451 handle_query_changes::<QueryProbe, _>(&backend, &(), args)
1452 .await
1453 .expect("queryChanges must succeed");
1454 assert_eq!(
1455 backend.take(),
1456 json!({
1457 "sinceQueryState": "q1",
1458 "filter": {"text": "hello"},
1459 "sort": [{"property": "receivedAt"}],
1460 "maxChanges": 10,
1461 "upToId": "m9",
1462 "collapseThreads": false,
1463 })
1464 );
1465 }
1466
1467 #[tokio::test]
1475 async fn non_object_filter_is_invalid_arguments() {
1476 for filter in [json!(42), json!("text"), json!(true), json!([])] {
1477 let backend = RecordingQueryBackend::default();
1478 let err = handle_query::<QueryProbe, _>(
1479 &backend,
1480 &(),
1481 json!({"accountId": "a1", "filter": filter}),
1482 )
1483 .await
1484 .expect_err("non-object filter must be rejected");
1485 assert_eq!(err.error_type.to_string(), "invalidArguments", "{filter}");
1486
1487 let err = handle_query_changes::<QueryProbe, _>(
1488 &backend,
1489 &(),
1490 json!({"accountId": "a1", "filter": filter, "sinceQueryState": "q1"}),
1491 )
1492 .await
1493 .expect_err("non-object filter must be rejected");
1494 assert_eq!(err.error_type.to_string(), "invalidArguments", "{filter}");
1495 assert!(backend.0.lock().unwrap().is_none(), "{filter}");
1496 }
1497 }
1498
1499 #[derive(Clone, Copy)]
1507 enum Canned {
1508 Ok,
1510 CannotCalculate,
1512 TooManyChanges(u64),
1514 Internal(&'static str),
1516 }
1517
1518 impl Canned {
1519 fn changes_error(self) -> BackendChangesError<LeakyQueryError> {
1520 match self {
1521 Canned::Ok => unreachable!("Canned::Ok is not an error"),
1522 Canned::CannotCalculate => BackendChangesError::CannotCalculate,
1523 Canned::TooManyChanges(limit) => BackendChangesError::TooManyChanges { limit },
1524 Canned::Internal(text) => BackendChangesError::Other(LeakyQueryError(text)),
1525 }
1526 }
1527 }
1528
1529 struct CannedBackend {
1533 account_exists: bool,
1534 outcome: Canned,
1535 }
1536
1537 const CANNED_OK: CannedBackend = CannedBackend {
1538 account_exists: true,
1539 outcome: Canned::Ok,
1540 };
1541
1542 impl JmapAccounts for CannedBackend {
1543 type Error = LeakyQueryError;
1544 type CallerCtx = ();
1545
1546 async fn account_exists(
1547 &self,
1548 _caller: &(),
1549 _account_id: &Id,
1550 ) -> Result<bool, Self::Error> {
1551 Ok(self.account_exists)
1552 }
1553 }
1554
1555 impl JmapReads for CannedBackend {
1556 async fn get_objects<O: GetObject + Send + Sync>(
1557 &self,
1558 _caller: &(),
1559 _account_id: &Id,
1560 _ids: Option<&[Id]>,
1561 _properties: Option<&[String]>,
1562 ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
1563 unreachable!("/get is not exercised")
1564 }
1565
1566 async fn get_state<O: JmapObject + Send + Sync>(
1567 &self,
1568 _caller: &(),
1569 _account_id: &Id,
1570 ) -> Result<State, Self::Error> {
1571 unreachable!("/get is not exercised")
1572 }
1573
1574 async fn get_changes<O: JmapObject + Send + Sync>(
1575 &self,
1576 _caller: &(),
1577 _account_id: &Id,
1578 _params: ChangesParams<'_>,
1579 ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
1580 match self.outcome {
1581 Canned::Ok => Ok(ChangesResult::new(
1582 vec![Id::from("c1")],
1583 vec![Id::from("u1")],
1584 vec![Id::from("d1")],
1585 true,
1586 State::from("s2"),
1587 )),
1588 other => Err(other.changes_error()),
1589 }
1590 }
1591
1592 async fn query_objects<O: QueryObject + Send + Sync>(
1593 &self,
1594 _caller: &(),
1595 _account_id: &Id,
1596 _params: QueryParams<'_, O>,
1597 ) -> Result<crate::backend::QueryResult, BackendQueryError<Self::Error>> {
1598 Ok(crate::backend::QueryResult::new(
1599 vec![Id::from("m1")],
1600 0,
1601 Some(7),
1602 State::from("q1"),
1603 true,
1604 ))
1605 }
1606
1607 async fn query_changes<O: QueryObject + Send + Sync>(
1608 &self,
1609 _caller: &(),
1610 _account_id: &Id,
1611 params: QueryChangesParams<'_, O>,
1612 ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
1613 match self.outcome {
1614 Canned::Ok => Ok(QueryChangesResult::new(
1615 params.since_query_state.clone(),
1616 State::from("q2"),
1617 Some(7),
1618 vec![Id::from("r1")],
1619 vec![crate::backend::AddedItem::new(Id::from("n1"), 0)],
1620 )),
1621 other => Err(other.changes_error()),
1622 }
1623 }
1624 }
1625
1626 #[tokio::test]
1633 async fn handle_changes_response_matches_rfc_shape() {
1634 let HandlerOutput { primary: resp, .. } = handle_changes::<QueryProbe, _>(
1635 &CANNED_OK,
1636 &(),
1637 json!({"accountId": "a1", "sinceState": "s1"}),
1638 &[],
1639 )
1640 .await
1641 .expect("/changes must succeed");
1642 assert_eq!(
1643 resp,
1644 json!({
1645 "accountId": "a1",
1646 "oldState": "s1",
1647 "newState": "s2",
1648 "hasMoreChanges": true,
1649 "updatedProperties": null,
1650 "created": ["c1"],
1651 "updated": ["u1"],
1652 "destroyed": ["d1"],
1653 })
1654 );
1655 }
1656
1657 const CORE: &str = "urn:ietf:params:jmap:core";
1662 const METADATA: &str = "urn:ietf:params:jmap:metadata";
1663
1664 struct MetadataChangesBackend {
1668 updated: Vec<Id>,
1669 updated_properties: Option<Vec<String>>,
1670 seen_ignore: std::sync::Mutex<Option<bool>>,
1671 }
1672
1673 impl MetadataChangesBackend {
1674 fn new(updated: &[&str], updated_properties: Option<&[&str]>) -> Self {
1675 Self {
1676 updated: updated.iter().map(|u| Id::from(*u)).collect(),
1677 updated_properties: updated_properties
1678 .map(|p| p.iter().map(|s| (*s).to_owned()).collect()),
1679 seen_ignore: std::sync::Mutex::new(None),
1680 }
1681 }
1682 }
1683
1684 impl JmapAccounts for MetadataChangesBackend {
1685 type Error = LeakyQueryError;
1686 type CallerCtx = ();
1687
1688 async fn account_exists(
1689 &self,
1690 _caller: &(),
1691 _account_id: &Id,
1692 ) -> Result<bool, Self::Error> {
1693 Ok(true)
1694 }
1695 }
1696
1697 impl JmapReads for MetadataChangesBackend {
1698 async fn get_objects<O: GetObject + Send + Sync>(
1699 &self,
1700 _caller: &(),
1701 _account_id: &Id,
1702 _ids: Option<&[Id]>,
1703 _properties: Option<&[String]>,
1704 ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
1705 unreachable!("only get_changes is exercised")
1706 }
1707
1708 async fn get_state<O: JmapObject + Send + Sync>(
1709 &self,
1710 _caller: &(),
1711 _account_id: &Id,
1712 ) -> Result<State, Self::Error> {
1713 unreachable!("only get_changes is exercised")
1714 }
1715
1716 async fn get_changes<O: JmapObject + Send + Sync>(
1717 &self,
1718 _caller: &(),
1719 _account_id: &Id,
1720 params: ChangesParams<'_>,
1721 ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
1722 *self.seen_ignore.lock().unwrap() = Some(params.ignore_metadata_only_changes);
1723 Ok(ChangesResult::new(
1724 Vec::new(),
1725 self.updated.clone(),
1726 Vec::new(),
1727 false,
1728 State::from("s2"),
1729 )
1730 .with_updated_properties(self.updated_properties.clone()))
1731 }
1732
1733 async fn query_objects<O: QueryObject + Send + Sync>(
1734 &self,
1735 _caller: &(),
1736 _account_id: &Id,
1737 _params: QueryParams<'_, O>,
1738 ) -> Result<crate::backend::QueryResult, BackendQueryError<Self::Error>> {
1739 unreachable!("only get_changes is exercised")
1740 }
1741
1742 async fn query_changes<O: QueryObject + Send + Sync>(
1743 &self,
1744 _caller: &(),
1745 _account_id: &Id,
1746 _params: QueryChangesParams<'_, O>,
1747 ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
1748 unreachable!("only get_changes is exercised")
1749 }
1750 }
1751
1752 async fn ignore_seen(using: &[&str], extra: Value) -> bool {
1755 let backend = MetadataChangesBackend::new(&["u1"], None);
1756 let mut args = json!({"accountId": "a1", "sinceState": "s1"});
1757 if let Value::Object(extra) = extra {
1758 args.as_object_mut().unwrap().extend(extra);
1759 }
1760 let using: Vec<String> = using.iter().map(|u| (*u).to_owned()).collect();
1761 handle_changes::<QueryProbe, _>(&backend, &(), args, &using)
1762 .await
1763 .expect("/changes must succeed");
1764 backend
1765 .seen_ignore
1766 .lock()
1767 .unwrap()
1768 .expect("backend must be called")
1769 }
1770
1771 #[tokio::test]
1778 async fn changes_without_metadata_capability_ignores_metadata_only_changes() {
1779 assert!(ignore_seen(&[CORE], json!({})).await);
1780 assert!(ignore_seen(&[CORE], json!({"ignoreMetadataOnlyChanges": false})).await);
1781 assert!(ignore_seen(&[CORE], json!({"ignoreMetadataOnlyChanges": "no"})).await);
1782 assert!(ignore_seen(&[], json!({})).await);
1783 }
1784
1785 #[tokio::test]
1788 async fn changes_with_metadata_capability_passes_ignore_argument() {
1789 assert!(!ignore_seen(&[CORE, METADATA], json!({})).await);
1790 assert!(
1791 !ignore_seen(
1792 &[CORE, METADATA],
1793 json!({"ignoreMetadataOnlyChanges": null})
1794 )
1795 .await
1796 );
1797 assert!(
1798 !ignore_seen(
1799 &[CORE, METADATA],
1800 json!({"ignoreMetadataOnlyChanges": false})
1801 )
1802 .await
1803 );
1804 assert!(
1805 ignore_seen(
1806 &[CORE, METADATA],
1807 json!({"ignoreMetadataOnlyChanges": true})
1808 )
1809 .await
1810 );
1811 }
1812
1813 #[tokio::test]
1817 async fn changes_rejects_non_boolean_ignore_argument() {
1818 let backend = MetadataChangesBackend::new(&["u1"], None);
1819 let err = handle_changes::<QueryProbe, _>(
1820 &backend,
1821 &(),
1822 json!({"accountId": "a1", "sinceState": "s1", "ignoreMetadataOnlyChanges": "yes"}),
1823 &[CORE.to_owned(), METADATA.to_owned()],
1824 )
1825 .await
1826 .expect_err("a string ignoreMetadataOnlyChanges must fail");
1827 assert_eq!(err.error_type.to_string(), "invalidArguments");
1828 assert!(
1829 backend.seen_ignore.lock().unwrap().is_none(),
1830 "backend must not be called"
1831 );
1832 }
1833
1834 #[tokio::test]
1841 async fn changes_reports_backend_updated_properties() {
1842 let backend = MetadataChangesBackend::new(&["u1"], Some(&["metadata"]));
1843 let HandlerOutput { primary: resp, .. } = handle_changes::<QueryProbe, _>(
1844 &backend,
1845 &(),
1846 json!({"accountId": "a1", "sinceState": "s1"}),
1847 &[CORE.to_owned(), METADATA.to_owned()],
1848 )
1849 .await
1850 .expect("/changes must succeed");
1851 assert_eq!(
1852 resp,
1853 json!({
1854 "accountId": "a1",
1855 "oldState": "s1",
1856 "newState": "s2",
1857 "hasMoreChanges": false,
1858 "updatedProperties": ["metadata"],
1859 "created": [],
1860 "updated": ["u1"],
1861 "destroyed": [],
1862 })
1863 );
1864 }
1865
1866 #[tokio::test]
1869 async fn changes_updated_properties_null_when_updated_empty() {
1870 let backend = MetadataChangesBackend::new(&[], Some(&["metadata"]));
1871 let HandlerOutput { primary: resp, .. } = handle_changes::<QueryProbe, _>(
1872 &backend,
1873 &(),
1874 json!({"accountId": "a1", "sinceState": "s1"}),
1875 &[CORE.to_owned(), METADATA.to_owned()],
1876 )
1877 .await
1878 .expect("/changes must succeed");
1879 assert_eq!(resp["updatedProperties"], Value::Null);
1880 assert!(
1881 resp.as_object().unwrap().contains_key("updatedProperties"),
1882 "updatedProperties must be present"
1883 );
1884 }
1885
1886 #[tokio::test]
1892 async fn handle_query_changes_response_matches_rfc_shape() {
1893 let HandlerOutput { primary: resp, .. } = handle_query_changes::<QueryProbe, _>(
1894 &CANNED_OK,
1895 &(),
1896 json!({"accountId": "a1", "sinceQueryState": "q1", "calculateTotal": true}),
1897 )
1898 .await
1899 .expect("/queryChanges must succeed");
1900 assert_eq!(
1901 resp,
1902 json!({
1903 "accountId": "a1",
1904 "oldQueryState": "q1",
1905 "newQueryState": "q2",
1906 "total": 7,
1907 "removed": ["r1"],
1908 "added": [{"id": "n1", "index": 0}],
1909 })
1910 );
1911
1912 let HandlerOutput { primary: resp, .. } = handle_query_changes::<QueryProbe, _>(
1913 &CANNED_OK,
1914 &(),
1915 json!({"accountId": "a1", "sinceQueryState": "q1"}),
1916 )
1917 .await
1918 .expect("/queryChanges must succeed");
1919 assert!(
1920 resp.get("total").is_none(),
1921 "total must be omitted without calculateTotal; got {resp}"
1922 );
1923 }
1924
1925 #[tokio::test]
1929 async fn handle_query_total_only_when_requested() {
1930 for (calculate_total, expected) in [(json!(true), Some(json!(7))), (json!(false), None)] {
1931 let HandlerOutput { primary: resp, .. } = handle_query::<QueryProbe, _>(
1932 &CANNED_OK,
1933 &(),
1934 json!({"accountId": "a1", "calculateTotal": calculate_total}),
1935 )
1936 .await
1937 .expect("/query must succeed");
1938 assert_eq!(resp.get("total").cloned(), expected, "{resp}");
1939 }
1940 }
1941
1942 #[tokio::test]
1947 async fn missing_or_non_string_since_state_is_invalid_arguments() {
1948 for since in [None, Some(json!(42))] {
1949 let mut args = json!({"accountId": "a1"});
1950 if let Some(v) = &since {
1951 args["sinceState"] = v.clone();
1952 }
1953 let err = handle_changes::<QueryProbe, _>(&CANNED_OK, &(), args, &[])
1954 .await
1955 .expect_err("/changes without a string sinceState must fail");
1956 assert_eq!(err.error_type.to_string(), "invalidArguments", "{since:?}");
1957
1958 let mut args = json!({"accountId": "a1"});
1959 if let Some(v) = &since {
1960 args["sinceQueryState"] = v.clone();
1961 }
1962 let err = handle_query_changes::<QueryProbe, _>(&CANNED_OK, &(), args)
1963 .await
1964 .expect_err("/queryChanges without a string sinceQueryState must fail");
1965 assert_eq!(err.error_type.to_string(), "invalidArguments", "{since:?}");
1966 }
1967 }
1968
1969 #[tokio::test]
1972 async fn non_string_up_to_id_is_invalid_arguments() {
1973 for up_to_id in [json!(5), json!(true), json!(["m1"]), json!({})] {
1974 let err = handle_query_changes::<QueryProbe, _>(
1975 &CANNED_OK,
1976 &(),
1977 json!({"accountId": "a1", "sinceQueryState": "q1", "upToId": up_to_id}),
1978 )
1979 .await
1980 .expect_err("non-Id upToId must be rejected");
1981 assert_eq!(err.error_type.to_string(), "invalidArguments", "{up_to_id}");
1982 }
1983 }
1984
1985 #[tokio::test]
1989 async fn handle_query_negative_limit_is_invalid_arguments() {
1990 let backend = RecordingQueryBackend::default();
1991 let err =
1992 handle_query::<QueryProbe, _>(&backend, &(), json!({"accountId": "a1", "limit": -1}))
1993 .await
1994 .expect_err("negative limit must be rejected");
1995 assert_eq!(err.error_type.to_string(), "invalidArguments");
1996 assert!(
1997 backend.0.lock().unwrap().is_none(),
1998 "backend must not be consulted"
1999 );
2000 }
2001
2002 #[tokio::test]
2008 async fn handle_query_negative_position_reaches_backend() {
2009 let backend = RecordingQueryBackend::default();
2010 handle_query::<QueryProbe, _>(&backend, &(), json!({"accountId": "a1", "position": -5}))
2011 .await
2012 .expect("negative position is valid");
2013 assert_eq!(backend.take()["position"], json!(-5));
2014 }
2015
2016 #[tokio::test]
2025 async fn changes_backend_errors_map_to_rfc_errors() {
2026 const CANARY: &str = "TOKEN-DO-NOT-LEAK-changes-b0a710ad";
2027 for (outcome, changes_type, query_changes_type) in [
2028 (
2029 Canned::CannotCalculate,
2030 "cannotCalculateChanges",
2031 "cannotCalculateChanges",
2032 ),
2033 (
2034 Canned::TooManyChanges(10),
2035 "cannotCalculateChanges",
2036 "tooManyChanges",
2037 ),
2038 (Canned::Internal(CANARY), "serverFail", "serverFail"),
2039 ] {
2040 let backend = CannedBackend {
2041 account_exists: true,
2042 outcome,
2043 };
2044 let changes = handle_changes::<QueryProbe, _>(
2045 &backend,
2046 &(),
2047 json!({"accountId": "a1", "sinceState": "s1"}),
2048 &[],
2049 )
2050 .await;
2051 let query_changes = handle_query_changes::<QueryProbe, _>(
2052 &backend,
2053 &(),
2054 json!({"accountId": "a1", "sinceQueryState": "q1"}),
2055 )
2056 .await;
2057 for (result, expected_type) in
2058 [(changes, changes_type), (query_changes, query_changes_type)]
2059 {
2060 let err = result.expect_err("backend error must fail the call");
2061 let wire = serde_json::to_value(&err).expect("JmapError must serialize");
2062 assert_eq!(wire["type"], expected_type, "{wire}");
2063 assert!(!wire.to_string().contains(CANARY), "leaked: {wire}");
2064 }
2065 }
2066 }
2067
2068 #[tokio::test]
2071 async fn unknown_account_is_account_not_found() {
2072 let backend = CannedBackend {
2073 account_exists: false,
2074 outcome: Canned::Ok,
2075 };
2076 let results = [
2077 handle_changes::<QueryProbe, _>(
2078 &backend,
2079 &(),
2080 json!({"accountId": "nope", "sinceState": "s1"}),
2081 &[],
2082 )
2083 .await,
2084 handle_query::<QueryProbe, _>(&backend, &(), json!({"accountId": "nope"})).await,
2085 handle_query_changes::<QueryProbe, _>(
2086 &backend,
2087 &(),
2088 json!({"accountId": "nope", "sinceQueryState": "q1"}),
2089 )
2090 .await,
2091 ];
2092 for result in results {
2093 let err = result.expect_err("unknown account must fail");
2094 assert_eq!(err.error_type.to_string(), "accountNotFound");
2095 }
2096 }
2097
2098 #[tokio::test]
2103 async fn handle_query_does_not_echo_wrongly_typed_value() {
2104 for name in ["limit", "position"] {
2105 let backend = RecordingQueryBackend::default();
2106 let mut args = json!({ "accountId": "a1" });
2107 args[name] = json!({ "note": "CANARY-zegc" });
2108 let err = handle_query::<QueryProbe, _>(&backend, &(), args)
2109 .await
2110 .expect_err("wrongly typed argument must be rejected");
2111 assert_eq!(err.error_type.to_string(), "invalidArguments", "{name}");
2112 let desc = err.description.as_deref().unwrap_or_default();
2113 assert!(desc.starts_with(name), "{desc}");
2114 assert!(desc.contains("got object"), "{desc}");
2115 assert!(!desc.contains("CANARY"), "{desc}");
2116 }
2117 }
2118}