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 list_json = serialize_value(&list)?;
209
210 Ok(HandlerOutput::new(json!({
211 "accountId": account_id.as_ref(),
212 "state": state.as_ref(),
213 "list": list_json,
214 "notFound": not_found_json(¬_found),
215 })))
216}
217
218pub async fn handle_get_with_metadata<O: GetObject, B: JmapBackend>(
237 backend: &B,
238 caller: &B::CallerCtx,
239 mut args: Value,
240 using: &[String],
241) -> Result<HandlerOutput, JmapError> {
242 let info = args
243 .get("accountId")
244 .and_then(Value::as_str)
245 .and_then(|s| Id::new_validated(s).ok())
246 .and_then(|id| backend.metadata_info::<O>(caller, &id));
247 let Some(info) = info else {
248 return handle_get::<O, B>(backend, caller, args).await;
249 };
250 let properties: Option<Vec<String>> = match args.get("properties") {
251 None | Some(Value::Null) => None,
252 Some(v) => match serde_json::from_value(v.clone()) {
253 Ok(props) => Some(props),
254 Err(_) => return handle_get::<O, B>(backend, caller, args).await,
256 },
257 };
258 let projection = MetadataProjection::new(properties.as_deref(), true, using, Some(&info))?;
259 if let Some(props) = properties {
260 let mut roots: Vec<String> = Vec::with_capacity(props.len());
261 for p in props {
262 let root = match p.split_once('/') {
263 Some((r @ ("metadata" | "privateMetadata"), _)) => r.to_owned(),
264 _ => p,
265 };
266 if !roots.contains(&root) {
267 roots.push(root);
268 }
269 }
270 args["properties"] = json!(roots);
271 }
272 let mut out = handle_get::<O, B>(backend, caller, args).await?;
273 if let Some(Value::Array(list)) = out.primary.get_mut("list") {
274 for item in list {
275 let source = item.clone();
276 projection.apply(&source, item);
277 }
278 }
279 Ok(out)
280}
281
282pub async fn handle_changes<O: JmapObject, B: JmapBackend>(
304 backend: &B,
305 caller: &B::CallerCtx,
306 args: Value,
307 using: &[String],
308) -> Result<HandlerOutput, JmapError> {
309 let (account_id, args) = extract_account_id(args)?;
310 if !backend
311 .account_exists(caller, &account_id)
312 .await
313 .map_err(|e| server_fail_from_backend(&e))?
314 {
315 return Err(JmapError::account_not_found());
316 }
317
318 let since_state: State = match args.get("sinceState").and_then(|v| v.as_str()) {
319 Some(s) => State::from(s),
320 None => return Err(JmapError::invalid_arguments("sinceState is required")),
321 };
322
323 let max_changes = crate::parse_max_changes(args.get("maxChanges"))?;
324
325 let uses_metadata = using
326 .iter()
327 .any(|u| u == jmap_metadata_types::JMAP_METADATA_URI);
328 let ignore_metadata_only_changes = !uses_metadata
329 || match args.get("ignoreMetadataOnlyChanges") {
330 None | Some(Value::Null) => false,
331 Some(Value::Bool(b)) => *b,
332 Some(v) => {
333 return Err(JmapError::invalid_arguments(format!(
334 "ignoreMetadataOnlyChanges: expected a boolean, got {}",
335 crate::helpers::json_type_name(v)
336 )));
337 }
338 };
339
340 let result = backend
341 .get_changes::<O>(
342 caller,
343 &account_id,
344 ChangesParams::new(&since_state)
345 .max_changes(max_changes)
346 .ignore_metadata_only_changes(ignore_metadata_only_changes),
347 )
348 .await
349 .map_err(changes_error_from_backend)?;
350 let updated_properties = if result.updated.is_empty() {
351 None
352 } else {
353 result.updated_properties
354 };
355
356 Ok(HandlerOutput::new(json!({
357 "accountId": account_id.as_ref(),
358 "oldState": since_state.as_ref(),
359 "newState": result.new_state.as_ref(),
360 "hasMoreChanges": result.has_more_changes,
361 "updatedProperties": updated_properties,
362 "created": result.created,
365 "updated": result.updated,
366 "destroyed": result.destroyed,
367 })))
368}
369
370pub async fn handle_query<O: QueryObject, B: JmapBackend>(
383 backend: &B,
384 caller: &B::CallerCtx,
385 args: Value,
386) -> Result<HandlerOutput, JmapError> {
387 let (account_id, mut args) = extract_account_id(args)?;
388 if !backend
389 .account_exists(caller, &account_id)
390 .await
391 .map_err(|e| server_fail_from_backend(&e))?
392 {
393 return Err(JmapError::account_not_found());
394 }
395
396 let calculate_total: bool = args
397 .get("calculateTotal")
398 .and_then(|v| v.as_bool())
399 .unwrap_or(false);
400
401 let limit: Option<u64> = match args.get("limit") {
402 None | Some(Value::Null) => None,
403 Some(v) => match v.as_u64() {
404 Some(n) => Some(n),
405 None => {
406 return Err(JmapError::invalid_arguments(format!(
407 "limit: expected a non-negative integer, got {}",
408 crate::helpers::json_type_name(v)
409 )));
410 }
411 },
412 };
413
414 let position: i64 = match args.get("position") {
415 None | Some(Value::Null) => 0,
416 Some(v) => v.as_i64().ok_or_else(|| {
417 JmapError::invalid_arguments(format!(
418 "position: expected an integer, got {}",
419 crate::helpers::json_type_name(v)
420 ))
421 })?,
422 };
423
424 let (anchor, anchor_offset) = query_anchor_args(&args)?;
425
426 let filter: Option<O::Filter> = filter_arg(&mut args)?;
427
428 let sort: Option<Vec<O::Comparator>> = optional_arg(&mut args, "sort", || {
429 JmapError::invalid_arguments("sort must be an array")
430 })?;
431
432 let result = backend
433 .query_objects::<O>(
434 caller,
435 &account_id,
436 QueryParams::new()
437 .filter(filter.as_ref())
438 .sort(sort.as_deref())
439 .limit(limit)
440 .position(position)
441 .anchor(anchor.as_ref())
442 .anchor_offset(anchor_offset),
443 )
444 .await
445 .map_err(JmapError::from)?;
446
447 let mut resp = json!({
448 "accountId": account_id.as_ref(),
449 "queryState": result.query_state.as_ref(),
450 "canCalculateChanges": result.can_calculate_changes,
451 "position": result.position,
452 "ids": result.ids,
455 });
456 if calculate_total && let Some(t) = result.total {
457 resp["total"] = json!(t);
458 }
459
460 Ok(HandlerOutput::new(resp))
461}
462
463pub async fn handle_query_changes<O: QueryObject, B: JmapBackend>(
474 backend: &B,
475 caller: &B::CallerCtx,
476 args: Value,
477) -> Result<HandlerOutput, JmapError> {
478 let (account_id, mut args) = extract_account_id(args)?;
479 if !backend
480 .account_exists(caller, &account_id)
481 .await
482 .map_err(|e| server_fail_from_backend(&e))?
483 {
484 return Err(JmapError::account_not_found());
485 }
486
487 let since_query_state: State = match args.get("sinceQueryState").and_then(|v| v.as_str()) {
488 Some(s) => State::from(s),
489 None => return Err(JmapError::invalid_arguments("sinceQueryState is required")),
490 };
491
492 let max_changes = crate::parse_max_changes(args.get("maxChanges"))?;
493
494 let up_to_id: Option<Id> = match args.get("upToId") {
495 None | Some(Value::Null) => None,
496 Some(Value::String(s)) => Some(Id::from(s.as_str())),
497 Some(_) => {
498 return Err(JmapError::invalid_arguments(
499 "upToId must be a string Id or null",
500 ));
501 }
502 };
503
504 let calculate_total: bool = args
505 .get("calculateTotal")
506 .and_then(|v| v.as_bool())
507 .unwrap_or(false);
508
509 let filter: Option<O::Filter> = filter_arg(&mut args)?;
510
511 let sort: Option<Vec<O::Comparator>> = optional_arg(&mut args, "sort", || {
512 JmapError::invalid_arguments("sort must be an array")
513 })?;
514
515 let result = backend
516 .query_changes::<O>(
517 caller,
518 &account_id,
519 QueryChangesParams::new(&since_query_state)
520 .filter(filter.as_ref())
521 .sort(sort.as_deref())
522 .max_changes(max_changes)
523 .up_to_id(up_to_id.as_ref()),
524 )
525 .await
526 .map_err(JmapError::from)?;
527
528 let added: Vec<Value> = result
529 .added
530 .iter()
531 .map(|item| {
532 json!({
533 "id": item.id.as_ref(),
534 "index": item.index,
535 })
536 })
537 .collect();
538
539 let mut resp = json!({
540 "accountId": account_id.as_ref(),
541 "oldQueryState": result.old_query_state.as_ref(),
542 "newQueryState": result.new_query_state.as_ref(),
543 "removed": result.removed,
545 "added": added,
546 });
547 if calculate_total && let Some(t) = result.total {
548 resp["total"] = json!(t);
549 }
550
551 Ok(HandlerOutput::new(resp))
552}
553
554#[cfg(test)]
555mod tests {
556 use super::*;
557
558 #[test]
569 fn server_fail_from_backend_drops_display_text() {
570 #[derive(Debug)]
571 struct LeakyError(&'static str);
572 impl std::fmt::Display for LeakyError {
573 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
574 f.write_str(self.0)
575 }
576 }
577 impl std::error::Error for LeakyError {}
578
579 const CANARY: &str = "TOKEN-DO-NOT-LEAK-c0ffee";
580 let err = LeakyError(CANARY);
581
582 let jmap_err = server_fail_from_backend(&err);
583
584 let wire = serde_json::to_value(&jmap_err).expect("JmapError must serialize");
589 let wire_str = wire.to_string();
590 assert!(
591 !wire_str.contains(CANARY),
592 "server_fail_from_backend must not echo backend error Display \
593 onto the wire; got {wire_str}"
594 );
595 assert_eq!(
597 wire["description"], SERVER_FAIL_INTERNAL_DESC,
598 "description must be the static 'internal error' string"
599 );
600 assert_eq!(wire["type"], "serverFail");
601 }
602
603 #[test]
609 fn server_fail_from_backend_accepts_generic_display() {
610 let _ = server_fail_from_backend("a string");
613 let _ = server_fail_from_backend(&"&str".to_owned());
614 let _ = server_fail_from_backend(&42_u64);
615 }
616
617 #[test]
628 fn server_fail_value_from_backend_drops_display_text() {
629 #[derive(Debug)]
630 struct LeakyError(&'static str);
631 impl std::fmt::Display for LeakyError {
632 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
633 f.write_str(self.0)
634 }
635 }
636 impl std::error::Error for LeakyError {}
637
638 const CANARY: &str = "TOKEN-DO-NOT-LEAK-d00d";
639 let err = LeakyError(CANARY);
640
641 let wire = server_fail_value_from_backend(&err);
642
643 let wire_str = wire.to_string();
645 assert!(
646 !wire_str.contains(CANARY),
647 "server_fail_value_from_backend must not echo backend error \
648 Display onto the wire; got {wire_str}"
649 );
650 assert_eq!(wire["type"], "serverFail");
652 assert_eq!(
653 wire["description"], SERVER_FAIL_INTERNAL_DESC,
654 "description must be the static 'internal error' string"
655 );
656 }
657
658 #[test]
664 fn server_fail_value_from_backend_accepts_generic_display() {
665 let _ = server_fail_value_from_backend("a string");
668 let _ = server_fail_value_from_backend(&"owned-String".to_owned());
669 let owned: String = "owned".to_string();
670 let _ = server_fail_value_from_backend(&owned);
671 let _ = server_fail_value_from_backend(&42_u64);
672 }
673
674 use crate::backend::{
679 BackendChangesError, BackendQueryError, ChangesResult, QueryChangesParams,
680 QueryChangesResult, QueryParams,
681 };
682
683 #[derive(serde::Serialize, serde::Deserialize)]
685 struct QueryProbe;
686
687 impl JmapObject for QueryProbe {
688 const TYPE_NAME: &'static str = "QueryProbe";
689 type Property = ();
690 }
691
692 impl QueryObject for QueryProbe {
693 type Filter = Value;
694 type Comparator = Value;
695 }
696
697 #[derive(Debug)]
698 struct LeakyQueryError(&'static str);
699
700 impl std::fmt::Display for LeakyQueryError {
701 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
702 f.write_str(self.0)
703 }
704 }
705
706 impl std::error::Error for LeakyQueryError {}
707
708 enum QueryFailure {
710 Method(JmapError),
712 Internal(&'static str),
715 }
716
717 struct QueryFailBackend(QueryFailure);
720
721 impl JmapBackend for QueryFailBackend {
722 type Error = LeakyQueryError;
723 type CallerCtx = ();
724
725 async fn account_exists(
726 &self,
727 _caller: &(),
728 _account_id: &Id,
729 ) -> Result<bool, Self::Error> {
730 Ok(true)
731 }
732
733 async fn get_objects<O: GetObject + Send + Sync>(
734 &self,
735 _caller: &(),
736 _account_id: &Id,
737 _ids: Option<&[Id]>,
738 _properties: Option<&[String]>,
739 ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
740 unreachable!("only query_objects is exercised")
741 }
742
743 async fn get_state<O: JmapObject + Send + Sync>(
744 &self,
745 _caller: &(),
746 _account_id: &Id,
747 ) -> Result<State, Self::Error> {
748 unreachable!("only query_objects is exercised")
749 }
750
751 async fn get_changes<O: JmapObject + Send + Sync>(
752 &self,
753 _caller: &(),
754 _account_id: &Id,
755 _params: ChangesParams<'_>,
756 ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
757 unreachable!("only query_objects is exercised")
758 }
759
760 async fn query_objects<O: QueryObject + Send + Sync>(
761 &self,
762 _caller: &(),
763 _account_id: &Id,
764 _params: QueryParams<'_, O>,
765 ) -> Result<crate::backend::QueryResult, BackendQueryError<Self::Error>> {
766 Err(match &self.0 {
767 QueryFailure::Method(e) => BackendQueryError::Method(e.clone()),
768 QueryFailure::Internal(text) => BackendQueryError::Other(LeakyQueryError(text)),
769 })
770 }
771
772 async fn query_changes<O: QueryObject + Send + Sync>(
773 &self,
774 _caller: &(),
775 _account_id: &Id,
776 _params: QueryChangesParams<'_, O>,
777 ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
778 unreachable!("only query_objects is exercised")
779 }
780 }
781
782 async fn query_error_wire(failure: QueryFailure) -> Value {
785 let backend = QueryFailBackend(failure);
786 let args = json!({
787 "accountId": "a1",
788 "filter": { "text": "hello" },
789 "anchor": "m1",
790 });
791 let err = match handle_query::<QueryProbe, _>(&backend, &(), args).await {
792 Ok(HandlerOutput { primary: resp, .. }) => {
793 panic!("query_objects failed but handle_query succeeded: {resp}")
794 }
795 Err(e) => e,
796 };
797 serde_json::to_value(&err).expect("JmapError must serialize")
798 }
799
800 #[tokio::test]
813 async fn handle_query_passes_backend_unsupported_filter_through() {
814 let mut expected = JmapError::unsupported_filter();
815 expected.description = Some("Message/query requires a chatId condition".into());
816
817 let wire = query_error_wire(QueryFailure::Method(expected.clone())).await;
818
819 assert_eq!(
820 wire,
821 serde_json::to_value(&expected).expect("JmapError must serialize"),
822 "backend unsupportedFilter must pass through handle_query unchanged"
823 );
824 }
825
826 #[tokio::test]
835 async fn handle_query_passes_backend_anchor_not_found_through() {
836 let expected = JmapError::anchor_not_found();
837
838 let wire = query_error_wire(QueryFailure::Method(expected.clone())).await;
839
840 assert_eq!(
841 wire,
842 serde_json::to_value(&expected).expect("JmapError must serialize"),
843 "backend anchorNotFound must pass through handle_query unchanged"
844 );
845 }
846
847 #[tokio::test]
852 async fn handle_query_redacts_backend_internal_error() {
853 const CANARY: &str = "TOKEN-DO-NOT-LEAK-query-5ca1ab1e";
854
855 let wire = query_error_wire(QueryFailure::Internal(CANARY)).await;
856
857 assert_eq!(wire["type"], "serverFail");
858 assert_eq!(wire["description"], SERVER_FAIL_INTERNAL_DESC);
859 assert!(
860 !wire.to_string().contains(CANARY),
861 "internal backend error Display must not reach the wire; got {wire}"
862 );
863 }
864
865 #[derive(serde::Serialize, serde::Deserialize)]
871 struct GetProbe;
872
873 impl JmapObject for GetProbe {
874 const TYPE_NAME: &'static str = "GetProbe";
875 type Property = ();
876 }
877
878 impl GetObject for GetProbe {}
879
880 struct GetProbeBackend;
883
884 impl JmapBackend for GetProbeBackend {
885 type Error = LeakyQueryError;
886 type CallerCtx = ();
887
888 async fn account_exists(
889 &self,
890 _caller: &(),
891 _account_id: &Id,
892 ) -> Result<bool, Self::Error> {
893 Ok(true)
894 }
895
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 Ok((vec![], ids.map(<[Id]>::to_vec).unwrap_or_default()))
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 Ok(State::from("s0"))
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 /get 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 unreachable!("only /get is exercised")
930 }
931
932 async fn query_changes<O: QueryObject + Send + Sync>(
933 &self,
934 _caller: &(),
935 _account_id: &Id,
936 _params: QueryChangesParams<'_, O>,
937 ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
938 unreachable!("only /get is exercised")
939 }
940 }
941
942 #[tokio::test]
957 async fn handle_get_over_max_objects_is_request_too_large() {
958 let ids: Vec<String> = (0..501).map(|i| format!("id{i}")).collect();
959 let args = json!({ "accountId": "a1", "ids": ids });
960
961 match handle_get::<GetProbe, _>(&GetProbeBackend, &(), args).await {
962 Ok(HandlerOutput { primary: resp, .. }) => panic!(
963 "501 ids exceed the maxObjectsInGet cap, but handle_get \
964 returned a response with {} notFound ids instead of \
965 requestTooLarge",
966 resp["notFound"].as_array().map_or(0, Vec::len)
967 ),
968 Err(e) => assert_eq!(e.error_type.to_string(), "requestTooLarge"),
969 }
970 }
971
972 #[tokio::test]
983 async fn handle_get_null_ids_is_not_counted_against_cap() {
984 let args = json!({ "accountId": "a1", "ids": null });
985
986 let HandlerOutput { primary: resp, .. } =
987 handle_get::<GetProbe, _>(&GetProbeBackend, &(), args)
988 .await
989 .expect("null ids must not be rejected by the maxObjectsInGet cap");
990 assert_eq!(resp["list"], json!([]));
991 }
992
993 #[derive(Default)]
997 struct RecordingQueryBackend(std::sync::Mutex<Option<Value>>);
998
999 impl RecordingQueryBackend {
1000 fn take(&self) -> Value {
1001 self.0
1002 .lock()
1003 .unwrap()
1004 .take()
1005 .expect("backend query method was not called")
1006 }
1007 }
1008
1009 impl JmapBackend for RecordingQueryBackend {
1010 type Error = LeakyQueryError;
1011 type CallerCtx = ();
1012
1013 async fn account_exists(
1014 &self,
1015 _caller: &(),
1016 _account_id: &Id,
1017 ) -> Result<bool, Self::Error> {
1018 Ok(true)
1019 }
1020
1021 async fn get_objects<O: GetObject + Send + Sync>(
1022 &self,
1023 _caller: &(),
1024 _account_id: &Id,
1025 _ids: Option<&[Id]>,
1026 _properties: Option<&[String]>,
1027 ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
1028 unreachable!("only queries are exercised")
1029 }
1030
1031 async fn get_state<O: JmapObject + Send + Sync>(
1032 &self,
1033 _caller: &(),
1034 _account_id: &Id,
1035 ) -> Result<State, Self::Error> {
1036 unreachable!("only queries are exercised")
1037 }
1038
1039 async fn get_changes<O: JmapObject + Send + Sync>(
1040 &self,
1041 _caller: &(),
1042 _account_id: &Id,
1043 _params: ChangesParams<'_>,
1044 ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
1045 unreachable!("only queries are exercised")
1046 }
1047
1048 async fn query_objects<O: QueryObject + Send + Sync>(
1049 &self,
1050 _caller: &(),
1051 _account_id: &Id,
1052 params: QueryParams<'_, O>,
1053 ) -> Result<crate::backend::QueryResult, BackendQueryError<Self::Error>> {
1054 *self.0.lock().unwrap() = Some(json!({
1055 "filter": params.filter.map(|f| serde_json::to_value(f).unwrap()),
1056 "sort": params.sort.map(|s| serde_json::to_value(s).unwrap()),
1057 "limit": params.limit,
1058 "position": params.position,
1059 "anchor": params.anchor,
1060 "anchorOffset": params.anchor_offset,
1061 }));
1062 Ok(crate::backend::QueryResult::new(
1063 vec![],
1064 0,
1065 None,
1066 State::from("q0"),
1067 false,
1068 ))
1069 }
1070
1071 async fn query_changes<O: QueryObject + Send + Sync>(
1072 &self,
1073 _caller: &(),
1074 _account_id: &Id,
1075 params: QueryChangesParams<'_, O>,
1076 ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
1077 *self.0.lock().unwrap() = Some(json!({
1078 "sinceQueryState": params.since_query_state,
1079 "filter": params.filter.map(|f| serde_json::to_value(f).unwrap()),
1080 "sort": params.sort.map(|s| serde_json::to_value(s).unwrap()),
1081 "maxChanges": params.max_changes,
1082 "upToId": params.up_to_id,
1083 "collapseThreads": params.collapse_threads,
1084 }));
1085 Ok(QueryChangesResult::new(
1086 params.since_query_state.clone(),
1087 State::from("q2"),
1088 None,
1089 vec![],
1090 vec![],
1091 ))
1092 }
1093 }
1094
1095 #[tokio::test]
1100 async fn handle_query_passes_every_argument_to_backend() {
1101 let backend = RecordingQueryBackend::default();
1102 let args = json!({
1103 "accountId": "a1",
1104 "filter": {"text": "hello"},
1105 "sort": [{"property": "receivedAt", "isAscending": false}],
1106 "position": 3,
1107 "anchor": "m7",
1108 "anchorOffset": -2,
1109 "limit": 25,
1110 });
1111 handle_query::<QueryProbe, _>(&backend, &(), args)
1112 .await
1113 .expect("query must succeed");
1114 assert_eq!(
1115 backend.take(),
1116 json!({
1117 "filter": {"text": "hello"},
1118 "sort": [{"property": "receivedAt", "isAscending": false}],
1119 "limit": 25,
1120 "position": 3,
1121 "anchor": "m7",
1122 "anchorOffset": -2,
1123 })
1124 );
1125 }
1126
1127 #[tokio::test]
1132 async fn handle_query_omitted_arguments_reach_backend_as_rfc_defaults() {
1133 let backend = RecordingQueryBackend::default();
1134 handle_query::<QueryProbe, _>(&backend, &(), json!({"accountId": "a1"}))
1135 .await
1136 .expect("query must succeed");
1137 assert_eq!(
1138 backend.take(),
1139 json!({
1140 "filter": null,
1141 "sort": null,
1142 "limit": null,
1143 "position": 0,
1144 "anchor": null,
1145 "anchorOffset": 0,
1146 })
1147 );
1148 }
1149
1150 #[tokio::test]
1157 async fn handle_query_changes_passes_every_argument_to_backend() {
1158 let backend = RecordingQueryBackend::default();
1159 let args = json!({
1160 "accountId": "a1",
1161 "filter": {"text": "hello"},
1162 "sort": [{"property": "receivedAt"}],
1163 "sinceQueryState": "q1",
1164 "maxChanges": 10,
1165 "upToId": "m9",
1166 });
1167 handle_query_changes::<QueryProbe, _>(&backend, &(), args)
1168 .await
1169 .expect("queryChanges must succeed");
1170 assert_eq!(
1171 backend.take(),
1172 json!({
1173 "sinceQueryState": "q1",
1174 "filter": {"text": "hello"},
1175 "sort": [{"property": "receivedAt"}],
1176 "maxChanges": 10,
1177 "upToId": "m9",
1178 "collapseThreads": false,
1179 })
1180 );
1181 }
1182
1183 #[tokio::test]
1191 async fn non_object_filter_is_invalid_arguments() {
1192 for filter in [json!(42), json!("text"), json!(true), json!([])] {
1193 let backend = RecordingQueryBackend::default();
1194 let err = handle_query::<QueryProbe, _>(
1195 &backend,
1196 &(),
1197 json!({"accountId": "a1", "filter": filter}),
1198 )
1199 .await
1200 .expect_err("non-object filter must be rejected");
1201 assert_eq!(err.error_type.to_string(), "invalidArguments", "{filter}");
1202
1203 let err = handle_query_changes::<QueryProbe, _>(
1204 &backend,
1205 &(),
1206 json!({"accountId": "a1", "filter": filter, "sinceQueryState": "q1"}),
1207 )
1208 .await
1209 .expect_err("non-object filter must be rejected");
1210 assert_eq!(err.error_type.to_string(), "invalidArguments", "{filter}");
1211 assert!(backend.0.lock().unwrap().is_none(), "{filter}");
1212 }
1213 }
1214
1215 #[derive(Clone, Copy)]
1223 enum Canned {
1224 Ok,
1226 CannotCalculate,
1228 TooManyChanges(u64),
1230 Internal(&'static str),
1232 }
1233
1234 impl Canned {
1235 fn changes_error(self) -> BackendChangesError<LeakyQueryError> {
1236 match self {
1237 Canned::Ok => unreachable!("Canned::Ok is not an error"),
1238 Canned::CannotCalculate => BackendChangesError::CannotCalculate,
1239 Canned::TooManyChanges(limit) => BackendChangesError::TooManyChanges { limit },
1240 Canned::Internal(text) => BackendChangesError::Other(LeakyQueryError(text)),
1241 }
1242 }
1243 }
1244
1245 struct CannedBackend {
1249 account_exists: bool,
1250 outcome: Canned,
1251 }
1252
1253 const CANNED_OK: CannedBackend = CannedBackend {
1254 account_exists: true,
1255 outcome: Canned::Ok,
1256 };
1257
1258 impl JmapBackend for CannedBackend {
1259 type Error = LeakyQueryError;
1260 type CallerCtx = ();
1261
1262 async fn account_exists(
1263 &self,
1264 _caller: &(),
1265 _account_id: &Id,
1266 ) -> Result<bool, Self::Error> {
1267 Ok(self.account_exists)
1268 }
1269
1270 async fn get_objects<O: GetObject + Send + Sync>(
1271 &self,
1272 _caller: &(),
1273 _account_id: &Id,
1274 _ids: Option<&[Id]>,
1275 _properties: Option<&[String]>,
1276 ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
1277 unreachable!("/get is not exercised")
1278 }
1279
1280 async fn get_state<O: JmapObject + Send + Sync>(
1281 &self,
1282 _caller: &(),
1283 _account_id: &Id,
1284 ) -> Result<State, Self::Error> {
1285 unreachable!("/get is not exercised")
1286 }
1287
1288 async fn get_changes<O: JmapObject + Send + Sync>(
1289 &self,
1290 _caller: &(),
1291 _account_id: &Id,
1292 _params: ChangesParams<'_>,
1293 ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
1294 match self.outcome {
1295 Canned::Ok => Ok(ChangesResult::new(
1296 vec![Id::from("c1")],
1297 vec![Id::from("u1")],
1298 vec![Id::from("d1")],
1299 true,
1300 State::from("s2"),
1301 )),
1302 other => Err(other.changes_error()),
1303 }
1304 }
1305
1306 async fn query_objects<O: QueryObject + Send + Sync>(
1307 &self,
1308 _caller: &(),
1309 _account_id: &Id,
1310 _params: QueryParams<'_, O>,
1311 ) -> Result<crate::backend::QueryResult, BackendQueryError<Self::Error>> {
1312 Ok(crate::backend::QueryResult::new(
1313 vec![Id::from("m1")],
1314 0,
1315 Some(7),
1316 State::from("q1"),
1317 true,
1318 ))
1319 }
1320
1321 async fn query_changes<O: QueryObject + Send + Sync>(
1322 &self,
1323 _caller: &(),
1324 _account_id: &Id,
1325 params: QueryChangesParams<'_, O>,
1326 ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
1327 match self.outcome {
1328 Canned::Ok => Ok(QueryChangesResult::new(
1329 params.since_query_state.clone(),
1330 State::from("q2"),
1331 Some(7),
1332 vec![Id::from("r1")],
1333 vec![crate::backend::AddedItem::new(Id::from("n1"), 0)],
1334 )),
1335 other => Err(other.changes_error()),
1336 }
1337 }
1338 }
1339
1340 #[tokio::test]
1347 async fn handle_changes_response_matches_rfc_shape() {
1348 let HandlerOutput { primary: resp, .. } = handle_changes::<QueryProbe, _>(
1349 &CANNED_OK,
1350 &(),
1351 json!({"accountId": "a1", "sinceState": "s1"}),
1352 &[],
1353 )
1354 .await
1355 .expect("/changes must succeed");
1356 assert_eq!(
1357 resp,
1358 json!({
1359 "accountId": "a1",
1360 "oldState": "s1",
1361 "newState": "s2",
1362 "hasMoreChanges": true,
1363 "updatedProperties": null,
1364 "created": ["c1"],
1365 "updated": ["u1"],
1366 "destroyed": ["d1"],
1367 })
1368 );
1369 }
1370
1371 const CORE: &str = "urn:ietf:params:jmap:core";
1376 const METADATA: &str = "urn:ietf:params:jmap:metadata";
1377
1378 struct MetadataChangesBackend {
1382 updated: Vec<Id>,
1383 updated_properties: Option<Vec<String>>,
1384 seen_ignore: std::sync::Mutex<Option<bool>>,
1385 }
1386
1387 impl MetadataChangesBackend {
1388 fn new(updated: &[&str], updated_properties: Option<&[&str]>) -> Self {
1389 Self {
1390 updated: updated.iter().map(|u| Id::from(*u)).collect(),
1391 updated_properties: updated_properties
1392 .map(|p| p.iter().map(|s| (*s).to_owned()).collect()),
1393 seen_ignore: std::sync::Mutex::new(None),
1394 }
1395 }
1396 }
1397
1398 impl JmapBackend for MetadataChangesBackend {
1399 type Error = LeakyQueryError;
1400 type CallerCtx = ();
1401
1402 async fn account_exists(
1403 &self,
1404 _caller: &(),
1405 _account_id: &Id,
1406 ) -> Result<bool, Self::Error> {
1407 Ok(true)
1408 }
1409
1410 async fn get_objects<O: GetObject + Send + Sync>(
1411 &self,
1412 _caller: &(),
1413 _account_id: &Id,
1414 _ids: Option<&[Id]>,
1415 _properties: Option<&[String]>,
1416 ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
1417 unreachable!("only get_changes is exercised")
1418 }
1419
1420 async fn get_state<O: JmapObject + Send + Sync>(
1421 &self,
1422 _caller: &(),
1423 _account_id: &Id,
1424 ) -> Result<State, Self::Error> {
1425 unreachable!("only get_changes is exercised")
1426 }
1427
1428 async fn get_changes<O: JmapObject + Send + Sync>(
1429 &self,
1430 _caller: &(),
1431 _account_id: &Id,
1432 params: ChangesParams<'_>,
1433 ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
1434 *self.seen_ignore.lock().unwrap() = Some(params.ignore_metadata_only_changes);
1435 Ok(ChangesResult::new(
1436 Vec::new(),
1437 self.updated.clone(),
1438 Vec::new(),
1439 false,
1440 State::from("s2"),
1441 )
1442 .with_updated_properties(self.updated_properties.clone()))
1443 }
1444
1445 async fn query_objects<O: QueryObject + Send + Sync>(
1446 &self,
1447 _caller: &(),
1448 _account_id: &Id,
1449 _params: QueryParams<'_, O>,
1450 ) -> Result<crate::backend::QueryResult, BackendQueryError<Self::Error>> {
1451 unreachable!("only get_changes is exercised")
1452 }
1453
1454 async fn query_changes<O: QueryObject + Send + Sync>(
1455 &self,
1456 _caller: &(),
1457 _account_id: &Id,
1458 _params: QueryChangesParams<'_, O>,
1459 ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
1460 unreachable!("only get_changes is exercised")
1461 }
1462 }
1463
1464 async fn ignore_seen(using: &[&str], extra: Value) -> bool {
1467 let backend = MetadataChangesBackend::new(&["u1"], None);
1468 let mut args = json!({"accountId": "a1", "sinceState": "s1"});
1469 if let Value::Object(extra) = extra {
1470 args.as_object_mut().unwrap().extend(extra);
1471 }
1472 let using: Vec<String> = using.iter().map(|u| (*u).to_owned()).collect();
1473 handle_changes::<QueryProbe, _>(&backend, &(), args, &using)
1474 .await
1475 .expect("/changes must succeed");
1476 backend
1477 .seen_ignore
1478 .lock()
1479 .unwrap()
1480 .expect("backend must be called")
1481 }
1482
1483 #[tokio::test]
1490 async fn changes_without_metadata_capability_ignores_metadata_only_changes() {
1491 assert!(ignore_seen(&[CORE], json!({})).await);
1492 assert!(ignore_seen(&[CORE], json!({"ignoreMetadataOnlyChanges": false})).await);
1493 assert!(ignore_seen(&[CORE], json!({"ignoreMetadataOnlyChanges": "no"})).await);
1494 assert!(ignore_seen(&[], json!({})).await);
1495 }
1496
1497 #[tokio::test]
1500 async fn changes_with_metadata_capability_passes_ignore_argument() {
1501 assert!(!ignore_seen(&[CORE, METADATA], json!({})).await);
1502 assert!(
1503 !ignore_seen(
1504 &[CORE, METADATA],
1505 json!({"ignoreMetadataOnlyChanges": null})
1506 )
1507 .await
1508 );
1509 assert!(
1510 !ignore_seen(
1511 &[CORE, METADATA],
1512 json!({"ignoreMetadataOnlyChanges": false})
1513 )
1514 .await
1515 );
1516 assert!(
1517 ignore_seen(
1518 &[CORE, METADATA],
1519 json!({"ignoreMetadataOnlyChanges": true})
1520 )
1521 .await
1522 );
1523 }
1524
1525 #[tokio::test]
1529 async fn changes_rejects_non_boolean_ignore_argument() {
1530 let backend = MetadataChangesBackend::new(&["u1"], None);
1531 let err = handle_changes::<QueryProbe, _>(
1532 &backend,
1533 &(),
1534 json!({"accountId": "a1", "sinceState": "s1", "ignoreMetadataOnlyChanges": "yes"}),
1535 &[CORE.to_owned(), METADATA.to_owned()],
1536 )
1537 .await
1538 .expect_err("a string ignoreMetadataOnlyChanges must fail");
1539 assert_eq!(err.error_type.to_string(), "invalidArguments");
1540 assert!(
1541 backend.seen_ignore.lock().unwrap().is_none(),
1542 "backend must not be called"
1543 );
1544 }
1545
1546 #[tokio::test]
1553 async fn changes_reports_backend_updated_properties() {
1554 let backend = MetadataChangesBackend::new(&["u1"], Some(&["metadata"]));
1555 let HandlerOutput { primary: resp, .. } = handle_changes::<QueryProbe, _>(
1556 &backend,
1557 &(),
1558 json!({"accountId": "a1", "sinceState": "s1"}),
1559 &[CORE.to_owned(), METADATA.to_owned()],
1560 )
1561 .await
1562 .expect("/changes must succeed");
1563 assert_eq!(
1564 resp,
1565 json!({
1566 "accountId": "a1",
1567 "oldState": "s1",
1568 "newState": "s2",
1569 "hasMoreChanges": false,
1570 "updatedProperties": ["metadata"],
1571 "created": [],
1572 "updated": ["u1"],
1573 "destroyed": [],
1574 })
1575 );
1576 }
1577
1578 #[tokio::test]
1581 async fn changes_updated_properties_null_when_updated_empty() {
1582 let backend = MetadataChangesBackend::new(&[], Some(&["metadata"]));
1583 let HandlerOutput { primary: resp, .. } = handle_changes::<QueryProbe, _>(
1584 &backend,
1585 &(),
1586 json!({"accountId": "a1", "sinceState": "s1"}),
1587 &[CORE.to_owned(), METADATA.to_owned()],
1588 )
1589 .await
1590 .expect("/changes must succeed");
1591 assert_eq!(resp["updatedProperties"], Value::Null);
1592 assert!(
1593 resp.as_object().unwrap().contains_key("updatedProperties"),
1594 "updatedProperties must be present"
1595 );
1596 }
1597
1598 #[tokio::test]
1604 async fn handle_query_changes_response_matches_rfc_shape() {
1605 let HandlerOutput { primary: resp, .. } = handle_query_changes::<QueryProbe, _>(
1606 &CANNED_OK,
1607 &(),
1608 json!({"accountId": "a1", "sinceQueryState": "q1", "calculateTotal": true}),
1609 )
1610 .await
1611 .expect("/queryChanges must succeed");
1612 assert_eq!(
1613 resp,
1614 json!({
1615 "accountId": "a1",
1616 "oldQueryState": "q1",
1617 "newQueryState": "q2",
1618 "total": 7,
1619 "removed": ["r1"],
1620 "added": [{"id": "n1", "index": 0}],
1621 })
1622 );
1623
1624 let HandlerOutput { primary: resp, .. } = handle_query_changes::<QueryProbe, _>(
1625 &CANNED_OK,
1626 &(),
1627 json!({"accountId": "a1", "sinceQueryState": "q1"}),
1628 )
1629 .await
1630 .expect("/queryChanges must succeed");
1631 assert!(
1632 resp.get("total").is_none(),
1633 "total must be omitted without calculateTotal; got {resp}"
1634 );
1635 }
1636
1637 #[tokio::test]
1641 async fn handle_query_total_only_when_requested() {
1642 for (calculate_total, expected) in [(json!(true), Some(json!(7))), (json!(false), None)] {
1643 let HandlerOutput { primary: resp, .. } = handle_query::<QueryProbe, _>(
1644 &CANNED_OK,
1645 &(),
1646 json!({"accountId": "a1", "calculateTotal": calculate_total}),
1647 )
1648 .await
1649 .expect("/query must succeed");
1650 assert_eq!(resp.get("total").cloned(), expected, "{resp}");
1651 }
1652 }
1653
1654 #[tokio::test]
1659 async fn missing_or_non_string_since_state_is_invalid_arguments() {
1660 for since in [None, Some(json!(42))] {
1661 let mut args = json!({"accountId": "a1"});
1662 if let Some(v) = &since {
1663 args["sinceState"] = v.clone();
1664 }
1665 let err = handle_changes::<QueryProbe, _>(&CANNED_OK, &(), args, &[])
1666 .await
1667 .expect_err("/changes without a string sinceState must fail");
1668 assert_eq!(err.error_type.to_string(), "invalidArguments", "{since:?}");
1669
1670 let mut args = json!({"accountId": "a1"});
1671 if let Some(v) = &since {
1672 args["sinceQueryState"] = v.clone();
1673 }
1674 let err = handle_query_changes::<QueryProbe, _>(&CANNED_OK, &(), args)
1675 .await
1676 .expect_err("/queryChanges without a string sinceQueryState must fail");
1677 assert_eq!(err.error_type.to_string(), "invalidArguments", "{since:?}");
1678 }
1679 }
1680
1681 #[tokio::test]
1684 async fn non_string_up_to_id_is_invalid_arguments() {
1685 for up_to_id in [json!(5), json!(true), json!(["m1"]), json!({})] {
1686 let err = handle_query_changes::<QueryProbe, _>(
1687 &CANNED_OK,
1688 &(),
1689 json!({"accountId": "a1", "sinceQueryState": "q1", "upToId": up_to_id}),
1690 )
1691 .await
1692 .expect_err("non-Id upToId must be rejected");
1693 assert_eq!(err.error_type.to_string(), "invalidArguments", "{up_to_id}");
1694 }
1695 }
1696
1697 #[tokio::test]
1701 async fn handle_query_negative_limit_is_invalid_arguments() {
1702 let backend = RecordingQueryBackend::default();
1703 let err =
1704 handle_query::<QueryProbe, _>(&backend, &(), json!({"accountId": "a1", "limit": -1}))
1705 .await
1706 .expect_err("negative limit must be rejected");
1707 assert_eq!(err.error_type.to_string(), "invalidArguments");
1708 assert!(
1709 backend.0.lock().unwrap().is_none(),
1710 "backend must not be consulted"
1711 );
1712 }
1713
1714 #[tokio::test]
1720 async fn handle_query_negative_position_reaches_backend() {
1721 let backend = RecordingQueryBackend::default();
1722 handle_query::<QueryProbe, _>(&backend, &(), json!({"accountId": "a1", "position": -5}))
1723 .await
1724 .expect("negative position is valid");
1725 assert_eq!(backend.take()["position"], json!(-5));
1726 }
1727
1728 #[tokio::test]
1737 async fn changes_backend_errors_map_to_rfc_errors() {
1738 const CANARY: &str = "TOKEN-DO-NOT-LEAK-changes-b0a710ad";
1739 for (outcome, changes_type, query_changes_type) in [
1740 (
1741 Canned::CannotCalculate,
1742 "cannotCalculateChanges",
1743 "cannotCalculateChanges",
1744 ),
1745 (
1746 Canned::TooManyChanges(10),
1747 "cannotCalculateChanges",
1748 "tooManyChanges",
1749 ),
1750 (Canned::Internal(CANARY), "serverFail", "serverFail"),
1751 ] {
1752 let backend = CannedBackend {
1753 account_exists: true,
1754 outcome,
1755 };
1756 let changes = handle_changes::<QueryProbe, _>(
1757 &backend,
1758 &(),
1759 json!({"accountId": "a1", "sinceState": "s1"}),
1760 &[],
1761 )
1762 .await;
1763 let query_changes = handle_query_changes::<QueryProbe, _>(
1764 &backend,
1765 &(),
1766 json!({"accountId": "a1", "sinceQueryState": "q1"}),
1767 )
1768 .await;
1769 for (result, expected_type) in
1770 [(changes, changes_type), (query_changes, query_changes_type)]
1771 {
1772 let err = result.expect_err("backend error must fail the call");
1773 let wire = serde_json::to_value(&err).expect("JmapError must serialize");
1774 assert_eq!(wire["type"], expected_type, "{wire}");
1775 assert!(!wire.to_string().contains(CANARY), "leaked: {wire}");
1776 }
1777 }
1778 }
1779
1780 #[tokio::test]
1783 async fn unknown_account_is_account_not_found() {
1784 let backend = CannedBackend {
1785 account_exists: false,
1786 outcome: Canned::Ok,
1787 };
1788 let results = [
1789 handle_changes::<QueryProbe, _>(
1790 &backend,
1791 &(),
1792 json!({"accountId": "nope", "sinceState": "s1"}),
1793 &[],
1794 )
1795 .await,
1796 handle_query::<QueryProbe, _>(&backend, &(), json!({"accountId": "nope"})).await,
1797 handle_query_changes::<QueryProbe, _>(
1798 &backend,
1799 &(),
1800 json!({"accountId": "nope", "sinceQueryState": "q1"}),
1801 )
1802 .await,
1803 ];
1804 for result in results {
1805 let err = result.expect_err("unknown account must fail");
1806 assert_eq!(err.error_type.to_string(), "accountNotFound");
1807 }
1808 }
1809
1810 #[tokio::test]
1815 async fn handle_query_does_not_echo_wrongly_typed_value() {
1816 for name in ["limit", "position"] {
1817 let backend = RecordingQueryBackend::default();
1818 let mut args = json!({ "accountId": "a1" });
1819 args[name] = json!({ "note": "CANARY-zegc" });
1820 let err = handle_query::<QueryProbe, _>(&backend, &(), args)
1821 .await
1822 .expect_err("wrongly typed argument must be rejected");
1823 assert_eq!(err.error_type.to_string(), "invalidArguments", "{name}");
1824 let desc = err.description.as_deref().unwrap_or_default();
1825 assert!(desc.starts_with(name), "{desc}");
1826 assert!(desc.contains("got object"), "{desc}");
1827 assert!(!desc.contains("CANARY"), "{desc}");
1828 }
1829 }
1830}