jmap_tasks_server/task.rs
1//! Task/* method handlers (draft-tasks-06 §4).
2//!
3//! The `isDraft` immutability constraint (once false, never true again) is
4//! enforced by [`crate::TasksBackend::update_object`], not by Task/set.
5//!
6//! # Wire-shape contract
7//!
8//! Every `handle_*` function in this module conforms to the canonical JMAP
9//! method shape. The `args: serde_json::Value` parameter MUST be a JSON
10//! Object whose fields match the corresponding RFC 8620 §5 method shape
11//! (`/get` → §5.1, `/changes` → §5.2, `/set` → §5.3, `/copy` → §5.4,
12//! `/query` → §5.5, `/queryChanges` → §5.6), with the type-specific
13//! arguments defined by draft-tasks-06 §4. The returned `Value` is the
14//! corresponding method-response object per the same section refs.
15//!
16//! The returned `HandlerOutput::extra_invocations` carries any invocations
17//! that this handler injected into the request stream (RFC 8620 §6.3).
18//! For the standard `/get`, `/changes`, `/set`, `/query`, and
19//! `/queryChanges` handlers in this module the vector is **always
20//! empty**. `handle_task_copy` is the one exception: it MAY emit
21//! `Task/set` follow-up invocations when `onSuccessDestroyOriginal` is
22//! true (RFC 8620 §5.4).
23//!
24//! Each handler returns `Err(JmapError)` for method-level failures (RFC 8620
25//! §3.6.2 and §5):
26//!
27//! - every handler: `accountNotFound`, `invalidArguments`, `serverFail`;
28//! - `/get`, `/set`: `requestTooLarge` past `maxObjectsInGet` /
29//! `maxObjectsInSet`;
30//! - `/set`, `/copy`: `stateMismatch`;
31//! - `/copy`: `fromAccountNotFound`;
32//! - `/changes`, `/queryChanges`: `cannotCalculateChanges`;
33//! - `/queryChanges`: `tooManyChanges`;
34//! - `/query`, `/queryChanges`: `unsupportedFilter`;
35//! - `/query`: `unsupportedSort`, `anchorNotFound`.
36//!
37//! Per-target failures inside a `/set` or `/copy` call surface in the
38//! `notCreated` / `notUpdated` / `notDestroyed` maps within `Ok((Value, ...))`,
39//! not as `Err`.
40
41use std::collections::BTreeMap;
42
43use jmap_tasks_types::{Filter, Task, TaskComparator, TaskFilter, TaskFilterCondition};
44use jmap_types::{Id, Invocation, JmapError, PatchObject, UTCDate};
45use serde::Deserialize;
46use serde_json::{Value, json};
47
48use crate::TasksBackend;
49use crate::helpers::{
50 SetAccumulators, check_metadata_entry, enforce_max_objects_in_set, extract_account_id,
51 finalize_set_response, reject_unsupported_sort, resolve_refs,
52};
53use jmap_server::{
54 HandlerOutput, QueryParams, backend_set_error_value, bool_arg, check_read_only_patch,
55 filter_arg, optional_arg, query_anchor_args, reject_server_set, server_fail_from_backend,
56 server_fail_value_from_backend,
57};
58
59// ---------------------------------------------------------------------------
60// Task/get
61// ---------------------------------------------------------------------------
62
63/// Handle a `Task/get` method call (draft-tasks-06 §4.5).
64///
65/// `args` is the RFC 8620 §5.1 `/get` request shape (`accountId`, optional
66/// `ids`, optional `properties`); the returned `Value` is the §5.1
67/// `/get` response shape (`accountId`, `state`, `list`, `notFound`).
68///
69/// `utcStart` and `utcDue` are returned only when `properties` names them:
70/// "This is not included by default and must be requested explicitly"
71/// (draft-tasks-06 §4). For each requested one,
72/// [`TasksBackend::compute_utc_times`] is called per returned task and the
73/// value is `UTCDate|null` (jmapio/jmap PR #464): `null` when the task has
74/// no `start` (for `utcStart`) or no `due` (for `utcDue`), the computed
75/// date otherwise. A task that has the local time but for which the backend
76/// returns `None` (it cannot convert, e.g. the default `compute_utc_times`)
77/// gets no key at all, since `null` would claim the local time is unset.
78/// The local-time inputs (`start`, `due`, `timeZone`, `timeZones`) are
79/// fetched for that even when `properties` leaves them out, and dropped
80/// again before the response, so only the requested properties are
81/// returned (RFC 8620 §5.1).
82///
83/// The `timeZone` argument (TimeZoneId, default `"Etc/UTC"`; jmapio/jmap
84/// #456, as CalendarEvent/get, draft-ietf-jmap-calendars-34 §5.7) is the
85/// zone for floating tasks: "Floating tasks will be interpreted as per the
86/// time zone given as a Task/get argument" (draft-tasks-06 §4). It is
87/// passed to `compute_utc_times` as `tz_hint`. A value that is neither a
88/// string nor `null` is `invalidArguments`.
89///
90/// `using` is the request's capability list (pass
91/// [`jmap_server::CallContext::using`]). When the backend lists Task for
92/// draft-ietf-jmap-metadata-05 ([`JmapAccounts::metadata_info`](jmap_server::JmapAccounts::metadata_info)),
93/// `metadata` is returned as an object, by default only with
94/// `urn:ietf:params:jmap:metadata` in `using`, and with that capability
95/// `properties` may hold `metadata/<namespace>` subselectors (-05 §2,
96/// §3.1); see [`jmap_server::handle_get_with_metadata`].
97///
98/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
99pub async fn handle_task_get<B: TasksBackend>(
100 backend: &B,
101 caller: &B::CallerCtx,
102 mut args: Value,
103 using: &[String],
104) -> Result<HandlerOutput, JmapError> {
105 // Determine whether utcStart / utcDue are requested. compute_utc_times
106 // needs the local-time inputs, which handle_get would otherwise project
107 // away; fetch the missing ones and strip them again below.
108 let mut strip: Vec<&str> = Vec::new();
109 let (want_start, want_due) = match args.get_mut("properties") {
110 // draft-tasks-06 §4: utcStart/utcDue are "not included by default
111 // and must be requested explicitly".
112 None | Some(Value::Null) => (false, false),
113 Some(Value::Array(props)) => {
114 let has = |name: &str| props.iter().any(|p| p == name);
115 let wanted = (has("utcStart"), has("utcDue"));
116 if wanted.0 || wanted.1 {
117 strip = ["start", "due", "timeZone", "timeZones"]
118 .into_iter()
119 .filter(|name| !has(name))
120 .collect();
121 props.extend(strip.iter().map(|name| json!(name)));
122 }
123 wanted
124 }
125 _ => (false, false),
126 };
127
128 // Peek accountId to thread through compute_utc_times (bd:JMAP-ops7.25).
129 // handle_get re-extracts and re-validates idempotently below; a malformed
130 // or missing accountId surfaces here as invalidArguments before the
131 // delegate call.
132 let account_id: Id = args
133 .get("accountId")
134 .and_then(|v| v.as_str())
135 .ok_or_else(|| JmapError::invalid_arguments("accountId is required"))
136 .and_then(|s| {
137 Id::new_validated(s).map_err(|e| {
138 JmapError::invalid_arguments(format!("accountId is not a valid Id: {e}"))
139 })
140 })?;
141
142 // jmapio/jmap #456: a Task/get `timeZone` argument as on CalendarEvent/get
143 // (draft-ietf-jmap-calendars-34 §5.7, "TimeZoneId (default:
144 // "Etc/UTC")"), the zone for floating tasks' utcStart/utcDue.
145 let time_zone: Option<String> = match args.as_object_mut().and_then(|a| a.remove("timeZone")) {
146 None | Some(Value::Null) => None,
147 Some(Value::String(s)) => Some(s),
148 Some(v) => {
149 return Err(JmapError::invalid_arguments(format!(
150 "timeZone: expected a string, got {}",
151 jmap_server::json_type_name(&v)
152 )));
153 }
154 };
155
156 // Delegate to the generic get handler.
157 let HandlerOutput {
158 primary: mut response,
159 extra_invocations: tail,
160 ..
161 } = jmap_server::handle_get_with_metadata::<Task, B>(backend, caller, args, using).await?;
162
163 // If utcStart or utcDue were requested, augment each returned task.
164 if (want_start || want_due)
165 && let Some(Value::Array(list)) = response.get_mut("list")
166 {
167 for item in list.iter_mut() {
168 if let Ok(task) = Task::deserialize(&*item) {
169 let (utc_start, utc_due) = backend
170 .compute_utc_times(caller, &account_id, &task, time_zone.as_deref())
171 .await;
172 // jmapio/jmap PR #464: `UTCDate|null`, null when the local
173 // time is not set.
174 let pairs = [
175 (want_start, "utcStart", task.start.is_some(), utc_start),
176 (want_due, "utcDue", task.due.is_some(), utc_due),
177 ];
178 for (wanted, key, has_local, utc) in pairs {
179 match (wanted, has_local, utc) {
180 (true, false, _) => item[key] = Value::Null,
181 (true, true, Some(d)) => item[key] = Value::String(d.into_inner()),
182 _ => {}
183 }
184 }
185 }
186 if let Some(obj) = item.as_object_mut() {
187 for name in &strip {
188 obj.remove(*name);
189 }
190 }
191 }
192 }
193
194 Ok(HandlerOutput::new(response).with_extra(tail))
195}
196
197// ---------------------------------------------------------------------------
198// Task/changes
199// ---------------------------------------------------------------------------
200
201/// Handle a `Task/changes` method call (draft-tasks-06 §4.6).
202///
203/// `args` is the RFC 8620 §5.2 `/changes` request shape (`accountId`,
204/// `sinceState`, optional `maxChanges`); the returned `Value` is the §5.2
205/// `/changes` response shape (`accountId`, `oldState`, `newState`,
206/// `hasMoreChanges`, `created`, `updated`, `destroyed`).
207///
208/// `using` is the request's capability list (pass
209/// [`jmap_server::CallContext::using`]); with
210/// `urn:ietf:params:jmap:metadata` the request may set
211/// draft-ietf-jmap-metadata-05 §3.3 `ignoreMetadataOnlyChanges`, and
212/// without it metadata-only changes are left out (-05 §3).
213///
214/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
215pub async fn handle_task_changes<B: TasksBackend>(
216 backend: &B,
217 caller: &B::CallerCtx,
218 args: Value,
219 using: &[String],
220) -> Result<HandlerOutput, JmapError> {
221 jmap_server::handle_changes::<Task, B>(backend, caller, args, using).await
222}
223
224// ---------------------------------------------------------------------------
225// Task/set
226// ---------------------------------------------------------------------------
227
228/// The Task properties that hold the id of another record, which a client
229/// may set to a `#creationId` reference (RFC 8620 §5.3).
230const TASK_ID_PROPERTIES: &[&str] = &["taskListId"];
231
232/// Handle a `Task/set` method call (draft-tasks-06 §4.7).
233///
234/// `args` is the RFC 8620 §5.3 `/set` request shape (`accountId`, optional
235/// `ifInState`, optional `create` / `update` / `destroy` maps); the
236/// returned `Value` is the §5.3 `/set` response shape (`accountId`,
237/// `oldState`, `newState`, plus the per-operation result maps).
238///
239/// **isDraft immutability**: this handler does not check `isDraft`. The
240/// backend's [`crate::TasksBackend::update_object`] MUST reject a patch that
241/// sets `isDraft: true` on a Task whose stored value is not `true` with
242/// `invalidProperties`, atomically with the write; the rejection is reported
243/// in `notUpdated`.
244///
245/// **`taskListId` references**: a `#creationId` value on create or update
246/// names a TaskList created earlier in the request and resolves against
247/// `created_ids` (pass [`jmap_server::CallContext::created_ids`]; RFC 8620
248/// §5.3). An unknown reference is `invalidProperties` naming `taskListId`.
249///
250/// `using` is the request's capability list (pass
251/// [`jmap_server::CallContext::using`]): a write to `metadata` or
252/// `privateMetadata` without `urn:ietf:params:jmap:metadata` is
253/// `invalidProperties` (draft-ietf-jmap-metadata-05 §3), as is `null` for
254/// either in a create (-05 §3.2). The backend validates the rest.
255///
256/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
257pub async fn handle_task_set<B: TasksBackend>(
258 backend: &B,
259 caller: &B::CallerCtx,
260 created_ids: &BTreeMap<Id, Id>,
261 args: Value,
262 using: &[String],
263) -> Result<HandlerOutput, JmapError> {
264 let (account_id, mut args) = extract_account_id(args)?;
265
266 // RFC 8620 §3.6.2: accountId not recognised → accountNotFound (method-level
267 // error). Without this, a /set against an unknown accountId would silently
268 // "succeed" with a fake oldState/newState envelope. Fixed in JMAP-gpt1.
269 if !backend
270 .account_exists(caller, &account_id)
271 .await
272 .map_err(|e| server_fail_from_backend(&e))?
273 {
274 return Err(JmapError::account_not_found());
275 }
276
277 // RFC 8620 §5.3 maxObjectsInSet (bd:JMAP-ayoz.41.5). Reject
278 // unbounded /set batches before touching the storage layer.
279 enforce_max_objects_in_set(&args, backend.max_objects_in_set(caller, &account_id))?;
280
281 let old_state = backend
282 .get_state::<Task>(caller, &account_id)
283 .await
284 .map_err(|e| server_fail_from_backend(&e))?;
285
286 if let Some(if_in_state) = args.get("ifInState").and_then(|v| v.as_str())
287 && if_in_state != old_state.as_ref()
288 {
289 return Err(JmapError::state_mismatch());
290 }
291
292 let mut created = serde_json::Map::new();
293 let mut not_created = serde_json::Map::new();
294 let mut updated = serde_json::Map::new();
295 let mut not_updated = serde_json::Map::new();
296 let mut destroyed_list: Vec<Value> = Vec::new();
297 let mut not_destroyed = serde_json::Map::new();
298 let mut mutated = false;
299
300 // -----------------------------------------------------------------------
301 // create
302 // -----------------------------------------------------------------------
303 if let Some(Value::Object(create_map)) = args.remove("create") {
304 for (create_id, mut obj_val) in create_map {
305 if let Some(err) = obj_val.as_object().and_then(reject_server_set::<Task>) {
306 not_created.insert(create_id, serde_json::Value::from(&err));
307 continue;
308 }
309 if let Some(Err(err)) = obj_val
310 .as_object()
311 .map(|o| check_metadata_entry(o, true, using))
312 {
313 not_created.insert(create_id, serde_json::Value::from(&*err));
314 continue;
315 }
316 if let Err(err) = resolve_refs(&mut obj_val, TASK_ID_PROPERTIES, created_ids) {
317 not_created.insert(create_id, serde_json::Value::from(&*err));
318 continue;
319 }
320 if let Some(prop) = obj_val
321 .as_object()
322 .and_then(|o| o.iter().find(|(_, v)| has_bad_person_uri(v)))
323 .map(|(k, _)| k.clone())
324 {
325 not_created.insert(create_id, person_uri_error(&prop));
326 continue;
327 }
328 // `Task.id` is optional, so the create parses without one and
329 // `build` sets the id the backend mints.
330 let mut task: Task = match serde_path_to_error::deserialize(obj_val) {
331 Ok(t) => t,
332 Err(e) => {
333 // RFC 8620 §5.3: invalidProperties SHOULD list the
334 // invalid properties; the first path segment is the
335 // top-level property whose value failed to parse.
336 let mut err =
337 json!({ "type": "invalidProperties", "description": e.to_string() });
338 if let Some(serde_path_to_error::Segment::Map { key }) = e.path().iter().next()
339 {
340 err["properties"] = json!([key]);
341 }
342 not_created.insert(create_id, err);
343 continue;
344 }
345 };
346
347 let build = move |id: &Id| {
348 task.id = Some(id.clone());
349 task
350 };
351 match backend
352 .create_object::<Task, _>(caller, &account_id, &create_id, build)
353 .await
354 {
355 Ok((_new_id, created_obj)) => {
356 mutated = true;
357 created.insert(create_id, jmap_server::serialize_value(&created_obj)?);
358 }
359 Err(e) => {
360 not_created.insert(create_id, backend_set_error_value(e));
361 }
362 }
363 }
364 }
365
366 // -----------------------------------------------------------------------
367 // update
368 // -----------------------------------------------------------------------
369 // RFC 8620 §5.3: update keys and destroy ids may name this call's creates.
370 jmap_server::resolve_set_id_refs(&mut args, created_ids, &created);
371 if let Some(Value::Object(update_map)) = args.remove("update") {
372 for (id_str, mut patch_val) in update_map {
373 // isDraft immutability (draft-tasks-06 §4 isDraft paragraph) is
374 // enforced by the backend in update_object, atomically with the
375 // write (TasksBackend::update_object, bd:JMAP-h47t.29).
376 let id = match jmap_server::parse_wire_id(&id_str, "id") {
377 Ok(id) => id,
378 Err(err) => {
379 not_updated.insert(id_str, serde_json::Value::from(&*err));
380 continue;
381 }
382 };
383
384 if let Err(err) = resolve_refs(&mut patch_val, TASK_ID_PROPERTIES, created_ids) {
385 not_updated.insert(id_str, serde_json::Value::from(&*err));
386 continue;
387 }
388 if let Some(prop) = patch_val.as_object().and_then(bad_person_uri_in_patch) {
389 not_updated.insert(id_str, person_uri_error(&prop));
390 continue;
391 }
392
393 // Convert wire-format Value into a typed PatchObject. RFC 8620
394 // §5.3 mandates a PatchObject is a JSON Object; non-object
395 // values produce an `invalidPatch` SetError.
396 let mut patch = match serde_json::from_value::<PatchObject>(patch_val) {
397 Ok(p) => p,
398 Err(e) => {
399 not_updated.insert(
400 id_str,
401 json!({ "type": "invalidPatch", "description": e.to_string() }),
402 );
403 continue;
404 }
405 };
406 // draft-ietf-jmap-tasks-06 §4: `id`, `baseTaskId` and `isOrigin`
407 // are server-set. A changed value is rejected, an identical one
408 // dropped (RFC 8620 §5.3); nothing left is a no-op success.
409 match check_read_only_patch::<_, Task>(
410 backend,
411 caller,
412 &account_id,
413 &id,
414 patch.as_map_mut(),
415 )
416 .await
417 {
418 Ok(false) => {}
419 Ok(true) => {
420 updated.insert(id_str, Value::Null);
421 continue;
422 }
423 Err(err) => {
424 not_updated.insert(id_str, err);
425 continue;
426 }
427 }
428
429 // Route to the per-user update path when every patch key targets
430 // a per-user Task property (draft-tasks-06 §4.5.1). Classified
431 // after the identical server-set values are dropped above, so
432 // they do not force a per-user change onto the shared path.
433 //
434 // PatchObject keys are RFC 6901 JSON Pointers (RFC 8620 §5.3), so a
435 // per-user keyword toggle is sent as `keywords/done`, not bare
436 // `keywords`. Classify on the FIRST pointer segment (the substring
437 // before the first '/'), not the whole key.
438 //
439 // A delete-shared-property patch like `{"title": null}` is a
440 // shared mutation and goes to `update_object`.
441 //
442 // Per-user property names (`keywords`, `color`, `freeBusyStatus`,
443 // `useDefaultAlerts`, `alerts`) contain no `/` or `~`, so a plain
444 // `split('/').next()` is correct without RFC 6901 unescaping.
445 let is_per_user_only = patch.as_map().keys().all(|k| {
446 let head = k.split('/').next().unwrap_or(k);
447 jmap_tasks_types::is_per_user_task_property(head)
448 });
449 if let Err(err) = check_metadata_entry(patch.as_map(), false, using) {
450 not_updated.insert(id_str, serde_json::Value::from(&*err));
451 continue;
452 }
453
454 let update_result = if is_per_user_only {
455 backend
456 .update_task_per_user(caller, &account_id, &id, patch)
457 .await
458 } else {
459 backend
460 .update_object::<Task>(caller, &account_id, &id, patch)
461 .await
462 };
463
464 match update_result {
465 Ok(Some(obj)) => {
466 mutated = true;
467 updated.insert(id_str, jmap_server::serialize_value(&obj)?);
468 }
469 Ok(None) => {
470 mutated = true;
471 updated.insert(id_str, Value::Null);
472 }
473 Err(e) => {
474 not_updated.insert(id_str, backend_set_error_value(e));
475 }
476 }
477 }
478 }
479
480 // -----------------------------------------------------------------------
481 // destroy
482 // -----------------------------------------------------------------------
483 if let Some(Value::Array(destroy_arr)) = args.remove("destroy") {
484 // RFC 8620 §5.3: every element of the destroy array MUST be a string Id.
485 // Two-pass validation is intentional: this up-front loop fails the whole
486 // request loudly; the `None => continue` arm in the inner match below
487 // is unreachable BECAUSE this pre-check ran. Future contributor: do NOT
488 // delete this pre-check on the reasoning that the inner match handles
489 // non-string elements — silent-skip is the wrong behaviour per the
490 // workspace "silent-drop is a data-integrity bug class" rule
491 // (JMAP-wlip.1).
492 let id_strs: Vec<&str> = destroy_arr
493 .iter()
494 .map(|v| {
495 v.as_str().ok_or_else(|| {
496 JmapError::invalid_arguments(format!(
497 "destroy: every element must be a string Id; got {}",
498 jmap_server::json_type_name(v)
499 ))
500 })
501 })
502 .collect::<Result<_, _>>()?;
503 for id_str in id_strs {
504 let id_str = id_str.to_owned();
505 let id = match jmap_server::parse_wire_id(&id_str, "id") {
506 Ok(id) => id,
507 Err(err) => {
508 not_destroyed.insert(id_str, serde_json::Value::from(&*err));
509 continue;
510 }
511 };
512
513 match backend
514 .destroy_object::<Task>(caller, &account_id, &id)
515 .await
516 {
517 Ok(()) => {
518 mutated = true;
519 destroyed_list.push(Value::String(id_str));
520 }
521 Err(e) => {
522 not_destroyed.insert(id_str, backend_set_error_value(e));
523 }
524 }
525 }
526 }
527
528 finalize_set_response::<B, Task>(
529 backend,
530 caller,
531 &account_id,
532 old_state,
533 mutated,
534 SetAccumulators {
535 created,
536 updated,
537 destroyed: destroyed_list,
538 not_created,
539 not_updated,
540 not_destroyed,
541 },
542 )
543 .await
544}
545
546// ---------------------------------------------------------------------------
547// Task/copy
548// ---------------------------------------------------------------------------
549
550/// Handle a `Task/copy` method call (draft-tasks-06 §4.8).
551///
552/// `args` is the RFC 8620 §5.4 `/copy` request shape (`fromAccountId`,
553/// optional `ifFromInState`, `accountId`, optional `ifInState`, `create`
554/// map, optional `onSuccessDestroyOriginal`, optional
555/// `destroyFromIfInState`); the returned `Value` is the §5.4 `/copy`
556/// response shape (`fromAccountId`, `accountId`, optional `oldState`,
557/// `newState`, optional `created`, optional `notCreated`).
558///
559/// `call_id` is the request's method-call id, used to construct any
560/// follow-up `Task/set` invocations injected when
561/// `onSuccessDestroyOriginal` is true (RFC 8620 §5.4 + §6.3).
562///
563/// Copies tasks from `fromAccountId` into the current account. The `create`
564/// map keys are client-side creation ids; the backend assigns new server-side
565/// ids.
566///
567/// `using` is the request's capability list (pass
568/// [`jmap_server::CallContext::using`]). draft-ietf-jmap-metadata-05 §3.4:
569/// the copy keeps the source's `metadata`, and its `privateMetadata` only
570/// with `urn:ietf:params:jmap:metadata` in `using` and when the
571/// destination supports it; neither is copied when the destination does
572/// not list Task ([`JmapAccounts::metadata_info`](jmap_server::JmapAccounts::metadata_info)).
573/// The create object "MAY include metadata and privateMetadata to override
574/// the copied values, with the same rules as a create in Foo/set": the
575/// handler rejects them without the capability and rejects `null`, and
576/// [`TasksBackend::copy_object`] validates the rest against the create
577/// object only: "Copied values are not revalidated against the
578/// destination account".
579///
580/// Returns `(response_args, extra_invocations)`. The extra invocation list
581/// is populated with a follow-up `Task/set` invocation when
582/// `onSuccessDestroyOriginal` is true (RFC 8620 §5.4); otherwise it is
583/// empty.
584/// `true` when `value` holds, at any depth, a Person object
585/// (draft-ietf-jmap-tasks §4.2.3 CheckItem `assignee`, §4.2.4 Comment
586/// `author`) whose `uri` is a string that is not an RFC 3986 URI
587/// (draft-atwood-jmap-updates-00 §7.1).
588fn has_bad_person_uri(value: &Value) -> bool {
589 match value {
590 Value::Object(m) => {
591 let bad_here = m.get("@type").and_then(Value::as_str) == Some("Person")
592 && m.get("uri")
593 .and_then(Value::as_str)
594 .is_some_and(|u| jmap_types::uri::check_uri(u).is_err());
595 bad_here || m.values().any(has_bad_person_uri)
596 }
597 Value::Array(a) => a.iter().any(has_bad_person_uri),
598 _ => false,
599 }
600}
601
602/// The top-level property of the first patch entry that writes a Person
603/// `uri` that is not an RFC 3986 URI: a value holding such a Person, or a
604/// pointer ending in `assignee/uri` or `author/uri` to a non-URI string.
605fn bad_person_uri_in_patch(patch: &serde_json::Map<String, Value>) -> Option<String> {
606 patch.iter().find_map(|(path, v)| {
607 let direct = (path.ends_with("/assignee/uri") || path.ends_with("/author/uri"))
608 && v.as_str()
609 .is_some_and(|u| jmap_types::uri::check_uri(u).is_err());
610 (direct || has_bad_person_uri(v)).then(|| path.split('/').next().unwrap_or(path).to_owned())
611 })
612}
613
614/// The `invalidProperties` SetError for a Person `uri` under `property`.
615fn person_uri_error(property: &str) -> Value {
616 json!({
617 "type": "invalidProperties",
618 "properties": [property],
619 "description": "a Person uri is not an RFC 3986 URI",
620 })
621}
622
623pub async fn handle_task_copy<B: TasksBackend>(
624 backend: &B,
625 caller: &B::CallerCtx,
626 args: Value,
627 call_id: &str,
628 using: &[String],
629) -> Result<HandlerOutput, JmapError> {
630 let (to_account_id, mut args) = extract_account_id(args)?;
631
632 if !backend
633 .account_exists(caller, &to_account_id)
634 .await
635 .map_err(|e| server_fail_from_backend(&e))?
636 {
637 return Err(JmapError::account_not_found());
638 }
639
640 let from_account_id_str = args
641 .remove("fromAccountId")
642 .and_then(|v| v.as_str().map(|s| s.to_owned()))
643 .ok_or_else(|| JmapError::invalid_arguments("fromAccountId is required"))?;
644 let from_account_id = Id::new_validated(from_account_id_str)
645 .map_err(|e| JmapError::invalid_arguments(format!("fromAccountId: {e}")))?;
646
647 // RFC 8620 §5.4: fromAccountId MUST differ from accountId. The canonical
648 // sibling jmap-mail-server enforces this in handle_email_copy; without it
649 // a same-account "copy" silently produces a duplicate within the source
650 // account, contradicting the meaning of /copy.
651 if from_account_id == to_account_id {
652 return Err(JmapError::invalid_arguments(
653 "fromAccountId must be different from accountId",
654 ));
655 }
656
657 // RFC 8620 §5.4: validate fromAccountId resolves to a real account;
658 // emit the spec-canonical `fromAccountNotFound` (not the generic
659 // `accountNotFound`) when it does not.
660 if !backend
661 .account_exists(caller, &from_account_id)
662 .await
663 .map_err(|e| server_fail_from_backend(&e))?
664 {
665 return Err(JmapError::from_account_not_found());
666 }
667
668 // RFC 8620 §5.4 `ifFromInState`: if supplied, the source-account Task
669 // state MUST match; otherwise abort with stateMismatch. Probed before
670 // the destination state so a stale source guard fails fast.
671 if let Some(if_from_in_state) = args.get("ifFromInState").and_then(|v| v.as_str()) {
672 let from_state = backend
673 .get_state::<Task>(caller, &from_account_id)
674 .await
675 .map_err(|e| server_fail_from_backend(&e))?;
676 if if_from_in_state != from_state.as_ref() {
677 return Err(JmapError::state_mismatch());
678 }
679 }
680
681 let old_state = backend
682 .get_state::<Task>(caller, &to_account_id)
683 .await
684 .map_err(|e| server_fail_from_backend(&e))?;
685
686 // RFC 8620 §5.4 `ifInState`: if supplied, the destination-account Task
687 // state MUST match; otherwise abort with stateMismatch.
688 if let Some(if_in_state) = args.get("ifInState").and_then(|v| v.as_str())
689 && if_in_state != old_state.as_ref()
690 {
691 return Err(JmapError::state_mismatch());
692 }
693
694 // RFC 8620 §5.4 `onSuccessDestroyOriginal` / `destroyFromIfInState`:
695 // parsed here so the request payload is consumed in handler-local order
696 // and so a clearly-shaped per-feature value is available below.
697 let on_success_destroy_original: bool = bool_arg(&args, "onSuccessDestroyOriginal", false);
698 let destroy_from_if_in_state: Option<String> = args
699 .get("destroyFromIfInState")
700 .and_then(|v| v.as_str())
701 .map(|s| s.to_owned());
702
703 let mut created = serde_json::Map::new();
704 let mut not_created = serde_json::Map::new();
705 let mut mutated = false;
706 // (create_id, source_id) pairs for entries that succeeded — fed to the
707 // implicit Task/set destroy below when onSuccessDestroyOriginal is true.
708 let mut copied_source_ids: Vec<(String, Id)> = Vec::new();
709
710 if let Some(Value::Object(create_map)) = args.remove("create") {
711 for (create_id, client_val) in create_map {
712 // RFC 8620 §5.4: the Foo object MUST contain an `id` property,
713 // which is the id (in the fromAccount) of the record to be copied.
714 // The earlier handler silently invented a "placeholder" id when
715 // the client omitted one, masking the missing-id case the spec
716 // treats as a hard requirement.
717 let Some(source_id_str) = client_val.get("id").and_then(|v| v.as_str()) else {
718 not_created.insert(
719 create_id,
720 json!({"type": "invalidProperties", "properties": ["id"]}),
721 );
722 continue;
723 };
724 let source_id: Id = match jmap_server::parse_wire_id(source_id_str, "id") {
725 Ok(id) => id,
726 Err(err) => {
727 not_created.insert(create_id, serde_json::Value::from(&*err));
728 continue;
729 }
730 };
731
732 // Fetch the source Task from `fromAccountId`. RFC 8620 §5.4 frames
733 // /copy as a read-from-source-then-create-in-destination operation;
734 // unknown source ids surface as `notFound` per-entry SetErrors.
735 let mut source_tasks: Vec<Task> = match backend
736 .get_objects::<Task>(
737 caller,
738 &from_account_id,
739 Some(std::slice::from_ref(&source_id)),
740 None,
741 )
742 .await
743 {
744 Ok((objs, not_found)) => {
745 if !not_found.is_empty() || objs.is_empty() {
746 not_created.insert(create_id, json!({"type": "notFound"}));
747 continue;
748 }
749 objs
750 }
751 Err(e) => {
752 not_created.insert(create_id, server_fail_value_from_backend(&e));
753 continue;
754 }
755 };
756
757 // RFC 8620 §5.4: "any other properties included [in the create
758 // entry] are used instead of the current value for that property
759 // on the original." Serialize the source, overlay client-supplied
760 // properties, strip the source id so the backend assigns a fresh
761 // server id. Pattern mirrors jmap-calendars-server event.rs:610-642.
762 // draft-ietf-jmap-metadata-05 §3.4: metadata overrides follow the
763 // Foo/set create rules (§3, §3.2).
764 if let Some(Err(err)) = client_val
765 .as_object()
766 .map(|o| check_metadata_entry(o, true, using))
767 {
768 not_created.insert(create_id, Value::from(&*err));
769 continue;
770 }
771 // -05 §3.4: "When the request does not use this capability, only
772 // metadata is copied", "privateMetadata is not copied when the
773 // destination does not support it, and neither property is
774 // copied when the data type is not listed in the destination
775 // account". The overrides are merged in below.
776 let info = backend.metadata_info::<Task>(caller, &to_account_id);
777 if !jmap_server::uses_metadata(using)
778 || !info.as_ref().is_some_and(|i| i.supports_private)
779 {
780 source_tasks[0].private_metadata = None;
781 }
782 if info.is_none() {
783 source_tasks[0].metadata = None;
784 }
785 let Ok(Value::Object(mut merged)) = serde_json::to_value(&source_tasks[0]) else {
786 not_created.insert(
787 create_id,
788 json!({
789 "type": "serverFail",
790 "description": "failed to serialize source Task",
791 }),
792 );
793 continue;
794 };
795 if let Value::Object(client_props) = &client_val {
796 for (k, v) in client_props {
797 if k != "id" {
798 merged.insert(k.clone(), v.clone());
799 }
800 }
801 }
802 merged.remove("id");
803 // draft-atwood-jmap-updates-00 §7.1, as for Task/set create.
804 if let Some(prop) = merged
805 .iter()
806 .find(|(_, v)| has_bad_person_uri(v))
807 .map(|(k, _)| k.clone())
808 {
809 not_created.insert(create_id, person_uri_error(&prop));
810 continue;
811 }
812
813 let task: Task = match serde_path_to_error::deserialize(Value::Object(merged)) {
814 Ok(t) => t,
815 Err(e) => {
816 // RFC 8620 §5.3: invalidProperties SHOULD list the
817 // invalid properties; the first path segment is the
818 // top-level property whose value failed to parse.
819 let mut err =
820 json!({ "type": "invalidProperties", "description": e.to_string() });
821 if let Some(serde_path_to_error::Segment::Map { key }) = e.path().iter().next()
822 {
823 err["properties"] = json!([key]);
824 }
825 not_created.insert(create_id, err);
826 continue;
827 }
828 };
829
830 // -05 §3.4: the backend validates only the metadata supplied in
831 // the create object; the copied values are not revalidated.
832 match backend
833 .copy_object(caller, &from_account_id, &to_account_id, task, &client_val)
834 .await
835 {
836 Ok((_new_id, created_task)) => {
837 mutated = true;
838 created.insert(
839 create_id.clone(),
840 jmap_server::serialize_value(&created_task)?,
841 );
842 copied_source_ids.push((create_id, source_id));
843 }
844 Err(e) => {
845 not_created.insert(create_id, backend_set_error_value(e));
846 }
847 }
848 }
849 }
850
851 let new_state = if mutated {
852 backend
853 .get_state::<Task>(caller, &to_account_id)
854 .await
855 .map_err(|e| server_fail_from_backend(&e))?
856 } else {
857 old_state.clone()
858 };
859
860 let resp = json!({
861 "fromAccountId": from_account_id.as_ref(),
862 "accountId": to_account_id.as_ref(),
863 "oldState": old_state.as_ref(),
864 "newState": new_state.as_ref(),
865 "created": if created.is_empty() { Value::Null } else { Value::Object(created) },
866 "notCreated": if not_created.is_empty() { Value::Null } else { Value::Object(not_created) },
867 });
868
869 // RFC 8620 §5.4 `onSuccessDestroyOriginal`: after emitting the Task/copy
870 // response, the server MUST make a single implicit Task/set call against
871 // fromAccountId destroying each successfully copied source record.
872 // `destroyFromIfInState`, if supplied, is passed through as the ifInState
873 // argument on that implicit call. The dispatcher returns the extra
874 // Invocation vec to the caller (RFC 8620 §6.3 chained responses).
875 // Pattern mirrors jmap-mail-server email.rs:2432-2575.
876 let mut extra: Vec<Invocation> = Vec::new();
877 if on_success_destroy_original && !copied_source_ids.is_empty() {
878 let from_old_state = backend
879 .get_state::<Task>(caller, &from_account_id)
880 .await
881 .map_err(|e| server_fail_from_backend(&e))?;
882
883 // Honour destroyFromIfInState on the implicit Task/set call. A
884 // mismatch yields a stateMismatch top-level error on the synthesized
885 // response (§5.4 inheriting §5.3 semantics on the chained call).
886 let mut destroy_state_mismatch = false;
887 if let Some(if_state) = destroy_from_if_in_state.as_deref()
888 && if_state != from_old_state.as_ref()
889 {
890 destroy_state_mismatch = true;
891 }
892
893 let mut destroyed_arr: Vec<Value> = Vec::new();
894 let mut not_destroyed = serde_json::Map::new();
895
896 if !destroy_state_mismatch {
897 for (_, source_id) in &copied_source_ids {
898 match backend
899 .destroy_object::<Task>(caller, &from_account_id, source_id)
900 .await
901 {
902 Ok(()) => {
903 destroyed_arr.push(Value::String(source_id.as_ref().to_owned()));
904 }
905 Err(e) => {
906 not_destroyed
907 .insert(source_id.as_ref().to_owned(), backend_set_error_value(e));
908 }
909 }
910 }
911 }
912
913 let from_new_state = backend
914 .get_state::<Task>(caller, &from_account_id)
915 .await
916 .map_err(|e| server_fail_from_backend(&e))?;
917
918 let set_resp = if destroy_state_mismatch {
919 json!({
920 "type": "stateMismatch",
921 })
922 } else {
923 json!({
924 "accountId": from_account_id.as_ref(),
925 "oldState": from_old_state.as_ref(),
926 "newState": from_new_state.as_ref(),
927 "created": Value::Null,
928 "updated": Value::Null,
929 "destroyed": if destroyed_arr.is_empty() { Value::Null } else { Value::Array(destroyed_arr) },
930 "notCreated": Value::Null,
931 "notUpdated": Value::Null,
932 "notDestroyed": if not_destroyed.is_empty() { Value::Null } else { Value::Object(not_destroyed) },
933 })
934 };
935
936 let method_name = if destroy_state_mismatch {
937 "error".to_owned()
938 } else {
939 "Task/set".to_owned()
940 };
941 extra.push(Invocation::new(method_name, set_resp, call_id.to_owned()));
942 }
943
944 Ok(HandlerOutput::new(resp).with_extra(extra))
945}
946
947// ---------------------------------------------------------------------------
948// Task/query
949// ---------------------------------------------------------------------------
950
951/// Handle a `Task/query` method call (draft-tasks-06 §4.13).
952///
953/// `args` is the RFC 8620 §5.5 `/query` request shape (`accountId`,
954/// optional `filter`, optional `sort`, optional `position`, optional
955/// `anchor`, optional `anchorOffset`, optional `limit`, optional
956/// `calculateTotal`); the returned `Value` is the §5.5 `/query`
957/// response shape (`accountId`, `queryState`, `canCalculateChanges`,
958/// `position`, `ids`, optional `total`).
959///
960/// The Task/query arguments of jmapio/jmap #456, as on CalendarEvent/query
961/// (draft-ietf-jmap-calendars-34 §5.11):
962///
963/// - `expandRecurrences`: Boolean (default `false`). "If true, the filter
964/// MUST be just a FilterCondition (not a FilterOperator) and MUST include
965/// both a "before" and "after" property; otherwise, the server MUST
966/// reject the call with an invalidArguments error." A window longer
967/// than [`TasksLimits::max_expanded_query_duration_seconds`](crate::TasksLimits::max_expanded_query_duration_seconds)
968/// (`maxExpandedQueryDuration`, draft-tasks-06 §1.6.2) is the
969/// `expandDurationTooLarge` method error, checked here and again by the
970/// backend.
971/// - `timeZone`: TimeZoneId (default `"Etc/UTC"`), the zone for the
972/// `after` / `before` conditions and for floating tasks. A value that is
973/// neither a string nor `null` is `invalidArguments`.
974///
975/// Both reach [`TasksBackend::query_tasks`] as a
976/// [`TaskQueryArgs`](crate::TaskQueryArgs). The backend may also return
977/// `cannotCalculateOccurrences`.
978///
979/// `using` is the request's capability list (pass
980/// [`jmap_server::CallContext::using`]); without
981/// `urn:ietf:params:jmap:metadata` a draft-ietf-jmap-metadata-05 §3.6
982/// filter condition is `unsupportedFilter` (-05 §3).
983///
984/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
985pub async fn handle_task_query<B: TasksBackend>(
986 backend: &B,
987 caller: &B::CallerCtx,
988 args: Value,
989 using: &[String],
990) -> Result<HandlerOutput, JmapError> {
991 jmap_server::reject_metadata_filter_arg(
992 &args,
993 jmap_tasks_types::TaskFilterCondition::has_metadata_condition,
994 using,
995 )?;
996 reject_unsupported_sort::<TaskComparator>(args.get("sort"))?;
997 let (account_id, mut args) = extract_account_id(args)?;
998 if !backend
999 .account_exists(caller, &account_id)
1000 .await
1001 .map_err(|e| server_fail_from_backend(&e))?
1002 {
1003 return Err(JmapError::account_not_found());
1004 }
1005 // Task has no localizable properties: as in the generic /query handler,
1006 // a non-null `language` is invalidArguments (draft-atwood-jmap-updates-00
1007 // §4.2).
1008 jmap_server::I18nProjection::from_args::<Task>(
1009 &mut args,
1010 &[],
1011 backend.i18n_info(caller, &account_id).as_ref(),
1012 )?;
1013
1014 // RFC 8620 §5.5 arguments.
1015 let calculate_total = bool_arg(&args, "calculateTotal", false);
1016 let limit: Option<u64> = match args.get("limit") {
1017 None | Some(Value::Null) => None,
1018 Some(v) => Some(v.as_u64().ok_or_else(|| {
1019 JmapError::invalid_arguments(format!(
1020 "limit: expected a non-negative integer, got {}",
1021 jmap_server::json_type_name(v)
1022 ))
1023 })?),
1024 };
1025 let position: i64 = match args.get("position") {
1026 None | Some(Value::Null) => 0,
1027 Some(v) => v.as_i64().ok_or_else(|| {
1028 JmapError::invalid_arguments(format!(
1029 "position: expected an integer, got {}",
1030 jmap_server::json_type_name(v)
1031 ))
1032 })?,
1033 };
1034 let (anchor, anchor_offset) = query_anchor_args(&args)?;
1035 let filter: Option<TaskFilter> = filter_arg(&mut args)?;
1036 let sort: Option<Vec<TaskComparator>> = optional_arg(&mut args, "sort", || {
1037 JmapError::invalid_arguments("sort must be an array")
1038 })?;
1039
1040 // jmapio/jmap #456 arguments.
1041 let expand_recurrences = bool_arg(&args, "expandRecurrences", false);
1042 let time_zone: Option<String> = optional_arg(&mut args, "timeZone", || {
1043 JmapError::invalid_arguments("timeZone must be a string")
1044 })?;
1045 if expand_recurrences {
1046 let condition = match &filter {
1047 Some(Filter::Condition(c)) if c.before.is_some() && c.after.is_some() => c,
1048 _ => {
1049 return Err(JmapError::invalid_arguments(
1050 "expandRecurrences requires a FilterCondition with both 'before' and 'after'",
1051 ));
1052 }
1053 };
1054 // Defense in depth; the backend re-checks (TasksBackend::query_tasks).
1055 if let Some(secs) = expand_duration_seconds(condition)
1056 && u64::try_from(secs).is_ok_and(|secs| {
1057 secs > backend
1058 .limits(caller, &account_id)
1059 .max_expanded_query_duration_seconds
1060 })
1061 {
1062 return Err(JmapError::custom("expandDurationTooLarge"));
1063 }
1064 }
1065 let query_args = crate::TaskQueryArgs::default()
1066 .with_expand_recurrences(expand_recurrences)
1067 .with_time_zone(time_zone);
1068
1069 let result = backend
1070 .query_tasks(
1071 caller,
1072 &account_id,
1073 QueryParams::new()
1074 .filter(filter.as_ref())
1075 .sort(sort.as_deref())
1076 .limit(limit)
1077 .position(position)
1078 .anchor(anchor.as_ref())
1079 .anchor_offset(anchor_offset),
1080 &query_args,
1081 )
1082 .await
1083 .map_err(JmapError::from)?;
1084
1085 let mut resp = json!({
1086 "accountId": account_id.as_ref(),
1087 "queryState": result.query_state.as_ref(),
1088 "canCalculateChanges": result.can_calculate_changes,
1089 "position": result.position,
1090 "ids": result.ids,
1091 });
1092 if calculate_total && let Some(t) = result.total {
1093 resp["total"] = json!(t);
1094 }
1095 Ok(HandlerOutput::new(resp))
1096}
1097
1098/// `before - after` of `condition` in seconds, for the
1099/// `maxExpandedQueryDuration` pre-check; `None` when a bound is missing or
1100/// does not parse.
1101///
1102/// Both bounds are `LocalDateTime`s read in the same `timeZone`, so their
1103/// difference is read as if both were UTC (the calendars-server pre-check
1104/// does the same). A time-zone transition inside the window can make the
1105/// real span differ by its offset change; the backend's own check is the
1106/// exact one.
1107pub(crate) fn expand_duration_seconds(condition: &TaskFilterCondition) -> Option<i64> {
1108 let epoch = |local: &jmap_tasks_types::LocalDateTime| {
1109 UTCDate::from(format!("{local}Z")).to_epoch_seconds().ok()
1110 };
1111 Some(epoch(condition.before.as_ref()?)? - epoch(condition.after.as_ref()?)?)
1112}
1113
1114// ---------------------------------------------------------------------------
1115// Task/queryChanges
1116// ---------------------------------------------------------------------------
1117
1118/// Handle a `Task/queryChanges` method call (draft-tasks-06 §4.14).
1119///
1120/// `args` is the RFC 8620 §5.6 `/queryChanges` request shape (`accountId`,
1121/// optional `filter`, optional `sort`, `sinceQueryState`, optional
1122/// `maxChanges`, optional `upToId`, optional `calculateTotal`); the
1123/// returned `Value` is the §5.6 `/queryChanges` response shape
1124/// (`accountId`, `oldQueryState`, `newQueryState`, optional `total`,
1125/// `removed`, `added`).
1126///
1127/// `using` is the request's capability list (pass
1128/// [`jmap_server::CallContext::using`]); without
1129/// `urn:ietf:params:jmap:metadata` a draft-ietf-jmap-metadata-05 §3.6
1130/// filter condition is `unsupportedFilter` (-05 §3).
1131///
1132/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
1133pub async fn handle_task_query_changes<B: TasksBackend>(
1134 backend: &B,
1135 caller: &B::CallerCtx,
1136 args: Value,
1137 using: &[String],
1138) -> Result<HandlerOutput, JmapError> {
1139 jmap_server::reject_metadata_filter_arg(
1140 &args,
1141 jmap_tasks_types::TaskFilterCondition::has_metadata_condition,
1142 using,
1143 )?;
1144 reject_unsupported_sort::<TaskComparator>(args.get("sort"))?;
1145 jmap_server::handle_query_changes::<Task, B>(backend, caller, args).await
1146}
1147
1148// ---------------------------------------------------------------------------
1149// Tests
1150// ---------------------------------------------------------------------------
1151
1152#[cfg(test)]
1153mod tests {
1154 use super::*;
1155 use serde_json::json;
1156
1157 use crate::test_support::MockBackend;
1158
1159 /// Oracle: RFC 8620 §5.5 `unsupportedSort`: "The sort is syntactically
1160 /// valid, but includes a property the server does not support sorting
1161 /// on". docs/specs/jmap-tasks-local.md Sorting (draft-ietf-jmap-calendars-34
1162 /// §5.11.2): "MUST be supported for sorting: `id`, `uid`, `start`. The
1163 /// following SHOULD be supported: `created`, `updated`." `title` is not
1164 /// among them, nor is -26's `recurrenceId`, which -34 dropped.
1165 #[tokio::test]
1166 async fn query_unlisted_sort_property_returns_unsupported_sort() {
1167 let backend = MockBackend::new_with_account("acc1");
1168 for property in ["title", "recurrenceId"] {
1169 let args = json!({ "accountId": "acc1", "sort": [{ "property": property }] });
1170 let err = handle_task_query(&backend, &(), args, &[])
1171 .await
1172 .expect_err("unlisted sort property must be rejected");
1173 assert_eq!(err.error_type.to_string(), "unsupportedSort", "{property}");
1174 }
1175 }
1176
1177 /// Oracle: as above; `Task/queryChanges` carries the same `sort`
1178 /// (RFC 8620 §5.6).
1179 #[tokio::test]
1180 async fn query_changes_unlisted_sort_property_returns_unsupported_sort() {
1181 let backend = MockBackend::new_with_account("acc1");
1182 let args = json!({
1183 "accountId": "acc1",
1184 "sinceQueryState": "0",
1185 "sort": [{ "property": "start" }, { "property": "title" }]
1186 });
1187 let err = handle_task_query_changes(&backend, &(), args, &[])
1188 .await
1189 .expect_err("unlisted sort property must be rejected");
1190 assert_eq!(err.error_type.to_string(), "unsupportedSort");
1191 }
1192
1193 /// Oracle: docs/specs/jmap-tasks-local.md Sorting: "The following
1194 /// properties MUST be supported for sorting: `id`, `uid`, `start`. The
1195 /// following SHOULD be supported: `created`, `updated`."
1196 #[tokio::test]
1197 async fn query_listed_sort_property_is_accepted() {
1198 let backend = MockBackend::new_with_account("acc1");
1199 for property in ["id", "uid", "start", "created", "updated"] {
1200 let args = json!({ "accountId": "acc1", "sort": [{ "property": property }] });
1201 handle_task_query(&backend, &(), args, &[])
1202 .await
1203 .expect("listed sort property must not be rejected");
1204 }
1205 }
1206
1207 /// Oracle: Task/get with unknown accountId returns accountNotFound.
1208 #[tokio::test]
1209 async fn get_unknown_account_returns_account_not_found() {
1210 let backend = MockBackend::new();
1211 let args = json!({ "accountId": "unknown", "ids": null });
1212 let result = handle_task_get(&backend, &(), args, &[]).await;
1213 let err = result.expect_err("must return error for unknown account");
1214 assert_eq!(err.error_type.to_string(), "accountNotFound");
1215 }
1216
1217 /// Oracle: Task/copy missing fromAccountId returns invalidArguments.
1218 #[tokio::test]
1219 async fn copy_missing_from_account_id_returns_invalid_arguments() {
1220 let backend = MockBackend::new_with_account("acc1");
1221 let args = json!({
1222 "accountId": "acc1",
1223 "create": {}
1224 });
1225 let result = handle_task_copy(&backend, &(), args, "c0", &[]).await;
1226 let err = result.expect_err("must return error when fromAccountId missing");
1227 assert_eq!(err.error_type.to_string(), "invalidArguments");
1228 }
1229
1230 /// Oracle: RFC 8620 §5.4 — fromAccountId MUST be different from accountId.
1231 /// A same-account request must be rejected with invalidArguments before
1232 /// any per-create work. Matches the canonical sibling jmap-mail-server
1233 /// at email.rs:2263-2268.
1234 #[tokio::test]
1235 async fn copy_same_account_returns_invalid_arguments() {
1236 let backend = MockBackend::new_with_account("acc1");
1237 let args = json!({
1238 "accountId": "acc1",
1239 "fromAccountId": "acc1",
1240 "create": {}
1241 });
1242 let result = handle_task_copy(&backend, &(), args, "c0", &[]).await;
1243 let err = result.expect_err("must reject same-account Task/copy per RFC 8620 §5.4");
1244 assert_eq!(err.error_type.to_string(), "invalidArguments");
1245 }
1246
1247 /// Oracle: RFC 8620 §5.4 — `fromAccountId` that does not resolve to a
1248 /// real account returns the spec-canonical `fromAccountNotFound` error,
1249 /// not the generic `accountNotFound`.
1250 #[tokio::test]
1251 async fn copy_unknown_from_account_returns_from_account_not_found() {
1252 let backend = MockBackend::new_with_account("acc1");
1253 let args = json!({
1254 "accountId": "acc1",
1255 "fromAccountId": "no-such-account",
1256 "create": {}
1257 });
1258 let result = handle_task_copy(&backend, &(), args, "c0", &[]).await;
1259 let err = result.expect_err("must reject unknown fromAccountId");
1260 assert_eq!(err.error_type.to_string(), "fromAccountNotFound");
1261 }
1262
1263 /// Oracle: RFC 8620 §5.4 — `ifFromInState` mismatch on the source
1264 /// account returns `stateMismatch`.
1265 #[tokio::test]
1266 async fn copy_if_from_in_state_mismatch_returns_state_mismatch() {
1267 let mut backend = MockBackend::new_with_account("acc1");
1268 backend.add_account("acc2");
1269 let args = json!({
1270 "accountId": "acc1",
1271 "fromAccountId": "acc2",
1272 "ifFromInState": "stale-source-state",
1273 "create": {}
1274 });
1275 let result = handle_task_copy(&backend, &(), args, "c0", &[]).await;
1276 let err = result.expect_err("must reject stale ifFromInState");
1277 assert_eq!(err.error_type.to_string(), "stateMismatch");
1278 }
1279
1280 /// Oracle: RFC 8620 §5.4 — `ifInState` mismatch on the destination
1281 /// account returns `stateMismatch`.
1282 #[tokio::test]
1283 async fn copy_if_in_state_mismatch_returns_state_mismatch() {
1284 let mut backend = MockBackend::new_with_account("acc1");
1285 backend.add_account("acc2");
1286 let args = json!({
1287 "accountId": "acc1",
1288 "fromAccountId": "acc2",
1289 "ifInState": "stale-destination-state",
1290 "create": {}
1291 });
1292 let result = handle_task_copy(&backend, &(), args, "c0", &[]).await;
1293 let err = result.expect_err("must reject stale ifInState");
1294 assert_eq!(err.error_type.to_string(), "stateMismatch");
1295 }
1296
1297 /// Oracle: RFC 8620 §5.4 — a create entry without an `id` property must
1298 /// produce a per-entry `invalidProperties` SetError naming `id`. The
1299 /// previous handler silently substituted a "placeholder" id, masking
1300 /// this hard requirement.
1301 #[tokio::test]
1302 async fn copy_create_entry_without_id_returns_invalid_properties() {
1303 let mut backend = MockBackend::new_with_account("acc1");
1304 backend.add_account("acc2");
1305 let args = json!({
1306 "accountId": "acc1",
1307 "fromAccountId": "acc2",
1308 "create": { "c1": {} }
1309 });
1310 let HandlerOutput { primary: resp, .. } = handle_task_copy(&backend, &(), args, "c0", &[])
1311 .await
1312 .expect("top-level call must succeed");
1313 let nc = resp["notCreated"].as_object().expect("notCreated present");
1314 let err = nc.get("c1").expect("c1 in notCreated");
1315 assert_eq!(err["type"], "invalidProperties");
1316 assert_eq!(err["properties"][0], "id");
1317 }
1318
1319 /// Oracle: RFC 8620 §5.4 — when the source id does not resolve to a
1320 /// Task in `fromAccountId`, the per-entry result is `notFound`.
1321 #[tokio::test]
1322 async fn copy_unknown_source_id_returns_not_found() {
1323 let mut backend = MockBackend::new_with_account("acc1");
1324 backend.add_account("acc2");
1325 let args = json!({
1326 "accountId": "acc1",
1327 "fromAccountId": "acc2",
1328 "create": { "c1": { "id": "no-such-task" } }
1329 });
1330 let HandlerOutput { primary: resp, .. } = handle_task_copy(&backend, &(), args, "c0", &[])
1331 .await
1332 .expect("top-level call must succeed");
1333 let nc = resp["notCreated"].as_object().expect("notCreated present");
1334 assert_eq!(nc["c1"]["type"], "notFound");
1335 }
1336
1337 /// Oracle: RFC 8620 §5.4 — the create entry's `id` selects WHAT to copy;
1338 /// client-supplied properties OTHER than `id` overlay the source values.
1339 /// Verify the handler actually round-trips through the source: seed a
1340 /// Task into `from_account`, request a copy that overrides `title`, and
1341 /// confirm the response carries the override.
1342 #[tokio::test]
1343 async fn copy_fetches_source_and_overlays_client_overrides() {
1344 let mut backend = MockBackend::new_with_account("acc1");
1345 backend.add_account("acc2");
1346 backend.seed_task("acc2", "src1", true); // source task in acc2
1347
1348 let args = json!({
1349 "accountId": "acc1",
1350 "fromAccountId": "acc2",
1351 "create": {
1352 "c1": { "id": "src1", "title": "Overridden title" }
1353 }
1354 });
1355 let HandlerOutput { primary: resp, .. } = handle_task_copy(&backend, &(), args, "c0", &[])
1356 .await
1357 .expect("top-level call must succeed");
1358
1359 // Source was fetched and the override applied: the created entry
1360 // carries the new title, not the source value (which had none).
1361 let created = resp["created"].as_object().expect("created present");
1362 let c1 = created.get("c1").expect("c1 in created");
1363 assert_eq!(
1364 c1["title"], "Overridden title",
1365 "client-supplied title must override source value: {resp}"
1366 );
1367 }
1368
1369 /// Oracle: RFC 8620 §5.4 — when `onSuccessDestroyOriginal` is true, the
1370 /// server emits a single implicit Task/set call against fromAccountId
1371 /// destroying each successfully copied source. The synthesized response
1372 /// appears in the extra Vec<Invocation> with the same callId as the
1373 /// triggering Task/copy. Mirrors canonical jmap-mail-server
1374 /// email.rs:2432-2575.
1375 #[tokio::test]
1376 async fn copy_on_success_destroy_original_emits_implicit_task_set() {
1377 let mut backend = MockBackend::new_with_account("acc1");
1378 backend.add_account("acc2");
1379 backend.seed_task("acc2", "src1", true);
1380
1381 let args = json!({
1382 "accountId": "acc1",
1383 "fromAccountId": "acc2",
1384 "onSuccessDestroyOriginal": true,
1385 "create": {
1386 "c1": { "id": "src1" }
1387 }
1388 });
1389 let HandlerOutput {
1390 extra_invocations: extra,
1391 ..
1392 } = handle_task_copy(&backend, &(), args, "c0", &[])
1393 .await
1394 .expect("top-level call must succeed");
1395
1396 // Exactly one synthesized invocation: ("Task/set", response, "c0").
1397 assert_eq!(extra.len(), 1, "must emit one implicit Task/set: {extra:?}");
1398 let Invocation {
1399 name: method,
1400 arguments: val,
1401 call_id: ci,
1402 } = &extra[0];
1403 assert_eq!(method, "Task/set");
1404 assert_eq!(ci, "c0");
1405 assert_eq!(val["accountId"], "acc2", "implicit set targets fromAccount");
1406 let destroyed = val["destroyed"]
1407 .as_array()
1408 .expect("destroyed must be array");
1409 assert_eq!(destroyed.len(), 1);
1410 assert_eq!(destroyed[0], "src1");
1411 // Both state fields are present on the synthesized response. Their
1412 // bump semantics depend on the underlying backend's get_state — the
1413 // MockBackend here always returns "0" so we only assert presence;
1414 // state-advance semantics are covered by stateful integration tests.
1415 assert!(val.get("oldState").is_some(), "oldState must be present");
1416 assert!(val.get("newState").is_some(), "newState must be present");
1417 }
1418
1419 /// Oracle: RFC 8620 §5.4 — `destroyFromIfInState` mismatch on the implicit
1420 /// Task/set call yields a `stateMismatch` error response in place of the
1421 /// normal Task/set body. The destroy MUST NOT proceed.
1422 #[tokio::test]
1423 async fn copy_destroy_from_if_in_state_mismatch_aborts_destroy() {
1424 let mut backend = MockBackend::new_with_account("acc1");
1425 backend.add_account("acc2");
1426 backend.seed_task("acc2", "src1", true);
1427
1428 let args = json!({
1429 "accountId": "acc1",
1430 "fromAccountId": "acc2",
1431 "onSuccessDestroyOriginal": true,
1432 "destroyFromIfInState": "stale-source-state",
1433 "create": {
1434 "c1": { "id": "src1" }
1435 }
1436 });
1437 let HandlerOutput {
1438 extra_invocations: extra,
1439 ..
1440 } = handle_task_copy(&backend, &(), args, "c0", &[])
1441 .await
1442 .expect("top-level call must succeed");
1443
1444 assert_eq!(extra.len(), 1);
1445 let Invocation { arguments: val, .. } = &extra[0];
1446 assert_eq!(val["type"], "stateMismatch");
1447 }
1448
1449 /// Oracle: RFC 8620 §5.4 — when `onSuccessDestroyOriginal` is false (or
1450 /// absent), no implicit Task/set call is synthesized.
1451 #[tokio::test]
1452 async fn copy_without_on_success_emits_no_extra_invocations() {
1453 let mut backend = MockBackend::new_with_account("acc1");
1454 backend.add_account("acc2");
1455 backend.seed_task("acc2", "src1", true);
1456
1457 let args = json!({
1458 "accountId": "acc1",
1459 "fromAccountId": "acc2",
1460 "create": {
1461 "c1": { "id": "src1" }
1462 }
1463 });
1464 let HandlerOutput {
1465 extra_invocations: extra,
1466 ..
1467 } = handle_task_copy(&backend, &(), args, "c0", &[])
1468 .await
1469 .expect("top-level call must succeed");
1470 assert!(
1471 extra.is_empty(),
1472 "no extra invocations without onSuccessDestroyOriginal: {extra:?}"
1473 );
1474 }
1475
1476 /// Oracle: Task/set empty destroy returns valid response.
1477 #[tokio::test]
1478 async fn set_empty_destroy_returns_valid_response() {
1479 let backend = MockBackend::new_with_account("acc1");
1480 let args = json!({ "accountId": "acc1", "destroy": [] });
1481 let HandlerOutput { primary: resp, .. } =
1482 handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1483 .await
1484 .expect("must not return top-level error");
1485 assert_eq!(resp["accountId"], "acc1");
1486 }
1487
1488 // ── isDraft immutability enforcement (draft-tasks-06 §4 (isDraft paragraph)) ─
1489
1490 /// Oracle: draft-tasks-06 §4 — "Once set to false, the value [isDraft]
1491 /// cannot be updated to true."
1492 /// A patch of {"isDraft": true} on a task that already has isDraft=false
1493 /// MUST be rejected with invalidProperties. The handler does no isDraft
1494 /// check, so this exercises the backend rejection reaching `notUpdated`.
1495 #[tokio::test]
1496 async fn set_is_draft_revert_rejected_when_current_is_false() {
1497 let mut backend = MockBackend::new_with_account("acc1");
1498 // Pre-seed a published (isDraft=false) task.
1499 backend.seed_task("acc1", "t1", false);
1500
1501 let args = json!({
1502 "accountId": "acc1",
1503 "update": {
1504 "t1": { "isDraft": true }
1505 }
1506 });
1507 let HandlerOutput { primary: resp, .. } =
1508 handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1509 .await
1510 .expect("must not return a top-level error");
1511
1512 let not_updated = resp["notUpdated"]
1513 .as_object()
1514 .expect("notUpdated must be an object");
1515 assert!(
1516 not_updated.contains_key("t1"),
1517 "t1 must appear in notUpdated: {resp}"
1518 );
1519 assert_eq!(
1520 not_updated["t1"]["type"].as_str(),
1521 Some("invalidProperties"),
1522 "error type must be invalidProperties"
1523 );
1524 assert_eq!(
1525 not_updated["t1"]["properties"][0].as_str(),
1526 Some("isDraft"),
1527 "properties must list isDraft"
1528 );
1529 }
1530
1531 /// Oracle: draft-tasks-06 §4 — patching {"isDraft": true} on a task that
1532 /// is already a draft (isDraft=true) is allowed (no state transition).
1533 #[tokio::test]
1534 async fn set_is_draft_true_on_draft_task_passes_to_backend() {
1535 let mut backend = MockBackend::new_with_account("acc1");
1536 // Pre-seed a draft task (isDraft=true).
1537 backend.seed_task("acc1", "t2", true);
1538
1539 let args = json!({
1540 "accountId": "acc1",
1541 "update": {
1542 "t2": { "isDraft": true }
1543 }
1544 });
1545 let HandlerOutput { primary: resp, .. } =
1546 handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1547 .await
1548 .expect("must not return a top-level error");
1549
1550 // The handler passes the patch to the backend (which returns Forbidden
1551 // in the mock). The important thing is it is NOT pre-rejected here —
1552 // it must NOT appear in notUpdated with type=="invalidProperties".
1553 if let Some(not_updated) = resp["notUpdated"].as_object()
1554 && let Some(err) = not_updated.get("t2")
1555 {
1556 assert_ne!(
1557 err["type"].as_str(),
1558 Some("invalidProperties"),
1559 "isDraft:true on an existing draft must not produce invalidProperties"
1560 );
1561 }
1562 }
1563
1564 /// Oracle: draft-tasks-06 §4 — patching {"isDraft": false} is always allowed
1565 /// (moving from draft to published is a one-way door going the right way).
1566 #[tokio::test]
1567 async fn set_is_draft_false_passes_to_backend() {
1568 let mut backend = MockBackend::new_with_account("acc1");
1569 backend.seed_task("acc1", "t3", true);
1570
1571 let args = json!({
1572 "accountId": "acc1",
1573 "update": {
1574 "t3": { "isDraft": false }
1575 }
1576 });
1577 let HandlerOutput { primary: resp, .. } =
1578 handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1579 .await
1580 .expect("must not return a top-level error");
1581
1582 // Like above: the patch must NOT be pre-rejected with invalidProperties.
1583 if let Some(not_updated) = resp["notUpdated"].as_object()
1584 && let Some(err) = not_updated.get("t3")
1585 {
1586 assert_ne!(
1587 err["type"].as_str(),
1588 Some("invalidProperties"),
1589 "isDraft:false must never produce invalidProperties"
1590 );
1591 }
1592 }
1593
1594 // ── compute_utc_times / utcStart wiring (draft-tasks-06 §4 (utcStart/utcDue paragraphs)) ─
1595
1596 /// Oracle: draft-tasks-06 §4 — utcStart is not returned unless explicitly
1597 /// requested in `properties`. The default impl returns None so it must be
1598 /// absent from the response when not requested.
1599 #[tokio::test]
1600 async fn get_without_utc_properties_omits_utc_fields() {
1601 let backend = MockBackend::new_with_account("acc1");
1602 let args = json!({
1603 "accountId": "acc1",
1604 "ids": null,
1605 "properties": ["id", "title"] // utcStart and utcDue NOT listed
1606 });
1607 let HandlerOutput { primary: resp, .. } = handle_task_get(&backend, &(), args, &[])
1608 .await
1609 .expect("must succeed");
1610 // The list is empty (no tasks seeded), but the response itself must be valid.
1611 assert_eq!(resp["accountId"], "acc1");
1612 // No utcStart or utcDue should appear in response items (list is empty so
1613 // this is vacuously satisfied, but the path is exercised without error).
1614 let list = resp["list"].as_array().expect("list must be an array");
1615 for item in list {
1616 assert!(
1617 item.get("utcStart").is_none(),
1618 "utcStart must not appear when not in properties"
1619 );
1620 }
1621 }
1622
1623 /// Oracle: draft-tasks-06 §4 — when utcStart is in properties, the handler
1624 /// calls compute_utc_times. The default impl returns (None, None) so
1625 /// no utcStart key is injected, but no error is raised either.
1626 #[tokio::test]
1627 async fn get_with_utc_start_in_properties_does_not_error() {
1628 let backend = MockBackend::new_with_account("acc1");
1629 let args = json!({
1630 "accountId": "acc1",
1631 "ids": null,
1632 "properties": ["id", "utcStart", "utcDue"]
1633 });
1634 let HandlerOutput { primary: resp, .. } = handle_task_get(&backend, &(), args, &[])
1635 .await
1636 .expect("must succeed with utcStart in properties");
1637 assert_eq!(resp["accountId"], "acc1");
1638 }
1639
1640 // ── per-user property routing (draft-tasks-06 §4.5.1) ──────────────────
1641 //
1642 // Routing is observable via MockBackend::per_user_calls — a counter that
1643 // increments inside `update_task_per_user` and stays at 0 for paths that
1644 // go to `update_object`. The earlier shape of these tests only asserted
1645 // that no `invalidProperties` error came back, which would pass even if
1646 // routing were inverted; tightened here to inspect the counter directly.
1647
1648 /// Oracle: draft-tasks-06 §4.5.1 — a patch with only per-user properties
1649 /// (bare keys, no JSON Pointer sub-paths) must route to update_task_per_user.
1650 #[tokio::test]
1651 async fn set_per_user_only_patch_routes_to_per_user_update() {
1652 use std::sync::atomic::Ordering;
1653 let backend = MockBackend::new_with_account("acc1");
1654 // color is a per-user property (§4.5.1).
1655 let args = json!({
1656 "accountId": "acc1",
1657 "update": { "t1": { "color": "#ff0000" } }
1658 });
1659 let _ = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1660 .await
1661 .expect("must not return top-level error");
1662 assert_eq!(
1663 backend.per_user_calls.load(Ordering::Relaxed),
1664 1,
1665 "per-user-only patch must route to update_task_per_user"
1666 );
1667 }
1668
1669 /// Oracle: draft-tasks-06 §4.5.1 + RFC 8620 §5.3 — JSON-pointer patches on
1670 /// per-user properties (e.g. `keywords/done: true` to toggle a single
1671 /// keyword, `alerts/0/offset: null` to clear an alert sub-field) must still
1672 /// route to update_task_per_user. The first pointer segment is the
1673 /// property name; the implementation MUST classify on that segment, not
1674 /// on the whole key.
1675 #[tokio::test]
1676 async fn set_per_user_json_pointer_patch_routes_to_per_user_update() {
1677 use std::sync::atomic::Ordering;
1678 let backend = MockBackend::new_with_account("acc1");
1679 let args = json!({
1680 "accountId": "acc1",
1681 "update": {
1682 "t1": {
1683 "keywords/done": true,
1684 "alerts/0/offset": null
1685 }
1686 }
1687 });
1688 let _ = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1689 .await
1690 .expect("must not return top-level error");
1691 assert_eq!(
1692 backend.per_user_calls.load(Ordering::Relaxed),
1693 1,
1694 "JSON-pointer patch on per-user properties must route to update_task_per_user"
1695 );
1696 }
1697
1698 /// Oracle: RFC 8620 §5.3 "Any server-set properties MAY be included in
1699 /// the patch if their value is identical to the current server value"
1700 /// and draft-tasks-06 §4.5.1: an identical `id` is no change, so a
1701 /// patch of it and a per-user keyword toggle is per-user only and
1702 /// routes to update_task_per_user.
1703 #[tokio::test]
1704 async fn set_identical_id_with_per_user_patch_routes_to_per_user_update() {
1705 use std::sync::atomic::Ordering;
1706 let mut backend = MockBackend::new_with_account("acc1");
1707 backend.seed_task("acc1", "t1", false);
1708 let args = json!({
1709 "accountId": "acc1",
1710 "update": { "t1": { "id": "t1", "keywords/done": true } }
1711 });
1712 let _ = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1713 .await
1714 .expect("must not return top-level error");
1715 assert_eq!(
1716 backend.per_user_calls.load(Ordering::Relaxed),
1717 1,
1718 "identical id must not move a per-user patch to update_object"
1719 );
1720 }
1721
1722 /// Oracle: draft-tasks-06 §4.5.1 — a patch on a shared property (title)
1723 /// must route to update_object.
1724 #[tokio::test]
1725 async fn set_shared_property_patch_routes_to_update_object() {
1726 use std::sync::atomic::Ordering;
1727 let backend = MockBackend::new_with_account("acc1");
1728 let args = json!({
1729 "accountId": "acc1",
1730 "update": { "t1": { "title": "New title" } }
1731 });
1732 let _ = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1733 .await
1734 .expect("must not return top-level error");
1735 assert_eq!(
1736 backend.per_user_calls.load(Ordering::Relaxed),
1737 0,
1738 "shared-property patch must NOT route to update_task_per_user"
1739 );
1740 }
1741
1742 /// Oracle: RFC 7396 / RFC 8620 §5.3 — `{"title": null}` is a delete-shared-
1743 /// property mutation, NOT a per-user mutation. The previous routing
1744 /// short-circuited on null values, misclassifying this as per-user-only.
1745 #[tokio::test]
1746 async fn set_shared_property_null_patch_routes_to_update_object() {
1747 use std::sync::atomic::Ordering;
1748 let backend = MockBackend::new_with_account("acc1");
1749 let args = json!({
1750 "accountId": "acc1",
1751 "update": { "t1": { "title": null } }
1752 });
1753 let _ = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1754 .await
1755 .expect("must not return top-level error");
1756 assert_eq!(
1757 backend.per_user_calls.load(Ordering::Relaxed),
1758 0,
1759 "delete-shared-property patch must NOT route to update_task_per_user"
1760 );
1761 }
1762
1763 /// Oracle: draft-tasks-06 §4.5.1 — a mixed patch (per-user + shared)
1764 /// routes to update_object, never update_task_per_user.
1765 #[tokio::test]
1766 async fn set_mixed_patch_routes_to_update_object() {
1767 use std::sync::atomic::Ordering;
1768 let backend = MockBackend::new_with_account("acc1");
1769 let args = json!({
1770 "accountId": "acc1",
1771 "update": { "t1": { "color": "#ff0000", "title": "New" } }
1772 });
1773 let _ = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1774 .await
1775 .expect("must not return top-level error");
1776 assert_eq!(
1777 backend.per_user_calls.load(Ordering::Relaxed),
1778 0,
1779 "mixed patch must route to update_object"
1780 );
1781 }
1782
1783 /// Oracle: RFC 8620 §5.3 — an empty PatchObject is a no-op, not a per-user
1784 /// mutation. The previous routing classified it as per-user-only via
1785 /// vacuous-truth on `iter().all`.
1786 #[tokio::test]
1787 async fn set_empty_patch_routes_to_update_object() {
1788 use std::sync::atomic::Ordering;
1789 let backend = MockBackend::new_with_account("acc1");
1790 let args = json!({
1791 "accountId": "acc1",
1792 "update": { "t1": {} }
1793 });
1794 let _ = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1795 .await
1796 .expect("must not return top-level error");
1797 assert_eq!(
1798 backend.per_user_calls.load(Ordering::Relaxed),
1799 0,
1800 "empty patch must NOT route to update_task_per_user"
1801 );
1802 }
1803
1804 /// RFC 8620 §5.3 types `destroy` as "Id[]|null", so an object element
1805 /// is "invalidArguments: One of the arguments is of the wrong type"
1806 /// (§3.6.2). The description names only the JSON type: §3.6.1 reserves
1807 /// it for "unstructured English text suitable for displaying to a
1808 /// developer", so the client-supplied value is never echoed
1809 /// (bd JMAP-zegc).
1810 #[tokio::test]
1811 async fn set_non_string_destroy_element_does_not_echo_value() {
1812 let backend = MockBackend::new_with_account("acc");
1813 let args = json!({ "accountId": "acc", "destroy": [{ "note": "CANARY-zegc" }] });
1814 let err = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1815 .await
1816 .expect_err("non-string destroy element must be a method error");
1817 assert_eq!(err.error_type.to_string(), "invalidArguments");
1818 let desc = err.description.as_deref().unwrap_or_default();
1819 assert!(desc.contains("got object"), "{desc}");
1820 assert!(!desc.contains("CANARY"), "{desc}");
1821 }
1822
1823 /// Oracle: RFC 8620 §5.3: for `invalidProperties` "the SetError object
1824 /// SHOULD also have a property called `properties` of type `String[]`
1825 /// that lists *all* the properties that were invalid". Each create below
1826 /// has exactly one hand-picked bad property.
1827 #[tokio::test]
1828 async fn set_create_typed_parse_failure_names_property() {
1829 let backend = MockBackend::new_with_account("acc1");
1830 let args = json!({
1831 "accountId": "acc1",
1832 "create": {
1833 "badTitle": { "title": 5 },
1834 "badSequence": { "sequence": "x" }
1835 }
1836 });
1837 let HandlerOutput { primary: resp, .. } =
1838 handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1839 .await
1840 .expect("must not return top-level error");
1841 assert!(resp["created"].is_null(), "nothing may be created: {resp}");
1842 for (cid, prop) in [("badTitle", "title"), ("badSequence", "sequence")] {
1843 let err = &resp["notCreated"][cid];
1844 assert_eq!(err["type"], "invalidProperties", "{cid}: {resp}");
1845 assert_eq!(err["properties"], json!([prop]), "{cid}: {resp}");
1846 }
1847 }
1848
1849 /// Oracle: RFC 8620 §5.3: for `invalidProperties` "the SetError object
1850 /// SHOULD also have a property called `properties` of type `String[]`
1851 /// that lists *all* the properties that were invalid". Each create below
1852 /// has exactly one hand-picked bad property override.
1853 #[tokio::test]
1854 async fn copy_typed_parse_failure_names_property() {
1855 let mut backend = MockBackend::new_with_account("acc1");
1856 backend.add_account("acc2");
1857 backend.seed_task("acc2", "src1", true);
1858 let args = json!({
1859 "accountId": "acc1",
1860 "fromAccountId": "acc2",
1861 "create": {
1862 "badTitle": { "id": "src1", "title": 5 }
1863 }
1864 });
1865 let HandlerOutput { primary: resp, .. } = handle_task_copy(&backend, &(), args, "c0", &[])
1866 .await
1867 .expect("must not return top-level error");
1868 assert!(resp["created"].is_null(), "nothing may be created: {resp}");
1869 let err = &resp["notCreated"]["badTitle"];
1870 assert_eq!(err["type"], "invalidProperties", "{resp}");
1871 assert_eq!(err["properties"], json!(["title"]), "{resp}");
1872 }
1873}