jmap-tasks-server 0.4.0

JMAP Tasks method handlers — backend-agnostic, plugs into jmap-server Dispatcher
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
//! TaskList/* method handlers (draft-tasks-06 §3).
//!
//! TaskList/set has a special `onDestroyRemoveTasks` argument: if false
//! (default) and the list contains tasks, the destroy is rejected with
//! `taskListHasTask`. If true, the handler destroys every Task in the list
//! through `destroy_object::<Task>` and then destroys the list; the backend
//! has no `onDestroyRemoveTasks` concept.
//!
//! # Wire-shape contract
//!
//! Every `handle_*` function in this module conforms to the canonical JMAP
//! method shape. The `args: serde_json::Value` parameter MUST be a JSON
//! Object whose fields match the corresponding RFC 8620 §5 method shape
//! (`/get` → §5.1, `/changes` → §5.2, `/set` → §5.3), with the
//! type-specific arguments defined by draft-tasks-06 §3. The returned
//! `Value` is the corresponding method-response object per the same
//! section refs.
//!
//! The returned `HandlerOutput::extra_invocations` carries any invocations
//! that this handler injected into the request stream (RFC 8620 §6.3);
//! for the handlers in this module the vector is **always empty**.
//!
//! Each handler returns `Err(JmapError)` for method-level failures (RFC 8620
//! §3.6.2 and §5):
//!
//! - every handler: `accountNotFound`, `invalidArguments`, `serverFail`;
//! - `/get`, `/set`: `requestTooLarge` past `maxObjectsInGet` /
//!   `maxObjectsInSet`;
//! - `/set`: `stateMismatch`;
//! - `/changes`: `cannotCalculateChanges`.
//!
//! Per-target failures inside `/set` surface in the `notCreated` / `notUpdated`
//! / `notDestroyed` maps within `Ok((Value, ...))`, not as `Err`.

use jmap_tasks_types::{Task, TaskFilterCondition, TaskList};
use jmap_types::{Filter, Id, JmapError, PatchObject};
use serde_json::{Value, json};

use crate::TasksBackend;
use crate::helpers::{
    SetAccumulators, check_map_key_ids, check_metadata_entry, enforce_max_objects_in_set,
    extract_account_id, finalize_set_response,
};
use jmap_server::{
    HandlerOutput, QueryParams, backend_set_error_value, bool_arg, reject_read_only_patch,
    reject_server_set, server_fail_from_backend, server_fail_value_from_backend,
};

// ---------------------------------------------------------------------------
// TaskList/get
// ---------------------------------------------------------------------------

/// Handle a `TaskList/get` method call (draft-tasks-06 §3.5).
///
/// `args` is the RFC 8620 §5.1 `/get` request shape (`accountId`, optional
/// `ids`, optional `properties`); the returned `Value` is the §5.1
/// `/get` response shape (`accountId`, `state`, `list`, `notFound`).
///
/// `using` is the request's capability list (pass
/// [`jmap_server::CallContext::using`]). When the backend lists TaskList for
/// draft-ietf-jmap-metadata-04 ([`JmapBackend::metadata_info`](jmap_server::JmapBackend::metadata_info)),
/// `metadata` is returned as an object, by default only with
/// `urn:ietf:params:jmap:metadata` in `using`, and with that capability
/// `properties` may hold `metadata/<namespace>` subselectors (-04 §2,
/// §3.1); see [`jmap_server::handle_get_with_metadata`].
///
/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
pub async fn handle_task_list_get<B: TasksBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    args: Value,
    using: &[String],
) -> Result<HandlerOutput, JmapError> {
    jmap_server::handle_get_with_metadata::<TaskList, B>(backend, caller, args, using).await
}

// ---------------------------------------------------------------------------
// TaskList/changes
// ---------------------------------------------------------------------------

/// Handle a `TaskList/changes` method call (draft-tasks-06 §3.6).
///
/// `args` is the RFC 8620 §5.2 `/changes` request shape (`accountId`,
/// `sinceState`, optional `maxChanges`); the returned `Value` is the §5.2
/// `/changes` response shape (`accountId`, `oldState`, `newState`,
/// `hasMoreChanges`, `created`, `updated`, `destroyed`).
///
/// `using` is the request's capability list (pass
/// [`jmap_server::CallContext::using`]); with
/// `urn:ietf:params:jmap:metadata` the request may set
/// draft-ietf-jmap-metadata-04 §3.3 `ignoreMetadataOnlyChanges`, and
/// without it metadata-only changes are left out (-04 §3).
///
/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
pub async fn handle_task_list_changes<B: TasksBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    args: Value,
    using: &[String],
) -> Result<HandlerOutput, JmapError> {
    jmap_server::handle_changes::<TaskList, B>(backend, caller, args, using).await
}

// ---------------------------------------------------------------------------
// TaskList/set
// ---------------------------------------------------------------------------

/// Handle a `TaskList/set` method call (draft-tasks-06 §3.7).
///
/// `args` is the RFC 8620 §5.3 `/set` request shape (`accountId`, optional
/// `ifInState`, optional `create` / `update` / `destroy` maps) plus the
/// draft-tasks-06 §3.7 `onDestroyRemoveTasks` extension argument
/// (default: `false`); the returned `Value` is the §5.3 `/set` response
/// shape (`accountId`, `oldState`, `newState`, plus the per-operation
/// result maps).
///
/// The `onDestroyRemoveTasks` argument (default: `false`) controls whether
/// tasks in a task list are cascade-destroyed when the list is destroyed.
/// If `false` and the list has tasks, the destroy is rejected with a
/// `taskListHasTask` SetError.
///
/// `using` is the request's capability list (pass
/// [`jmap_server::CallContext::using`]): a write to `metadata` or
/// `privateMetadata` without `urn:ietf:params:jmap:metadata` is
/// `invalidProperties` (draft-ietf-jmap-metadata-04 §3), as is `null` for
/// either in a create (-04 §3.2). The backend validates the rest.
///
/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
pub async fn handle_task_list_set<B: TasksBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    args: Value,
    using: &[String],
) -> Result<HandlerOutput, JmapError> {
    let (account_id, mut args) = extract_account_id(args)?;

    // RFC 8620 §3.6.2: accountId not recognised → accountNotFound (method-level
    // error). Without this, a /set against an unknown accountId would silently
    // "succeed" with a fake oldState/newState envelope. Fixed in JMAP-gpt1.
    if !backend
        .account_exists(caller, &account_id)
        .await
        .map_err(|e| server_fail_from_backend(&e))?
    {
        return Err(JmapError::account_not_found());
    }

    // RFC 8620 §5.3 maxObjectsInSet (bd:JMAP-ayoz.41.5). Reject
    // unbounded /set batches before touching the storage layer.
    enforce_max_objects_in_set(&args, backend.max_objects_in_set(caller, &account_id))?;

    // Parse onDestroyRemoveTasks (default: false)
    let on_destroy_remove_tasks = bool_arg(&args, "onDestroyRemoveTasks", false);

    let old_state = backend
        .get_state::<TaskList>(caller, &account_id)
        .await
        .map_err(|e| server_fail_from_backend(&e))?;

    if let Some(if_in_state) = args.get("ifInState").and_then(|v| v.as_str())
        && if_in_state != old_state.as_ref()
    {
        return Err(JmapError::state_mismatch());
    }

    let mut created = serde_json::Map::new();
    let mut not_created = serde_json::Map::new();
    let mut updated = serde_json::Map::new();
    let mut not_updated = serde_json::Map::new();
    let mut destroyed_list: Vec<Value> = Vec::new();
    let mut not_destroyed = serde_json::Map::new();
    let mut mutated = false;

    // -----------------------------------------------------------------------
    // create
    // -----------------------------------------------------------------------
    if let Some(Value::Object(create_map)) = args.remove("create") {
        for (create_id, obj_val) in create_map {
            if let Some(err) = obj_val.as_object().and_then(reject_server_set::<TaskList>) {
                not_created.insert(create_id, serde_json::Value::from(&err));
                continue;
            }
            if let Some(Err(err)) = obj_val
                .as_object()
                .map(|o| check_metadata_entry(o, true, using))
            {
                not_created.insert(create_id, serde_json::Value::from(&*err));
                continue;
            }
            // draft-ietf-jmap-tasks-06 §3 `shareWith`: Id[TaskRights], keyed
            // by Principal id.
            if let Some(Err(err)) = obj_val
                .as_object()
                .map(|o| check_map_key_ids(o, "shareWith"))
            {
                not_created.insert(create_id, serde_json::Value::from(&*err));
                continue;
            }
            // `TaskList.id` is required, so the parse fills it with
            // `jmap_server::CREATE_ID_PLACEHOLDER`; `build`
            // overwrites it with the id the backend mints.
            let obj_with_id = match obj_val {
                Value::Object(mut m) => {
                    m.insert("id".to_owned(), jmap_server::CREATE_ID_PLACEHOLDER.into());
                    // RFC 8620 §5.3: the server fills omitted properties that
                    // have a default. draft-ietf-jmap-tasks-06 §3:
                    // `isSubscribed` SHOULD default to true for any new task
                    // list created by the user themselves.
                    m.entry("isSubscribed").or_insert(Value::Bool(true));
                    // `myRights` is server-set (draft-ietf-jmap-tasks-06 §3)
                    // and TaskList requires it, so the server supplies it.
                    //
                    // ponytail: the creator holds every right, as the owner of
                    // a task list in their own account; a backend with finer
                    // sharing may replace `myRights` in `create_object`.
                    m.insert(
                        "myRights".to_owned(),
                        json!({
                            "mayReadItems": true,
                            "mayWriteAll": true,
                            "mayWriteOwn": true,
                            "mayUpdatePrivate": true,
                            "mayRSVP": true,
                            "mayAdmin": true,
                            "mayDelete": true,
                        }),
                    );
                    Value::Object(m)
                }
                other => other,
            };

            let mut task_list: TaskList = match serde_json::from_value(obj_with_id) {
                Ok(tl) => tl,
                Err(e) => {
                    not_created.insert(
                        create_id,
                        json!({ "type": "invalidProperties", "description": e.to_string() }),
                    );
                    continue;
                }
            };

            let build = move |id: &Id| {
                task_list.id = id.clone();
                task_list
            };
            match backend
                .create_object::<TaskList, _>(caller, &account_id, &create_id, build)
                .await
            {
                Ok((_new_id, created_obj)) => {
                    mutated = true;
                    created.insert(create_id, jmap_server::serialize_value(&created_obj)?);
                }
                Err(e) => {
                    not_created.insert(create_id, backend_set_error_value(e));
                }
            }
        }
    }

    // -----------------------------------------------------------------------
    // update
    // -----------------------------------------------------------------------
    if let Some(Value::Object(update_map)) = args.remove("update") {
        for (id_str, patch_val) in update_map {
            let id = match jmap_server::parse_wire_id(&id_str, "id") {
                Ok(id) => id,
                Err(err) => {
                    not_updated.insert(id_str, serde_json::Value::from(&*err));
                    continue;
                }
            };

            // Convert wire-format Value into a typed PatchObject. RFC 8620
            // §5.3 mandates a PatchObject is a JSON Object; non-object
            // values produce an `invalidPatch` SetError.
            let patch = match serde_json::from_value::<PatchObject>(patch_val) {
                Ok(p) => p,
                Err(e) => {
                    not_updated.insert(
                        id_str,
                        json!({ "type": "invalidPatch", "description": e.to_string() }),
                    );
                    continue;
                }
            };
            if let Some(err) = reject_read_only_patch::<TaskList>(patch.as_map(), None) {
                not_updated.insert(id_str, serde_json::Value::from(&err));
                continue;
            }
            if let Err(err) = check_metadata_entry(patch.as_map(), false, using) {
                not_updated.insert(id_str, serde_json::Value::from(&*err));
                continue;
            }
            if let Err(err) = check_map_key_ids(patch.as_map(), "shareWith") {
                not_updated.insert(id_str, serde_json::Value::from(&*err));
                continue;
            }

            match backend
                .update_object::<TaskList>(caller, &account_id, &id, patch)
                .await
            {
                Ok(Some(obj)) => {
                    mutated = true;
                    updated.insert(id_str, jmap_server::serialize_value(&obj)?);
                }
                Ok(None) => {
                    mutated = true;
                    updated.insert(id_str, Value::Null);
                }
                Err(e) => {
                    not_updated.insert(id_str, backend_set_error_value(e));
                }
            }
        }
    }

    // -----------------------------------------------------------------------
    // destroy
    // -----------------------------------------------------------------------
    if let Some(Value::Array(destroy_arr)) = args.remove("destroy") {
        // RFC 8620 §5.3: every element of the destroy array MUST be a string Id.
        // Two-pass validation is intentional: this up-front loop fails the whole
        // request loudly; the `None => continue` arm in the inner match below
        // is unreachable BECAUSE this pre-check ran. Future contributor: do NOT
        // delete this pre-check on the reasoning that the inner match handles
        // non-string elements — silent-skip is the wrong behaviour per the
        // workspace "silent-drop is a data-integrity bug class" rule
        // (JMAP-wlip.1).
        let id_strs: Vec<&str> = destroy_arr
            .iter()
            .map(|v| {
                v.as_str().ok_or_else(|| {
                    JmapError::invalid_arguments(format!(
                        "destroy: every element must be a string Id; got {}",
                        jmap_server::json_type_name(v)
                    ))
                })
            })
            .collect::<Result<_, _>>()?;
        for id_str in id_strs {
            let id_str = id_str.to_owned();
            let id = match jmap_server::parse_wire_id(&id_str, "id") {
                Ok(id) => id,
                Err(err) => {
                    not_destroyed.insert(id_str, serde_json::Value::from(&*err));
                    continue;
                }
            };

            // Check for tasks in the list if onDestroyRemoveTasks is false.
            // The three-way result distinguishes 'definitely empty',
            // 'definitely has tasks', and 'transient backend failure'
            // (analogous to bd:JMAP-ic0j.4 for calendars).
            if !on_destroy_remove_tasks {
                match backend.task_list_has_tasks(caller, &account_id, &id).await {
                    Ok(true) => {
                        not_destroyed.insert(id_str, json!({ "type": "taskListHasTask" }));
                        continue;
                    }
                    Ok(false) => {
                        // proceed to destroy below
                    }
                    Err(e) => {
                        not_destroyed.insert(id_str, server_fail_value_from_backend(&e));
                        continue;
                    }
                }
            }

            // draft-tasks-06 §3.4: "If true, any Tasks that were in the
            // TaskList will be removed from it, and they will be destroyed."
            // A failed cascade leaves the list in place rather than
            // orphaning the Tasks that remain.
            if on_destroy_remove_tasks
                && let Err(value) = destroy_task_list_tasks(backend, caller, &account_id, &id).await
            {
                not_destroyed.insert(id_str, value);
                continue;
            }

            match backend
                .destroy_object::<TaskList>(caller, &account_id, &id)
                .await
            {
                Ok(()) => {
                    mutated = true;
                    destroyed_list.push(Value::String(id_str));
                }
                Err(e) => {
                    not_destroyed.insert(id_str, backend_set_error_value(e));
                }
            }
        }
    }

    finalize_set_response::<B, TaskList>(
        backend,
        caller,
        &account_id,
        old_state,
        mutated,
        SetAccumulators {
            created,
            updated,
            destroyed: destroyed_list,
            not_created,
            not_updated,
            not_destroyed,
        },
    )
    .await
}

/// Destroy every Task whose `taskListId` is `task_list_id`
/// (draft-tasks-06 §3.4 `onDestroyRemoveTasks: true`).
///
/// A Task belongs to exactly one TaskList, so each one is destroyed
/// outright; there is no membership to patch out as in the Calendar and
/// Mailbox cascades.
///
/// # Errors
///
/// Returns the redacted wire-format SetError [`Value`] for the TaskList's
/// `notDestroyed` entry on the first failed query, fetch or destroy. A
/// typed [`BackendSetError::SetError`] keeps its JMAP type; every other
/// failure becomes `serverFail`.
async fn destroy_task_list_tasks<B: TasksBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    account_id: &Id,
    task_list_id: &Id,
) -> Result<(), Value> {
    let mut condition = TaskFilterCondition::default();
    condition.task_list_id = Some(task_list_id.clone());
    let filter = Filter::Condition(condition);
    let ids = backend
        .query_objects::<Task>(caller, account_id, QueryParams::new().filter(Some(&filter)))
        .await
        .map_err(|e| server_fail_value_from_backend(&e))?
        .ids;
    if ids.is_empty() {
        return Ok(());
    }

    // Re-check membership on the fetched Tasks so a backend whose filter
    // over-matches cannot destroy Tasks belonging to another list.
    let (tasks, _not_found): (Vec<Task>, _) = backend
        .get_objects::<Task>(caller, account_id, Some(&ids), None)
        .await
        .map_err(|e| server_fail_value_from_backend(&e))?;
    for task in tasks {
        if task.task_list_id.as_ref() != Some(task_list_id) {
            continue;
        }
        let Some(task_id) = task.id.as_ref() else {
            return Err(server_fail_value_from_backend(&"missing task id"));
        };
        backend
            .destroy_object::<Task>(caller, account_id, task_id)
            .await
            .map_err(backend_set_error_value)?;
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    use crate::test_support::MockBackend;

    /// Oracle: TaskList/get with unknown accountId returns accountNotFound.
    #[tokio::test]
    async fn get_unknown_account_returns_account_not_found() {
        let backend = MockBackend::new();
        let args = json!({ "accountId": "unknown", "ids": null });
        let result = handle_task_list_get(&backend, &(), args, &[]).await;
        let err = result.expect_err("must return error for unknown account");
        assert_eq!(err.error_type.to_string(), "accountNotFound");
    }

    /// Oracle: TaskList/set destroy with onDestroyRemoveTasks=false and tasks
    /// in the list → taskListHasTask error (draft-ietf-jmap-tasks-06 §3.4).
    #[tokio::test]
    async fn set_destroy_with_tasks_returns_task_list_has_task() {
        let mut backend = MockBackend::new_with_account("acc1");
        backend.add_task_list_with_task("acc1", "list1");

        let args = json!({
            "accountId": "acc1",
            "destroy": ["list1"],
            "onDestroyRemoveTasks": false
        });
        let HandlerOutput { primary: resp, .. } = handle_task_list_set(&backend, &(), args, &[])
            .await
            .expect("must not return top-level error");

        assert_eq!(
            resp["notDestroyed"]["list1"]["type"], "taskListHasTask",
            "must return taskListHasTask: {resp}"
        );
        assert!(
            resp["destroyed"].is_null(),
            "destroyed must be null: {resp}"
        );
    }

    /// Oracle: TaskList/set destroy with onDestroyRemoveTasks=true ignores
    /// task list contents and destroys it.
    #[tokio::test]
    async fn set_destroy_with_on_destroy_remove_tasks_true_succeeds() {
        let mut backend = MockBackend::new_with_account("acc1");
        backend.add_task_list_with_task("acc1", "list1");

        let args = json!({
            "accountId": "acc1",
            "destroy": ["list1"],
            "onDestroyRemoveTasks": true
        });
        let HandlerOutput { primary: resp, .. } = handle_task_list_set(&backend, &(), args, &[])
            .await
            .expect("must not return top-level error");

        // With onDestroyRemoveTasks=true the list should be destroyed
        // (mock backend's destroy_object will find it and remove it)
        let destroyed = resp["destroyed"].as_array();
        assert!(
            destroyed.is_some(),
            "destroyed array must be present: {resp}"
        );
    }

    /// Oracle: TaskList/set with no operations returns empty /set response.
    #[tokio::test]
    async fn set_empty_returns_valid_response() {
        let backend = MockBackend::new_with_account("acc1");
        let args = json!({ "accountId": "acc1", "destroy": [] });
        let HandlerOutput { primary: resp, .. } = handle_task_list_set(&backend, &(), args, &[])
            .await
            .expect("must not return top-level error");
        assert_eq!(resp["accountId"], "acc1");
        assert!(resp["destroyed"].is_null());
    }
}