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>(
190 backend: &B,
191 caller: &B::CallerCtx,
192 args: Value,
193) -> Result<HandlerOutput, JmapError> {
194 get_impl::<O, B>(backend, caller, args, &[]).await
195}
196
197async fn get_impl<O: GetObject, B: JmapBackend>(
203 backend: &B,
204 caller: &B::CallerCtx,
205 args: Value,
206 using: &[String],
207) -> Result<HandlerOutput, JmapError> {
208 let (account_id, mut args) = extract_account_id(args)?;
209 if !backend
210 .account_exists(caller, &account_id)
211 .await
212 .map_err(|e| server_fail_from_backend(&e))?
213 {
214 return Err(JmapError::account_not_found());
215 }
216 enforce_max_objects_in_get(&args, backend.max_objects_in_get(caller, &account_id))?;
217
218 let i18n = I18nProjection::from_args::<O>(
219 &mut args,
220 using,
221 backend.i18n_info(caller, &account_id).as_ref(),
222 )?;
223
224 let ids: Option<Vec<Id>> = optional_arg(&mut args, "ids", || {
225 JmapError::invalid_arguments("ids must be an Id array")
226 })?;
227
228 let properties: Option<Vec<String>> = optional_arg(&mut args, "properties", || {
229 JmapError::invalid_arguments("properties must be a string array")
230 })?;
231 let backend_properties = i18n.backend_properties(properties.as_deref());
232
233 let ids_slice = ids.as_deref();
234 let (list, not_found) = backend
235 .get_objects::<O>(
236 caller,
237 &account_id,
238 ids_slice,
239 backend_properties.as_deref(),
240 )
241 .await
242 .map_err(|e| server_fail_from_backend(&e))?;
243
244 let state = backend
245 .get_state::<O>(caller, &account_id)
246 .await
247 .map_err(|e| server_fail_from_backend(&e))?;
248
249 let mut list_json = serialize_value(&list)?;
256
257 if let Value::Array(items) = &mut list_json {
258 for item in items {
259 if let Value::Object(map) = item {
260 i18n.apply(map);
263 if let Some(props) = &properties {
271 map.retain(|k, _| k == "id" || props.iter().any(|p| p == k));
272 }
273 }
274 }
275 }
276
277 Ok(HandlerOutput::new(json!({
278 "accountId": account_id.as_ref(),
279 "state": state.as_ref(),
280 "list": list_json,
281 "notFound": not_found_json(¬_found),
282 })))
283}
284
285pub async fn handle_get_with_metadata<O: GetObject, B: JmapBackend>(
315 backend: &B,
316 caller: &B::CallerCtx,
317 mut args: Value,
318 using: &[String],
319) -> Result<HandlerOutput, JmapError> {
320 let info = args
321 .get("accountId")
322 .and_then(Value::as_str)
323 .and_then(|s| Id::new_validated(s).ok())
324 .and_then(|id| backend.metadata_info::<O>(caller, &id));
325 let Some(info) = info else {
326 return get_impl::<O, B>(backend, caller, args, using).await;
327 };
328 let properties: Option<Vec<String>> = match args.get("properties") {
329 None | Some(Value::Null) => None,
330 Some(v) => match serde_json::from_value(v.clone()) {
331 Ok(props) => Some(props),
332 Err(_) => return get_impl::<O, B>(backend, caller, args, using).await,
334 },
335 };
336 let projection = MetadataProjection::new(properties.as_deref(), true, using, Some(&info))?;
337 if let Some(props) = properties {
338 let mut roots: Vec<String> = Vec::with_capacity(props.len());
339 for p in props {
340 let root = match p.split_once('/') {
341 Some((r @ ("metadata" | "privateMetadata"), _)) => r.to_owned(),
342 _ => p,
343 };
344 if !roots.contains(&root) {
345 roots.push(root);
346 }
347 }
348 args["properties"] = json!(roots);
349 }
350 let mut out = get_impl::<O, B>(backend, caller, args, using).await?;
351 if let Some(Value::Array(list)) = out.primary.get_mut("list") {
352 for item in list {
353 let source = item.clone();
354 projection.apply(&source, item);
355 }
356 }
357 Ok(out)
358}
359
360pub async fn handle_changes<O: JmapObject, B: JmapBackend>(
398 backend: &B,
399 caller: &B::CallerCtx,
400 args: Value,
401 using: &[String],
402) -> Result<HandlerOutput, JmapError> {
403 let (account_id, args) = extract_account_id(args)?;
404 if !backend
405 .account_exists(caller, &account_id)
406 .await
407 .map_err(|e| server_fail_from_backend(&e))?
408 {
409 return Err(JmapError::account_not_found());
410 }
411
412 let since_state: State = match args.get("sinceState").and_then(|v| v.as_str()) {
413 Some(s) => State::from(s),
414 None => return Err(JmapError::invalid_arguments("sinceState is required")),
415 };
416
417 let max_changes = crate::parse_max_changes(args.get("maxChanges"))?;
418
419 let uses_metadata = using
420 .iter()
421 .any(|u| u == jmap_metadata_types::JMAP_METADATA_URI);
422 let ignore_metadata_only_changes = !uses_metadata
423 || match args.get("ignoreMetadataOnlyChanges") {
424 None | Some(Value::Null) => false,
425 Some(Value::Bool(b)) => *b,
426 Some(v) => {
427 return Err(JmapError::invalid_arguments(format!(
428 "ignoreMetadataOnlyChanges: expected a boolean, got {}",
429 crate::helpers::json_type_name(v)
430 )));
431 }
432 };
433
434 let result = backend
435 .get_changes::<O>(
436 caller,
437 &account_id,
438 ChangesParams::new(&since_state)
439 .max_changes(max_changes)
440 .ignore_metadata_only_changes(ignore_metadata_only_changes),
441 )
442 .await
443 .map_err(changes_error_from_backend)?;
444 let updated_properties = if result.updated.is_empty() {
445 None
446 } else {
447 result.updated_properties
448 };
449
450 Ok(HandlerOutput::new(json!({
451 "accountId": account_id.as_ref(),
452 "oldState": since_state.as_ref(),
453 "newState": result.new_state.as_ref(),
454 "hasMoreChanges": result.has_more_changes,
455 "updatedProperties": updated_properties,
456 "created": result.created,
459 "updated": result.updated,
460 "destroyed": result.destroyed,
461 })))
462}
463
464pub async fn handle_query<O: QueryObject, B: JmapBackend>(
500 backend: &B,
501 caller: &B::CallerCtx,
502 args: Value,
503) -> Result<HandlerOutput, JmapError> {
504 query_impl::<O, B>(backend, caller, args, &[]).await
505}
506
507pub async fn handle_query_with_i18n<O: QueryObject, B: JmapBackend>(
522 backend: &B,
523 caller: &B::CallerCtx,
524 args: Value,
525 using: &[String],
526) -> Result<HandlerOutput, JmapError> {
527 query_impl::<O, B>(backend, caller, args, using).await
528}
529
530async fn query_impl<O: QueryObject, B: JmapBackend>(
532 backend: &B,
533 caller: &B::CallerCtx,
534 args: Value,
535 using: &[String],
536) -> Result<HandlerOutput, JmapError> {
537 let (account_id, mut args) = extract_account_id(args)?;
538 if !backend
539 .account_exists(caller, &account_id)
540 .await
541 .map_err(|e| server_fail_from_backend(&e))?
542 {
543 return Err(JmapError::account_not_found());
544 }
545
546 let i18n = I18nProjection::from_args::<O>(
549 &mut args,
550 using,
551 backend.i18n_info(caller, &account_id).as_ref(),
552 )?;
553 let language = i18n.language();
554
555 let calculate_total: bool = args
556 .get("calculateTotal")
557 .and_then(|v| v.as_bool())
558 .unwrap_or(false);
559
560 let limit: Option<u64> = match args.get("limit") {
561 None | Some(Value::Null) => None,
562 Some(v) => match v.as_u64() {
563 Some(n) => Some(n),
564 None => {
565 return Err(JmapError::invalid_arguments(format!(
566 "limit: expected a non-negative integer, got {}",
567 crate::helpers::json_type_name(v)
568 )));
569 }
570 },
571 };
572
573 let position: i64 = match args.get("position") {
574 None | Some(Value::Null) => 0,
575 Some(v) => v.as_i64().ok_or_else(|| {
576 JmapError::invalid_arguments(format!(
577 "position: expected an integer, got {}",
578 crate::helpers::json_type_name(v)
579 ))
580 })?,
581 };
582
583 let (anchor, anchor_offset) = query_anchor_args(&args)?;
584
585 let filter: Option<O::Filter> = filter_arg(&mut args)?;
586
587 let sort: Option<Vec<O::Comparator>> = optional_arg(&mut args, "sort", || {
588 JmapError::invalid_arguments("sort must be an array")
589 })?;
590
591 let result = backend
592 .query_objects::<O>(
593 caller,
594 &account_id,
595 QueryParams::new()
596 .filter(filter.as_ref())
597 .sort(sort.as_deref())
598 .limit(limit)
599 .position(position)
600 .anchor(anchor.as_ref())
601 .anchor_offset(anchor_offset)
602 .language(language),
603 )
604 .await
605 .map_err(JmapError::from)?;
606
607 let mut resp = json!({
608 "accountId": account_id.as_ref(),
609 "queryState": crate::localized_query_state(&result.query_state, language).as_ref(),
610 "canCalculateChanges": result.can_calculate_changes,
611 "position": result.position,
612 "ids": result.ids,
615 });
616 if calculate_total && let Some(t) = result.total {
617 resp["total"] = json!(t);
618 }
619
620 Ok(HandlerOutput::new(resp))
621}
622
623pub async fn handle_query_changes<O: QueryObject, B: JmapBackend>(
657 backend: &B,
658 caller: &B::CallerCtx,
659 args: Value,
660) -> Result<HandlerOutput, JmapError> {
661 query_changes_impl::<O, B>(backend, caller, args, &[]).await
662}
663
664pub async fn handle_query_changes_with_i18n<O: QueryObject, B: JmapBackend>(
677 backend: &B,
678 caller: &B::CallerCtx,
679 args: Value,
680 using: &[String],
681) -> Result<HandlerOutput, JmapError> {
682 query_changes_impl::<O, B>(backend, caller, args, using).await
683}
684
685async fn query_changes_impl<O: QueryObject, B: JmapBackend>(
688 backend: &B,
689 caller: &B::CallerCtx,
690 args: Value,
691 using: &[String],
692) -> Result<HandlerOutput, JmapError> {
693 let (account_id, mut args) = extract_account_id(args)?;
694 if !backend
695 .account_exists(caller, &account_id)
696 .await
697 .map_err(|e| server_fail_from_backend(&e))?
698 {
699 return Err(JmapError::account_not_found());
700 }
701
702 let i18n = I18nProjection::from_args::<O>(
705 &mut args,
706 using,
707 backend.i18n_info(caller, &account_id).as_ref(),
708 )?;
709 let language = i18n.language();
710
711 let since_query_state: State = match args.get("sinceQueryState").and_then(|v| v.as_str()) {
712 Some(s) => State::from(s),
713 None => return Err(JmapError::invalid_arguments("sinceQueryState is required")),
714 };
715 let since_query_state = crate::unwrap_query_state(&since_query_state, language)?;
716
717 let max_changes = crate::parse_max_changes(args.get("maxChanges"))?;
718
719 let up_to_id: Option<Id> = match args.get("upToId") {
720 None | Some(Value::Null) => None,
721 Some(Value::String(s)) => Some(Id::from(s.as_str())),
722 Some(_) => {
723 return Err(JmapError::invalid_arguments(
724 "upToId must be a string Id or null",
725 ));
726 }
727 };
728
729 let calculate_total: bool = args
730 .get("calculateTotal")
731 .and_then(|v| v.as_bool())
732 .unwrap_or(false);
733
734 let filter: Option<O::Filter> = filter_arg(&mut args)?;
735
736 let sort: Option<Vec<O::Comparator>> = optional_arg(&mut args, "sort", || {
737 JmapError::invalid_arguments("sort must be an array")
738 })?;
739
740 let result = backend
741 .query_changes::<O>(
742 caller,
743 &account_id,
744 QueryChangesParams::new(&since_query_state)
745 .filter(filter.as_ref())
746 .sort(sort.as_deref())
747 .max_changes(max_changes)
748 .up_to_id(up_to_id.as_ref())
749 .language(language),
750 )
751 .await
752 .map_err(JmapError::from)?;
753
754 let added: Vec<Value> = result
755 .added
756 .iter()
757 .map(|item| {
758 json!({
759 "id": item.id.as_ref(),
760 "index": item.index,
761 })
762 })
763 .collect();
764
765 let mut resp = json!({
766 "accountId": account_id.as_ref(),
767 "oldQueryState": crate::localized_query_state(&result.old_query_state, language).as_ref(),
768 "newQueryState": crate::localized_query_state(&result.new_query_state, language).as_ref(),
769 "removed": result.removed,
771 "added": added,
772 });
773 if calculate_total && let Some(t) = result.total {
774 resp["total"] = json!(t);
775 }
776
777 Ok(HandlerOutput::new(resp))
778}
779
780#[cfg(test)]
781mod tests {
782 use super::*;
783 use crate::{JmapAccounts, JmapReads};
784
785 #[test]
796 fn server_fail_from_backend_drops_display_text() {
797 #[derive(Debug)]
798 struct LeakyError(&'static str);
799 impl std::fmt::Display for LeakyError {
800 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
801 f.write_str(self.0)
802 }
803 }
804 impl std::error::Error for LeakyError {}
805
806 const CANARY: &str = "TOKEN-DO-NOT-LEAK-c0ffee";
807 let err = LeakyError(CANARY);
808
809 let jmap_err = server_fail_from_backend(&err);
810
811 let wire = serde_json::to_value(&jmap_err).expect("JmapError must serialize");
816 let wire_str = wire.to_string();
817 assert!(
818 !wire_str.contains(CANARY),
819 "server_fail_from_backend must not echo backend error Display \
820 onto the wire; got {wire_str}"
821 );
822 assert_eq!(
824 wire["description"], SERVER_FAIL_INTERNAL_DESC,
825 "description must be the static 'internal error' string"
826 );
827 assert_eq!(wire["type"], "serverFail");
828 }
829
830 #[test]
836 fn server_fail_from_backend_accepts_generic_display() {
837 let _ = server_fail_from_backend("a string");
840 let _ = server_fail_from_backend(&"&str".to_owned());
841 let _ = server_fail_from_backend(&42_u64);
842 }
843
844 #[test]
855 fn server_fail_value_from_backend_drops_display_text() {
856 #[derive(Debug)]
857 struct LeakyError(&'static str);
858 impl std::fmt::Display for LeakyError {
859 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
860 f.write_str(self.0)
861 }
862 }
863 impl std::error::Error for LeakyError {}
864
865 const CANARY: &str = "TOKEN-DO-NOT-LEAK-d00d";
866 let err = LeakyError(CANARY);
867
868 let wire = server_fail_value_from_backend(&err);
869
870 let wire_str = wire.to_string();
872 assert!(
873 !wire_str.contains(CANARY),
874 "server_fail_value_from_backend must not echo backend error \
875 Display onto the wire; got {wire_str}"
876 );
877 assert_eq!(wire["type"], "serverFail");
879 assert_eq!(
880 wire["description"], SERVER_FAIL_INTERNAL_DESC,
881 "description must be the static 'internal error' string"
882 );
883 }
884
885 #[test]
891 fn server_fail_value_from_backend_accepts_generic_display() {
892 let _ = server_fail_value_from_backend("a string");
895 let _ = server_fail_value_from_backend(&"owned-String".to_owned());
896 let owned: String = "owned".to_string();
897 let _ = server_fail_value_from_backend(&owned);
898 let _ = server_fail_value_from_backend(&42_u64);
899 }
900
901 use crate::backend::{
906 BackendChangesError, BackendQueryError, ChangesResult, QueryChangesParams,
907 QueryChangesResult, QueryParams,
908 };
909
910 #[derive(serde::Serialize, serde::Deserialize)]
912 struct QueryProbe;
913
914 impl JmapObject for QueryProbe {
915 const TYPE_NAME: &'static str = "QueryProbe";
916 type Property = ();
917 }
918
919 impl QueryObject for QueryProbe {
920 type Filter = Value;
921 type Comparator = Value;
922 }
923
924 #[derive(Debug)]
925 struct LeakyQueryError(&'static str);
926
927 impl std::fmt::Display for LeakyQueryError {
928 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
929 f.write_str(self.0)
930 }
931 }
932
933 impl std::error::Error for LeakyQueryError {}
934
935 enum QueryFailure {
937 Method(JmapError),
939 Internal(&'static str),
942 }
943
944 struct QueryFailBackend(QueryFailure);
947
948 impl JmapAccounts for QueryFailBackend {
949 type Error = LeakyQueryError;
950 type CallerCtx = ();
951
952 async fn account_exists(
953 &self,
954 _caller: &(),
955 _account_id: &Id,
956 ) -> Result<bool, Self::Error> {
957 Ok(true)
958 }
959 }
960
961 impl JmapReads for QueryFailBackend {
962 async fn get_objects<O: GetObject + Send + Sync>(
963 &self,
964 _caller: &(),
965 _account_id: &Id,
966 _ids: Option<&[Id]>,
967 _properties: Option<&[String]>,
968 ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
969 unreachable!("only query_objects is exercised")
970 }
971
972 async fn get_state<O: JmapObject + Send + Sync>(
973 &self,
974 _caller: &(),
975 _account_id: &Id,
976 ) -> Result<State, Self::Error> {
977 unreachable!("only query_objects is exercised")
978 }
979
980 async fn get_changes<O: JmapObject + Send + Sync>(
981 &self,
982 _caller: &(),
983 _account_id: &Id,
984 _params: ChangesParams<'_>,
985 ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
986 unreachable!("only query_objects is exercised")
987 }
988
989 async fn query_objects<O: QueryObject + Send + Sync>(
990 &self,
991 _caller: &(),
992 _account_id: &Id,
993 _params: QueryParams<'_, O>,
994 ) -> Result<crate::backend::QueryResult, BackendQueryError<Self::Error>> {
995 Err(match &self.0 {
996 QueryFailure::Method(e) => BackendQueryError::Method(e.clone()),
997 QueryFailure::Internal(text) => BackendQueryError::Other(LeakyQueryError(text)),
998 })
999 }
1000
1001 async fn query_changes<O: QueryObject + Send + Sync>(
1002 &self,
1003 _caller: &(),
1004 _account_id: &Id,
1005 _params: QueryChangesParams<'_, O>,
1006 ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
1007 unreachable!("only query_objects is exercised")
1008 }
1009 }
1010
1011 async fn query_error_wire(failure: QueryFailure) -> Value {
1014 let backend = QueryFailBackend(failure);
1015 let args = json!({
1016 "accountId": "a1",
1017 "filter": { "text": "hello" },
1018 "anchor": "m1",
1019 });
1020 let err = match handle_query::<QueryProbe, _>(&backend, &(), args).await {
1021 Ok(HandlerOutput { primary: resp, .. }) => {
1022 panic!("query_objects failed but handle_query succeeded: {resp}")
1023 }
1024 Err(e) => e,
1025 };
1026 serde_json::to_value(&err).expect("JmapError must serialize")
1027 }
1028
1029 #[tokio::test]
1042 async fn handle_query_passes_backend_unsupported_filter_through() {
1043 let mut expected = JmapError::unsupported_filter();
1044 expected.description = Some("Message/query requires a chatId condition".into());
1045
1046 let wire = query_error_wire(QueryFailure::Method(expected.clone())).await;
1047
1048 assert_eq!(
1049 wire,
1050 serde_json::to_value(&expected).expect("JmapError must serialize"),
1051 "backend unsupportedFilter must pass through handle_query unchanged"
1052 );
1053 }
1054
1055 #[tokio::test]
1064 async fn handle_query_passes_backend_anchor_not_found_through() {
1065 let expected = JmapError::anchor_not_found();
1066
1067 let wire = query_error_wire(QueryFailure::Method(expected.clone())).await;
1068
1069 assert_eq!(
1070 wire,
1071 serde_json::to_value(&expected).expect("JmapError must serialize"),
1072 "backend anchorNotFound must pass through handle_query unchanged"
1073 );
1074 }
1075
1076 #[tokio::test]
1081 async fn handle_query_redacts_backend_internal_error() {
1082 const CANARY: &str = "TOKEN-DO-NOT-LEAK-query-5ca1ab1e";
1083
1084 let wire = query_error_wire(QueryFailure::Internal(CANARY)).await;
1085
1086 assert_eq!(wire["type"], "serverFail");
1087 assert_eq!(wire["description"], SERVER_FAIL_INTERNAL_DESC);
1088 assert!(
1089 !wire.to_string().contains(CANARY),
1090 "internal backend error Display must not reach the wire; got {wire}"
1091 );
1092 }
1093
1094 #[derive(serde::Serialize, serde::Deserialize)]
1100 struct GetProbe;
1101
1102 impl JmapObject for GetProbe {
1103 const TYPE_NAME: &'static str = "GetProbe";
1104 type Property = ();
1105 }
1106
1107 impl GetObject for GetProbe {}
1108
1109 struct GetProbeBackend;
1112
1113 impl JmapAccounts for GetProbeBackend {
1114 type Error = LeakyQueryError;
1115 type CallerCtx = ();
1116
1117 async fn account_exists(
1118 &self,
1119 _caller: &(),
1120 _account_id: &Id,
1121 ) -> Result<bool, Self::Error> {
1122 Ok(true)
1123 }
1124 }
1125
1126 impl JmapReads for GetProbeBackend {
1127 async fn get_objects<O: GetObject + Send + Sync>(
1128 &self,
1129 _caller: &(),
1130 _account_id: &Id,
1131 ids: Option<&[Id]>,
1132 _properties: Option<&[String]>,
1133 ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
1134 Ok((vec![], ids.map(<[Id]>::to_vec).unwrap_or_default()))
1135 }
1136
1137 async fn get_state<O: JmapObject + Send + Sync>(
1138 &self,
1139 _caller: &(),
1140 _account_id: &Id,
1141 ) -> Result<State, Self::Error> {
1142 Ok(State::from("s0"))
1143 }
1144
1145 async fn get_changes<O: JmapObject + Send + Sync>(
1146 &self,
1147 _caller: &(),
1148 _account_id: &Id,
1149 _params: ChangesParams<'_>,
1150 ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
1151 unreachable!("only /get is exercised")
1152 }
1153
1154 async fn query_objects<O: QueryObject + Send + Sync>(
1155 &self,
1156 _caller: &(),
1157 _account_id: &Id,
1158 _params: QueryParams<'_, O>,
1159 ) -> Result<crate::backend::QueryResult, BackendQueryError<Self::Error>> {
1160 unreachable!("only /get is exercised")
1161 }
1162
1163 async fn query_changes<O: QueryObject + Send + Sync>(
1164 &self,
1165 _caller: &(),
1166 _account_id: &Id,
1167 _params: QueryChangesParams<'_, O>,
1168 ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
1169 unreachable!("only /get is exercised")
1170 }
1171 }
1172
1173 #[tokio::test]
1188 async fn handle_get_over_max_objects_is_request_too_large() {
1189 let ids: Vec<String> = (0..501).map(|i| format!("id{i}")).collect();
1190 let args = json!({ "accountId": "a1", "ids": ids });
1191
1192 match handle_get::<GetProbe, _>(&GetProbeBackend, &(), args).await {
1193 Ok(HandlerOutput { primary: resp, .. }) => panic!(
1194 "501 ids exceed the maxObjectsInGet cap, but handle_get \
1195 returned a response with {} notFound ids instead of \
1196 requestTooLarge",
1197 resp["notFound"].as_array().map_or(0, Vec::len)
1198 ),
1199 Err(e) => assert_eq!(e.error_type.to_string(), "requestTooLarge"),
1200 }
1201 }
1202
1203 #[tokio::test]
1214 async fn handle_get_null_ids_is_not_counted_against_cap() {
1215 let args = json!({ "accountId": "a1", "ids": null });
1216
1217 let HandlerOutput { primary: resp, .. } =
1218 handle_get::<GetProbe, _>(&GetProbeBackend, &(), args)
1219 .await
1220 .expect("null ids must not be rejected by the maxObjectsInGet cap");
1221 assert_eq!(resp["list"], json!([]));
1222 }
1223
1224 struct FullObjectBackend;
1228
1229 impl JmapAccounts for FullObjectBackend {
1230 type Error = LeakyQueryError;
1231 type CallerCtx = ();
1232
1233 async fn account_exists(
1234 &self,
1235 _caller: &(),
1236 _account_id: &Id,
1237 ) -> Result<bool, Self::Error> {
1238 Ok(true)
1239 }
1240 }
1241
1242 impl JmapReads for FullObjectBackend {
1243 async fn get_objects<O: GetObject + Send + Sync>(
1244 &self,
1245 _caller: &(),
1246 _account_id: &Id,
1247 _ids: Option<&[Id]>,
1248 _properties: Option<&[String]>,
1249 ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
1250 let obj = serde_json::from_value(json!({
1251 "id": "o1", "name": "n", "color": "c"
1252 }))
1253 .expect("fixture must deserialize");
1254 Ok((vec![obj], vec![]))
1255 }
1256
1257 async fn get_state<O: JmapObject + Send + Sync>(
1258 &self,
1259 _caller: &(),
1260 _account_id: &Id,
1261 ) -> Result<State, Self::Error> {
1262 Ok(State::from("s0"))
1263 }
1264
1265 async fn get_changes<O: JmapObject + Send + Sync>(
1266 &self,
1267 _caller: &(),
1268 _account_id: &Id,
1269 _params: ChangesParams<'_>,
1270 ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
1271 unreachable!("only /get is exercised")
1272 }
1273
1274 async fn query_objects<O: QueryObject + Send + Sync>(
1275 &self,
1276 _caller: &(),
1277 _account_id: &Id,
1278 _params: QueryParams<'_, O>,
1279 ) -> Result<crate::backend::QueryResult, BackendQueryError<Self::Error>> {
1280 unreachable!("only /get is exercised")
1281 }
1282
1283 async fn query_changes<O: QueryObject + Send + Sync>(
1284 &self,
1285 _caller: &(),
1286 _account_id: &Id,
1287 _params: QueryChangesParams<'_, O>,
1288 ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
1289 unreachable!("only /get is exercised")
1290 }
1291 }
1292
1293 #[derive(serde::Serialize, serde::Deserialize)]
1295 struct Swatch {
1296 id: String,
1297 name: String,
1298 color: String,
1299 }
1300
1301 impl JmapObject for Swatch {
1302 const TYPE_NAME: &'static str = "Swatch";
1303 type Property = ();
1304 }
1305
1306 impl GetObject for Swatch {}
1307
1308 #[tokio::test]
1315 async fn handle_get_returns_only_requested_properties_and_id() {
1316 let args = json!({ "accountId": "a1", "ids": ["o1"], "properties": ["name"] });
1317
1318 let HandlerOutput { primary: resp, .. } =
1319 handle_get::<Swatch, _>(&FullObjectBackend, &(), args)
1320 .await
1321 .expect("valid /get must succeed");
1322 assert_eq!(resp["list"], json!([{ "id": "o1", "name": "n" }]));
1323 }
1324
1325 #[tokio::test]
1328 async fn handle_get_null_properties_returns_all() {
1329 let args = json!({ "accountId": "a1", "ids": ["o1"], "properties": null });
1330
1331 let HandlerOutput { primary: resp, .. } =
1332 handle_get::<Swatch, _>(&FullObjectBackend, &(), args)
1333 .await
1334 .expect("valid /get must succeed");
1335 assert_eq!(
1336 resp["list"],
1337 json!([{ "id": "o1", "name": "n", "color": "c" }])
1338 );
1339 }
1340
1341 #[derive(Default)]
1345 struct RecordingQueryBackend(std::sync::Mutex<Option<Value>>);
1346
1347 impl RecordingQueryBackend {
1348 fn take(&self) -> Value {
1349 self.0
1350 .lock()
1351 .unwrap()
1352 .take()
1353 .expect("backend query method was not called")
1354 }
1355 }
1356
1357 impl JmapAccounts for RecordingQueryBackend {
1358 type Error = LeakyQueryError;
1359 type CallerCtx = ();
1360
1361 async fn account_exists(
1362 &self,
1363 _caller: &(),
1364 _account_id: &Id,
1365 ) -> Result<bool, Self::Error> {
1366 Ok(true)
1367 }
1368 }
1369
1370 impl JmapReads for RecordingQueryBackend {
1371 async fn get_objects<O: GetObject + Send + Sync>(
1372 &self,
1373 _caller: &(),
1374 _account_id: &Id,
1375 _ids: Option<&[Id]>,
1376 _properties: Option<&[String]>,
1377 ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
1378 unreachable!("only queries are exercised")
1379 }
1380
1381 async fn get_state<O: JmapObject + Send + Sync>(
1382 &self,
1383 _caller: &(),
1384 _account_id: &Id,
1385 ) -> Result<State, Self::Error> {
1386 unreachable!("only queries are exercised")
1387 }
1388
1389 async fn get_changes<O: JmapObject + Send + Sync>(
1390 &self,
1391 _caller: &(),
1392 _account_id: &Id,
1393 _params: ChangesParams<'_>,
1394 ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
1395 unreachable!("only queries are exercised")
1396 }
1397
1398 async fn query_objects<O: QueryObject + Send + Sync>(
1399 &self,
1400 _caller: &(),
1401 _account_id: &Id,
1402 params: QueryParams<'_, O>,
1403 ) -> Result<crate::backend::QueryResult, BackendQueryError<Self::Error>> {
1404 *self.0.lock().unwrap() = Some(json!({
1405 "filter": params.filter.map(|f| serde_json::to_value(f).unwrap()),
1406 "sort": params.sort.map(|s| serde_json::to_value(s).unwrap()),
1407 "limit": params.limit,
1408 "position": params.position,
1409 "anchor": params.anchor,
1410 "anchorOffset": params.anchor_offset,
1411 }));
1412 Ok(crate::backend::QueryResult::new(
1413 vec![],
1414 0,
1415 None,
1416 State::from("q0"),
1417 false,
1418 ))
1419 }
1420
1421 async fn query_changes<O: QueryObject + Send + Sync>(
1422 &self,
1423 _caller: &(),
1424 _account_id: &Id,
1425 params: QueryChangesParams<'_, O>,
1426 ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
1427 *self.0.lock().unwrap() = Some(json!({
1428 "sinceQueryState": params.since_query_state,
1429 "filter": params.filter.map(|f| serde_json::to_value(f).unwrap()),
1430 "sort": params.sort.map(|s| serde_json::to_value(s).unwrap()),
1431 "maxChanges": params.max_changes,
1432 "upToId": params.up_to_id,
1433 "collapseThreads": params.collapse_threads,
1434 }));
1435 Ok(QueryChangesResult::new(
1436 params.since_query_state.clone(),
1437 State::from("q2"),
1438 None,
1439 vec![],
1440 vec![],
1441 ))
1442 }
1443 }
1444
1445 #[tokio::test]
1450 async fn handle_query_passes_every_argument_to_backend() {
1451 let backend = RecordingQueryBackend::default();
1452 let args = json!({
1453 "accountId": "a1",
1454 "filter": {"text": "hello"},
1455 "sort": [{"property": "receivedAt", "isAscending": false}],
1456 "position": 3,
1457 "anchor": "m7",
1458 "anchorOffset": -2,
1459 "limit": 25,
1460 });
1461 handle_query::<QueryProbe, _>(&backend, &(), args)
1462 .await
1463 .expect("query must succeed");
1464 assert_eq!(
1465 backend.take(),
1466 json!({
1467 "filter": {"text": "hello"},
1468 "sort": [{"property": "receivedAt", "isAscending": false}],
1469 "limit": 25,
1470 "position": 3,
1471 "anchor": "m7",
1472 "anchorOffset": -2,
1473 })
1474 );
1475 }
1476
1477 #[tokio::test]
1482 async fn handle_query_omitted_arguments_reach_backend_as_rfc_defaults() {
1483 let backend = RecordingQueryBackend::default();
1484 handle_query::<QueryProbe, _>(&backend, &(), json!({"accountId": "a1"}))
1485 .await
1486 .expect("query must succeed");
1487 assert_eq!(
1488 backend.take(),
1489 json!({
1490 "filter": null,
1491 "sort": null,
1492 "limit": null,
1493 "position": 0,
1494 "anchor": null,
1495 "anchorOffset": 0,
1496 })
1497 );
1498 }
1499
1500 #[tokio::test]
1507 async fn handle_query_changes_passes_every_argument_to_backend() {
1508 let backend = RecordingQueryBackend::default();
1509 let args = json!({
1510 "accountId": "a1",
1511 "filter": {"text": "hello"},
1512 "sort": [{"property": "receivedAt"}],
1513 "sinceQueryState": "q1",
1514 "maxChanges": 10,
1515 "upToId": "m9",
1516 });
1517 handle_query_changes::<QueryProbe, _>(&backend, &(), args)
1518 .await
1519 .expect("queryChanges must succeed");
1520 assert_eq!(
1521 backend.take(),
1522 json!({
1523 "sinceQueryState": "q1",
1524 "filter": {"text": "hello"},
1525 "sort": [{"property": "receivedAt"}],
1526 "maxChanges": 10,
1527 "upToId": "m9",
1528 "collapseThreads": false,
1529 })
1530 );
1531 }
1532
1533 #[tokio::test]
1541 async fn non_object_filter_is_invalid_arguments() {
1542 for filter in [json!(42), json!("text"), json!(true), json!([])] {
1543 let backend = RecordingQueryBackend::default();
1544 let err = handle_query::<QueryProbe, _>(
1545 &backend,
1546 &(),
1547 json!({"accountId": "a1", "filter": filter}),
1548 )
1549 .await
1550 .expect_err("non-object filter must be rejected");
1551 assert_eq!(err.error_type.to_string(), "invalidArguments", "{filter}");
1552
1553 let err = handle_query_changes::<QueryProbe, _>(
1554 &backend,
1555 &(),
1556 json!({"accountId": "a1", "filter": filter, "sinceQueryState": "q1"}),
1557 )
1558 .await
1559 .expect_err("non-object filter must be rejected");
1560 assert_eq!(err.error_type.to_string(), "invalidArguments", "{filter}");
1561 assert!(backend.0.lock().unwrap().is_none(), "{filter}");
1562 }
1563 }
1564
1565 #[derive(Clone, Copy)]
1573 enum Canned {
1574 Ok,
1576 CannotCalculate,
1578 TooManyChanges(u64),
1580 Internal(&'static str),
1582 }
1583
1584 impl Canned {
1585 fn changes_error(self) -> BackendChangesError<LeakyQueryError> {
1586 match self {
1587 Canned::Ok => unreachable!("Canned::Ok is not an error"),
1588 Canned::CannotCalculate => BackendChangesError::CannotCalculate,
1589 Canned::TooManyChanges(limit) => BackendChangesError::TooManyChanges { limit },
1590 Canned::Internal(text) => BackendChangesError::Other(LeakyQueryError(text)),
1591 }
1592 }
1593 }
1594
1595 struct CannedBackend {
1599 account_exists: bool,
1600 outcome: Canned,
1601 }
1602
1603 const CANNED_OK: CannedBackend = CannedBackend {
1604 account_exists: true,
1605 outcome: Canned::Ok,
1606 };
1607
1608 impl JmapAccounts for CannedBackend {
1609 type Error = LeakyQueryError;
1610 type CallerCtx = ();
1611
1612 async fn account_exists(
1613 &self,
1614 _caller: &(),
1615 _account_id: &Id,
1616 ) -> Result<bool, Self::Error> {
1617 Ok(self.account_exists)
1618 }
1619 }
1620
1621 impl JmapReads for CannedBackend {
1622 async fn get_objects<O: GetObject + Send + Sync>(
1623 &self,
1624 _caller: &(),
1625 _account_id: &Id,
1626 _ids: Option<&[Id]>,
1627 _properties: Option<&[String]>,
1628 ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
1629 unreachable!("/get is not exercised")
1630 }
1631
1632 async fn get_state<O: JmapObject + Send + Sync>(
1633 &self,
1634 _caller: &(),
1635 _account_id: &Id,
1636 ) -> Result<State, Self::Error> {
1637 unreachable!("/get is not exercised")
1638 }
1639
1640 async fn get_changes<O: JmapObject + Send + Sync>(
1641 &self,
1642 _caller: &(),
1643 _account_id: &Id,
1644 _params: ChangesParams<'_>,
1645 ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
1646 match self.outcome {
1647 Canned::Ok => Ok(ChangesResult::new(
1648 vec![Id::from("c1")],
1649 vec![Id::from("u1")],
1650 vec![Id::from("d1")],
1651 true,
1652 State::from("s2"),
1653 )),
1654 other => Err(other.changes_error()),
1655 }
1656 }
1657
1658 async fn query_objects<O: QueryObject + Send + Sync>(
1659 &self,
1660 _caller: &(),
1661 _account_id: &Id,
1662 _params: QueryParams<'_, O>,
1663 ) -> Result<crate::backend::QueryResult, BackendQueryError<Self::Error>> {
1664 Ok(crate::backend::QueryResult::new(
1665 vec![Id::from("m1")],
1666 0,
1667 Some(7),
1668 State::from("q1"),
1669 true,
1670 ))
1671 }
1672
1673 async fn query_changes<O: QueryObject + Send + Sync>(
1674 &self,
1675 _caller: &(),
1676 _account_id: &Id,
1677 params: QueryChangesParams<'_, O>,
1678 ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
1679 match self.outcome {
1680 Canned::Ok => Ok(QueryChangesResult::new(
1681 params.since_query_state.clone(),
1682 State::from("q2"),
1683 Some(7),
1684 vec![Id::from("r1")],
1685 vec![crate::backend::AddedItem::new(Id::from("n1"), 0)],
1686 )),
1687 other => Err(other.changes_error()),
1688 }
1689 }
1690 }
1691
1692 #[tokio::test]
1699 async fn handle_changes_response_matches_rfc_shape() {
1700 let HandlerOutput { primary: resp, .. } = handle_changes::<QueryProbe, _>(
1701 &CANNED_OK,
1702 &(),
1703 json!({"accountId": "a1", "sinceState": "s1"}),
1704 &[],
1705 )
1706 .await
1707 .expect("/changes must succeed");
1708 assert_eq!(
1709 resp,
1710 json!({
1711 "accountId": "a1",
1712 "oldState": "s1",
1713 "newState": "s2",
1714 "hasMoreChanges": true,
1715 "updatedProperties": null,
1716 "created": ["c1"],
1717 "updated": ["u1"],
1718 "destroyed": ["d1"],
1719 })
1720 );
1721 }
1722
1723 const CORE: &str = "urn:ietf:params:jmap:core";
1728 const METADATA: &str = "urn:ietf:params:jmap:metadata";
1729
1730 struct MetadataChangesBackend {
1734 updated: Vec<Id>,
1735 updated_properties: Option<Vec<String>>,
1736 seen_ignore: std::sync::Mutex<Option<bool>>,
1737 }
1738
1739 impl MetadataChangesBackend {
1740 fn new(updated: &[&str], updated_properties: Option<&[&str]>) -> Self {
1741 Self {
1742 updated: updated.iter().map(|u| Id::from(*u)).collect(),
1743 updated_properties: updated_properties
1744 .map(|p| p.iter().map(|s| (*s).to_owned()).collect()),
1745 seen_ignore: std::sync::Mutex::new(None),
1746 }
1747 }
1748 }
1749
1750 impl JmapAccounts for MetadataChangesBackend {
1751 type Error = LeakyQueryError;
1752 type CallerCtx = ();
1753
1754 async fn account_exists(
1755 &self,
1756 _caller: &(),
1757 _account_id: &Id,
1758 ) -> Result<bool, Self::Error> {
1759 Ok(true)
1760 }
1761 }
1762
1763 impl JmapReads for MetadataChangesBackend {
1764 async fn get_objects<O: GetObject + Send + Sync>(
1765 &self,
1766 _caller: &(),
1767 _account_id: &Id,
1768 _ids: Option<&[Id]>,
1769 _properties: Option<&[String]>,
1770 ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
1771 unreachable!("only get_changes is exercised")
1772 }
1773
1774 async fn get_state<O: JmapObject + Send + Sync>(
1775 &self,
1776 _caller: &(),
1777 _account_id: &Id,
1778 ) -> Result<State, Self::Error> {
1779 unreachable!("only get_changes is exercised")
1780 }
1781
1782 async fn get_changes<O: JmapObject + Send + Sync>(
1783 &self,
1784 _caller: &(),
1785 _account_id: &Id,
1786 params: ChangesParams<'_>,
1787 ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
1788 *self.seen_ignore.lock().unwrap() = Some(params.ignore_metadata_only_changes);
1789 Ok(ChangesResult::new(
1790 Vec::new(),
1791 self.updated.clone(),
1792 Vec::new(),
1793 false,
1794 State::from("s2"),
1795 )
1796 .with_updated_properties(self.updated_properties.clone()))
1797 }
1798
1799 async fn query_objects<O: QueryObject + Send + Sync>(
1800 &self,
1801 _caller: &(),
1802 _account_id: &Id,
1803 _params: QueryParams<'_, O>,
1804 ) -> Result<crate::backend::QueryResult, BackendQueryError<Self::Error>> {
1805 unreachable!("only get_changes is exercised")
1806 }
1807
1808 async fn query_changes<O: QueryObject + Send + Sync>(
1809 &self,
1810 _caller: &(),
1811 _account_id: &Id,
1812 _params: QueryChangesParams<'_, O>,
1813 ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
1814 unreachable!("only get_changes is exercised")
1815 }
1816 }
1817
1818 async fn ignore_seen(using: &[&str], extra: Value) -> bool {
1821 let backend = MetadataChangesBackend::new(&["u1"], None);
1822 let mut args = json!({"accountId": "a1", "sinceState": "s1"});
1823 if let Value::Object(extra) = extra {
1824 args.as_object_mut().unwrap().extend(extra);
1825 }
1826 let using: Vec<String> = using.iter().map(|u| (*u).to_owned()).collect();
1827 handle_changes::<QueryProbe, _>(&backend, &(), args, &using)
1828 .await
1829 .expect("/changes must succeed");
1830 backend
1831 .seen_ignore
1832 .lock()
1833 .unwrap()
1834 .expect("backend must be called")
1835 }
1836
1837 #[tokio::test]
1844 async fn changes_without_metadata_capability_ignores_metadata_only_changes() {
1845 assert!(ignore_seen(&[CORE], json!({})).await);
1846 assert!(ignore_seen(&[CORE], json!({"ignoreMetadataOnlyChanges": false})).await);
1847 assert!(ignore_seen(&[CORE], json!({"ignoreMetadataOnlyChanges": "no"})).await);
1848 assert!(ignore_seen(&[], json!({})).await);
1849 }
1850
1851 #[tokio::test]
1854 async fn changes_with_metadata_capability_passes_ignore_argument() {
1855 assert!(!ignore_seen(&[CORE, METADATA], json!({})).await);
1856 assert!(
1857 !ignore_seen(
1858 &[CORE, METADATA],
1859 json!({"ignoreMetadataOnlyChanges": null})
1860 )
1861 .await
1862 );
1863 assert!(
1864 !ignore_seen(
1865 &[CORE, METADATA],
1866 json!({"ignoreMetadataOnlyChanges": false})
1867 )
1868 .await
1869 );
1870 assert!(
1871 ignore_seen(
1872 &[CORE, METADATA],
1873 json!({"ignoreMetadataOnlyChanges": true})
1874 )
1875 .await
1876 );
1877 }
1878
1879 #[tokio::test]
1883 async fn changes_rejects_non_boolean_ignore_argument() {
1884 let backend = MetadataChangesBackend::new(&["u1"], None);
1885 let err = handle_changes::<QueryProbe, _>(
1886 &backend,
1887 &(),
1888 json!({"accountId": "a1", "sinceState": "s1", "ignoreMetadataOnlyChanges": "yes"}),
1889 &[CORE.to_owned(), METADATA.to_owned()],
1890 )
1891 .await
1892 .expect_err("a string ignoreMetadataOnlyChanges must fail");
1893 assert_eq!(err.error_type.to_string(), "invalidArguments");
1894 assert!(
1895 backend.seen_ignore.lock().unwrap().is_none(),
1896 "backend must not be called"
1897 );
1898 }
1899
1900 #[tokio::test]
1907 async fn changes_reports_backend_updated_properties() {
1908 let backend = MetadataChangesBackend::new(&["u1"], Some(&["metadata"]));
1909 let HandlerOutput { primary: resp, .. } = handle_changes::<QueryProbe, _>(
1910 &backend,
1911 &(),
1912 json!({"accountId": "a1", "sinceState": "s1"}),
1913 &[CORE.to_owned(), METADATA.to_owned()],
1914 )
1915 .await
1916 .expect("/changes must succeed");
1917 assert_eq!(
1918 resp,
1919 json!({
1920 "accountId": "a1",
1921 "oldState": "s1",
1922 "newState": "s2",
1923 "hasMoreChanges": false,
1924 "updatedProperties": ["metadata"],
1925 "created": [],
1926 "updated": ["u1"],
1927 "destroyed": [],
1928 })
1929 );
1930 }
1931
1932 #[tokio::test]
1935 async fn changes_updated_properties_null_when_updated_empty() {
1936 let backend = MetadataChangesBackend::new(&[], Some(&["metadata"]));
1937 let HandlerOutput { primary: resp, .. } = handle_changes::<QueryProbe, _>(
1938 &backend,
1939 &(),
1940 json!({"accountId": "a1", "sinceState": "s1"}),
1941 &[CORE.to_owned(), METADATA.to_owned()],
1942 )
1943 .await
1944 .expect("/changes must succeed");
1945 assert_eq!(resp["updatedProperties"], Value::Null);
1946 assert!(
1947 resp.as_object().unwrap().contains_key("updatedProperties"),
1948 "updatedProperties must be present"
1949 );
1950 }
1951
1952 #[tokio::test]
1958 async fn handle_query_changes_response_matches_rfc_shape() {
1959 let HandlerOutput { primary: resp, .. } = handle_query_changes::<QueryProbe, _>(
1960 &CANNED_OK,
1961 &(),
1962 json!({"accountId": "a1", "sinceQueryState": "q1", "calculateTotal": true}),
1963 )
1964 .await
1965 .expect("/queryChanges must succeed");
1966 assert_eq!(
1967 resp,
1968 json!({
1969 "accountId": "a1",
1970 "oldQueryState": "q1",
1971 "newQueryState": "q2",
1972 "total": 7,
1973 "removed": ["r1"],
1974 "added": [{"id": "n1", "index": 0}],
1975 })
1976 );
1977
1978 let HandlerOutput { primary: resp, .. } = handle_query_changes::<QueryProbe, _>(
1979 &CANNED_OK,
1980 &(),
1981 json!({"accountId": "a1", "sinceQueryState": "q1"}),
1982 )
1983 .await
1984 .expect("/queryChanges must succeed");
1985 assert!(
1986 resp.get("total").is_none(),
1987 "total must be omitted without calculateTotal; got {resp}"
1988 );
1989 }
1990
1991 #[tokio::test]
1995 async fn handle_query_total_only_when_requested() {
1996 for (calculate_total, expected) in [(json!(true), Some(json!(7))), (json!(false), None)] {
1997 let HandlerOutput { primary: resp, .. } = handle_query::<QueryProbe, _>(
1998 &CANNED_OK,
1999 &(),
2000 json!({"accountId": "a1", "calculateTotal": calculate_total}),
2001 )
2002 .await
2003 .expect("/query must succeed");
2004 assert_eq!(resp.get("total").cloned(), expected, "{resp}");
2005 }
2006 }
2007
2008 #[tokio::test]
2013 async fn missing_or_non_string_since_state_is_invalid_arguments() {
2014 for since in [None, Some(json!(42))] {
2015 let mut args = json!({"accountId": "a1"});
2016 if let Some(v) = &since {
2017 args["sinceState"] = v.clone();
2018 }
2019 let err = handle_changes::<QueryProbe, _>(&CANNED_OK, &(), args, &[])
2020 .await
2021 .expect_err("/changes without a string sinceState must fail");
2022 assert_eq!(err.error_type.to_string(), "invalidArguments", "{since:?}");
2023
2024 let mut args = json!({"accountId": "a1"});
2025 if let Some(v) = &since {
2026 args["sinceQueryState"] = v.clone();
2027 }
2028 let err = handle_query_changes::<QueryProbe, _>(&CANNED_OK, &(), args)
2029 .await
2030 .expect_err("/queryChanges without a string sinceQueryState must fail");
2031 assert_eq!(err.error_type.to_string(), "invalidArguments", "{since:?}");
2032 }
2033 }
2034
2035 #[tokio::test]
2038 async fn non_string_up_to_id_is_invalid_arguments() {
2039 for up_to_id in [json!(5), json!(true), json!(["m1"]), json!({})] {
2040 let err = handle_query_changes::<QueryProbe, _>(
2041 &CANNED_OK,
2042 &(),
2043 json!({"accountId": "a1", "sinceQueryState": "q1", "upToId": up_to_id}),
2044 )
2045 .await
2046 .expect_err("non-Id upToId must be rejected");
2047 assert_eq!(err.error_type.to_string(), "invalidArguments", "{up_to_id}");
2048 }
2049 }
2050
2051 #[tokio::test]
2055 async fn handle_query_negative_limit_is_invalid_arguments() {
2056 let backend = RecordingQueryBackend::default();
2057 let err =
2058 handle_query::<QueryProbe, _>(&backend, &(), json!({"accountId": "a1", "limit": -1}))
2059 .await
2060 .expect_err("negative limit must be rejected");
2061 assert_eq!(err.error_type.to_string(), "invalidArguments");
2062 assert!(
2063 backend.0.lock().unwrap().is_none(),
2064 "backend must not be consulted"
2065 );
2066 }
2067
2068 #[tokio::test]
2074 async fn handle_query_negative_position_reaches_backend() {
2075 let backend = RecordingQueryBackend::default();
2076 handle_query::<QueryProbe, _>(&backend, &(), json!({"accountId": "a1", "position": -5}))
2077 .await
2078 .expect("negative position is valid");
2079 assert_eq!(backend.take()["position"], json!(-5));
2080 }
2081
2082 #[tokio::test]
2091 async fn changes_backend_errors_map_to_rfc_errors() {
2092 const CANARY: &str = "TOKEN-DO-NOT-LEAK-changes-b0a710ad";
2093 for (outcome, changes_type, query_changes_type) in [
2094 (
2095 Canned::CannotCalculate,
2096 "cannotCalculateChanges",
2097 "cannotCalculateChanges",
2098 ),
2099 (
2100 Canned::TooManyChanges(10),
2101 "cannotCalculateChanges",
2102 "tooManyChanges",
2103 ),
2104 (Canned::Internal(CANARY), "serverFail", "serverFail"),
2105 ] {
2106 let backend = CannedBackend {
2107 account_exists: true,
2108 outcome,
2109 };
2110 let changes = handle_changes::<QueryProbe, _>(
2111 &backend,
2112 &(),
2113 json!({"accountId": "a1", "sinceState": "s1"}),
2114 &[],
2115 )
2116 .await;
2117 let query_changes = handle_query_changes::<QueryProbe, _>(
2118 &backend,
2119 &(),
2120 json!({"accountId": "a1", "sinceQueryState": "q1"}),
2121 )
2122 .await;
2123 for (result, expected_type) in
2124 [(changes, changes_type), (query_changes, query_changes_type)]
2125 {
2126 let err = result.expect_err("backend error must fail the call");
2127 let wire = serde_json::to_value(&err).expect("JmapError must serialize");
2128 assert_eq!(wire["type"], expected_type, "{wire}");
2129 assert!(!wire.to_string().contains(CANARY), "leaked: {wire}");
2130 }
2131 }
2132 }
2133
2134 #[tokio::test]
2137 async fn unknown_account_is_account_not_found() {
2138 let backend = CannedBackend {
2139 account_exists: false,
2140 outcome: Canned::Ok,
2141 };
2142 let results = [
2143 handle_changes::<QueryProbe, _>(
2144 &backend,
2145 &(),
2146 json!({"accountId": "nope", "sinceState": "s1"}),
2147 &[],
2148 )
2149 .await,
2150 handle_query::<QueryProbe, _>(&backend, &(), json!({"accountId": "nope"})).await,
2151 handle_query_changes::<QueryProbe, _>(
2152 &backend,
2153 &(),
2154 json!({"accountId": "nope", "sinceQueryState": "q1"}),
2155 )
2156 .await,
2157 ];
2158 for result in results {
2159 let err = result.expect_err("unknown account must fail");
2160 assert_eq!(err.error_type.to_string(), "accountNotFound");
2161 }
2162 }
2163
2164 #[tokio::test]
2169 async fn handle_query_does_not_echo_wrongly_typed_value() {
2170 for name in ["limit", "position"] {
2171 let backend = RecordingQueryBackend::default();
2172 let mut args = json!({ "accountId": "a1" });
2173 args[name] = json!({ "note": "CANARY-zegc" });
2174 let err = handle_query::<QueryProbe, _>(&backend, &(), args)
2175 .await
2176 .expect_err("wrongly typed argument must be rejected");
2177 assert_eq!(err.error_type.to_string(), "invalidArguments", "{name}");
2178 let desc = err.description.as_deref().unwrap_or_default();
2179 assert!(desc.starts_with(name), "{desc}");
2180 assert!(desc.contains("got object"), "{desc}");
2181 assert!(!desc.contains("CANARY"), "{desc}");
2182 }
2183 }
2184}