1use crate::HandlerOutput;
27use jmap_types::{Id, JmapError, State};
28use serde_json::{Value, json};
29
30use crate::backend::{
31 BackendChangesError, ChangesParams, GetObject, JmapBackend, JmapObject, QueryChangesParams,
32 QueryObject, QueryParams,
33};
34use crate::helpers::{
35 MetadataProjection, enforce_max_objects_in_get, extract_account_id, filter_arg, not_found_json,
36 optional_arg, query_anchor_args, serialize_value,
37};
38
39pub const SERVER_FAIL_INTERNAL_DESC: &str = "internal error";
46
47pub fn server_fail_from_backend<E: std::fmt::Display + ?Sized>(_err: &E) -> JmapError {
85 JmapError::server_fail(SERVER_FAIL_INTERNAL_DESC)
86}
87
88pub fn changes_error_from_backend<E: std::error::Error>(err: BackendChangesError<E>) -> JmapError {
100 match err {
101 BackendChangesError::TooManyChanges { .. } => JmapError::cannot_calculate_changes(),
102 other => JmapError::from(other),
103 }
104}
105
106pub fn server_fail_value_from_backend<E: std::fmt::Display + ?Sized>(_err: &E) -> Value {
152 json!({
153 "type": "serverFail",
154 "description": SERVER_FAIL_INTERNAL_DESC,
155 })
156}
157
158pub async fn handle_get<O: GetObject, B: JmapBackend>(
169 backend: &B,
170 caller: &B::CallerCtx,
171 args: Value,
172) -> Result<HandlerOutput, JmapError> {
173 let (account_id, mut args) = extract_account_id(args)?;
174 if !backend
175 .account_exists(caller, &account_id)
176 .await
177 .map_err(|e| server_fail_from_backend(&e))?
178 {
179 return Err(JmapError::account_not_found());
180 }
181 enforce_max_objects_in_get(&args, backend.max_objects_in_get(caller, &account_id))?;
182
183 let ids: Option<Vec<Id>> = optional_arg(&mut args, "ids", || {
184 JmapError::invalid_arguments("ids must be an Id array")
185 })?;
186
187 let properties: Option<Vec<String>> = optional_arg(&mut args, "properties", || {
188 JmapError::invalid_arguments("properties must be a string array")
189 })?;
190
191 let ids_slice = ids.as_deref();
192 let (list, not_found) = backend
193 .get_objects::<O>(caller, &account_id, ids_slice, properties.as_deref())
194 .await
195 .map_err(|e| server_fail_from_backend(&e))?;
196
197 let state = backend
198 .get_state::<O>(caller, &account_id)
199 .await
200 .map_err(|e| server_fail_from_backend(&e))?;
201
202 let mut list_json = serialize_value(&list)?;
209
210 if let (Some(props), Value::Array(items)) = (&properties, &mut list_json) {
216 for item in items {
217 if let Value::Object(map) = item {
218 map.retain(|k, _| k == "id" || props.iter().any(|p| p == k));
219 }
220 }
221 }
222
223 Ok(HandlerOutput::new(json!({
224 "accountId": account_id.as_ref(),
225 "state": state.as_ref(),
226 "list": list_json,
227 "notFound": not_found_json(¬_found),
228 })))
229}
230
231pub async fn handle_get_with_metadata<O: GetObject, B: JmapBackend>(
250 backend: &B,
251 caller: &B::CallerCtx,
252 mut args: Value,
253 using: &[String],
254) -> Result<HandlerOutput, JmapError> {
255 let info = args
256 .get("accountId")
257 .and_then(Value::as_str)
258 .and_then(|s| Id::new_validated(s).ok())
259 .and_then(|id| backend.metadata_info::<O>(caller, &id));
260 let Some(info) = info else {
261 return handle_get::<O, B>(backend, caller, args).await;
262 };
263 let properties: Option<Vec<String>> = match args.get("properties") {
264 None | Some(Value::Null) => None,
265 Some(v) => match serde_json::from_value(v.clone()) {
266 Ok(props) => Some(props),
267 Err(_) => return handle_get::<O, B>(backend, caller, args).await,
269 },
270 };
271 let projection = MetadataProjection::new(properties.as_deref(), true, using, Some(&info))?;
272 if let Some(props) = properties {
273 let mut roots: Vec<String> = Vec::with_capacity(props.len());
274 for p in props {
275 let root = match p.split_once('/') {
276 Some((r @ ("metadata" | "privateMetadata"), _)) => r.to_owned(),
277 _ => p,
278 };
279 if !roots.contains(&root) {
280 roots.push(root);
281 }
282 }
283 args["properties"] = json!(roots);
284 }
285 let mut out = handle_get::<O, B>(backend, caller, args).await?;
286 if let Some(Value::Array(list)) = out.primary.get_mut("list") {
287 for item in list {
288 let source = item.clone();
289 projection.apply(&source, item);
290 }
291 }
292 Ok(out)
293}
294
295pub async fn handle_changes<O: JmapObject, B: JmapBackend>(
317 backend: &B,
318 caller: &B::CallerCtx,
319 args: Value,
320 using: &[String],
321) -> Result<HandlerOutput, JmapError> {
322 let (account_id, args) = extract_account_id(args)?;
323 if !backend
324 .account_exists(caller, &account_id)
325 .await
326 .map_err(|e| server_fail_from_backend(&e))?
327 {
328 return Err(JmapError::account_not_found());
329 }
330
331 let since_state: State = match args.get("sinceState").and_then(|v| v.as_str()) {
332 Some(s) => State::from(s),
333 None => return Err(JmapError::invalid_arguments("sinceState is required")),
334 };
335
336 let max_changes = crate::parse_max_changes(args.get("maxChanges"))?;
337
338 let uses_metadata = using
339 .iter()
340 .any(|u| u == jmap_metadata_types::JMAP_METADATA_URI);
341 let ignore_metadata_only_changes = !uses_metadata
342 || match args.get("ignoreMetadataOnlyChanges") {
343 None | Some(Value::Null) => false,
344 Some(Value::Bool(b)) => *b,
345 Some(v) => {
346 return Err(JmapError::invalid_arguments(format!(
347 "ignoreMetadataOnlyChanges: expected a boolean, got {}",
348 crate::helpers::json_type_name(v)
349 )));
350 }
351 };
352
353 let result = backend
354 .get_changes::<O>(
355 caller,
356 &account_id,
357 ChangesParams::new(&since_state)
358 .max_changes(max_changes)
359 .ignore_metadata_only_changes(ignore_metadata_only_changes),
360 )
361 .await
362 .map_err(changes_error_from_backend)?;
363 let updated_properties = if result.updated.is_empty() {
364 None
365 } else {
366 result.updated_properties
367 };
368
369 Ok(HandlerOutput::new(json!({
370 "accountId": account_id.as_ref(),
371 "oldState": since_state.as_ref(),
372 "newState": result.new_state.as_ref(),
373 "hasMoreChanges": result.has_more_changes,
374 "updatedProperties": updated_properties,
375 "created": result.created,
378 "updated": result.updated,
379 "destroyed": result.destroyed,
380 })))
381}
382
383pub async fn handle_query<O: QueryObject, B: JmapBackend>(
396 backend: &B,
397 caller: &B::CallerCtx,
398 args: Value,
399) -> Result<HandlerOutput, JmapError> {
400 let (account_id, mut args) = extract_account_id(args)?;
401 if !backend
402 .account_exists(caller, &account_id)
403 .await
404 .map_err(|e| server_fail_from_backend(&e))?
405 {
406 return Err(JmapError::account_not_found());
407 }
408
409 let calculate_total: bool = args
410 .get("calculateTotal")
411 .and_then(|v| v.as_bool())
412 .unwrap_or(false);
413
414 let limit: Option<u64> = match args.get("limit") {
415 None | Some(Value::Null) => None,
416 Some(v) => match v.as_u64() {
417 Some(n) => Some(n),
418 None => {
419 return Err(JmapError::invalid_arguments(format!(
420 "limit: expected a non-negative integer, got {}",
421 crate::helpers::json_type_name(v)
422 )));
423 }
424 },
425 };
426
427 let position: i64 = match args.get("position") {
428 None | Some(Value::Null) => 0,
429 Some(v) => v.as_i64().ok_or_else(|| {
430 JmapError::invalid_arguments(format!(
431 "position: expected an integer, got {}",
432 crate::helpers::json_type_name(v)
433 ))
434 })?,
435 };
436
437 let (anchor, anchor_offset) = query_anchor_args(&args)?;
438
439 let filter: Option<O::Filter> = filter_arg(&mut args)?;
440
441 let sort: Option<Vec<O::Comparator>> = optional_arg(&mut args, "sort", || {
442 JmapError::invalid_arguments("sort must be an array")
443 })?;
444
445 let result = backend
446 .query_objects::<O>(
447 caller,
448 &account_id,
449 QueryParams::new()
450 .filter(filter.as_ref())
451 .sort(sort.as_deref())
452 .limit(limit)
453 .position(position)
454 .anchor(anchor.as_ref())
455 .anchor_offset(anchor_offset),
456 )
457 .await
458 .map_err(JmapError::from)?;
459
460 let mut resp = json!({
461 "accountId": account_id.as_ref(),
462 "queryState": result.query_state.as_ref(),
463 "canCalculateChanges": result.can_calculate_changes,
464 "position": result.position,
465 "ids": result.ids,
468 });
469 if calculate_total && let Some(t) = result.total {
470 resp["total"] = json!(t);
471 }
472
473 Ok(HandlerOutput::new(resp))
474}
475
476pub async fn handle_query_changes<O: QueryObject, B: JmapBackend>(
487 backend: &B,
488 caller: &B::CallerCtx,
489 args: Value,
490) -> Result<HandlerOutput, JmapError> {
491 let (account_id, mut args) = extract_account_id(args)?;
492 if !backend
493 .account_exists(caller, &account_id)
494 .await
495 .map_err(|e| server_fail_from_backend(&e))?
496 {
497 return Err(JmapError::account_not_found());
498 }
499
500 let since_query_state: State = match args.get("sinceQueryState").and_then(|v| v.as_str()) {
501 Some(s) => State::from(s),
502 None => return Err(JmapError::invalid_arguments("sinceQueryState is required")),
503 };
504
505 let max_changes = crate::parse_max_changes(args.get("maxChanges"))?;
506
507 let up_to_id: Option<Id> = match args.get("upToId") {
508 None | Some(Value::Null) => None,
509 Some(Value::String(s)) => Some(Id::from(s.as_str())),
510 Some(_) => {
511 return Err(JmapError::invalid_arguments(
512 "upToId must be a string Id or null",
513 ));
514 }
515 };
516
517 let calculate_total: bool = args
518 .get("calculateTotal")
519 .and_then(|v| v.as_bool())
520 .unwrap_or(false);
521
522 let filter: Option<O::Filter> = filter_arg(&mut args)?;
523
524 let sort: Option<Vec<O::Comparator>> = optional_arg(&mut args, "sort", || {
525 JmapError::invalid_arguments("sort must be an array")
526 })?;
527
528 let result = backend
529 .query_changes::<O>(
530 caller,
531 &account_id,
532 QueryChangesParams::new(&since_query_state)
533 .filter(filter.as_ref())
534 .sort(sort.as_deref())
535 .max_changes(max_changes)
536 .up_to_id(up_to_id.as_ref()),
537 )
538 .await
539 .map_err(JmapError::from)?;
540
541 let added: Vec<Value> = result
542 .added
543 .iter()
544 .map(|item| {
545 json!({
546 "id": item.id.as_ref(),
547 "index": item.index,
548 })
549 })
550 .collect();
551
552 let mut resp = json!({
553 "accountId": account_id.as_ref(),
554 "oldQueryState": result.old_query_state.as_ref(),
555 "newQueryState": result.new_query_state.as_ref(),
556 "removed": result.removed,
558 "added": added,
559 });
560 if calculate_total && let Some(t) = result.total {
561 resp["total"] = json!(t);
562 }
563
564 Ok(HandlerOutput::new(resp))
565}
566
567#[cfg(test)]
568mod tests {
569 use super::*;
570
571 #[test]
582 fn server_fail_from_backend_drops_display_text() {
583 #[derive(Debug)]
584 struct LeakyError(&'static str);
585 impl std::fmt::Display for LeakyError {
586 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
587 f.write_str(self.0)
588 }
589 }
590 impl std::error::Error for LeakyError {}
591
592 const CANARY: &str = "TOKEN-DO-NOT-LEAK-c0ffee";
593 let err = LeakyError(CANARY);
594
595 let jmap_err = server_fail_from_backend(&err);
596
597 let wire = serde_json::to_value(&jmap_err).expect("JmapError must serialize");
602 let wire_str = wire.to_string();
603 assert!(
604 !wire_str.contains(CANARY),
605 "server_fail_from_backend must not echo backend error Display \
606 onto the wire; got {wire_str}"
607 );
608 assert_eq!(
610 wire["description"], SERVER_FAIL_INTERNAL_DESC,
611 "description must be the static 'internal error' string"
612 );
613 assert_eq!(wire["type"], "serverFail");
614 }
615
616 #[test]
622 fn server_fail_from_backend_accepts_generic_display() {
623 let _ = server_fail_from_backend("a string");
626 let _ = server_fail_from_backend(&"&str".to_owned());
627 let _ = server_fail_from_backend(&42_u64);
628 }
629
630 #[test]
641 fn server_fail_value_from_backend_drops_display_text() {
642 #[derive(Debug)]
643 struct LeakyError(&'static str);
644 impl std::fmt::Display for LeakyError {
645 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
646 f.write_str(self.0)
647 }
648 }
649 impl std::error::Error for LeakyError {}
650
651 const CANARY: &str = "TOKEN-DO-NOT-LEAK-d00d";
652 let err = LeakyError(CANARY);
653
654 let wire = server_fail_value_from_backend(&err);
655
656 let wire_str = wire.to_string();
658 assert!(
659 !wire_str.contains(CANARY),
660 "server_fail_value_from_backend must not echo backend error \
661 Display onto the wire; got {wire_str}"
662 );
663 assert_eq!(wire["type"], "serverFail");
665 assert_eq!(
666 wire["description"], SERVER_FAIL_INTERNAL_DESC,
667 "description must be the static 'internal error' string"
668 );
669 }
670
671 #[test]
677 fn server_fail_value_from_backend_accepts_generic_display() {
678 let _ = server_fail_value_from_backend("a string");
681 let _ = server_fail_value_from_backend(&"owned-String".to_owned());
682 let owned: String = "owned".to_string();
683 let _ = server_fail_value_from_backend(&owned);
684 let _ = server_fail_value_from_backend(&42_u64);
685 }
686
687 use crate::backend::{
692 BackendChangesError, BackendQueryError, ChangesResult, QueryChangesParams,
693 QueryChangesResult, QueryParams,
694 };
695
696 #[derive(serde::Serialize, serde::Deserialize)]
698 struct QueryProbe;
699
700 impl JmapObject for QueryProbe {
701 const TYPE_NAME: &'static str = "QueryProbe";
702 type Property = ();
703 }
704
705 impl QueryObject for QueryProbe {
706 type Filter = Value;
707 type Comparator = Value;
708 }
709
710 #[derive(Debug)]
711 struct LeakyQueryError(&'static str);
712
713 impl std::fmt::Display for LeakyQueryError {
714 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
715 f.write_str(self.0)
716 }
717 }
718
719 impl std::error::Error for LeakyQueryError {}
720
721 enum QueryFailure {
723 Method(JmapError),
725 Internal(&'static str),
728 }
729
730 struct QueryFailBackend(QueryFailure);
733
734 impl JmapBackend for QueryFailBackend {
735 type Error = LeakyQueryError;
736 type CallerCtx = ();
737
738 async fn account_exists(
739 &self,
740 _caller: &(),
741 _account_id: &Id,
742 ) -> Result<bool, Self::Error> {
743 Ok(true)
744 }
745
746 async fn get_objects<O: GetObject + Send + Sync>(
747 &self,
748 _caller: &(),
749 _account_id: &Id,
750 _ids: Option<&[Id]>,
751 _properties: Option<&[String]>,
752 ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
753 unreachable!("only query_objects is exercised")
754 }
755
756 async fn get_state<O: JmapObject + Send + Sync>(
757 &self,
758 _caller: &(),
759 _account_id: &Id,
760 ) -> Result<State, Self::Error> {
761 unreachable!("only query_objects is exercised")
762 }
763
764 async fn get_changes<O: JmapObject + Send + Sync>(
765 &self,
766 _caller: &(),
767 _account_id: &Id,
768 _params: ChangesParams<'_>,
769 ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
770 unreachable!("only query_objects is exercised")
771 }
772
773 async fn query_objects<O: QueryObject + Send + Sync>(
774 &self,
775 _caller: &(),
776 _account_id: &Id,
777 _params: QueryParams<'_, O>,
778 ) -> Result<crate::backend::QueryResult, BackendQueryError<Self::Error>> {
779 Err(match &self.0 {
780 QueryFailure::Method(e) => BackendQueryError::Method(e.clone()),
781 QueryFailure::Internal(text) => BackendQueryError::Other(LeakyQueryError(text)),
782 })
783 }
784
785 async fn query_changes<O: QueryObject + Send + Sync>(
786 &self,
787 _caller: &(),
788 _account_id: &Id,
789 _params: QueryChangesParams<'_, O>,
790 ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
791 unreachable!("only query_objects is exercised")
792 }
793 }
794
795 async fn query_error_wire(failure: QueryFailure) -> Value {
798 let backend = QueryFailBackend(failure);
799 let args = json!({
800 "accountId": "a1",
801 "filter": { "text": "hello" },
802 "anchor": "m1",
803 });
804 let err = match handle_query::<QueryProbe, _>(&backend, &(), args).await {
805 Ok(HandlerOutput { primary: resp, .. }) => {
806 panic!("query_objects failed but handle_query succeeded: {resp}")
807 }
808 Err(e) => e,
809 };
810 serde_json::to_value(&err).expect("JmapError must serialize")
811 }
812
813 #[tokio::test]
826 async fn handle_query_passes_backend_unsupported_filter_through() {
827 let mut expected = JmapError::unsupported_filter();
828 expected.description = Some("Message/query requires a chatId condition".into());
829
830 let wire = query_error_wire(QueryFailure::Method(expected.clone())).await;
831
832 assert_eq!(
833 wire,
834 serde_json::to_value(&expected).expect("JmapError must serialize"),
835 "backend unsupportedFilter must pass through handle_query unchanged"
836 );
837 }
838
839 #[tokio::test]
848 async fn handle_query_passes_backend_anchor_not_found_through() {
849 let expected = JmapError::anchor_not_found();
850
851 let wire = query_error_wire(QueryFailure::Method(expected.clone())).await;
852
853 assert_eq!(
854 wire,
855 serde_json::to_value(&expected).expect("JmapError must serialize"),
856 "backend anchorNotFound must pass through handle_query unchanged"
857 );
858 }
859
860 #[tokio::test]
865 async fn handle_query_redacts_backend_internal_error() {
866 const CANARY: &str = "TOKEN-DO-NOT-LEAK-query-5ca1ab1e";
867
868 let wire = query_error_wire(QueryFailure::Internal(CANARY)).await;
869
870 assert_eq!(wire["type"], "serverFail");
871 assert_eq!(wire["description"], SERVER_FAIL_INTERNAL_DESC);
872 assert!(
873 !wire.to_string().contains(CANARY),
874 "internal backend error Display must not reach the wire; got {wire}"
875 );
876 }
877
878 #[derive(serde::Serialize, serde::Deserialize)]
884 struct GetProbe;
885
886 impl JmapObject for GetProbe {
887 const TYPE_NAME: &'static str = "GetProbe";
888 type Property = ();
889 }
890
891 impl GetObject for GetProbe {}
892
893 struct GetProbeBackend;
896
897 impl JmapBackend for GetProbeBackend {
898 type Error = LeakyQueryError;
899 type CallerCtx = ();
900
901 async fn account_exists(
902 &self,
903 _caller: &(),
904 _account_id: &Id,
905 ) -> Result<bool, Self::Error> {
906 Ok(true)
907 }
908
909 async fn get_objects<O: GetObject + Send + Sync>(
910 &self,
911 _caller: &(),
912 _account_id: &Id,
913 ids: Option<&[Id]>,
914 _properties: Option<&[String]>,
915 ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
916 Ok((vec![], ids.map(<[Id]>::to_vec).unwrap_or_default()))
917 }
918
919 async fn get_state<O: JmapObject + Send + Sync>(
920 &self,
921 _caller: &(),
922 _account_id: &Id,
923 ) -> Result<State, Self::Error> {
924 Ok(State::from("s0"))
925 }
926
927 async fn get_changes<O: JmapObject + Send + Sync>(
928 &self,
929 _caller: &(),
930 _account_id: &Id,
931 _params: ChangesParams<'_>,
932 ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
933 unreachable!("only /get is exercised")
934 }
935
936 async fn query_objects<O: QueryObject + Send + Sync>(
937 &self,
938 _caller: &(),
939 _account_id: &Id,
940 _params: QueryParams<'_, O>,
941 ) -> Result<crate::backend::QueryResult, BackendQueryError<Self::Error>> {
942 unreachable!("only /get is exercised")
943 }
944
945 async fn query_changes<O: QueryObject + Send + Sync>(
946 &self,
947 _caller: &(),
948 _account_id: &Id,
949 _params: QueryChangesParams<'_, O>,
950 ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
951 unreachable!("only /get is exercised")
952 }
953 }
954
955 #[tokio::test]
970 async fn handle_get_over_max_objects_is_request_too_large() {
971 let ids: Vec<String> = (0..501).map(|i| format!("id{i}")).collect();
972 let args = json!({ "accountId": "a1", "ids": ids });
973
974 match handle_get::<GetProbe, _>(&GetProbeBackend, &(), args).await {
975 Ok(HandlerOutput { primary: resp, .. }) => panic!(
976 "501 ids exceed the maxObjectsInGet cap, but handle_get \
977 returned a response with {} notFound ids instead of \
978 requestTooLarge",
979 resp["notFound"].as_array().map_or(0, Vec::len)
980 ),
981 Err(e) => assert_eq!(e.error_type.to_string(), "requestTooLarge"),
982 }
983 }
984
985 #[tokio::test]
996 async fn handle_get_null_ids_is_not_counted_against_cap() {
997 let args = json!({ "accountId": "a1", "ids": null });
998
999 let HandlerOutput { primary: resp, .. } =
1000 handle_get::<GetProbe, _>(&GetProbeBackend, &(), args)
1001 .await
1002 .expect("null ids must not be rejected by the maxObjectsInGet cap");
1003 assert_eq!(resp["list"], json!([]));
1004 }
1005
1006 struct FullObjectBackend;
1010
1011 impl JmapBackend for FullObjectBackend {
1012 type Error = LeakyQueryError;
1013 type CallerCtx = ();
1014
1015 async fn account_exists(
1016 &self,
1017 _caller: &(),
1018 _account_id: &Id,
1019 ) -> Result<bool, Self::Error> {
1020 Ok(true)
1021 }
1022
1023 async fn get_objects<O: GetObject + Send + Sync>(
1024 &self,
1025 _caller: &(),
1026 _account_id: &Id,
1027 _ids: Option<&[Id]>,
1028 _properties: Option<&[String]>,
1029 ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
1030 let obj = serde_json::from_value(json!({
1031 "id": "o1", "name": "n", "color": "c"
1032 }))
1033 .expect("fixture must deserialize");
1034 Ok((vec![obj], vec![]))
1035 }
1036
1037 async fn get_state<O: JmapObject + Send + Sync>(
1038 &self,
1039 _caller: &(),
1040 _account_id: &Id,
1041 ) -> Result<State, Self::Error> {
1042 Ok(State::from("s0"))
1043 }
1044
1045 async fn get_changes<O: JmapObject + Send + Sync>(
1046 &self,
1047 _caller: &(),
1048 _account_id: &Id,
1049 _params: ChangesParams<'_>,
1050 ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
1051 unreachable!("only /get is exercised")
1052 }
1053
1054 async fn query_objects<O: QueryObject + Send + Sync>(
1055 &self,
1056 _caller: &(),
1057 _account_id: &Id,
1058 _params: QueryParams<'_, O>,
1059 ) -> Result<crate::backend::QueryResult, BackendQueryError<Self::Error>> {
1060 unreachable!("only /get is exercised")
1061 }
1062
1063 async fn query_changes<O: QueryObject + Send + Sync>(
1064 &self,
1065 _caller: &(),
1066 _account_id: &Id,
1067 _params: QueryChangesParams<'_, O>,
1068 ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
1069 unreachable!("only /get is exercised")
1070 }
1071 }
1072
1073 #[derive(serde::Serialize, serde::Deserialize)]
1075 struct Swatch {
1076 id: String,
1077 name: String,
1078 color: String,
1079 }
1080
1081 impl JmapObject for Swatch {
1082 const TYPE_NAME: &'static str = "Swatch";
1083 type Property = ();
1084 }
1085
1086 impl GetObject for Swatch {}
1087
1088 #[tokio::test]
1095 async fn handle_get_returns_only_requested_properties_and_id() {
1096 let args = json!({ "accountId": "a1", "ids": ["o1"], "properties": ["name"] });
1097
1098 let HandlerOutput { primary: resp, .. } =
1099 handle_get::<Swatch, _>(&FullObjectBackend, &(), args)
1100 .await
1101 .expect("valid /get must succeed");
1102 assert_eq!(resp["list"], json!([{ "id": "o1", "name": "n" }]));
1103 }
1104
1105 #[tokio::test]
1108 async fn handle_get_null_properties_returns_all() {
1109 let args = json!({ "accountId": "a1", "ids": ["o1"], "properties": null });
1110
1111 let HandlerOutput { primary: resp, .. } =
1112 handle_get::<Swatch, _>(&FullObjectBackend, &(), args)
1113 .await
1114 .expect("valid /get must succeed");
1115 assert_eq!(
1116 resp["list"],
1117 json!([{ "id": "o1", "name": "n", "color": "c" }])
1118 );
1119 }
1120
1121 #[derive(Default)]
1125 struct RecordingQueryBackend(std::sync::Mutex<Option<Value>>);
1126
1127 impl RecordingQueryBackend {
1128 fn take(&self) -> Value {
1129 self.0
1130 .lock()
1131 .unwrap()
1132 .take()
1133 .expect("backend query method was not called")
1134 }
1135 }
1136
1137 impl JmapBackend for RecordingQueryBackend {
1138 type Error = LeakyQueryError;
1139 type CallerCtx = ();
1140
1141 async fn account_exists(
1142 &self,
1143 _caller: &(),
1144 _account_id: &Id,
1145 ) -> Result<bool, Self::Error> {
1146 Ok(true)
1147 }
1148
1149 async fn get_objects<O: GetObject + Send + Sync>(
1150 &self,
1151 _caller: &(),
1152 _account_id: &Id,
1153 _ids: Option<&[Id]>,
1154 _properties: Option<&[String]>,
1155 ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
1156 unreachable!("only queries are exercised")
1157 }
1158
1159 async fn get_state<O: JmapObject + Send + Sync>(
1160 &self,
1161 _caller: &(),
1162 _account_id: &Id,
1163 ) -> Result<State, Self::Error> {
1164 unreachable!("only queries are exercised")
1165 }
1166
1167 async fn get_changes<O: JmapObject + Send + Sync>(
1168 &self,
1169 _caller: &(),
1170 _account_id: &Id,
1171 _params: ChangesParams<'_>,
1172 ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
1173 unreachable!("only queries are exercised")
1174 }
1175
1176 async fn query_objects<O: QueryObject + Send + Sync>(
1177 &self,
1178 _caller: &(),
1179 _account_id: &Id,
1180 params: QueryParams<'_, O>,
1181 ) -> Result<crate::backend::QueryResult, BackendQueryError<Self::Error>> {
1182 *self.0.lock().unwrap() = Some(json!({
1183 "filter": params.filter.map(|f| serde_json::to_value(f).unwrap()),
1184 "sort": params.sort.map(|s| serde_json::to_value(s).unwrap()),
1185 "limit": params.limit,
1186 "position": params.position,
1187 "anchor": params.anchor,
1188 "anchorOffset": params.anchor_offset,
1189 }));
1190 Ok(crate::backend::QueryResult::new(
1191 vec![],
1192 0,
1193 None,
1194 State::from("q0"),
1195 false,
1196 ))
1197 }
1198
1199 async fn query_changes<O: QueryObject + Send + Sync>(
1200 &self,
1201 _caller: &(),
1202 _account_id: &Id,
1203 params: QueryChangesParams<'_, O>,
1204 ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
1205 *self.0.lock().unwrap() = Some(json!({
1206 "sinceQueryState": params.since_query_state,
1207 "filter": params.filter.map(|f| serde_json::to_value(f).unwrap()),
1208 "sort": params.sort.map(|s| serde_json::to_value(s).unwrap()),
1209 "maxChanges": params.max_changes,
1210 "upToId": params.up_to_id,
1211 "collapseThreads": params.collapse_threads,
1212 }));
1213 Ok(QueryChangesResult::new(
1214 params.since_query_state.clone(),
1215 State::from("q2"),
1216 None,
1217 vec![],
1218 vec![],
1219 ))
1220 }
1221 }
1222
1223 #[tokio::test]
1228 async fn handle_query_passes_every_argument_to_backend() {
1229 let backend = RecordingQueryBackend::default();
1230 let args = json!({
1231 "accountId": "a1",
1232 "filter": {"text": "hello"},
1233 "sort": [{"property": "receivedAt", "isAscending": false}],
1234 "position": 3,
1235 "anchor": "m7",
1236 "anchorOffset": -2,
1237 "limit": 25,
1238 });
1239 handle_query::<QueryProbe, _>(&backend, &(), args)
1240 .await
1241 .expect("query must succeed");
1242 assert_eq!(
1243 backend.take(),
1244 json!({
1245 "filter": {"text": "hello"},
1246 "sort": [{"property": "receivedAt", "isAscending": false}],
1247 "limit": 25,
1248 "position": 3,
1249 "anchor": "m7",
1250 "anchorOffset": -2,
1251 })
1252 );
1253 }
1254
1255 #[tokio::test]
1260 async fn handle_query_omitted_arguments_reach_backend_as_rfc_defaults() {
1261 let backend = RecordingQueryBackend::default();
1262 handle_query::<QueryProbe, _>(&backend, &(), json!({"accountId": "a1"}))
1263 .await
1264 .expect("query must succeed");
1265 assert_eq!(
1266 backend.take(),
1267 json!({
1268 "filter": null,
1269 "sort": null,
1270 "limit": null,
1271 "position": 0,
1272 "anchor": null,
1273 "anchorOffset": 0,
1274 })
1275 );
1276 }
1277
1278 #[tokio::test]
1285 async fn handle_query_changes_passes_every_argument_to_backend() {
1286 let backend = RecordingQueryBackend::default();
1287 let args = json!({
1288 "accountId": "a1",
1289 "filter": {"text": "hello"},
1290 "sort": [{"property": "receivedAt"}],
1291 "sinceQueryState": "q1",
1292 "maxChanges": 10,
1293 "upToId": "m9",
1294 });
1295 handle_query_changes::<QueryProbe, _>(&backend, &(), args)
1296 .await
1297 .expect("queryChanges must succeed");
1298 assert_eq!(
1299 backend.take(),
1300 json!({
1301 "sinceQueryState": "q1",
1302 "filter": {"text": "hello"},
1303 "sort": [{"property": "receivedAt"}],
1304 "maxChanges": 10,
1305 "upToId": "m9",
1306 "collapseThreads": false,
1307 })
1308 );
1309 }
1310
1311 #[tokio::test]
1319 async fn non_object_filter_is_invalid_arguments() {
1320 for filter in [json!(42), json!("text"), json!(true), json!([])] {
1321 let backend = RecordingQueryBackend::default();
1322 let err = handle_query::<QueryProbe, _>(
1323 &backend,
1324 &(),
1325 json!({"accountId": "a1", "filter": filter}),
1326 )
1327 .await
1328 .expect_err("non-object filter must be rejected");
1329 assert_eq!(err.error_type.to_string(), "invalidArguments", "{filter}");
1330
1331 let err = handle_query_changes::<QueryProbe, _>(
1332 &backend,
1333 &(),
1334 json!({"accountId": "a1", "filter": filter, "sinceQueryState": "q1"}),
1335 )
1336 .await
1337 .expect_err("non-object filter must be rejected");
1338 assert_eq!(err.error_type.to_string(), "invalidArguments", "{filter}");
1339 assert!(backend.0.lock().unwrap().is_none(), "{filter}");
1340 }
1341 }
1342
1343 #[derive(Clone, Copy)]
1351 enum Canned {
1352 Ok,
1354 CannotCalculate,
1356 TooManyChanges(u64),
1358 Internal(&'static str),
1360 }
1361
1362 impl Canned {
1363 fn changes_error(self) -> BackendChangesError<LeakyQueryError> {
1364 match self {
1365 Canned::Ok => unreachable!("Canned::Ok is not an error"),
1366 Canned::CannotCalculate => BackendChangesError::CannotCalculate,
1367 Canned::TooManyChanges(limit) => BackendChangesError::TooManyChanges { limit },
1368 Canned::Internal(text) => BackendChangesError::Other(LeakyQueryError(text)),
1369 }
1370 }
1371 }
1372
1373 struct CannedBackend {
1377 account_exists: bool,
1378 outcome: Canned,
1379 }
1380
1381 const CANNED_OK: CannedBackend = CannedBackend {
1382 account_exists: true,
1383 outcome: Canned::Ok,
1384 };
1385
1386 impl JmapBackend for CannedBackend {
1387 type Error = LeakyQueryError;
1388 type CallerCtx = ();
1389
1390 async fn account_exists(
1391 &self,
1392 _caller: &(),
1393 _account_id: &Id,
1394 ) -> Result<bool, Self::Error> {
1395 Ok(self.account_exists)
1396 }
1397
1398 async fn get_objects<O: GetObject + Send + Sync>(
1399 &self,
1400 _caller: &(),
1401 _account_id: &Id,
1402 _ids: Option<&[Id]>,
1403 _properties: Option<&[String]>,
1404 ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
1405 unreachable!("/get is not exercised")
1406 }
1407
1408 async fn get_state<O: JmapObject + Send + Sync>(
1409 &self,
1410 _caller: &(),
1411 _account_id: &Id,
1412 ) -> Result<State, Self::Error> {
1413 unreachable!("/get is not exercised")
1414 }
1415
1416 async fn get_changes<O: JmapObject + Send + Sync>(
1417 &self,
1418 _caller: &(),
1419 _account_id: &Id,
1420 _params: ChangesParams<'_>,
1421 ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
1422 match self.outcome {
1423 Canned::Ok => Ok(ChangesResult::new(
1424 vec![Id::from("c1")],
1425 vec![Id::from("u1")],
1426 vec![Id::from("d1")],
1427 true,
1428 State::from("s2"),
1429 )),
1430 other => Err(other.changes_error()),
1431 }
1432 }
1433
1434 async fn query_objects<O: QueryObject + Send + Sync>(
1435 &self,
1436 _caller: &(),
1437 _account_id: &Id,
1438 _params: QueryParams<'_, O>,
1439 ) -> Result<crate::backend::QueryResult, BackendQueryError<Self::Error>> {
1440 Ok(crate::backend::QueryResult::new(
1441 vec![Id::from("m1")],
1442 0,
1443 Some(7),
1444 State::from("q1"),
1445 true,
1446 ))
1447 }
1448
1449 async fn query_changes<O: QueryObject + Send + Sync>(
1450 &self,
1451 _caller: &(),
1452 _account_id: &Id,
1453 params: QueryChangesParams<'_, O>,
1454 ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
1455 match self.outcome {
1456 Canned::Ok => Ok(QueryChangesResult::new(
1457 params.since_query_state.clone(),
1458 State::from("q2"),
1459 Some(7),
1460 vec![Id::from("r1")],
1461 vec![crate::backend::AddedItem::new(Id::from("n1"), 0)],
1462 )),
1463 other => Err(other.changes_error()),
1464 }
1465 }
1466 }
1467
1468 #[tokio::test]
1475 async fn handle_changes_response_matches_rfc_shape() {
1476 let HandlerOutput { primary: resp, .. } = handle_changes::<QueryProbe, _>(
1477 &CANNED_OK,
1478 &(),
1479 json!({"accountId": "a1", "sinceState": "s1"}),
1480 &[],
1481 )
1482 .await
1483 .expect("/changes must succeed");
1484 assert_eq!(
1485 resp,
1486 json!({
1487 "accountId": "a1",
1488 "oldState": "s1",
1489 "newState": "s2",
1490 "hasMoreChanges": true,
1491 "updatedProperties": null,
1492 "created": ["c1"],
1493 "updated": ["u1"],
1494 "destroyed": ["d1"],
1495 })
1496 );
1497 }
1498
1499 const CORE: &str = "urn:ietf:params:jmap:core";
1504 const METADATA: &str = "urn:ietf:params:jmap:metadata";
1505
1506 struct MetadataChangesBackend {
1510 updated: Vec<Id>,
1511 updated_properties: Option<Vec<String>>,
1512 seen_ignore: std::sync::Mutex<Option<bool>>,
1513 }
1514
1515 impl MetadataChangesBackend {
1516 fn new(updated: &[&str], updated_properties: Option<&[&str]>) -> Self {
1517 Self {
1518 updated: updated.iter().map(|u| Id::from(*u)).collect(),
1519 updated_properties: updated_properties
1520 .map(|p| p.iter().map(|s| (*s).to_owned()).collect()),
1521 seen_ignore: std::sync::Mutex::new(None),
1522 }
1523 }
1524 }
1525
1526 impl JmapBackend for MetadataChangesBackend {
1527 type Error = LeakyQueryError;
1528 type CallerCtx = ();
1529
1530 async fn account_exists(
1531 &self,
1532 _caller: &(),
1533 _account_id: &Id,
1534 ) -> Result<bool, Self::Error> {
1535 Ok(true)
1536 }
1537
1538 async fn get_objects<O: GetObject + Send + Sync>(
1539 &self,
1540 _caller: &(),
1541 _account_id: &Id,
1542 _ids: Option<&[Id]>,
1543 _properties: Option<&[String]>,
1544 ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
1545 unreachable!("only get_changes is exercised")
1546 }
1547
1548 async fn get_state<O: JmapObject + Send + Sync>(
1549 &self,
1550 _caller: &(),
1551 _account_id: &Id,
1552 ) -> Result<State, Self::Error> {
1553 unreachable!("only get_changes is exercised")
1554 }
1555
1556 async fn get_changes<O: JmapObject + Send + Sync>(
1557 &self,
1558 _caller: &(),
1559 _account_id: &Id,
1560 params: ChangesParams<'_>,
1561 ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
1562 *self.seen_ignore.lock().unwrap() = Some(params.ignore_metadata_only_changes);
1563 Ok(ChangesResult::new(
1564 Vec::new(),
1565 self.updated.clone(),
1566 Vec::new(),
1567 false,
1568 State::from("s2"),
1569 )
1570 .with_updated_properties(self.updated_properties.clone()))
1571 }
1572
1573 async fn query_objects<O: QueryObject + Send + Sync>(
1574 &self,
1575 _caller: &(),
1576 _account_id: &Id,
1577 _params: QueryParams<'_, O>,
1578 ) -> Result<crate::backend::QueryResult, BackendQueryError<Self::Error>> {
1579 unreachable!("only get_changes is exercised")
1580 }
1581
1582 async fn query_changes<O: QueryObject + Send + Sync>(
1583 &self,
1584 _caller: &(),
1585 _account_id: &Id,
1586 _params: QueryChangesParams<'_, O>,
1587 ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
1588 unreachable!("only get_changes is exercised")
1589 }
1590 }
1591
1592 async fn ignore_seen(using: &[&str], extra: Value) -> bool {
1595 let backend = MetadataChangesBackend::new(&["u1"], None);
1596 let mut args = json!({"accountId": "a1", "sinceState": "s1"});
1597 if let Value::Object(extra) = extra {
1598 args.as_object_mut().unwrap().extend(extra);
1599 }
1600 let using: Vec<String> = using.iter().map(|u| (*u).to_owned()).collect();
1601 handle_changes::<QueryProbe, _>(&backend, &(), args, &using)
1602 .await
1603 .expect("/changes must succeed");
1604 backend
1605 .seen_ignore
1606 .lock()
1607 .unwrap()
1608 .expect("backend must be called")
1609 }
1610
1611 #[tokio::test]
1618 async fn changes_without_metadata_capability_ignores_metadata_only_changes() {
1619 assert!(ignore_seen(&[CORE], json!({})).await);
1620 assert!(ignore_seen(&[CORE], json!({"ignoreMetadataOnlyChanges": false})).await);
1621 assert!(ignore_seen(&[CORE], json!({"ignoreMetadataOnlyChanges": "no"})).await);
1622 assert!(ignore_seen(&[], json!({})).await);
1623 }
1624
1625 #[tokio::test]
1628 async fn changes_with_metadata_capability_passes_ignore_argument() {
1629 assert!(!ignore_seen(&[CORE, METADATA], json!({})).await);
1630 assert!(
1631 !ignore_seen(
1632 &[CORE, METADATA],
1633 json!({"ignoreMetadataOnlyChanges": null})
1634 )
1635 .await
1636 );
1637 assert!(
1638 !ignore_seen(
1639 &[CORE, METADATA],
1640 json!({"ignoreMetadataOnlyChanges": false})
1641 )
1642 .await
1643 );
1644 assert!(
1645 ignore_seen(
1646 &[CORE, METADATA],
1647 json!({"ignoreMetadataOnlyChanges": true})
1648 )
1649 .await
1650 );
1651 }
1652
1653 #[tokio::test]
1657 async fn changes_rejects_non_boolean_ignore_argument() {
1658 let backend = MetadataChangesBackend::new(&["u1"], None);
1659 let err = handle_changes::<QueryProbe, _>(
1660 &backend,
1661 &(),
1662 json!({"accountId": "a1", "sinceState": "s1", "ignoreMetadataOnlyChanges": "yes"}),
1663 &[CORE.to_owned(), METADATA.to_owned()],
1664 )
1665 .await
1666 .expect_err("a string ignoreMetadataOnlyChanges must fail");
1667 assert_eq!(err.error_type.to_string(), "invalidArguments");
1668 assert!(
1669 backend.seen_ignore.lock().unwrap().is_none(),
1670 "backend must not be called"
1671 );
1672 }
1673
1674 #[tokio::test]
1681 async fn changes_reports_backend_updated_properties() {
1682 let backend = MetadataChangesBackend::new(&["u1"], Some(&["metadata"]));
1683 let HandlerOutput { primary: resp, .. } = handle_changes::<QueryProbe, _>(
1684 &backend,
1685 &(),
1686 json!({"accountId": "a1", "sinceState": "s1"}),
1687 &[CORE.to_owned(), METADATA.to_owned()],
1688 )
1689 .await
1690 .expect("/changes must succeed");
1691 assert_eq!(
1692 resp,
1693 json!({
1694 "accountId": "a1",
1695 "oldState": "s1",
1696 "newState": "s2",
1697 "hasMoreChanges": false,
1698 "updatedProperties": ["metadata"],
1699 "created": [],
1700 "updated": ["u1"],
1701 "destroyed": [],
1702 })
1703 );
1704 }
1705
1706 #[tokio::test]
1709 async fn changes_updated_properties_null_when_updated_empty() {
1710 let backend = MetadataChangesBackend::new(&[], Some(&["metadata"]));
1711 let HandlerOutput { primary: resp, .. } = handle_changes::<QueryProbe, _>(
1712 &backend,
1713 &(),
1714 json!({"accountId": "a1", "sinceState": "s1"}),
1715 &[CORE.to_owned(), METADATA.to_owned()],
1716 )
1717 .await
1718 .expect("/changes must succeed");
1719 assert_eq!(resp["updatedProperties"], Value::Null);
1720 assert!(
1721 resp.as_object().unwrap().contains_key("updatedProperties"),
1722 "updatedProperties must be present"
1723 );
1724 }
1725
1726 #[tokio::test]
1732 async fn handle_query_changes_response_matches_rfc_shape() {
1733 let HandlerOutput { primary: resp, .. } = handle_query_changes::<QueryProbe, _>(
1734 &CANNED_OK,
1735 &(),
1736 json!({"accountId": "a1", "sinceQueryState": "q1", "calculateTotal": true}),
1737 )
1738 .await
1739 .expect("/queryChanges must succeed");
1740 assert_eq!(
1741 resp,
1742 json!({
1743 "accountId": "a1",
1744 "oldQueryState": "q1",
1745 "newQueryState": "q2",
1746 "total": 7,
1747 "removed": ["r1"],
1748 "added": [{"id": "n1", "index": 0}],
1749 })
1750 );
1751
1752 let HandlerOutput { primary: resp, .. } = handle_query_changes::<QueryProbe, _>(
1753 &CANNED_OK,
1754 &(),
1755 json!({"accountId": "a1", "sinceQueryState": "q1"}),
1756 )
1757 .await
1758 .expect("/queryChanges must succeed");
1759 assert!(
1760 resp.get("total").is_none(),
1761 "total must be omitted without calculateTotal; got {resp}"
1762 );
1763 }
1764
1765 #[tokio::test]
1769 async fn handle_query_total_only_when_requested() {
1770 for (calculate_total, expected) in [(json!(true), Some(json!(7))), (json!(false), None)] {
1771 let HandlerOutput { primary: resp, .. } = handle_query::<QueryProbe, _>(
1772 &CANNED_OK,
1773 &(),
1774 json!({"accountId": "a1", "calculateTotal": calculate_total}),
1775 )
1776 .await
1777 .expect("/query must succeed");
1778 assert_eq!(resp.get("total").cloned(), expected, "{resp}");
1779 }
1780 }
1781
1782 #[tokio::test]
1787 async fn missing_or_non_string_since_state_is_invalid_arguments() {
1788 for since in [None, Some(json!(42))] {
1789 let mut args = json!({"accountId": "a1"});
1790 if let Some(v) = &since {
1791 args["sinceState"] = v.clone();
1792 }
1793 let err = handle_changes::<QueryProbe, _>(&CANNED_OK, &(), args, &[])
1794 .await
1795 .expect_err("/changes without a string sinceState must fail");
1796 assert_eq!(err.error_type.to_string(), "invalidArguments", "{since:?}");
1797
1798 let mut args = json!({"accountId": "a1"});
1799 if let Some(v) = &since {
1800 args["sinceQueryState"] = v.clone();
1801 }
1802 let err = handle_query_changes::<QueryProbe, _>(&CANNED_OK, &(), args)
1803 .await
1804 .expect_err("/queryChanges without a string sinceQueryState must fail");
1805 assert_eq!(err.error_type.to_string(), "invalidArguments", "{since:?}");
1806 }
1807 }
1808
1809 #[tokio::test]
1812 async fn non_string_up_to_id_is_invalid_arguments() {
1813 for up_to_id in [json!(5), json!(true), json!(["m1"]), json!({})] {
1814 let err = handle_query_changes::<QueryProbe, _>(
1815 &CANNED_OK,
1816 &(),
1817 json!({"accountId": "a1", "sinceQueryState": "q1", "upToId": up_to_id}),
1818 )
1819 .await
1820 .expect_err("non-Id upToId must be rejected");
1821 assert_eq!(err.error_type.to_string(), "invalidArguments", "{up_to_id}");
1822 }
1823 }
1824
1825 #[tokio::test]
1829 async fn handle_query_negative_limit_is_invalid_arguments() {
1830 let backend = RecordingQueryBackend::default();
1831 let err =
1832 handle_query::<QueryProbe, _>(&backend, &(), json!({"accountId": "a1", "limit": -1}))
1833 .await
1834 .expect_err("negative limit must be rejected");
1835 assert_eq!(err.error_type.to_string(), "invalidArguments");
1836 assert!(
1837 backend.0.lock().unwrap().is_none(),
1838 "backend must not be consulted"
1839 );
1840 }
1841
1842 #[tokio::test]
1848 async fn handle_query_negative_position_reaches_backend() {
1849 let backend = RecordingQueryBackend::default();
1850 handle_query::<QueryProbe, _>(&backend, &(), json!({"accountId": "a1", "position": -5}))
1851 .await
1852 .expect("negative position is valid");
1853 assert_eq!(backend.take()["position"], json!(-5));
1854 }
1855
1856 #[tokio::test]
1865 async fn changes_backend_errors_map_to_rfc_errors() {
1866 const CANARY: &str = "TOKEN-DO-NOT-LEAK-changes-b0a710ad";
1867 for (outcome, changes_type, query_changes_type) in [
1868 (
1869 Canned::CannotCalculate,
1870 "cannotCalculateChanges",
1871 "cannotCalculateChanges",
1872 ),
1873 (
1874 Canned::TooManyChanges(10),
1875 "cannotCalculateChanges",
1876 "tooManyChanges",
1877 ),
1878 (Canned::Internal(CANARY), "serverFail", "serverFail"),
1879 ] {
1880 let backend = CannedBackend {
1881 account_exists: true,
1882 outcome,
1883 };
1884 let changes = handle_changes::<QueryProbe, _>(
1885 &backend,
1886 &(),
1887 json!({"accountId": "a1", "sinceState": "s1"}),
1888 &[],
1889 )
1890 .await;
1891 let query_changes = handle_query_changes::<QueryProbe, _>(
1892 &backend,
1893 &(),
1894 json!({"accountId": "a1", "sinceQueryState": "q1"}),
1895 )
1896 .await;
1897 for (result, expected_type) in
1898 [(changes, changes_type), (query_changes, query_changes_type)]
1899 {
1900 let err = result.expect_err("backend error must fail the call");
1901 let wire = serde_json::to_value(&err).expect("JmapError must serialize");
1902 assert_eq!(wire["type"], expected_type, "{wire}");
1903 assert!(!wire.to_string().contains(CANARY), "leaked: {wire}");
1904 }
1905 }
1906 }
1907
1908 #[tokio::test]
1911 async fn unknown_account_is_account_not_found() {
1912 let backend = CannedBackend {
1913 account_exists: false,
1914 outcome: Canned::Ok,
1915 };
1916 let results = [
1917 handle_changes::<QueryProbe, _>(
1918 &backend,
1919 &(),
1920 json!({"accountId": "nope", "sinceState": "s1"}),
1921 &[],
1922 )
1923 .await,
1924 handle_query::<QueryProbe, _>(&backend, &(), json!({"accountId": "nope"})).await,
1925 handle_query_changes::<QueryProbe, _>(
1926 &backend,
1927 &(),
1928 json!({"accountId": "nope", "sinceQueryState": "q1"}),
1929 )
1930 .await,
1931 ];
1932 for result in results {
1933 let err = result.expect_err("unknown account must fail");
1934 assert_eq!(err.error_type.to_string(), "accountNotFound");
1935 }
1936 }
1937
1938 #[tokio::test]
1943 async fn handle_query_does_not_echo_wrongly_typed_value() {
1944 for name in ["limit", "position"] {
1945 let backend = RecordingQueryBackend::default();
1946 let mut args = json!({ "accountId": "a1" });
1947 args[name] = json!({ "note": "CANARY-zegc" });
1948 let err = handle_query::<QueryProbe, _>(&backend, &(), args)
1949 .await
1950 .expect_err("wrongly typed argument must be rejected");
1951 assert_eq!(err.error_type.to_string(), "invalidArguments", "{name}");
1952 let desc = err.description.as_deref().unwrap_or_default();
1953 assert!(desc.starts_with(name), "{desc}");
1954 assert!(desc.contains("got object"), "{desc}");
1955 assert!(!desc.contains("CANARY"), "{desc}");
1956 }
1957 }
1958}